home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / dist-packages / apt / cache.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  15.7 KB  |  475 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import os
  5. import sys
  6. import apt_pkg
  7. from apt import Package
  8. import apt.progress as apt
  9.  
  10. class FetchCancelledException(IOError):
  11.     '''Exception that is thrown when the user cancels a fetch operation.'''
  12.     pass
  13.  
  14.  
  15. class FetchFailedException(IOError):
  16.     '''Exception that is thrown when fetching fails.'''
  17.     pass
  18.  
  19.  
  20. class LockFailedException(IOError):
  21.     '''Exception that is thrown when locking fails.'''
  22.     pass
  23.  
  24.  
  25. class Cache(object):
  26.     """Dictionary-like package cache.
  27.  
  28.     This class has all the packages that are available in it's
  29.     dictionary
  30.     """
  31.     
  32.     def __init__(self, progress = None, rootdir = None, memonly = False):
  33.         self._callbacks = { }
  34.         if memonly:
  35.             apt_pkg.Config.Set('Dir::Cache::pkgcache', '')
  36.         
  37.         if rootdir:
  38.             if os.path.exists(rootdir + '/etc/apt/apt.conf'):
  39.                 apt_pkg.ReadConfigFile(apt_pkg.Config, rootdir + '/etc/apt/apt.conf')
  40.             
  41.             if os.path.isdir(rootdir + '/etc/apt/apt.conf.d'):
  42.                 apt_pkg.ReadConfigDir(apt_pkg.Config, rootdir + '/etc/apt/apt.conf.d')
  43.             
  44.             apt_pkg.Config.Set('Dir', rootdir)
  45.             apt_pkg.Config.Set('Dir::State::status', rootdir + '/var/lib/dpkg/status')
  46.         
  47.         self.open(progress)
  48.  
  49.     
  50.     def _runCallbacks(self, name):
  51.         ''' internal helper to run a callback '''
  52.         if name in self._callbacks:
  53.             for callback in self._callbacks[name]:
  54.                 callback()
  55.             
  56.         
  57.  
  58.     
  59.     def open(self, progress):
  60.         ''' Open the package cache, after that it can be used like
  61.             a dictionary
  62.         '''
  63.         self._runCallbacks('cache_pre_open')
  64.         self._cache = apt_pkg.GetCache(progress)
  65.         self._depcache = apt_pkg.GetDepCache(self._cache)
  66.         self._records = apt_pkg.GetPkgRecords(self._cache)
  67.         self._list = apt_pkg.GetPkgSourceList()
  68.         self._list.ReadMainList()
  69.         self._dict = { }
  70.         if progress is not None:
  71.             progress.Op = 'Building data structures'
  72.         
  73.         i = last = 0
  74.         size = len(self._cache.Packages)
  75.         for pkg in self._cache.Packages:
  76.             if progress is not None and last + 100 < i:
  77.                 progress.update((i / float(size)) * 100)
  78.                 last = i
  79.             
  80.             if len(pkg.VersionList) > 0:
  81.                 self._dict[pkg.Name] = Package(self._cache, self._depcache, self._records, self._list, self, pkg)
  82.             
  83.             i += 1
  84.         
  85.         if progress is not None:
  86.             progress.done()
  87.         
  88.         self._runCallbacks('cache_post_open')
  89.  
  90.     
  91.     def __getitem__(self, key):
  92.         ''' look like a dictionary (get key) '''
  93.         return self._dict[key]
  94.  
  95.     
  96.     def __iter__(self):
  97.         for pkgname in self._dict.keys():
  98.             yield self._dict[pkgname]
  99.         
  100.         raise StopIteration
  101.  
  102.     
  103.     def has_key(self, key):
  104.         return key in self._dict
  105.  
  106.     
  107.     def __contains__(self, key):
  108.         return key in self._dict
  109.  
  110.     
  111.     def __len__(self):
  112.         return len(self._dict)
  113.  
  114.     
  115.     def keys(self):
  116.         return self._dict.keys()
  117.  
  118.     
  119.     def getChanges(self):
  120.         ''' Get the marked changes '''
  121.         changes = []
  122.         for name in self._dict.keys():
  123.             p = self._dict[name]
  124.             if p.markedUpgrade and p.markedInstall and p.markedDelete and p.markedDowngrade or p.markedReinstall:
  125.                 changes.append(p)
  126.                 continue
  127.         
  128.         return changes
  129.  
  130.     
  131.     def upgrade(self, distUpgrade = False):
  132.         ''' Upgrade the all package, DistUpgrade will also install
  133.             new dependencies
  134.         '''
  135.         self.cachePreChange()
  136.         self._depcache.Upgrade(distUpgrade)
  137.         self.cachePostChange()
  138.  
  139.     
  140.     def requiredDownload(self):
  141.         '''Get the size of the packages that are required to download.'''
  142.         pm = apt_pkg.GetPackageManager(self._depcache)
  143.         fetcher = apt_pkg.GetAcquire()
  144.         pm.GetArchives(fetcher, self._list, self._records)
  145.         return fetcher.FetchNeeded
  146.  
  147.     requiredDownload = property(requiredDownload)
  148.     
  149.     def additionalRequiredSpace(self):
  150.         '''Get the size of the additional required space on the fs.'''
  151.         return self._depcache.UsrSize
  152.  
  153.     additionalRequiredSpace = property(additionalRequiredSpace)
  154.     
  155.     def reqReinstallPkgs(self):
  156.         '''Return the packages not downloadable packages in reqreinst state.'''
  157.         reqreinst = set()
  158.         for pkg in self:
  159.             if not (pkg.candidateDownloadable):
  160.                 if pkg._pkg.InstState == apt_pkg.InstStateReInstReq or pkg._pkg.InstState == apt_pkg.InstStateHoldReInstReq:
  161.                     reqreinst.add(pkg.name)
  162.                     continue
  163.         
  164.         return reqreinst
  165.  
  166.     reqReinstallPkgs = property(reqReinstallPkgs)
  167.     
  168.     def _runFetcher(self, fetcher):
  169.         res = fetcher.Run()
  170.         failed = False
  171.         transient = False
  172.         errMsg = ''
  173.         for item in fetcher.Items:
  174.             if item.Status == item.StatDone:
  175.                 continue
  176.             
  177.             if item.StatIdle:
  178.                 transient = True
  179.                 continue
  180.             
  181.             errMsg += 'Failed to fetch %s %s\n' % (item.DescURI, item.ErrorText)
  182.             failed = True
  183.         
  184.         if res == fetcher.ResultCancelled:
  185.             raise FetchCancelledException(errMsg)
  186.         res == fetcher.ResultCancelled
  187.         if failed:
  188.             raise FetchFailedException(errMsg)
  189.         failed
  190.         return res
  191.  
  192.     
  193.     def _fetchArchives(self, fetcher, pm):
  194.         ''' fetch the needed archives '''
  195.         lockfile = apt_pkg.Config.FindDir('Dir::Cache::Archives') + 'lock'
  196.         lock = apt_pkg.GetLock(lockfile)
  197.         if lock < 0:
  198.             raise LockFailedException('Failed to lock %s' % lockfile)
  199.         lock < 0
  200.         
  201.         try:
  202.             if not pm.GetArchives(fetcher, self._list, self._records):
  203.                 return False
  204.             return self._runFetcher(fetcher)
  205.         finally:
  206.             os.close(lock)
  207.  
  208.  
  209.     
  210.     def isVirtualPackage(self, pkgname):
  211.         '''Return whether the package is a virtual package.'''
  212.         pkg = self._cache[pkgname]
  213.         if pkg.ProvidesList:
  214.             pass
  215.         return bool(not (pkg.VersionList))
  216.  
  217.     
  218.     def getProvidingPackages(self, virtual):
  219.         '''
  220.         Return a list of packages which provide the virtual package of the
  221.         specified name
  222.         '''
  223.         providers = []
  224.         
  225.         try:
  226.             vp = self._cache[virtual]
  227.             if len(vp.VersionList) != 0:
  228.                 return providers
  229.         except KeyError:
  230.             return providers
  231.  
  232.         for pkg in self:
  233.             v = self._depcache.GetCandidateVer(pkg._pkg)
  234.             if v is None:
  235.                 continue
  236.             
  237.             for p in v.ProvidesList:
  238.                 if virtual == p[0]:
  239.                     providers.append(pkg)
  240.                     continue
  241.             
  242.         
  243.         return providers
  244.  
  245.     
  246.     def update(self, fetchProgress = None):
  247.         ''' run the equivalent of apt-get update '''
  248.         lockfile = apt_pkg.Config.FindDir('Dir::State::Lists') + 'lock'
  249.         lock = apt_pkg.GetLock(lockfile)
  250.         if lock < 0:
  251.             raise LockFailedException('Failed to lock %s' % lockfile)
  252.         lock < 0
  253.         
  254.         try:
  255.             if fetchProgress is None:
  256.                 fetchProgress = apt.progress.FetchProgress()
  257.             
  258.             return self._cache.Update(fetchProgress, self._list)
  259.         finally:
  260.             os.close(lock)
  261.  
  262.  
  263.     
  264.     def installArchives(self, pm, installProgress):
  265.         installProgress.startUpdate()
  266.         res = installProgress.run(pm)
  267.         installProgress.finishUpdate()
  268.         return res
  269.  
  270.     
  271.     def commit(self, fetchProgress = None, installProgress = None):
  272.         ''' Apply the marked changes to the cache '''
  273.         if fetchProgress is None:
  274.             fetchProgress = apt.progress.FetchProgress()
  275.         
  276.         if installProgress is None:
  277.             installProgress = apt.progress.InstallProgress()
  278.         
  279.         pm = apt_pkg.GetPackageManager(self._depcache)
  280.         fetcher = apt_pkg.GetAcquire(fetchProgress)
  281.         while True:
  282.             res = self._fetchArchives(fetcher, pm)
  283.             res = self.installArchives(pm, installProgress)
  284.             if res == pm.ResultCompleted:
  285.                 break
  286.             
  287.             if res == pm.ResultFailed:
  288.                 raise SystemError('installArchives() failed')
  289.             res == pm.ResultFailed
  290.             fetcher.Shutdown()
  291.         return res == pm.ResultCompleted
  292.  
  293.     
  294.     def clear(self):
  295.         ''' Unmark all changes '''
  296.         self._depcache.Init()
  297.  
  298.     
  299.     def cachePostChange(self):
  300.         ''' called internally if the cache has changed, emit a signal then '''
  301.         self._runCallbacks('cache_post_change')
  302.  
  303.     
  304.     def cachePreChange(self):
  305.         ''' called internally if the cache is about to change, emit
  306.             a signal then '''
  307.         self._runCallbacks('cache_pre_change')
  308.  
  309.     
  310.     def connect(self, name, callback):
  311.         ''' connect to a signal, currently only used for
  312.             cache_{post,pre}_{changed,open} '''
  313.         if name not in self._callbacks:
  314.             self._callbacks[name] = []
  315.         
  316.         self._callbacks[name].append(callback)
  317.  
  318.  
  319.  
  320. class Filter(object):
  321.     ''' Filter base class '''
  322.     
  323.     def apply(self, pkg):
  324.         ''' Filter function, return True if the package matchs a
  325.             filter criteria and False otherwise
  326.         '''
  327.         return True
  328.  
  329.  
  330.  
  331. class MarkedChangesFilter(Filter):
  332.     ''' Filter that returns all marked changes '''
  333.     
  334.     def apply(self, pkg):
  335.         if pkg.markedInstall and pkg.markedDelete or pkg.markedUpgrade:
  336.             return True
  337.         return False
  338.  
  339.  
  340.  
  341. class FilteredCache(object):
  342.     ''' A package cache that is filtered.
  343.  
  344.         Can work on a existing cache or create a new one
  345.     '''
  346.     
  347.     def __init__(self, cache = None, progress = None):
  348.         if cache is None:
  349.             self.cache = Cache(progress)
  350.         else:
  351.             self.cache = cache
  352.         self.cache.connect('cache_post_change', self.filterCachePostChange)
  353.         self.cache.connect('cache_post_open', self.filterCachePostChange)
  354.         self._filtered = { }
  355.         self._filters = []
  356.  
  357.     
  358.     def __len__(self):
  359.         return len(self._filtered)
  360.  
  361.     
  362.     def __getitem__(self, key):
  363.         return self.cache._dict[key]
  364.  
  365.     
  366.     def __iter__(self):
  367.         for pkgname in self._filtered:
  368.             yield self.cache[pkgname]
  369.         
  370.  
  371.     
  372.     def keys(self):
  373.         return self._filtered.keys()
  374.  
  375.     
  376.     def has_key(self, key):
  377.         return key in self._filtered
  378.  
  379.     
  380.     def __contains__(self, key):
  381.         return key in self._filtered
  382.  
  383.     
  384.     def _reapplyFilter(self):
  385.         ''' internal helper to refilter '''
  386.         self._filtered = { }
  387.         for pkg in self.cache._dict.keys():
  388.             for f in self._filters:
  389.                 if f.apply(self.cache._dict[pkg]):
  390.                     self._filtered[pkg] = 1
  391.                     break
  392.                     continue
  393.             
  394.         
  395.  
  396.     
  397.     def setFilter(self, filter):
  398.         '''Set the current active filter.'''
  399.         self._filters = []
  400.         self._filters.append(filter)
  401.         self.cache.cachePostChange()
  402.  
  403.     
  404.     def filterCachePostChange(self):
  405.         '''Called internally if the cache changes, emit a signal then.'''
  406.         self._reapplyFilter()
  407.  
  408.     
  409.     def __getattr__(self, key):
  410.         '''we try to look exactly like a real cache.'''
  411.         return getattr(self.cache, key)
  412.  
  413.  
  414.  
  415. def cache_pre_changed():
  416.     print 'cache pre changed'
  417.  
  418.  
  419. def cache_post_changed():
  420.     print 'cache post changed'
  421.  
  422. if __name__ == '__main__':
  423.     print 'Cache self test'
  424.     apt_pkg.init()
  425.     c = Cache(apt.progress.OpTextProgress())
  426.     c.connect('cache_pre_change', cache_pre_changed)
  427.     c.connect('cache_post_change', cache_post_changed)
  428.     print 'aptitude' in c
  429.     p = c['aptitude']
  430.     print p.name
  431.     print len(c)
  432.     for pkg in c.keys():
  433.         x = c[pkg].name
  434.     
  435.     c.upgrade()
  436.     changes = c.getChanges()
  437.     print len(changes)
  438.     for p in changes:
  439.         x = p.name
  440.     
  441.     for d in [
  442.         '/tmp/pytest',
  443.         '/tmp/pytest/partial']:
  444.         if not os.path.exists(d):
  445.             os.mkdir(d)
  446.         
  447.     
  448.     apt_pkg.Config.Set('Dir::Cache::Archives', '/tmp/pytest')
  449.     pm = apt_pkg.GetPackageManager(c._depcache)
  450.     fetcher = apt_pkg.GetAcquire(apt.progress.TextFetchProgress())
  451.     c._fetchArchives(fetcher, pm)
  452.     print 'Testing filtered cache (argument is old cache)'
  453.     f = FilteredCache(c)
  454.     f.cache.connect('cache_pre_change', cache_pre_changed)
  455.     f.cache.connect('cache_post_change', cache_post_changed)
  456.     f.cache.upgrade()
  457.     f.setFilter(MarkedChangesFilter())
  458.     print len(f)
  459.     for pkg in f.keys():
  460.         x = f[pkg].name
  461.     
  462.     print len(f)
  463.     print 'Testing filtered cache (no argument)'
  464.     f = FilteredCache(progress = OpTextProgress())
  465.     f.cache.connect('cache_pre_change', cache_pre_changed)
  466.     f.cache.connect('cache_post_change', cache_post_changed)
  467.     f.cache.upgrade()
  468.     f.setFilter(MarkedChangesFilter())
  469.     print len(f)
  470.     for pkg in f.keys():
  471.         x = f[pkg].name
  472.     
  473.     print len(f)
  474.  
  475.