Created
June 21, 2019 19:16
-
-
Save tomzx/f509ad92bf7361bf03890916c17262f5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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