Phillip J. Eby | 069159b | 2006-04-18 04:05:34 +0000 | [diff] [blame] | 1 | import distutils, os |
| 2 | from setuptools import Command |
| 3 | from distutils.util import convert_path |
| 4 | from distutils import log |
| 5 | from distutils.errors import * |
| 6 | |
| 7 | class rotate(Command): |
| 8 | """Delete older distributions""" |
| 9 | |
| 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 | |
| 17 | boolean_options = [] |
| 18 | |
| 19 | def initialize_options(self): |
| 20 | self.match = None |
| 21 | self.dist_dir = None |
| 22 | self.keep = None |
| 23 | |
| 24 | def finalize_options(self): |
| 25 | if self.match is None: |
| 26 | raise DistutilsOptionError( |
| 27 | "Must specify one or more (comma-separated) match patterns " |
| 28 | "(e.g. '.zip' or '.egg')" |
| 29 | ) |
| 30 | if self.keep is None: |
Tim Peters | 584b0e0 | 2006-04-18 17:32:12 +0000 | [diff] [blame^] | 31 | raise DistutilsOptionError("Must specify number of files to keep") |
Phillip J. Eby | 069159b | 2006-04-18 04:05:34 +0000 | [diff] [blame] | 32 | try: |
| 33 | self.keep = int(self.keep) |
| 34 | except ValueError: |
| 35 | raise DistutilsOptionError("--keep must be an integer") |
| 36 | if isinstance(self.match, basestring): |
| 37 | self.match = [ |
| 38 | convert_path(p.strip()) for p in self.match.split(',') |
| 39 | ] |
| 40 | self.set_undefined_options('bdist',('dist_dir', 'dist_dir')) |
| 41 | |
| 42 | def run(self): |
| 43 | self.run_command("egg_info") |
| 44 | from glob import glob |
| 45 | for pattern in self.match: |
| 46 | pattern = self.distribution.get_name()+'*'+pattern |
| 47 | files = glob(os.path.join(self.dist_dir,pattern)) |
| 48 | files = [(os.path.getmtime(f),f) for f in files] |
| 49 | files.sort() |
| 50 | files.reverse() |
| 51 | |
| 52 | log.info("%d file(s) matching %s", len(files), pattern) |
| 53 | files = files[self.keep:] |
| 54 | for (t,f) in files: |
| 55 | log.info("Deleting %s", f) |
| 56 | if not self.dry_run: |
| 57 | os.unlink(f) |