forked from JohannesBuchner/fstring-downgrade
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfstring-downgrade.py
More file actions
executable file
·53 lines (50 loc) · 1.36 KB
/
Copy pathfstring-downgrade.py
File metadata and controls
executable file
·53 lines (50 loc) · 1.36 KB
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
#!/usr/bin/env python3
import sys
import re
import shutil
in_name = sys.argv[1]
out_name = in_name + '-nofstrings.py'
out = open(out_name, 'w')
for fullline in open(sys.argv[1]):
linestart = 0
#print("line: '%s'" % (fullline))
while True:
line = fullline[linestart:]
if "f'" not in line and 'f"' not in line:
out.write(line)
break
if "f'" in line:
start = "f'"
end = "'"
elif 'f"' in line:
start = 'f"'
end = '"'
istart = line.index(start)
iinside = istart + len(start)
if end not in line[iinside:]:
print("skipping problematic part: '%s'" % line.rstrip())
out.write(line)
linestart += len(line)
continue
try:
iend = iinside + line[iinside:].index(end)
part = line[iinside:iend]
matches = re.findall(r'{([^}:]*)(:[^}]*)?}', part)
keys = [key for key, format in matches]
part = re.sub(r'{([^}:]*)((:[^}]*)?)}', r'{\2}', part)
#print(' "%s": matches:%s keys:%s' % (part, matches, keys))
out.write(line[:istart])
out.write(start.replace('f', ''))
out.write(part)
out.write(end)
if len(keys) > 0:
out.write('.format(' + ', '.join(['%s' % (key) for key in keys]) + ')')
#out.write(line[iend+len(end):])
linestart += iend + len(end)
except:
print("skipping problematic line: '%s'" % line.rstrip())
out.write(line)
linestart += len(line)
rewrite = True
if rewrite:
shutil.move(out_name, in_name)