File size: 3,311 Bytes
985c397 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | # SPDX-License-Identifier: LGPL-2.1-or-later
import os, sys, re, FCFileTools
verbose = 0
dcount = fcount = 0
def replaceTemplate(dirName, oldName, newName):
"""
modify contents from dirName and below, replace oldName by newName
"""
for file in os.listdir(dirName):
pathName = os.path.join(dirName, file)
if not os.path.isdir(pathName):
try:
print(pathName)
origFile = open(pathName) # open file
lines = origFile.readlines() # read the file...
origFile.close() # ... and close it
output = open(pathName, "w") # open the file again
for line in lines:
if line.find(oldName) != -1: # search for 'oldName' and replace it
line = line.replace(oldName, newName)
output.write(line) # write the modified line back
output.close # close the file
except Exception:
print("Error modifying ", pathName, " -- skipped")
print(sys.exc_info()[0], sys.exc_info()[1])
else:
try:
replaceTemplate(pathName, oldName, newName)
except Exception:
print("Error changing to directory ", pathName, " -- skipped")
print(sys.exc_info()[0], sys.exc_info()[1])
def copyTemplate(dirFrom, dirTo, oldName, newName, MatchFile, MatchDir):
"""
copy contents of dirFrom and below to dirTo
"""
global dcount, fcount
for file in os.listdir(dirFrom): # for files/dirs here
print(file)
pathFrom = os.path.join(dirFrom, file)
pathTo = os.path.join(dirTo, file) # extend both paths
if pathTo.find(oldName) != -1:
pathTo = pathTo.replace(oldName, newName) # rename file if 'oldName' is found
if not os.path.isdir(pathFrom): # copy simple files
hit = 0
for matchpat in MatchFile:
if re.match(matchpat, file):
hit = 1
break
if hit:
print("Ignore file " + file)
continue
try:
if verbose > 1:
print("copying ", pathFrom, " to ", pathTo)
FCFileTools.cpfile(pathFrom, pathTo)
fcount = fcount + 1
except Exception:
print("Error copying ", pathFrom, " to ", pathTo, " -- skipped")
print(sys.exc_info()[0], sys.exc_info()[1])
else:
hit = 0
for matchpat in MatchDir:
if re.match(matchpat, file):
hit = 1
break
if hit:
print("Ignore directory " + file)
continue
if verbose:
print("copying dir ", pathFrom, " to ", pathTo)
try:
os.mkdir(pathTo) # make new subdir
copyTemplate(
pathFrom, pathTo, oldName, newName, MatchFile, MatchDir
) # recurse into subdirs
dcount = dcount + 1
except Exception:
print("Error creating ", pathTo, " -- skipped")
print(sys.exc_info()[0], sys.exc_info()[1])
|