check_invalid_imports.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import os
  2. import re
  3. import sys
  4. from pathlib import Path
  5. """
  6. Run this file with the Cura project root as the working directory
  7. Checks for invalid imports. When importing from plugins, there will be no problems when running from source,
  8. but for some build types the plugins dir is not on the path, so relative imports should be used instead. eg:
  9. from ..UltimakerCloudScope import UltimakerCloudScope <-- OK
  10. import plugins.Toolbox.src ... <-- NOT OK
  11. """
  12. class InvalidImportsChecker:
  13. # compile regex
  14. REGEX = re.compile(r"^\s*(from plugins|import plugins)")
  15. def check(self):
  16. """ Checks for invalid imports
  17. :return: True if checks passed, False when the test fails
  18. """
  19. cwd = os.getcwd()
  20. cura_result = checker.check_dir(os.path.join(cwd, "cura"))
  21. plugins_result = checker.check_dir(os.path.join(cwd, "plugins"))
  22. result = cura_result and plugins_result
  23. if not result:
  24. print("error: sources contain invalid imports. Use relative imports when referencing plugin source files")
  25. return result
  26. def check_dir(self, root_dir: str) -> bool:
  27. """ Checks a directory for invalid imports
  28. :return: True if checks passed, False when the test fails
  29. """
  30. passed = True
  31. for path_like in Path(root_dir).rglob('*.py'):
  32. if not self.check_file(str(path_like)):
  33. passed = False
  34. return passed
  35. def check_file(self, file_path):
  36. """ Checks a file for invalid imports
  37. :return: True if checks passed, False when the test fails
  38. """
  39. passed = True
  40. with open(file_path, 'r', encoding = "utf-8") as inputFile:
  41. # loop through each line in file
  42. for line_i, line in enumerate(inputFile, 1):
  43. # check if we have a regex match
  44. match = self.REGEX.search(line)
  45. if match:
  46. path = os.path.relpath(file_path)
  47. print("{path}:{line_i}:{match}".format(path=path, line_i=line_i, match=match.group(1)))
  48. passed = False
  49. return passed
  50. if __name__ == "__main__":
  51. checker = InvalidImportsChecker()
  52. sys.exit(0 if checker.check() else 1)