-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmacros.py
68 lines (52 loc) · 1.66 KB
/
macros.py
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
"""
Reads `<package>/version.py`, and replaces all instances
of `${UPPER_CASE_VARIABLE}` in files with the `.in` suffix
with their corresponding values. Useful for, e.g., keeping
the version up-to-date in the README.
"""
import os
import glob
import sys
import re
verbose = len(sys.argv) > 1 and sys.argv[1] == '-v'
package = 'ftperiodogram'
if verbose:
print("reading version.py")
with open(os.path.join(package, 'version.py'), 'r') as f:
exec(f.read())
if verbose:
print("generating dictionary")
variables = {lvar : globals()[lvar] for lvar in locals().keys()
if lvar.isupper()}
if verbose:
print("vars:")
for var in variables.keys():
print(" %s"%var)
# get list of .in files
infiles = glob.glob('*.in')
if verbose:
print("infiles:")
for infile in infiles:
print(" %s"%infile)
if verbose:
print("replacements:")
# replace variables in each file
for infile in infiles:
ofile = infile.replace('.in', '')
with open(infile, 'r') as f:
# read text
txt = f.read()
ninstances_total = 0
for variable in variables.keys():
key = "${%s}"%(variable)
value = str(variables[variable])
regex_key = re.escape(key)
ninstances = len([m.start()
for m in re.finditer(regex_key, txt)])
if verbose and ninstances > 0:
print(" ".join([" [%s] replacing %d"%(infile, ninstances),
"instances of '%s' with '%s'"%(key, value)]))
txt = txt.replace(key, value)
# write replaced text
with open(ofile, 'w') as fo:
fo.write(txt)