Skip to content

Instantly share code, notes, and snippets.

@tomzx
Created June 21, 2019 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomzx/f509ad92bf7361bf03890916c17262f5 to your computer and use it in GitHub Desktop.
Save tomzx/f509ad92bf7361bf03890916c17262f5 to your computer and use it in GitHub Desktop.
import os
import re
from argparse import ArgumentParser
argument_parser = ArgumentParser()
argument_parser.add_argument('root')
argument_parser.add_argument('file')
args = argument_parser.parse_args()
args_root = os.path.abspath(args.root)
args_file = os.path.abspath(args.file)
module = args_root[args_root.rfind('/') + 1:]
module_path = args_file.replace(args_root, '')
module_path = module_path[1:module_path.rfind('/')]
module_path = module_path.replace('/', '.')
module_path = f'{module}.{module_path}'
module_parts = module_path.split('.')
regex = r'from (\.+)'
print(f'Processing {args_file}...')
with open(args_file, 'r') as file:
content = file.read()
x = {}
matches = re.finditer(regex, content, re.MULTILINE)
for match_index, match in enumerate(matches, start=1):
matched_string = match.group()
x[matched_string] = None
x = sorted(x.keys(), key=lambda x: len(x), reverse=True)
for old in x:
dot_count = old.count('.')
replace = '.'.join(module_parts[:len(module_parts)-(dot_count-1)])
new = f'from {replace}.'
content = content.replace(old, new)
with open(args_file, 'w') as file:
file.write(content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment