rotate.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from distutils.util import convert_path
  2. from distutils import log
  3. from distutils.errors import DistutilsOptionError
  4. import os
  5. import shutil
  6. from setuptools import Command
  7. class rotate(Command):
  8. """Delete older distributions"""
  9. description = "delete older distributions, keeping N newest files"
  10. user_options = [
  11. ('match=', 'm', "patterns to match (required)"),
  12. ('dist-dir=', 'd', "directory where the distributions are"),
  13. ('keep=', 'k', "number of matching distributions to keep"),
  14. ]
  15. boolean_options = []
  16. def initialize_options(self):
  17. self.match = None
  18. self.dist_dir = None
  19. self.keep = None
  20. def finalize_options(self):
  21. if self.match is None:
  22. raise DistutilsOptionError(
  23. "Must specify one or more (comma-separated) match patterns "
  24. "(e.g. '.zip' or '.egg')"
  25. )
  26. if self.keep is None:
  27. raise DistutilsOptionError("Must specify number of files to keep")
  28. try:
  29. self.keep = int(self.keep)
  30. except ValueError as e:
  31. raise DistutilsOptionError("--keep must be an integer") from e
  32. if isinstance(self.match, str):
  33. self.match = [convert_path(p.strip()) for p in self.match.split(',')]
  34. self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
  35. def run(self):
  36. self.run_command("egg_info")
  37. from glob import glob
  38. for pattern in self.match:
  39. pattern = self.distribution.get_name() + '*' + pattern
  40. files = glob(os.path.join(self.dist_dir, pattern))
  41. files = [(os.path.getmtime(f), f) for f in files]
  42. files.sort()
  43. files.reverse()
  44. log.info("%d file(s) matching %s", len(files), pattern)
  45. files = files[self.keep :]
  46. for t, f in files:
  47. log.info("Deleting %s", f)
  48. if not self.dry_run:
  49. if os.path.isdir(f):
  50. shutil.rmtree(f)
  51. else:
  52. os.unlink(f)