41 lines
1.2 KiB
Python
41 lines
1.2 KiB
Python
import re
|
|
import sys
|
|
|
|
def refactor_file(filepath):
|
|
with open(filepath, 'r', encoding='utf-8') as f:
|
|
content = f.read()
|
|
|
|
# Pattern to find:
|
|
# try {
|
|
# const response = await ...
|
|
# return ...
|
|
# } catch (error) {
|
|
# throw new Error(...) or throw error
|
|
# }
|
|
|
|
# This regex matches the try/catch block and replaces it with the inner code
|
|
# It accounts for indentation and multi-line content
|
|
pattern = r'try\s*\{([\s\S]*?)\}\s*catch\s*\(error\)\s*\{[\s\S]*?\}'
|
|
|
|
def replacement(match):
|
|
inner_code = match.group(1)
|
|
# Strip one level of indentation (usually 2 spaces)
|
|
lines = inner_code.split('\n')
|
|
new_lines = []
|
|
for line in lines:
|
|
if line.startswith(' '):
|
|
new_lines.append(line[2:])
|
|
elif line.startswith(' '):
|
|
new_lines.append(line[2:])
|
|
else:
|
|
new_lines.append(line)
|
|
return '\n'.join(new_lines).strip()
|
|
|
|
new_content = re.sub(pattern, replacement, content)
|
|
|
|
with open(filepath, 'w', encoding='utf-8') as f:
|
|
f.write(new_content)
|
|
|
|
if __name__ == "__main__":
|
|
refactor_file(sys.argv[1])
|