rotate.py 2.1 KB

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