fixrelativeimports.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import os
  2. import re
  3. RELATIVE_IMPORT = re.compile(r'(from|import) \.\.+([a-z]+)?')
  4. def walk_directory(root, dirs, files):
  5. for file_path in files:
  6. if 'project_template' not in root and file_path.lower().endswith('.py'):
  7. clean_file(os.path.join(root, file_path))
  8. def clean_file(file_path):
  9. py_source = file(file_path).read()
  10. if 'from ..' in py_source or 'import ..' in py_source:
  11. print '====' * 8
  12. print file_path
  13. print '====' * 8
  14. package = file_path.rstrip('.py').split('/')
  15. def replace_import(matchobj):
  16. prefix, suffix = matchobj.group(0).split()
  17. return '{} {}'.format(prefix, clean_import(package, suffix))
  18. py_source = RELATIVE_IMPORT.sub(replace_import, py_source)
  19. #print py_source
  20. with open(file_path, 'w') as package:
  21. print file_path
  22. package.write(py_source)
  23. def clean_import(package, match):
  24. path = match[1:]
  25. import_path = package[:]
  26. while match and match[0] == '.':
  27. import_path = import_path[:-1]
  28. match = match[1:]
  29. if match:
  30. import_path.append(match)
  31. return '.'.join(import_path)
  32. if __name__ == '__main__':
  33. for args in os.walk('../misago'):
  34. walk_directory(*args)
  35. print "\nDone! Don't forget to run isort to fix imports ordering!"