Created
April 5, 2017 08:27
-
-
Save sveitser/38b04f46b7b97a6db1dd0563ec00e0f1 to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/env python3.6 | |
"""Python replace absolute imports with relative ones. | |
HARDLY TESTED. Use at own risk. | |
Only works from imports of type "from ... import ...". | |
Doesn't fix indentation for multiline imports. | |
Usage: show changes: ./fix_import.py package_directory | |
write changes: ./fix_import.py package_directory write | |
""" | |
import glob | |
import os | |
import sys | |
pkg = sys.argv[1] | |
for fname in glob.glob(f'{pkg}/**/*.py', recursive=True): | |
depth = len([x for x in fname if x == '/']) | |
current_module = os.path.dirname(fname).split('/') | |
with open(fname) as f: | |
data = f.readlines() | |
new_lines = [] | |
for line in data: | |
if line.startswith(f'from {pkg}') and 'import' in line: | |
print(line) | |
_, abs_import, _, *targets = line.split(' ') | |
target = ' '.join(targets) | |
import_module = abs_import.split('.') | |
n_match = 0 | |
for imp, cur in zip(import_module, current_module): | |
if imp == cur: | |
n_match += 1 | |
else: | |
break | |
not_matched = depth - n_match | |
dots = '.' * (not_matched + 1) | |
remaining_imports = '.'.join(import_module[n_match:]) | |
new_line = f'from {dots}{remaining_imports} import {target}' | |
print('fixing\t', line.strip(), 'in', fname) | |
print('\t', new_line) | |
else: | |
new_line = line | |
new_lines.append(new_line) | |
if len(sys.argv) == 3 and sys.argv[2] == 'write': | |
with open(fname, 'w') as f: | |
f.writelines(new_lines) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment