RemovingOldPackageVersions

#  GPL v2 code.
#  Original author: Radim Kolar <hsn/at/cybermail.net>
#  Home page: http://home.tiscali.cz/~cz210552/
#
#  Modifications by Craig Box & Perry Lorier
#
#  APT-SMARTCLEAN
#
#  This programs cleans APT package cache directory. Unlike apt-get autoclean,
#  it leaves in cache directory only last version of package even if this
#  package is no longer available for download. This is less aggressive
#  cleaning than autoclean does.
#
#  ARGUMENTS -s  ... dry run
#            dir1 dir2 .. dirX ... operate on these directories
#
#  Changelog
#
#    VERSION 1 - 18 Aug 2003 First version
#    VERSION 2 - 05 Oct 2006 Update for Ubuntu MOTU use.
#                Now takes directories to run on as command line parameters.

import os
import sys

def cleanaptcache(dryrun=0,dirs=('/var/cache/apt/archives/','/var/cache/apt/archives/partial/')):
    for dir in dirs:
       packages={} # versions
       fnames={}   # file names
       for file in os.listdir(dir):
          if file[-4:] != '.deb': continue
          parsed=file.split('_')
          if len(parsed) != 3: continue
          parsed[1]=parsed[1].replace('%3a',':')
          if parsed[0] in packages:
              print 'Found',parsed[0],parsed[1],'have',packages[parsed[0]]
              argz=['dpkg','--compare-versions',parsed[1],'lt',packages[parsed[0]]]
              rc=os.spawnvp(os.P_WAIT,'dpkg',argz)
              if rc==2: continue
              if rc==0:
                 print "Deleting",file
                 if not dryrun: os.unlink(dir+os.sep+file)
                 continue
              elif rc==1:
                 print "Deleting",fnames[parsed[0]]
                 if not dryrun: os.unlink(dir+os.sep+fnames[parsed[0]])

          packages[parsed[0]]=parsed[1]
          fnames[parsed[0]]=file


if __name__=="__main__":
        #working dpkg test
        sys.stdout.write("Running on Debian-")
        sys.stdout.flush()
        rc=os.spawnlp(os.P_WAIT,'dpkg','dpkg','--print-architecture')
        if rc!=0:
                print "No working dpkg found! Are you running Debian?"
                sys.exit(rc)
        if len(sys.argv)>1 and sys.argv[1]=='-s':
                dryrun=1
                print "Dry run is enabled. Not deleting anything."
                dirs=sys.argv[2:]
        else:
                dryrun=0
                dirs=sys.argv[1:]
        if dirs==[]:
                print "Please specify a directory."
                sys.exit(rc);
                # uncomment to work on default cache dirs if no dirs specified 
                # dirs=('/var/cache/apt/archives/','/var/cache/apt/archives/partial/')
        cleanaptcache(dryrun,dirs)

RemovingOldPackageVersions (last edited 2010-02-07 00:23:12 by vpn-8061f40e)