Debian Codegraph @

utils/scripts/dolfinreplace

raw
1 #!/usr/bin/python
2 #
3 # Replace string in dolfin files
4 #
5 # dolfinreplace s0 s1 [-sv]
6 #
7 # Example:
8 #
9 # dolfinreplace foo bar
10 #
11 # Johan Hake, 2008-19-09
12 #
13 # Modified by Anders Logg 2008, 2014
14
15 from os import path
16 import glob
17
18 # File post fixes to look in
19 post_fixes = [".h", ".cpp", ".i", ".tex", ".py", ".rst"]
20
21 # Primitive exclusion of some directories
22 exclude_patterns = ["build.", "local."]
23
24 # Global variables
25 count = 0
26 changed_files = 0
27 report_lines = []
28 dolfin_root = path.abspath(path.join(path.dirname(path.abspath(__file__)),
29 path.pardir, path.pardir))
30
31 # Output strings
32 post_fix_string = ", ".join( "'%s'"%s for s in post_fixes)
33
34 start_str = """Replacing '%s' with '%s' in all %s files..."""
35
36 report_str = """
37 %d occurences replaced in %d files:
38
39 %s
40 %s"""
41
42 def replace(args, dirname, filenames):
43 """ Replace replaces[0] with replaces[1]
44
45 In all fnames with post fixes in 'post_fixes' replace replaces[0] with replaces[1]
46 """
47 global count, report_lines, changed_files
48 (s0, s1), options = args
49
50 _filenames = filenames[:]
51 for f in _filenames:
52 for exclude in exclude_patterns:
53 if exclude in f:
54 filenames.remove(f)
55
56 for filename in glob.glob(path.join(dirname, options.pattern)):
57 if path.splitext(filename)[1] in post_fixes:
58 fullpath_filename = path.join(dirname,filename)
59 f = open(fullpath_filename, "r")
60 if options.verbose:
61 changed_lines = []
62 lines = f.readlines()
63 num_changed = 0
64 for i, line in enumerate(lines):
65 num = line.count(s0)
66 if num>0:
67 num_changed += num
68 changed_lines.append(" "*8+line.replace(s0,\
69 "\033[4m%s\033[0;0m"%s0).strip())
70 lines[i] = line.replace(s0, s1)
71 count += num_changed
72 output = "".join(lines)
73 else:
74 input = f.read()
75 num_changed = input.count(s0)
76 count += num_changed
77 output = input.replace(s0, s1)
78
79 f.close()
80
81 if not options.simulate and num_changed > 0:
82 f = open(fullpath_filename, "w")
83 f.write(output)
84 f.close()
85
86 if num_changed > 0:
87 changed_files += 1
88 report_lines.append(" "*4+fullpath_filename)
89 if options.verbose:
90 report_lines.extend(changed_lines)
91 report_lines.append("")
92
93 def options_parser():
94 import optparse
95 usage ="""Usage: %prog [options] arg1 arg2
96
97 Replaces string 'arg1' with 'arg2' in files in the present directory tree.
98
99 For options, see dolfinreplace --help."""
100
101 parser = optparse.OptionParser(usage=usage)
102 parser.add_option("-s", "--simulate", help="simulate the replacement",
103 action="store_true", dest="simulate", default=False)
104 parser.add_option("-p", "--pattern", help="a glob compatible pattern "
105 "for which files should be looked into. "\
106 "[default: '%default']", action="store",\
107 dest="pattern", default="*")
108 parser.add_option("-v", "--verbose", help="verbosely print each line that"\
109 " includes the searched pattern.", action="store_true", \
110 dest="verbose", default=False)
111 return parser
112
113 def main():
114 parser = options_parser()
115 options, args = parser.parse_args()
116
117 if len(args) != 2:
118 parser.error("incorrect number of arguments")
119
120 s0, s1 = args[0].replace("\\", ""), args[1].replace("\\", "")
121
122 print start_str%(s0,s1,post_fix_string)
123
124 # Do it!
125 path.walk(dolfin_root, replace, ((s0, s1), options))
126 if count > 0:
127 if options.simulate:
128 simulate_str = "\nSimulating, no replacement done..."
129 else:
130 simulate_str = ""
131
132 if report_lines[-1]:
133 report_lines.pop(-1)
134
135 print report_str % (count, changed_files, "\n".\
136 join(report_lines), simulate_str)
137 else:
138 print "Done\n\nNo occurens of '%s' found"%args[0]
139
140 if __name__ == "__main__":
141 main()