| 1 |
""" |
| 2 |
File- and directory related helpers for resource utilities. |
| 3 |
""" |
| 4 |
|
| 5 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 6 |
#c |
| 7 |
#c This program is free software, covered by the GNU GPL. See the |
| 8 |
#c COPYING file in the source distribution. |
| 9 |
|
| 10 |
|
| 11 |
import os |
| 12 |
import re |
| 13 |
import warnings |
| 14 |
|
| 15 |
from gavo import base |
| 16 |
from gavo import rscdef |
| 17 |
from gavo.base import parsecontext |
| 18 |
|
| 19 |
class Error(base.Error): |
| 20 |
pass |
| 21 |
|
| 22 |
|
| 23 |
fnamePat = re.compile(r"([^.]*)(\..*)") |
| 24 |
def stingySplitext(fName): |
| 25 |
"""returns name, extension for fName. |
| 26 |
|
| 27 |
The main difference to os.path.splitext is that the main name is not allowed |
| 28 |
to contain dots and the extension can contain more than one dot. |
| 29 |
|
| 30 |
fName is supposed to be a single file name without any path specifier |
| 31 |
(you might get away with it if your directories do not contain dots, though). |
| 32 |
""" |
| 33 |
mat = fnamePat.match(fName) |
| 34 |
if mat: |
| 35 |
return mat.group(1), mat.group(2) |
| 36 |
else: |
| 37 |
return fName, "" |
| 38 |
|
| 39 |
|
| 40 |
class FileRenamer(object): |
| 41 |
"""is a name mapper for file rename operations and the like. |
| 42 |
|
| 43 |
Warning: This whole thing more or less pretends there are no |
| 44 |
symlinks. |
| 45 |
""" |
| 46 |
def __init__(self, map, showOnly=False): |
| 47 |
self.map, self.showOnly = map, showOnly |
| 48 |
|
| 49 |
@classmethod |
| 50 |
def loadFromFile(cls, inF, **kwargs): |
| 51 |
"""returns a name map for whatever is serialized in the file inF. |
| 52 |
|
| 53 |
The format of fName is line-base, with each line being one of |
| 54 |
|
| 55 |
- empty -- ignored |
| 56 |
- beginning with a hash -- ignored |
| 57 |
- <old> -> <new> -- introducing a map |
| 58 |
""" |
| 59 |
map = {} |
| 60 |
try: |
| 61 |
for ln in inF: |
| 62 |
if not ln.strip() or ln.strip().startswith("#"): |
| 63 |
continue |
| 64 |
old, new = [s.strip() for s in ln.split("->", 2)] |
| 65 |
if old in map: |
| 66 |
raise Error("Two mappings for %s"%old) |
| 67 |
map[old] = new |
| 68 |
except ValueError: |
| 69 |
raise base.ui.logOldExc(Error("Invalid mapping line: %s"%repr(ln))) |
| 70 |
return cls(map, **kwargs) |
| 71 |
|
| 72 |
def getFileMap(self, path): |
| 73 |
"""returns a dictionary old->new of renames within path. |
| 74 |
""" |
| 75 |
fileMap = {} |
| 76 |
for dir, subdirs, fNames in os.walk(path): |
| 77 |
for fName in fNames: |
| 78 |
stem, ext = stingySplitext(fName) |
| 79 |
if stem in self.map: |
| 80 |
fileMap[os.path.join(dir, fName)] = os.path.join(dir, |
| 81 |
self.map[stem]+ext) |
| 82 |
return fileMap |
| 83 |
|
| 84 |
def makeRenameProc(self, fileMap): |
| 85 |
"""returns a sequence of (old,new) pairs that, when executed, keep |
| 86 |
any new from clobbering any existing old. |
| 87 |
|
| 88 |
The function will raise an Error if there's a cycle in fileMap. fileMap |
| 89 |
will be destroyed by this procedure |
| 90 |
""" |
| 91 |
proc = [] |
| 92 |
def addOp(src, dest, sources=None): |
| 93 |
if sources is None: |
| 94 |
sources = set() |
| 95 |
if dest in sources: |
| 96 |
raise Error("Rename cycle involving %s"%sources) |
| 97 |
if dest in fileMap: |
| 98 |
sources.add(src) |
| 99 |
addOp(dest, fileMap.pop(dest), sources) |
| 100 |
proc.append((src, dest)) |
| 101 |
while fileMap: |
| 102 |
addOp(*fileMap.popitem()) |
| 103 |
return proc |
| 104 |
|
| 105 |
def renameInPath(self, path): |
| 106 |
"""performs a name map below path. |
| 107 |
|
| 108 |
The rules are: |
| 109 |
|
| 110 |
- extensions are ignored -- if we map foo to bar, foo.txt and foo.asc |
| 111 |
will be renamed bar.txt and foo.txt respectively |
| 112 |
- the order of statements in the source is irrelevant. However, we try |
| 113 |
not to clobber anything we've just renamed and will complain about |
| 114 |
cycles. Also, each file will be renamed not more than once. |
| 115 |
""" |
| 116 |
fileMap = self.getFileMap(path) |
| 117 |
for src, dest in self.makeRenameProc(fileMap): |
| 118 |
if os.path.exists(dest): |
| 119 |
raise Error("Request to clobber %s"%repr(dest)) |
| 120 |
if os.path.exists(src): |
| 121 |
if self.showOnly: |
| 122 |
print("%s -> %s"%(src, dest)) |
| 123 |
else: |
| 124 |
os.rename(src, dest) |
| 125 |
else: |
| 126 |
if not os.path.exists(dest): |
| 127 |
warnings.warn("Neither source nor dest found in pair %s, %s"%(src, |
| 128 |
dest)) |
| 129 |
|
| 130 |
def renameInPaths(self, pathList): |
| 131 |
for path in pathList: |
| 132 |
self.renameInPath(path) |
| 133 |
|
| 134 |
|
| 135 |
def iterSources(ddId, args=[]): |
| 136 |
"""iterates over the current sources of the data descriptor ddId (which is |
| 137 |
qualified like rdId#id |
| 138 |
|
| 139 |
If you pass something nonempty to args, an iterator over its values |
| 140 |
will be returned. This is for convenient implementation of scripts |
| 141 |
that work on CL arguments if given, on all files otherwise. |
| 142 |
""" |
| 143 |
if args: |
| 144 |
return iter(args) |
| 145 |
else: |
| 146 |
if ddId.count("#")!=1: |
| 147 |
raise base.ReportableError("iterSources must get a fully qualified id" |
| 148 |
" (i.e., one with exactly one hash).") |
| 149 |
dd = parsecontext.resolveCrossId(ddId, rscdef.DataDescriptor) |
| 150 |
return dd.sources.iterSources() |