fixabsoluteimports.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import os
  2. def walk_directory(root, dirs, files):
  3. for file_path in files:
  4. if 'project_template' not in root and file_path.lower().endswith('.py'):
  5. clean_file(os.path.join(root, file_path))
  6. def clean_file(file_path):
  7. py_source = file(file_path).read()
  8. if 'misago.' in py_source:
  9. package = file_path.rstrip('.py').split('/')[:-1]
  10. parse_file = True
  11. save_file = False
  12. cursor = 0
  13. while parse_file:
  14. try:
  15. import_start = py_source.index('from ', cursor)
  16. import_end = py_source.index(' import', import_start)
  17. cursor = import_end
  18. import_len = import_end - import_start
  19. import_path = py_source[import_start:import_end].lstrip('from').strip()
  20. if import_path.startswith('misago.'):
  21. cleaned_import = clean_import(package, import_path.split('.'))
  22. if cleaned_import:
  23. save_file = True
  24. cleaned_import_string = 'from {}'.format('.'.join(cleaned_import))
  25. py_source = ''.join((py_source[:import_start], cleaned_import_string, py_source[import_end:]))
  26. cursor -= import_end - import_start - len(cleaned_import_string)
  27. except ValueError:
  28. parse_file = False
  29. if save_file:
  30. with open(file_path, 'w') as package:
  31. print file_path
  32. package.write(py_source)
  33. def clean_import(package, import_path):
  34. if len(package) < 2 or len(import_path) < 2:
  35. return
  36. if package[:2] != import_path[:2]:
  37. return
  38. if package == import_path:
  39. # import from sibling module
  40. return ['', '']
  41. if len(package) < len(import_path) and package == import_path[:len(package)]:
  42. # import from child module
  43. return [''] + import_path[len(package):]
  44. # find upwards path
  45. overlap_len = 2
  46. while True:
  47. if package[:overlap_len + 1] != import_path[:overlap_len + 1]:
  48. break
  49. overlap_len += 1
  50. upward_path = (['', ''] * (len(package) - overlap_len))[:-1]
  51. # append eventual downwards path
  52. return upward_path + import_path[overlap_len:]
  53. if __name__ == '__main__':
  54. for args in os.walk('misago'):
  55. walk_directory(*args)
  56. print "\nDone! Don't forget to run isort to fix imports ordering!"