74 lines
2.1 KiB
Python
74 lines
2.1 KiB
Python
"""
|
|
Utility script to safely remove 'with flask_app.app_context():' blocks
|
|
and unindent their inner bodies by 4 spaces.
|
|
"""
|
|
import re
|
|
import sys
|
|
import py_compile
|
|
|
|
def clean_file(filepath: str):
|
|
with open(filepath, 'r', encoding='utf-8') as f:
|
|
lines = f.readlines()
|
|
|
|
new_lines = []
|
|
i = 0
|
|
in_context = False
|
|
context_indent = 0
|
|
|
|
while i < len(lines):
|
|
line = lines[i]
|
|
|
|
# 1. Skip imports of get_flask_app
|
|
if re.match(r'^\s*from database import get_flask_app\s*$', line):
|
|
i += 1
|
|
continue
|
|
if re.match(r'^\s*flask_app = get_flask_app\(\)\s*$', line):
|
|
i += 1
|
|
continue
|
|
if re.match(r'^\s*f_app = get_flask_app\(\)\s*$', line):
|
|
i += 1
|
|
continue
|
|
|
|
# 2. Check for with flask_app.app_context():
|
|
match = re.match(r'^(\s*)with (flask_app|f_app)\.app_context\(\):\s*$', line)
|
|
if match:
|
|
in_context = True
|
|
context_indent = len(match.group(1))
|
|
i += 1
|
|
continue
|
|
|
|
if in_context:
|
|
if not line.strip():
|
|
new_lines.append(line)
|
|
i += 1
|
|
continue
|
|
|
|
current_indent = len(line) - len(line.lstrip())
|
|
if current_indent > context_indent:
|
|
# Unindent 4 spaces
|
|
if line.startswith(' ' * (context_indent + 4)):
|
|
unindented = line[4:]
|
|
else:
|
|
unindented = line[current_indent - context_indent:]
|
|
new_lines.append(unindented)
|
|
i += 1
|
|
continue
|
|
else:
|
|
# Context ended
|
|
in_context = False
|
|
# Do not increment, process this line normally
|
|
|
|
new_lines.append(line)
|
|
i += 1
|
|
|
|
content = ''.join(new_lines)
|
|
with open(filepath, 'w', encoding='utf-8') as f:
|
|
f.write(content)
|
|
|
|
py_compile.compile(filepath, doraise=True)
|
|
print(f"Successfully cleaned & compiled {filepath}")
|
|
|
|
if __name__ == '__main__':
|
|
for p in sys.argv[1:]:
|
|
clean_file(p)
|