codekingpro/portable-devtools
114k
1from distutils.util import convert_path2from distutils import log3from distutils.errors import DistutilsOptionError4import os5import shutil6from typing import List7 8from setuptools import Command9 10 11class rotate(Command):12 """Delete older distributions"""13 14 description = "delete older distributions, keeping N newest files"15 user_options = [16 ('match=', 'm', "patterns to match (required)"),17 ('dist-dir=', 'd', "directory where the distributions are"),18 ('keep=', 'k', "number of matching distributions to keep"),19 ]20 21 boolean_options: List[str] = []22 23 def initialize_options(self):24 self.match = None25 self.dist_dir = None26 self.keep = None27 28 def finalize_options(self):29 if self.match is None:30 raise DistutilsOptionError(31 "Must specify one or more (comma-separated) match patterns "32 "(e.g. '.zip' or '.egg')"33 )34 if self.keep is None:35 raise DistutilsOptionError("Must specify number of files to keep")36 try:37 self.keep = int(self.keep)38 except ValueError as e:39 raise DistutilsOptionError("--keep must be an integer") from e40 if isinstance(self.match, str):41 self.match = [convert_path(p.strip()) for p in self.match.split(',')]42 self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))43 44 def run(self):45 self.run_command("egg_info")46 from glob import glob47 48 for pattern in self.match:49 pattern = self.distribution.get_name() + '*' + pattern50 files = glob(os.path.join(self.dist_dir, pattern))51 files = [(os.path.getmtime(f), f) for f in files]52 files.sort()53 files.reverse()54 55 log.info("%d file(s) matching %s", len(files), pattern)56 files = files[self.keep :]57 for t, f in files:58 log.info("Deleting %s", f)59 if not self.dry_run:60 if os.path.isdir(f):61 shutil.rmtree(f)62 else:63 os.unlink(f)64 