Path: blob/development/scripts/format_whitespace.py
3153 views
import re1import subprocess234UPSTREAM = 'https://github.com/Grasscutters/Grasscutter.git'5RATCHET = 'LintRatchet'6RATCHET_FALLBACK = 'c517b8a2c95473811eb07e12e73c4a69e59fbbdc'789re_leading_whitespace = re.compile(r'^[ \t]+', re.MULTILINE) # Replace with \1.replace('\t', ' ')10re_trailing_whitespace = re.compile(r'[ \t]+$', re.MULTILINE) # Replace with ''11# Replace 'for (foo){bar' with 'for (foo) {bar'12re_bracket_space = re.compile(r'\) *\{(?!\})') # Replace with ') {'13# Replace 'for(foo)' with 'foo (bar)'14re_keyword_space = re.compile(r'(?<=\b)(if|for|while|switch|try|else|catch|finally|synchronized) *(?=[\(\{])') # Replace with '\1 '151617def get_changed_filelist():18# subprocess.run(['git', 'fetch', UPSTREAM, f'{RATCHET}:{RATCHET}']) # Ensure LintRatchet ref is matched to upstream19# result = subprocess.run(['git', 'diff', RATCHET, '--name-only'], capture_output=True, text=True)20# if result.returncode != 0:21# print(f'{RATCHET} not found, trying fallback {RATCHET_FALLBACK}')22print(f'Attempting to diff against {RATCHET_FALLBACK}')23result = subprocess.run(['git', 'diff', RATCHET_FALLBACK, '--name-only'], capture_output=True, text=True)24if result.returncode != 0:25# print('Fallback is also missing, aborting.')26print(f'Could not find {RATCHET_FALLBACK}, aborting.')27exit(1)28return result.stdout.strip().split('\n')293031def format_string(data: str):32data = re_leading_whitespace.sub(lambda m: m.group(0).replace('\t', ' '), data)33data = re_trailing_whitespace.sub('', data)34data = re_bracket_space.sub(') {', data)35data = re_keyword_space.sub(r'\1 ', data)36if not data.endswith('\n'): # Enforce trailing \n37data = data + '\n'38return data394041def format_file(filename: str) -> bool:42try:43with open(filename, 'r') as file:44data = file.read()45data = format_string(data)46with open(filename, 'w') as file:47file.write(data)48return True49except FileNotFoundError:50print(f'File not found, probably deleted: {filename}')51return False525354def main():55filelist = [f for f in get_changed_filelist() if f.endswith('.java') and not f.startswith('src/generated')]56replaced = 057not_found = 058if not filelist:59print('No changed files due for formatting!')60return61print('Changed files due for formatting: ', filelist)62for file in filelist:63if format_file(file):64replaced += 165else:66not_found += 167print(f'Format complete! {replaced} formatted, {not_found} missing.')686970if __name__ == '__main__':71main()727374