setuptools_commands.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import glob
  2. import os
  3. import sys
  4. from typing import Any, Dict, Iterator, List
  5. from warnings import warn
  6. import setuptools # type: ignore
  7. from . import api
  8. from .settings import DEFAULT_CONFIG
  9. class ISortCommand(setuptools.Command): # type: ignore
  10. """The :class:`ISortCommand` class is used by setuptools to perform
  11. imports checks on registered modules.
  12. """
  13. description = "Run isort on modules registered in setuptools"
  14. user_options: List[Any] = []
  15. def initialize_options(self) -> None:
  16. default_settings = vars(DEFAULT_CONFIG).copy()
  17. for key, value in default_settings.items():
  18. setattr(self, key, value)
  19. def finalize_options(self) -> None:
  20. """Get options from config files."""
  21. self.arguments: Dict[str, Any] = {} # skipcq: PYL-W0201
  22. self.arguments["settings_path"] = os.getcwd()
  23. def distribution_files(self) -> Iterator[str]:
  24. """Find distribution packages."""
  25. # This is verbatim from flake8
  26. if self.distribution.packages: # pragma: no cover
  27. package_dirs = self.distribution.package_dir or {}
  28. for package in self.distribution.packages:
  29. pkg_dir = package
  30. if package in package_dirs:
  31. pkg_dir = package_dirs[package]
  32. elif "" in package_dirs: # pragma: no cover
  33. pkg_dir = package_dirs[""] + os.path.sep + pkg_dir
  34. yield pkg_dir.replace(".", os.path.sep)
  35. if self.distribution.py_modules:
  36. for filename in self.distribution.py_modules:
  37. yield "%s.py" % filename
  38. # Don't miss the setup.py file itself
  39. yield "setup.py"
  40. def run(self) -> None:
  41. arguments = self.arguments
  42. wrong_sorted_files = False
  43. for path in self.distribution_files():
  44. for python_file in glob.iglob(os.path.join(path, "*.py")):
  45. try:
  46. if not api.check_file(python_file, **arguments):
  47. wrong_sorted_files = True # pragma: no cover
  48. except OSError as error: # pragma: no cover
  49. warn(f"Unable to parse file {python_file} due to {error}")
  50. if wrong_sorted_files:
  51. sys.exit(1) # pragma: no cover