Debian Codegraph @

cmake/tribits/refactoring/token-replace.py

raw
1 #!/bin/env python3
2
3 usageHelp = r"""
4
5 Replace a given token string with another string in a file (but only touch the
6 file if there were changes).
7
8 This will only match complete tokens that match the regex:
9
10 ([^A-Za-z0-9_])|^)<token-to-replace)[^A-Za-z0-9_]
11 """
12
13
14 def getCmndLineOptions():
15 from argparse import ArgumentParser, RawDescriptionHelpFormatter
16
17 clp = ArgumentParser(description=usageHelp,
18 formatter_class=RawDescriptionHelpFormatter)
19
20 clp.add_argument(
21 "-t", dest="tokenToReplace", required=True,
22 help="Token to repalce" )
23
24 clp.add_argument(
25 "-r", dest="replacementString", required=True,
26 help="Replacement string" )
27
28 clp.add_argument(
29 "-f", dest="inputFile", required=True,
30 help="Input file (and also output if -o <file> not specified)" )
31
32 clp.add_argument(
33 "-o", dest="outputFile", default="",
34 help="Output file (optional)" )
35
36 options = clp.parse_args(sys.argv[1:])
37
38 if options.outputFile == "":
39 options.outputFile = options.inputFile
40
41 return options
42
43
44 #
45 # Main()
46 #
47
48 if __name__ == '__main__':
49
50 import sys, re
51
52 inOptions = getCmndLineOptions()
53
54 beginLineTokenPattern = re.compile(
55 fr'^{inOptions.tokenToReplace}([^A-Za-z0-9_])' )
56 midLineTokenPattern = re.compile(
57 fr'([^A-Za-z0-9_]){inOptions.tokenToReplace}([^A-Za-z0-9_])' )
58
59 with open(inOptions.inputFile, 'r') as file:
60 lines = file.readlines()
61
62 fileWasChanged = False
63 newLines = []
64 for line in lines:
65 newLine = beginLineTokenPattern.sub(
66 inOptions.replacementString + r'\1',
67 line)
68 newLine = midLineTokenPattern.sub(
69 r'\1' + inOptions.replacementString + r'\2',
70 newLine)
71 if newLine != line:
72 fileWasChanged = True
73 newLines.append(newLine)
74
75 if (fileWasChanged or inOptions.outputFile != inOptions.inputFile):
76 with open(inOptions.outputFile, 'w') as file:
77 file.writelines(newLines)