-
Notifications
You must be signed in to change notification settings - Fork 0
/
template_converter.py
109 lines (80 loc) · 2.59 KB
/
template_converter.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import os
import sys
import re
import itertools
BLOCK_BEGIN = "/** begin block"
BLOCK_END = " /** end block **/"
def process_params(param_str):
line_split = param_str.split("\n")
params = {}
for line in line_split[1:-1]:
line = line[3:]
name = line.split(" = ")[0]
param_ = line.split(" = ")[1][1:-1].split(",")
param_ = [a.strip() for a in param_]
params[name] = param_
ls = []
for p in params:
ls.append(len(params[p]))
assert ls.count(ls[0]) == len(ls)
return params, len(params), ls[0]
def process_code(code, params, count):
news = []
for c in range(count):
new_code = str(code)
for p in params:
new_code = new_code.replace("$%s$" % p, params[p][c])
news.append(new_code)
return news
def process(str_):
# print (str_)
# x = re.search(r'%s(.*?)%s' % (BLOCK_BEGIN, BLOCK_END), str_).group(1)
# x = re.findall("(?=/** begin block)[\S\s]*(?=/** end block **/)", str_, flags=re.S)
# print (x)
ind = 0
add = '#' * 80
add_lines = ["THIS CODE IS AUTOGENERATED FROM A TEMPLATE", "TO MAKE CHANGES, EDIT THE ORIGINAL .src FILE"]
for l in add_lines:
diff = 80 - len(l)
diff //= 2
diff -= 1
add += "\n#" + " " * diff
add += l
add += " " * diff
add += "#"
add += "\n"
add += "#" * 80
add += "\n*/"
add += "\n\n"
str_ = "/*\n" + add + str_
while True:
start = str_.find(BLOCK_BEGIN, ind)
if start == -1:
break
start_end = str_.find("*/", start)
start_end = str_.find("\n", start_end)
end = str_.find("/** end block **/", start_end)
param_span = [start, start_end+1]
code_span = [start_end, end]
params = str_[start:start_end]
code = str_[start_end:end]
params, p_count, o_count = process_params(params)
new_code = process_code(code, params, o_count)
str_ = str_[:start_end+1] + "".join(new_code) + str_[end:]
# end = str_.find("/** end block **/", start_end)
ind += end
return str_
if __name__ == "__main__":
files = sys.argv[1:]
for file in files:
fid = open(file, 'r')
(base, ext) = os.path.splitext(file)
newname = base
outfile = open(newname, 'w')
allstr = fid.read()
# try:
writestr = process(allstr)
# except ValueError:
# e = get_exception()
# raise ValueError("In %s loop at %s" % (file, e))
outfile.write(writestr)