Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
grasscutters
GitHub Repository: grasscutters/grasscutter
Path: blob/development/scripts/format_whitespace.py
3153 views
1
import re
2
import subprocess
3
4
5
UPSTREAM = 'https://github.com/Grasscutters/Grasscutter.git'
6
RATCHET = 'LintRatchet'
7
RATCHET_FALLBACK = 'c517b8a2c95473811eb07e12e73c4a69e59fbbdc'
8
9
10
re_leading_whitespace = re.compile(r'^[ \t]+', re.MULTILINE) # Replace with \1.replace('\t', ' ')
11
re_trailing_whitespace = re.compile(r'[ \t]+$', re.MULTILINE) # Replace with ''
12
# Replace 'for (foo){bar' with 'for (foo) {bar'
13
re_bracket_space = re.compile(r'\) *\{(?!\})') # Replace with ') {'
14
# Replace 'for(foo)' with 'foo (bar)'
15
re_keyword_space = re.compile(r'(?<=\b)(if|for|while|switch|try|else|catch|finally|synchronized) *(?=[\(\{])') # Replace with '\1 '
16
17
18
def get_changed_filelist():
19
# subprocess.run(['git', 'fetch', UPSTREAM, f'{RATCHET}:{RATCHET}']) # Ensure LintRatchet ref is matched to upstream
20
# result = subprocess.run(['git', 'diff', RATCHET, '--name-only'], capture_output=True, text=True)
21
# if result.returncode != 0:
22
# print(f'{RATCHET} not found, trying fallback {RATCHET_FALLBACK}')
23
print(f'Attempting to diff against {RATCHET_FALLBACK}')
24
result = subprocess.run(['git', 'diff', RATCHET_FALLBACK, '--name-only'], capture_output=True, text=True)
25
if result.returncode != 0:
26
# print('Fallback is also missing, aborting.')
27
print(f'Could not find {RATCHET_FALLBACK}, aborting.')
28
exit(1)
29
return result.stdout.strip().split('\n')
30
31
32
def format_string(data: str):
33
data = re_leading_whitespace.sub(lambda m: m.group(0).replace('\t', ' '), data)
34
data = re_trailing_whitespace.sub('', data)
35
data = re_bracket_space.sub(') {', data)
36
data = re_keyword_space.sub(r'\1 ', data)
37
if not data.endswith('\n'): # Enforce trailing \n
38
data = data + '\n'
39
return data
40
41
42
def format_file(filename: str) -> bool:
43
try:
44
with open(filename, 'r') as file:
45
data = file.read()
46
data = format_string(data)
47
with open(filename, 'w') as file:
48
file.write(data)
49
return True
50
except FileNotFoundError:
51
print(f'File not found, probably deleted: {filename}')
52
return False
53
54
55
def main():
56
filelist = [f for f in get_changed_filelist() if f.endswith('.java') and not f.startswith('src/generated')]
57
replaced = 0
58
not_found = 0
59
if not filelist:
60
print('No changed files due for formatting!')
61
return
62
print('Changed files due for formatting: ', filelist)
63
for file in filelist:
64
if format_file(file):
65
replaced += 1
66
else:
67
not_found += 1
68
print(f'Format complete! {replaced} formatted, {not_found} missing.')
69
70
71
if __name__ == '__main__':
72
main()
73
74