-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert.py
More file actions
71 lines (64 loc) · 2.3 KB
/
convert.py
File metadata and controls
71 lines (64 loc) · 2.3 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import argparse
import os
import re
from typing import List, Tuple
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument('files', nargs='*')
parser.add_argument('--base-dir', default='.')
parser.add_argument('--strip_only', action='store_true')
parser.add_argument('--extensions', default=('.h', '.c', '.hpp', '.cpp', '.d', '.m', '.py', '.pyi', '.pyw', '.dave', '.mak', 'Makefile', '.dasm', 'CMakeLists.txt'), nargs='*')
parser.add_argument('--dry-run', action='store_true')
args = parser.parse_args()
run(**vars(args))
def run(files:List[str], extensions:List[str], base_dir:str='.', strip_only:bool=False, dry_run:bool=False) -> None:
if not files:
files = find_files(base_dir, tuple(extensions))
for f in files:
changed = 0
with open(f, 'rb') as rp:
lines = []
for line in rp:
line = line.decode('utf-8')
oldline = line
line = line.rstrip()
if not strip_only:
line = convert(line)
lines.append(line)
changed += ((line+'\n') != oldline)
# only rewrite files we actually are changing
if not changed:
continue
if dry_run:
print(f, 'would change')
continue
with open(f, 'wb') as wp:
for line in lines:
wp.write(line.encode('utf8')+b'\n')
wp.flush()
def find_files(d:str, extensions:Tuple[str, ...]) -> List[str]:
result: List[str] = []
if 'PythonEmbed' in d:
return result
for f in os.listdir(d):
if f.startswith('.'):
continue
p = os.path.join(d, f)
if os.path.isdir(p):
result += find_files(p, extensions)
continue
if f.endswith(extensions):
result.append(p)
return result
def convert(original:str, compiled_replacements=[]) -> str:
replacements = [
]
if replacements and not compiled_replacements:
for pattern, repl in replacements:
comp = re.compile(pattern)
compiled_replacements.append((comp, repl))
for pattern, repl in compiled_replacements:
original = re.sub(pattern, repl, original)
return original
if __name__ == '__main__':
main()