From b147f1846cd26ab25ad925105f52421992395918 Mon Sep 17 00:00:00 2001 From: Ben Finney Date: Fri, 16 May 2008 14:58:00 +1000 Subject: Remove trailing whitespace. --- apt/cache.py | 42 +++++++++++++++++++++--------------------- apt/cdrom.py | 2 +- apt/debfile.py | 6 +++--- apt/package.py | 30 +++++++++++++++--------------- apt/progress.py | 26 +++++++++++++------------- 5 files changed, 53 insertions(+), 53 deletions(-) (limited to 'apt') diff --git a/apt/cache.py b/apt/cache.py index a92bd5be..6773aeec 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -1,19 +1,19 @@ # cache.py - apt cache abstraction -# +# # Copyright (c) 2005 Canonical -# +# # Author: Michael Vogt -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 @@ -36,7 +36,7 @@ class LockFailedException(IOError): pass class Cache(object): - """ Dictionary-like package cache + """ Dictionary-like package cache This class has all the packages that are available in it's dictionary """ @@ -53,7 +53,7 @@ class Cache(object): if self._callbacks.has_key(name): for callback in self._callbacks[name]: callback() - + def open(self, progress): """ Open the package cache, after that it can be used like a dictionary @@ -80,12 +80,12 @@ class Cache(object): self._dict[pkg.Name] = Package(self._cache, self._depcache, self._records, self._list, self, pkg) - + i += 1 if progress != None: progress.done() self._runCallbacks("cache_post_open") - + def __getitem__(self, key): """ look like a dictionary (get key) """ return self._dict[key] @@ -106,7 +106,7 @@ class Cache(object): def getChanges(self): """ Get the marked changes """ - changes = [] + changes = [] for name in self._dict.keys(): p = self._dict[name] if p.markedUpgrade or p.markedInstall or p.markedDelete or \ @@ -127,7 +127,7 @@ class Cache(object): " return the packages not downloadable packages in reqreinst state " reqreinst = set() for pkg in self: - if (not pkg.candidateDownloadable and + if (not pkg.candidateDownloadable and (pkg._pkg.InstState == apt_pkg.InstStateReInstReq or pkg._pkg.InstState == apt_pkg.InstStateHoldReInstReq)): reqreinst.add(pkg.name) @@ -136,7 +136,7 @@ class Cache(object): def _runFetcher(self, fetcher): # do the actual fetching res = fetcher.Run() - + # now check the result (this is the code from apt-get.cc) failed = False transient = False @@ -189,13 +189,13 @@ class Cache(object): return self._cache.Update(fetchProgress, self._list) finally: os.close(lock) - + def installArchives(self, pm, installProgress): installProgress.startUpdate() res = installProgress.run(pm) installProgress.finishUpdate() return res - + def commit(self, fetchProgress=None, installProgress=None): """ Apply the marked changes to the cache """ # FIXME: @@ -276,7 +276,7 @@ class FilteredCache(object): self._filters = [] def __len__(self): return len(self._filtered) - + def __getitem__(self, key): return self.cache._dict[key] @@ -294,7 +294,7 @@ class FilteredCache(object): if f.apply(self.cache._dict[pkg]): self._filtered[pkg] = 1 break - + def setFilter(self, filter): " set the current active filter " self._filters = [] @@ -318,7 +318,7 @@ class FilteredCache(object): return self.__dict__[key] else: return getattr(self.cache, key) - + def cache_pre_changed(): print "cache pre changed" @@ -370,7 +370,7 @@ if __name__ == "__main__": for pkg in f.keys(): #print c[pkg].name x = f[pkg].name - + print len(f) print "Testing filtered cache (no argument)" @@ -383,5 +383,5 @@ if __name__ == "__main__": for pkg in f.keys(): #print c[pkg].name x = f[pkg].name - + print len(f) diff --git a/apt/cdrom.py b/apt/cdrom.py index 9d4b62cb..c0e57094 100644 --- a/apt/cdrom.py +++ b/apt/cdrom.py @@ -44,4 +44,4 @@ class Cdrom(object): if not line.startswith("#") and cdid in line: return True return False - + diff --git a/apt/debfile.py b/apt/debfile.py index ddde5bf1..73e0288d 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -27,7 +27,7 @@ class DebPackage(object): def __getitem__(self, key): return self._sections[key] - + def filelist(self): """ return the list of files in the deb """ files = [] @@ -49,10 +49,10 @@ class DebPackage(object): if __name__ == "__main__": import sys - + d = DebPackage(sys.argv[1]) print d["Section"] print d["Maintainer"] print "Files:" print "\n".join(d.filelist) - + diff --git a/apt/package.py b/apt/package.py index ac045969..043f58ca 100644 --- a/apt/package.py +++ b/apt/package.py @@ -1,19 +1,19 @@ # package.py - apt package abstraction -# +# # Copyright (c) 2005 Canonical -# +# # Author: Michael Vogt -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 @@ -83,7 +83,7 @@ class Package(object): if ver == None: #print "No version for: %s (Candidate: %s)" % (self._pkg.Name, UseCandidate) return False - + if ver.FileList == None: print "No FileList for: %s " % self._pkg.Name() return False @@ -138,7 +138,7 @@ class Package(object): base_deps.append(BaseDependency(depOr.TargetPkg.Name, depOr.CompType, depOr.TargetVer, (t == "PreDepends"))) depends_list.append(Dependency(base_deps)) return depends_list - + def candidateDependencies(self): """ return a list of candidate dependencies """ candver = self._depcache.GetCandidateVer(self._pkg) @@ -146,7 +146,7 @@ class Package(object): return [] return self._getDependencies(candver) candidateDependencies = property(candidateDependencies) - + def installedDependencies(self): """ return a list of installed dependencies """ ver = self._pkg.CurrentVer @@ -263,7 +263,7 @@ class Package(object): return "" return self._records.LongDesc rawDescription = property(rawDescription) - + def candidateRecord(self): " return the full pkgrecord as string of the candidate version " if not self._lookupRecord(True): @@ -292,7 +292,7 @@ class Package(object): def markedDelete(self): """ Package is marked for delete """ return self._depcache.MarkedDelete(self._pkg) - markedDelete = property(markedDelete) + markedDelete = property(markedDelete) def markedKeep(self): """ Package is marked for keep """ @@ -315,7 +315,7 @@ class Package(object): isInstalled = property(isInstalled) def isUpgradable(self): - """ Package is upgradable """ + """ Package is upgradable """ return self.isInstalled and self._depcache.IsUpgradable(self._pkg) isUpgradable = property(isUpgradable) @@ -364,7 +364,7 @@ class Package(object): "site '%s' isTrusted: '%s'"% (self.component, self.archive, self.origin, self.label, self.site, self.trusted) - + def candidateOrigin(self): ver = self._depcache.GetCandidateVer(self._pkg) if not ver: @@ -424,7 +424,7 @@ class Package(object): object as argument """ self._depcache.Commit(fprogress, iprogress) - + # self-test if __name__ == "__main__": diff --git a/apt/progress.py b/apt/progress.py index bb1bce35..19237a01 100644 --- a/apt/progress.py +++ b/apt/progress.py @@ -1,19 +1,19 @@ # Progress.py - progress reporting classes -# +# # Copyright (c) 2005 Canonical -# +# # Author: Michael Vogt -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 @@ -69,18 +69,18 @@ class FetchProgress(object): dlFailed : "Failed", dlHit : "Hit", dlIgnored : "Ignored"} - + def __init__(self): self.eta = 0.0 self.percent = 0.0 pass - + def start(self): pass - + def stop(self): pass - + def updateStatus(self, uri, descr, shortDescr, status): pass @@ -115,7 +115,7 @@ class TextFetchProgress(FetchProgress): sys.stdout.flush() return True def stop(self): - print "\rDone downloading " + print "\rDone downloading " def mediaChange(self, medium, drive): """ react to media change events """ res = True; @@ -144,7 +144,7 @@ class DumbInstallProgress(object): class InstallProgress(DumbInstallProgress): """ A InstallProgress that is pretty useful. It supports the attributes 'percent' 'status' and callbacks - for the dpkg errors and conffiles and status changes + for the dpkg errors and conffiles and status changes """ def __init__(self): DumbInstallProgress.__init__(self) -- cgit v1.2.3 From a953d82143f0ec979e18f17e8d9bbacbac954868 Mon Sep 17 00:00:00 2001 From: Ben Finney Date: Fri, 16 May 2008 16:11:06 +1000 Subject: Fixes to blank lines, to conform with PEP 8. --- apt/cache.py | 17 +++++++++++++++++ apt/cdrom.py | 6 +++++- apt/debfile.py | 6 ++++-- apt/package.py | 25 ++++++++++++++++++++++++- apt/progress.py | 37 ++++++++++++++++++++++++++++++++++++- aptsources/__init__.py | 1 - aptsources/distinfo.py | 27 +++++++++++++++++++++++++-- aptsources/distro.py | 13 ++++++++++++- aptsources/sourceslist.py | 19 +++++++++++++++---- doc/examples/acquire.py | 4 +--- doc/examples/action.py | 12 ------------ doc/examples/build-deps.py | 2 ++ doc/examples/cdrom.py | 6 ------ doc/examples/deb_inspect.py | 3 +++ doc/examples/desc.py | 1 - doc/examples/gui-inst.py | 19 +++++++++++++------ doc/examples/inst.py | 10 ++++++---- doc/examples/progress.py | 14 ++++++++++++++ doc/examples/recommends.py | 6 ++---- tests/cache.py | 2 ++ tests/depcache.py | 1 + tests/lock.py | 1 - tests/pkgproblemresolver.py | 1 + tests/pkgrecords.py | 2 ++ tests/pkgsrcrecords.py | 2 ++ tests/test_aptsources.py | 3 +++ utils/get_debian_mirrors.py | 2 ++ utils/get_ubuntu_mirrors.py | 2 -- utils/get_ubuntu_mirrors_from_lp.py | 3 +++ 29 files changed, 195 insertions(+), 52 deletions(-) (limited to 'apt') diff --git a/apt/cache.py b/apt/cache.py index 6773aeec..35da7970 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -25,16 +25,22 @@ import apt.progress import os import sys + class FetchCancelledException(IOError): " Exception that is thrown when the user cancels a fetch operation " pass + + class FetchFailedException(IOError): " Exception that is thrown when fetching fails " pass + + class LockFailedException(IOError): " Exception that is thrown when locking fails " pass + class Cache(object): """ Dictionary-like package cache This class has all the packages that are available in it's @@ -227,6 +233,7 @@ class Cache(object): return (res == pm.ResultCompleted) # cache changes + def cachePostChange(self): " called internally if the cache has changed, emit a signal then " self._runCallbacks("cache_post_change") @@ -243,28 +250,36 @@ class Cache(object): self._callbacks[name] = [] self._callbacks[name].append(callback) + # ----------------------------- experimental interface + + class Filter(object): """ Filter base class """ + def apply(self, pkg): """ Filter function, return True if the package matchs a filter criteria and False otherwise """ return True + class MarkedChangesFilter(Filter): """ Filter that returns all marked changes """ + def apply(self, pkg): if pkg.markedInstall or pkg.markedDelete or pkg.markedUpgrade: return True else: return False + class FilteredCache(object): """ A package cache that is filtered. Can work on a existing cache or create a new one """ + def __init__(self, cache=None, progress=None): if cache == None: self.cache = Cache(progress) @@ -274,6 +289,7 @@ class FilteredCache(object): self.cache.connect("cache_post_open", self.filterCachePostChange) self._filtered = {} self._filters = [] + def __len__(self): return len(self._filtered) @@ -323,6 +339,7 @@ class FilteredCache(object): def cache_pre_changed(): print "cache pre changed" + def cache_post_changed(): print "cache post changed" diff --git a/apt/cdrom.py b/apt/cdrom.py index c0e57094..7f9b4776 100644 --- a/apt/cdrom.py +++ b/apt/cdrom.py @@ -1,7 +1,9 @@ import apt_pkg from progress import CdromProgress + class Cdrom(object): + def __init__(self, progress=None, mountpoint=None, nomount=True): """ Support for apt-cdrom like features. Options: @@ -22,15 +24,18 @@ class Cdrom(object): apt_pkg.Config.Set("APT::CDROM::NoMount", "true") else: apt_pkg.Config.Set("APT::CDROM::NoMount", "false") + def add(self): " add cdrom to the sources.list " return self._cdrom.Add(self._progress) + def ident(self): " identify the cdrom " (res, ident) = self._cdrom.Ident(self._progress) if res: return ident return None + @property def inSourcesList(self): " check if the cdrom is already in the current sources.list " @@ -44,4 +49,3 @@ class Cdrom(object): if not line.startswith("#") and cdid in line: return True return False - diff --git a/apt/debfile.py b/apt/debfile.py index 73e0288d..365847d7 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -4,9 +4,11 @@ from apt_inst import arCheckMember from gettext import gettext as _ + class NoDebArchiveException(IOError): pass + class DebPackage(object): _supported_data_members = ("data.tar.gz", "data.tar.bz2", "data.tar.lzma") @@ -31,10 +33,12 @@ class DebPackage(object): def filelist(self): """ return the list of files in the deb """ files = [] + def extract_cb(What,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor): #print "%s '%s','%s',%u,%u,%u,%u,%u,%u,%u"\ # % (What,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor) files.append(Name) + for member in self._supported_data_members: if arCheckMember(open(self.filename), member): try: @@ -46,7 +50,6 @@ class DebPackage(object): filelist = property(filelist) - if __name__ == "__main__": import sys @@ -55,4 +58,3 @@ if __name__ == "__main__": print d["Maintainer"] print "Files:" print "\n".join(d.filelist) - diff --git a/apt/package.py b/apt/package.py index 043f58ca..b771c677 100644 --- a/apt/package.py +++ b/apt/package.py @@ -26,40 +26,53 @@ import string #from gettext import gettext as _ import gettext + + def _(s): return gettext.dgettext("python-apt", s) + class BaseDependency(object): " a single dependency " + def __init__(self, name, rel, ver, pre): self.name = name self.relation = rel self.version = ver self.preDepend = pre + class Dependency(object): + def __init__(self, alternatives): self.or_dependencies = alternatives + class Record(object): """ represents a pkgRecord, can be accessed like a dictionary and gives the original package record if accessed as a string """ + def __init__(self, s): self._str = s self._rec = apt_pkg.ParseSection(s) + def __str__(self): return self._str + def __getitem__(self, key): k = self._rec.get(key) if k is None: raise KeyError return k + def has_key(self, key): return self._rec.has_key(key) + class Package(object): """ This class represents a package in the cache """ + def __init__(self, cache, depcache, records, sourcelist, pcache, pkgiter): """ Init the Package object """ self._cache = cache # low level cache @@ -71,6 +84,7 @@ class Package(object): pass # helper + def _lookupRecord(self, UseCandidate=True): """ internal helper that moves the Records to the right position, must be called before _records is accessed """ @@ -173,6 +187,7 @@ class Package(object): if ver == None: return False return ver.Downloadable + def candidateDownloadable(self): " returns if the canidate is downloadable " return self._downloadable(useCandidate=True) @@ -279,6 +294,7 @@ class Package(object): installedRecord = property(installedRecord) # depcache states + def markedInstall(self): """ Package is marked for install """ return self._depcache.MarkedInstall(self._pkg) @@ -320,6 +336,7 @@ class Package(object): isUpgradable = property(isUpgradable) # size + def packageSize(self): """ The size of the candidate deb package """ ver = self._depcache.GetCandidateVer(self._pkg) @@ -345,8 +362,9 @@ class Package(object): return ver.InstalledSize installedSize = property(installedSize) - # canidate origin class Origin: + """ Candidate origin """ + def __init__(self, pkg, VerFileIter): self.component = VerFileIter.Component self.archive = VerFileIter.Archive @@ -359,6 +377,7 @@ class Package(object): self.trusted = True else: self.trusted = False + def __repr__(self): return "component: '%s' archive: '%s' origin: '%s' label: '%s' " \ "site '%s' isTrusted: '%s'"% (self.component, self.archive, @@ -376,11 +395,13 @@ class Package(object): candidateOrigin = property(candidateOrigin) # depcache actions + def markKeep(self): """ mark a package for keep """ self._pcache.cachePreChange() self._depcache.MarkKeep(self._pkg) self._pcache.cachePostChange() + def markDelete(self, autoFix=True, purge=False): """ mark a package for delete. Run the resolver if autoFix is set. Mark the package as purge (remove with configuration) if 'purge' @@ -397,6 +418,7 @@ class Package(object): Fix.InstallProtect() Fix.Resolve() self._pcache.cachePostChange() + def markInstall(self, autoFix=True, autoInst=True, fromUser=True): """ mark a package for install. Run the resolver if autoFix is set, automatically install required dependencies if autoInst is set @@ -411,6 +433,7 @@ class Package(object): fixer.Protect(self._pkg) fixer.Resolve(True) self._pcache.cachePostChange() + def markUpgrade(self): """ mark a package for upgrade """ if self.isUpgradable: diff --git a/apt/progress.py b/apt/progress.py index 19237a01..b50b2915 100644 --- a/apt/progress.py +++ b/apt/progress.py @@ -30,29 +30,36 @@ import apt_pkg import apt + class OpProgress(object): """ Abstract class to implement reporting on cache opening Subclass this class to implement simple Operation progress reporting """ + def __init__(self): pass + def update(self, percent): pass + def done(self): pass + class OpTextProgress(OpProgress): """ A simple text based cache open reporting class """ + def __init__(self): OpProgress.__init__(self) + def update(self, percent): sys.stdout.write("\r%s: %.2i " % (self.subOp,percent)) sys.stdout.flush() + def done(self): sys.stdout.write("\r%s: Done\n" % self.op) - class FetchProgress(object): """ Report the download/fetching progress Subclass this class to implement fetch progress reporting @@ -92,17 +99,22 @@ class FetchProgress(object): if self.currentCPS > 0: self.eta = (self.totalBytes-self.currentBytes)/float(self.currentCPS) return True + def mediaChange(self, medium, drive): pass + class TextFetchProgress(FetchProgress): """ Ready to use progress object for terminal windows """ + def __init__(self): self.items = {} + def updateStatus(self, uri, descr, shortDescr, status): if status != self.dlQueued: print "\r%s %s" % (self.dlStatusStr[status], descr) self.items[uri] = status + def pulse(self): FetchProgress.pulse(self) if self.currentCPS > 0: @@ -114,8 +126,10 @@ class TextFetchProgress(FetchProgress): print "\r%s" % (s), sys.stdout.flush() return True + def stop(self): print "\rDone downloading " + def mediaChange(self, medium, drive): """ react to media change events """ res = True; @@ -126,26 +140,34 @@ class TextFetchProgress(FetchProgress): res = false; return res + class DumbInstallProgress(object): """ Report the install progress Subclass this class to implement install progress reporting """ + def __init__(self): pass + def startUpdate(self): pass + def run(self, pm): return pm.DoInstall() + def finishUpdate(self): pass + def updateInterface(self): pass + class InstallProgress(DumbInstallProgress): """ A InstallProgress that is pretty useful. It supports the attributes 'percent' 'status' and callbacks for the dpkg errors and conffiles and status changes """ + def __init__(self): DumbInstallProgress.__init__(self) self.selectTimeout = 0.1 @@ -156,15 +178,19 @@ class InstallProgress(DumbInstallProgress): self.read = "" self.percent = 0.0 self.status = "" + def error(self, pkg, errormsg): " called when a error is detected during the install " pass + def conffile(self,current,new): " called when a conffile question from dpkg is detected " pass + def statusChange(self, pkg, percent, status): " called when the status changed " pass + def updateInterface(self): if self.statusfd != None: try: @@ -199,8 +225,10 @@ class InstallProgress(DumbInstallProgress): self.percent = float(percent) self.status = string.strip(status_str) self.read = "" + def fork(self): return os.fork() + def waitChild(self): while True: select.select([self.statusfd],[],[], self.selectTimeout) @@ -209,6 +237,7 @@ class InstallProgress(DumbInstallProgress): if pid == self.child_pid: break return os.WEXITSTATUS(res) + def run(self, pm): pid = self.fork() if pid == 0: @@ -219,20 +248,26 @@ class InstallProgress(DumbInstallProgress): res = self.waitChild() return res + class CdromProgress: """ Report the cdrom add progress Subclass this class to implement cdrom add progress reporting """ + def __init__(self): pass + def update(self, text, step): """ update is called regularly so that the gui can be redrawn """ pass + def askCdromName(self): pass + def changeCdrom(self): pass + # module test code if __name__ == "__main__": import apt_pkg diff --git a/aptsources/__init__.py b/aptsources/__init__.py index 8b137891..e69de29b 100644 --- a/aptsources/__init__.py +++ b/aptsources/__init__.py @@ -1 +0,0 @@ - diff --git a/aptsources/distinfo.py b/aptsources/distinfo.py index bc567a3a..4a601be3 100644 --- a/aptsources/distinfo.py +++ b/aptsources/distinfo.py @@ -28,14 +28,17 @@ import gettext from os import getenv import ConfigParser import string +import re #from gettext import gettext as _ import gettext + + def _(s): return gettext.dgettext("python-apt", s) -import re class Template: + def __init__(self): self.name = None self.child = False @@ -62,11 +65,14 @@ class Template: else: return False + class Component: + def __init__(self, name, desc=None, long_desc=None): self.name = name self.description = desc self.description_long = long_desc + def get_description(self): if self.description_long != None: return self.description_long @@ -74,24 +80,32 @@ class Component: return self.description else: return None + def set_description(self, desc): self.description = desc + def set_description_long(self, desc): self.description_long = desc + def get_description_long(self): return self.description_long + class Mirror: ''' Storage for mirror related information ''' + def __init__(self, proto, hostname, dir, location=None): self.hostname = hostname self.repositories = [] self.add_repository(proto, dir) self.location = location + def add_repository(self, proto, dir): self.repositories.append(Repository(proto, dir)) + def get_repositories_for_proto(self, proto): return filter(lambda r: r.proto == proto, self.repositories) + def has_repository(self, proto, dir): if dir is None: return False @@ -99,28 +113,38 @@ class Mirror: if r.proto == proto and dir in r.dir: return True return False + def get_repo_urls(self): return map(lambda r: r.get_url(self.hostname), self.repositories) + def get_location(self): return self.location + def set_location(self, location): self.location = location + class Repository: + def __init__(self, proto, dir): self.proto = proto self.dir = dir + def get_info(self): return self.proto, self.dir + def get_url(self, hostname): return "%s://%s/%s" % (self.proto, hostname, self.dir) + def split_url(url): ''' split a given URL into the protocoll, the hostname and the dir part ''' return map(lambda a,b: a, re.split(":*\/+", url, maxsplit=2), [None, None, None]) + class DistInfo: + def __init__(self, dist = None, base_dir = "/usr/share/python-apt/templates"): @@ -140,7 +164,6 @@ class DistInfo: self.dist = dist - map_mirror_sets = {} dist_fname = "%s/%s.info" % (base_dir, dist) diff --git a/aptsources/distro.py b/aptsources/distro.py index 0a977445..faccc271 100644 --- a/aptsources/distro.py +++ b/aptsources/distro.py @@ -28,13 +28,17 @@ import os import sys import gettext + + def _(s): return gettext.dgettext("python-apt", s) class NoDistroTemplateException(Exception): pass + class Distribution: + def __init__(self, id, codename, description, release): """ Container for distribution specific informations """ # LSB information @@ -199,6 +203,7 @@ class Distribution: def get_server_list(self): ''' Return a list of used and suggested servers ''' + def compare_mirrors(mir1, mir2): '''Helper function that handles comaprision of mirror urls that could contain trailing slashes''' @@ -271,6 +276,7 @@ class Distribution: comp: the component that should be enabled """ + def add_component_only_once(source, comps_per_dist): """ Check if we already added the component to the repository, since @@ -347,6 +353,7 @@ class Distribution: def change_server(self, uri): ''' Change the server of all distro specific sources to a given host ''' + def change_server_of_source(source, uri, seen): # Avoid creating duplicate entries source.uri = uri @@ -357,6 +364,7 @@ class Distribution: seen.append([source.uri, source.dist, comp]) if len(source.comps) < 1: self.sourceslist.remove(source) + seen_binary = [] seen_source = [] self.default_server = uri @@ -377,6 +385,7 @@ class Distribution: else: return False + class DebianDistribution(Distribution): ''' Class to support specific Debian features ''' @@ -408,12 +417,15 @@ class DebianDistribution(Distribution): Distribution.get_mirrors(self, mirror_template="http://ftp.%s.debian.org/debian/") + class UbuntuDistribution(Distribution): ''' Class to support specific Ubuntu features ''' + def get_mirrors(self): Distribution.get_mirrors(self, mirror_template="http://%s.archive.ubuntu.com/ubuntu/") + def get_distro(): ''' Check the currently used distribution and return the corresponding distriubtion class that supports distro specific features. ''' @@ -430,4 +442,3 @@ def get_distro(): return DebianDistribution(id, codename, description, release) else: return Distribution(id, codename, description, release) - diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index 4067920a..a8a772a0 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -36,7 +36,10 @@ import sys #from UpdateManager.Common.DistInfo import DistInfo from distinfo import DistInfo + # some global helpers + + def is_mirror(master_uri, compare_uri): """check if the given add_url is idential or a mirror of orig_uri e.g. master_uri = archive.ubuntu.com @@ -66,12 +69,15 @@ def is_mirror(master_uri, compare_uri): return True return False + def uniq(s): """ simple and efficient way to return uniq list """ return list(set(s)) + class SourceEntry: """ single sources.list entry """ + def __init__(self, line,file=None): self.invalid = False # is the source entry valid self.disabled = False # is it disabled ('#' in front) @@ -96,7 +102,6 @@ class SourceEntry: self.dist == other.dist and self.comps == other.comps) - def mysplit(self, line): """ a split() implementation that understands the sources.list format better and takes [] into account (for e.g. cdroms) """ @@ -208,13 +213,17 @@ class SourceEntry: line += "\n" return line + class NullMatcher(object): """ a Matcher that does nothing """ + def match(self, s): return True + class SourcesList: """ represents the full sources.list + sources.list.d file """ + def __init__(self, withMatcher=True, matcherPath="/usr/share/python-apt/templates/"): @@ -383,9 +392,12 @@ class SourcesList: #print self.parents return (parents, used_child_templates) -# matcher class to make a source entry look nice -# lots of predefined matchers to make it i18n/gettext friendly + class SourceEntryMatcher: + """ matcher class to make a source entry look nice + lots of predefined matchers to make it i18n/gettext friendly + """ + def __init__(self, matcherPath): self.templates = [] # Get the human readable channel and comp names from the channel .infos @@ -435,4 +447,3 @@ if __name__ == "__main__": "http://de.archive.ubuntu.com/ubuntu/") print is_mirror("http://archive.ubuntu.com/ubuntu/", "http://de.archive.ubuntu.com/ubuntu") - diff --git a/doc/examples/acquire.py b/doc/examples/acquire.py index cce3fb0d..07f8da0e 100644 --- a/doc/examples/acquire.py +++ b/doc/examples/acquire.py @@ -4,6 +4,7 @@ import os import sys import tempfile + def get_file(fetcher, uri, destFile): cwd = os.getcwd() # create a temp dir @@ -86,6 +87,3 @@ print "fetcher.Run() returned: %s" % res print "now runing pm.DoInstall()" res = pm.DoInstall(1) print "pm.DoInstall() returned: %s"% res - - - diff --git a/doc/examples/action.py b/doc/examples/action.py index adf26539..9277129e 100644 --- a/doc/examples/action.py +++ b/doc/examples/action.py @@ -21,15 +21,6 @@ cache.Update(progress) print "Exiting" sys.exit(0) - - - - - - - - - iter = cache["base-config"] print "example package iter: %s" % iter @@ -45,7 +36,6 @@ depcache.Init(progress) #sys.exit() - # get a canidate version ver= depcache.GetCandidateVer(iter) print "Candidate version: %s " % ver @@ -66,7 +56,6 @@ depcache.MarkDelete(iter) print "DelCount: %s " % depcache.DelCount print "%s.MarkedDelete(): %s" % (iter.Name, depcache.MarkedDelete(iter)) - iter = cache["3dchess"] print "\nMarking '%s' for install" % iter.Name depcache.MarkInstall(iter) @@ -100,7 +89,6 @@ for pkg in cache.Packages: if pkg.CurrentVer != None and not depcache.MarkedInstall(pkg) and depcache.IsUpgradable(pkg): print "Upgrade didn't upgrade (kept): %s" % pkg.Name - print "\nPerforming DistUpgrade" depcache.Upgrade(True) print "Keep: %s " % depcache.KeepCount diff --git a/doc/examples/build-deps.py b/doc/examples/build-deps.py index fae7b55b..2d83a54f 100755 --- a/doc/examples/build-deps.py +++ b/doc/examples/build-deps.py @@ -5,6 +5,7 @@ import apt_pkg import sys import sets # only needed for python2.3, python2.4 supports this naively + def get_source_pkg(pkg, records, depcache): """ get the source package name of a given package """ version = depcache.GetCandidateVer(pkg) @@ -18,6 +19,7 @@ def get_source_pkg(pkg, records, depcache): srcpkg = pkg.Name return srcpkg + # main apt_pkg.init() cache = apt_pkg.GetCache() diff --git a/doc/examples/cdrom.py b/doc/examples/cdrom.py index bf044d7c..e54eb763 100644 --- a/doc/examples/cdrom.py +++ b/doc/examples/cdrom.py @@ -22,11 +22,5 @@ print "ident result is: %s (%s) " % (res, ident) apt_pkg.Config.Set("APT::CDROM::Rename", "True") cdrom.Add(progress) - - print "Exiting" sys.exit(0) - - - - diff --git a/doc/examples/deb_inspect.py b/doc/examples/deb_inspect.py index b57526c6..68219d6d 100755 --- a/doc/examples/deb_inspect.py +++ b/doc/examples/deb_inspect.py @@ -6,6 +6,7 @@ import apt_inst import sys import os.path + def Callback(What,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor): """ callback for debExtract """ @@ -40,8 +41,10 @@ if __name__ == "__main__": dir = "/tmp/deb" os.mkdir(dir) apt_inst.debExtractArchive(open(file),dir) + def visit(arg, dirname, names): print "%s/" % dirname for file in names: print "\t%s" % file + os.path.walk(dir, visit, None) diff --git a/doc/examples/desc.py b/doc/examples/desc.py index 87b9473b..1d43f2f9 100644 --- a/doc/examples/desc.py +++ b/doc/examples/desc.py @@ -22,4 +22,3 @@ records.Lookup((f,index)) desc = records.LongDesc print len(desc) print desc - diff --git a/doc/examples/gui-inst.py b/doc/examples/gui-inst.py index 5e5d2c99..28887d34 100755 --- a/doc/examples/gui-inst.py +++ b/doc/examples/gui-inst.py @@ -18,7 +18,9 @@ import posix from apt.progress import OpProgress, FetchProgress, InstallProgress + class GuiFetchProgress(gtk.Window, FetchProgress): + def __init__(self): gtk.Window.__init__(self) self.vbox = gtk.VBox() @@ -31,12 +33,15 @@ class GuiFetchProgress(gtk.Window, FetchProgress): self.vbox.pack_start(self.progress) self.vbox.pack_start(self.label) self.resize(300,100) + def start(self): print "start" self.progress.set_fraction(0.0) self.show() + def stop(self): self.hide() + def pulse(self): FetchProgress.pulse(self) self.label.set_text("Speed: %s/s" % apt_pkg.SizeToStr(self.currentCPS)) @@ -45,7 +50,9 @@ class GuiFetchProgress(gtk.Window, FetchProgress): gtk.main_iteration() return True + class TermInstallProgress(InstallProgress, gtk.Window): + def __init__(self): gtk.Window.__init__(self) InstallProgress.__init__(self) @@ -63,13 +70,16 @@ class TermInstallProgress(InstallProgress, gtk.Window): self.progressbar = gtk.ProgressBar() self.progressbar.show() box.pack_start(self.progressbar) + def child_exited(self,term, pid, status): print "child_exited: %s %s %s %s" % (self,term,pid,status) self.apt_status = posix.WEXITSTATUS(status) self.finished = True + def startUpdate(self): print "start" self.show() + def waitChild(self): while not self.finished: self.updateInterface() @@ -78,18 +88,20 @@ class TermInstallProgress(InstallProgress, gtk.Window): time.sleep(0.001) sys.stdin.readline() return self.apt_status + def statusChange(self, pkg, percent, status): print "statusChange", pkg, percent self.progressbar.set_fraction(float(percent)/100.0) self.progressbar.set_text(string.strip(status)) + def fork(self): env = ["VTE_PTY_KEEP_FD=%s"%self.writefd] return self.term.forkpty(envv=env) + cache = apt.Cache() print "Available packages: %s " % cache._cache.PackageCount - # update the cache fprogress = GuiFetchProgress() iprogress = TermInstallProgress() @@ -101,12 +113,10 @@ iprogress = TermInstallProgress() #depcache.ReadPinFile() #depcache.Init(progress) - # show the interface while gtk.events_pending(): gtk.main_iteration() - pkg = cache["3dchess"] print "\n%s"%pkg.name @@ -119,6 +129,3 @@ cache.commit(fprogress, iprogress) print "Exiting" sys.exit(0) - - - diff --git a/doc/examples/inst.py b/doc/examples/inst.py index ff9d452c..d1e2ff99 100644 --- a/doc/examples/inst.py +++ b/doc/examples/inst.py @@ -8,10 +8,13 @@ import time from apt.progress import InstallProgress + class TextInstallProgress(InstallProgress): + def __init__(self): apt.progress.InstallProgress.__init__(self) self.last = 0.0 + def updateInterface(self): InstallProgress.updateInterface(self) if self.last >= self.percent: @@ -19,11 +22,14 @@ class TextInstallProgress(InstallProgress): sys.stdout.write("\r[%s] %s\n" %(self.percent, self.status)) sys.stdout.flush() self.last = self.percent + def conffile(self,current,new): print "conffile prompt: %s %s" % (current,new) + def error(self, errorstr): print "got dpkg error: '%s'" % errorstr + cache = apt.Cache(apt.progress.OpTextProgress()) fprogress = apt.progress.TextFetchProgress() @@ -42,7 +48,3 @@ res = cache.commit(fprogress, iprogress) print res sys.exit(0) - - - - diff --git a/doc/examples/progress.py b/doc/examples/progress.py index b90253cb..39e73e70 100644 --- a/doc/examples/progress.py +++ b/doc/examples/progress.py @@ -4,7 +4,9 @@ import sys import time import string + class TextProgress(apt.OpProgress): + def __init__(self): self.last=0.0 @@ -21,6 +23,7 @@ class TextProgress(apt.OpProgress): class TextFetchProgress(apt.FetchProgress): + def __init__(self): pass @@ -32,6 +35,7 @@ class TextFetchProgress(apt.FetchProgress): def updateStatus(self, uri, descr, shortDescr, status): print "UpdateStatus: '%s' '%s' '%s' '%i'" % (uri,descr,shortDescr, status) + def pulse(self): print "Pulse: CPS: %s/s; Bytes: %s/%s; Item: %s/%s" % (SizeToStr(self.currentCPS), SizeToStr(self.currentBytes), SizeToStr(self.totalBytes), self.currentItems, self.totalItems) return True @@ -43,15 +47,20 @@ class TextFetchProgress(apt.FetchProgress): class TextInstallProgress(apt.InstallProgress): + def __init__(self): apt.InstallProgress.__init__(self) pass + def startUpdate(self): print "StartUpdate" + def finishUpdate(self): print "FinishUpdate" + def statusChange(self, pkg, percent, status): print "[%s] %s: %s" % (percent, pkg, status) + def updateInterface(self): apt.InstallProgress.updateInterface(self) # usefull to e.g. redraw a GUI @@ -59,17 +68,22 @@ class TextInstallProgress(apt.InstallProgress): class TextCdromProgress(apt.CdromProgress): + def __init__(self): pass + # update is called regularly so that the gui can be redrawn + def update(self, text, step): # check if we actually have some text to display if text != "": print "Update: %s %s" % (string.strip(text), step) + def askCdromName(self): print "Please enter cd-name: ", cd_name = sys.stdin.readline() return (True, string.strip(cd_name)) + def changeCdrom(self): print "Please insert cdrom and press " answer = sys.stdin.readline() diff --git a/doc/examples/recommends.py b/doc/examples/recommends.py index c1a7eb2e..03d46068 100755 --- a/doc/examples/recommends.py +++ b/doc/examples/recommends.py @@ -5,6 +5,7 @@ apt_pkg.init() cache = apt_pkg.GetCache() + class Wanted: def __init__(self, name): @@ -12,6 +13,7 @@ class Wanted: self.recommended = [] self.suggested = [] + wanted = {} for package in cache.Packages: @@ -35,7 +37,3 @@ ks.sort() for want in ks: print want, wanted[want].recommended, wanted[want].suggested - - - - diff --git a/tests/cache.py b/tests/cache.py index 3ec87b40..34535e68 100644 --- a/tests/cache.py +++ b/tests/cache.py @@ -6,6 +6,7 @@ import apt_pkg import sys + def main(): apt_pkg.init() cache = apt_pkg.GetCache() @@ -44,6 +45,7 @@ def main(): print "\r%i/%i=%.3f%% " % (i,all,(float(i)/float(all)*100)), + if __name__ == "__main__": main() sys.exit(0) diff --git a/tests/depcache.py b/tests/depcache.py index 5c78c3a1..635fea14 100644 --- a/tests/depcache.py +++ b/tests/depcache.py @@ -6,6 +6,7 @@ import apt_pkg import sys + def main(): apt_pkg.init() cache = apt_pkg.GetCache() diff --git a/tests/lock.py b/tests/lock.py index 86d704ea..a3d962d7 100644 --- a/tests/lock.py +++ b/tests/lock.py @@ -44,4 +44,3 @@ if __name__ == "__main__": fd = apt_pkg.GetLock(lock,True) print "Lockfile fd (child): %s" % fd sys.exit(0) - diff --git a/tests/pkgproblemresolver.py b/tests/pkgproblemresolver.py index 0ed32ea6..546e2f16 100644 --- a/tests/pkgproblemresolver.py +++ b/tests/pkgproblemresolver.py @@ -6,6 +6,7 @@ import apt_pkg import sys + def main(): apt_pkg.init() cache = apt_pkg.GetCache() diff --git a/tests/pkgrecords.py b/tests/pkgrecords.py index 43723569..308505f7 100644 --- a/tests/pkgrecords.py +++ b/tests/pkgrecords.py @@ -7,6 +7,7 @@ import apt_pkg import sys + def main(): apt_pkg.init() cache = apt_pkg.GetCache() @@ -31,6 +32,7 @@ def main(): pass print "\r%i/%i=%.3f%% " % (i,cache.PackageCount, (float(i)/float(cache.PackageCount)*100)), + if __name__ == "__main__": main() sys.exit(0) diff --git a/tests/pkgsrcrecords.py b/tests/pkgsrcrecords.py index 06c4a1ef..410140c8 100644 --- a/tests/pkgsrcrecords.py +++ b/tests/pkgsrcrecords.py @@ -7,6 +7,7 @@ import apt_pkg import sys + def main(): apt_pkg.init() cache = apt_pkg.GetCache() @@ -20,6 +21,7 @@ def main(): pass print "\r%i/%i=%.3f%% " % (i,cache.PackageCount, (float(i)/float(cache.PackageCount)*100)), + if __name__ == "__main__": main() sys.exit(0) diff --git a/tests/test_aptsources.py b/tests/test_aptsources.py index 734503d2..08c8194a 100644 --- a/tests/test_aptsources.py +++ b/tests/test_aptsources.py @@ -6,7 +6,9 @@ import apt_pkg import os import copy + class TestAptSources(unittest.TestCase): + def __init__(self, methodName): unittest.TestCase.__init__(self, methodName) apt_pkg.init() @@ -123,5 +125,6 @@ class TestAptSources(unittest.TestCase): for key in found: self.assertEqual(found[key], 1) + if __name__ == "__main__": unittest.main() diff --git a/utils/get_debian_mirrors.py b/utils/get_debian_mirrors.py index 512731ed..2e3c7296 100755 --- a/utils/get_debian_mirrors.py +++ b/utils/get_debian_mirrors.py @@ -39,11 +39,13 @@ req = urllib2.Request("http://www.debian.org/mirror/mirrors_full") match = re.compile("^.*>([A-Za-z0-9-.\/_]+)<\/a>.*\n$") match_location = re.compile('^.*') + def add_sites(line, proto, sites, mirror_type): path = match.sub(r"\1", line) for site in sites: mirror_type.append("%s://%s%s\n" % (proto, site.lstrip(), path)) + try: print "Downloading mirrors list from the Debian website..." uri=urllib2.urlopen(req) diff --git a/utils/get_ubuntu_mirrors.py b/utils/get_ubuntu_mirrors.py index 605edcf5..8482615d 100755 --- a/utils/get_ubuntu_mirrors.py +++ b/utils/get_ubuntu_mirrors.py @@ -57,5 +57,3 @@ for mirror in mirrors: list.write("%s\n" % mirror) list.close() print "Done." - - diff --git a/utils/get_ubuntu_mirrors_from_lp.py b/utils/get_ubuntu_mirrors_from_lp.py index 1f41e34b..59ddd84e 100755 --- a/utils/get_ubuntu_mirrors_from_lp.py +++ b/utils/get_ubuntu_mirrors_from_lp.py @@ -64,6 +64,8 @@ content_splits = re.split(r'.+?', content)[0]) lines=[] + + def find(split): country = re.search(r"(.+?)", split) if not country: @@ -78,6 +80,7 @@ def find(split): split) map(lambda u: lines.append(u[0]), urls) + map(find, content_splits) print "Writing local mirrors list: %s" % list_path -- cgit v1.2.3 From ad7bc46acd80451de21ce58450edb0f4367a5c79 Mon Sep 17 00:00:00 2001 From: Ben Finney Date: Fri, 16 May 2008 16:50:38 +1000 Subject: Fix code indentation to 4 spaces, to conform with PEP 8. --- apt/progress.py | 8 +- aptsources/distro.py | 734 +++++++++++++++++++-------------------- aptsources/sourceslist.py | 762 ++++++++++++++++++++--------------------- doc/examples/acquire.py | 38 +- doc/examples/build-deps.py | 72 ++-- doc/examples/checkstate.py | 34 +- doc/examples/config.py | 16 +- doc/examples/configisc.py | 24 +- doc/examples/dependant-pkgs.py | 34 +- doc/examples/gui-inst.py | 48 +-- doc/examples/inst.py | 36 +- doc/examples/print_uris.py | 16 +- doc/examples/progress.py | 4 +- doc/examples/recommends.py | 38 +- doc/examples/records.py | 10 +- doc/examples/sources.py | 6 +- doc/examples/tagfile.py | 4 +- doc/examples/versiontest.py | 40 +-- tests/cache.py | 74 ++-- tests/depcache.py | 76 ++-- tests/lock.py | 6 +- tests/memleak.py | 54 +-- tests/pkgproblemresolver.py | 110 +++--- tests/pkgrecords.py | 48 +-- tests/pkgsrcrecords.py | 26 +- utils/get_ubuntu_mirrors.py | 8 +- 26 files changed, 1163 insertions(+), 1163 deletions(-) (limited to 'apt') diff --git a/apt/progress.py b/apt/progress.py index b50b2915..6f72197e 100644 --- a/apt/progress.py +++ b/apt/progress.py @@ -188,14 +188,14 @@ class InstallProgress(DumbInstallProgress): pass def statusChange(self, pkg, percent, status): - " called when the status changed " - pass + " called when the status changed " + pass def updateInterface(self): if self.statusfd != None: try: - while not self.read.endswith("\n"): - self.read += os.read(self.statusfd.fileno(),1) + while not self.read.endswith("\n"): + self.read += os.read(self.statusfd.fileno(),1) except OSError, (errno,errstr): # resource temporarly unavailable is ignored if errno != EAGAIN and errnor != EWOULDBLOCK: diff --git a/aptsources/distro.py b/aptsources/distro.py index faccc271..962c57bc 100644 --- a/aptsources/distro.py +++ b/aptsources/distro.py @@ -34,396 +34,396 @@ def _(s): return gettext.dgettext("python-apt", s) class NoDistroTemplateException(Exception): - pass + pass class Distribution: - def __init__(self, id, codename, description, release): - """ Container for distribution specific informations """ - # LSB information - self.id = id - self.codename = codename - self.description = description - self.release = release - - self.binary_type = "deb" - self.source_type = "deb-src" - - def get_sources(self, sourceslist): - """ - Find the corresponding template, main and child sources - for the distribution - """ - - self.sourceslist = sourceslist - # corresponding sources - self.source_template = None - self.child_sources = [] - self.main_sources = [] - self.disabled_sources = [] - self.cdrom_sources = [] - self.download_comps = [] - self.enabled_comps = [] - self.cdrom_comps = [] - self.used_media = [] - self.get_source_code = False - self.source_code_sources = [] - - # location of the sources - self.default_server = "" - self.main_server = "" - self.nearest_server = "" - self.used_servers = [] - - # find the distro template - for template in self.sourceslist.matcher.templates: - if self.is_codename(template.name) and\ - template.distribution == self.id: - #print "yeah! found a template for %s" % self.description - #print template.description, template.base_uri, template.components - self.source_template = template - break - if self.source_template == None: - raise (NoDistroTemplateException, - "Error: could not find a distribution template") - - # find main and child sources - media = [] - comps = [] - cdrom_comps = [] - enabled_comps = [] - source_code = [] - for source in self.sourceslist.list: - if source.invalid == False and\ - self.is_codename(source.dist) and\ - source.template and\ - self.is_codename(source.template.name): - #print "yeah! found a distro repo: %s" % source.line - # cdroms need do be handled differently - if source.uri.startswith("cdrom:") and \ - source.disabled == False: - self.cdrom_sources.append(source) - cdrom_comps.extend(source.comps) - elif source.uri.startswith("cdrom:") and \ - source.disabled == True: - self.cdrom_sources.append(source) - elif source.type == self.binary_type and \ - source.disabled == False: - self.main_sources.append(source) - comps.extend(source.comps) - media.append(source.uri) - elif source.type == self.binary_type and \ - source.disabled == True: - self.disabled_sources.append(source) - elif source.type == self.source_type and source.disabled == False: - self.source_code_sources.append(source) - elif source.type == self.source_type and source.disabled == True: - self.disabled_sources.append(source) - if source.invalid == False and\ - source.template in self.source_template.children: - if source.disabled == False and source.type == self.binary_type: - self.child_sources.append(source) - elif source.disabled == False and source.type == self.source_type: - self.source_code_sources.append(source) - else: - self.disabled_sources.append(source) - self.download_comps = set(comps) - self.cdrom_comps = set(cdrom_comps) - enabled_comps.extend(comps) - enabled_comps.extend(cdrom_comps) - self.enabled_comps = set(enabled_comps) - self.used_media = set(media) - - self.get_mirrors() - - def get_mirrors(self, mirror_template=None): - """ - Provide a set of mirrors where you can get the distribution from - """ - # the main server is stored in the template - self.main_server = self.source_template.base_uri - - # other used servers - for medium in self.used_media: - if not medium.startswith("cdrom:"): - # seems to be a network source - self.used_servers.append(medium) - - if len(self.main_sources) == 0: - self.default_server = self.main_server - else: - self.default_server = self.main_sources[0].uri - - # get a list of country codes and real names - self.countries = {} - try: - f = open("/usr/share/iso-codes/iso_3166.tab", "r") - lines = f.readlines() - for line in lines: - parts = line.split("\t") - self.countries[parts[0].lower()] = parts[1].strip() - except: - print "could not open file '%s'" % file - else: - f.close() - - # try to guess the nearest mirror from the locale - self.country = None - self.country_code = None - locale = os.getenv("LANG", default="en.UK") - a = locale.find("_") - z = locale.find(".") - if z == -1: - z = len(locale) - country_code = locale[a+1:z].lower() - - if mirror_template: - self.nearest_server = mirror_template % country_code - - if self.countries.has_key(country_code): - self.country = self.countries[country_code] - self.country_code = country_code - - def _get_mirror_name(self, server): - ''' Try to get a human readable name for the main mirror of a country - Customize for different distributions ''' - country = None - i = server.find("://") - l = server.find(".archive.ubuntu.com") - if i != -1 and l != -1: - country = server[i+len("://"):l] - if self.countries.has_key(country): - # TRANSLATORS: %s is a country - return _("Server for %s") % \ - gettext.dgettext("iso_3166", - self.countries[country].rstrip()).rstrip() - else: - return("%s" % server.rstrip("/ ")) - - def get_server_list(self): - ''' Return a list of used and suggested servers ''' - - def compare_mirrors(mir1, mir2): - '''Helper function that handles comaprision of mirror urls - that could contain trailing slashes''' - return re.match(mir1.strip("/ "), mir2.rstrip("/ ")) - - # Store all available servers: - # Name, URI, active - mirrors = [] - if len(self.used_servers) < 1 or \ - (len(self.used_servers) == 1 and \ - compare_mirrors(self.used_servers[0], self.main_server)): - mirrors.append([_("Main server"), self.main_server, True]) - mirrors.append([self._get_mirror_name(self.nearest_server), - self.nearest_server, False]) - elif len(self.used_servers) == 1 and not \ - compare_mirrors(self.used_servers[0], self.main_server): - mirrors.append([_("Main server"), self.main_server, False]) - # Only one server is used - server = self.used_servers[0] - - # Append the nearest server if it's not already used - if not compare_mirrors(server, self.nearest_server): + def __init__(self, id, codename, description, release): + """ Container for distribution specific informations """ + # LSB information + self.id = id + self.codename = codename + self.description = description + self.release = release + + self.binary_type = "deb" + self.source_type = "deb-src" + + def get_sources(self, sourceslist): + """ + Find the corresponding template, main and child sources + for the distribution + """ + + self.sourceslist = sourceslist + # corresponding sources + self.source_template = None + self.child_sources = [] + self.main_sources = [] + self.disabled_sources = [] + self.cdrom_sources = [] + self.download_comps = [] + self.enabled_comps = [] + self.cdrom_comps = [] + self.used_media = [] + self.get_source_code = False + self.source_code_sources = [] + + # location of the sources + self.default_server = "" + self.main_server = "" + self.nearest_server = "" + self.used_servers = [] + + # find the distro template + for template in self.sourceslist.matcher.templates: + if self.is_codename(template.name) and\ + template.distribution == self.id: + #print "yeah! found a template for %s" % self.description + #print template.description, template.base_uri, template.components + self.source_template = template + break + if self.source_template == None: + raise (NoDistroTemplateException, + "Error: could not find a distribution template") + + # find main and child sources + media = [] + comps = [] + cdrom_comps = [] + enabled_comps = [] + source_code = [] + for source in self.sourceslist.list: + if source.invalid == False and\ + self.is_codename(source.dist) and\ + source.template and\ + self.is_codename(source.template.name): + #print "yeah! found a distro repo: %s" % source.line + # cdroms need do be handled differently + if source.uri.startswith("cdrom:") and \ + source.disabled == False: + self.cdrom_sources.append(source) + cdrom_comps.extend(source.comps) + elif source.uri.startswith("cdrom:") and \ + source.disabled == True: + self.cdrom_sources.append(source) + elif source.type == self.binary_type and \ + source.disabled == False: + self.main_sources.append(source) + comps.extend(source.comps) + media.append(source.uri) + elif source.type == self.binary_type and \ + source.disabled == True: + self.disabled_sources.append(source) + elif source.type == self.source_type and source.disabled == False: + self.source_code_sources.append(source) + elif source.type == self.source_type and source.disabled == True: + self.disabled_sources.append(source) + if source.invalid == False and\ + source.template in self.source_template.children: + if source.disabled == False and source.type == self.binary_type: + self.child_sources.append(source) + elif source.disabled == False and source.type == self.source_type: + self.source_code_sources.append(source) + else: + self.disabled_sources.append(source) + self.download_comps = set(comps) + self.cdrom_comps = set(cdrom_comps) + enabled_comps.extend(comps) + enabled_comps.extend(cdrom_comps) + self.enabled_comps = set(enabled_comps) + self.used_media = set(media) + + self.get_mirrors() + + def get_mirrors(self, mirror_template=None): + """ + Provide a set of mirrors where you can get the distribution from + """ + # the main server is stored in the template + self.main_server = self.source_template.base_uri + + # other used servers + for medium in self.used_media: + if not medium.startswith("cdrom:"): + # seems to be a network source + self.used_servers.append(medium) + + if len(self.main_sources) == 0: + self.default_server = self.main_server + else: + self.default_server = self.main_sources[0].uri + + # get a list of country codes and real names + self.countries = {} + try: + f = open("/usr/share/iso-codes/iso_3166.tab", "r") + lines = f.readlines() + for line in lines: + parts = line.split("\t") + self.countries[parts[0].lower()] = parts[1].strip() + except: + print "could not open file '%s'" % file + else: + f.close() + + # try to guess the nearest mirror from the locale + self.country = None + self.country_code = None + locale = os.getenv("LANG", default="en.UK") + a = locale.find("_") + z = locale.find(".") + if z == -1: + z = len(locale) + country_code = locale[a+1:z].lower() + + if mirror_template: + self.nearest_server = mirror_template % country_code + + if self.countries.has_key(country_code): + self.country = self.countries[country_code] + self.country_code = country_code + + def _get_mirror_name(self, server): + ''' Try to get a human readable name for the main mirror of a country + Customize for different distributions ''' + country = None + i = server.find("://") + l = server.find(".archive.ubuntu.com") + if i != -1 and l != -1: + country = server[i+len("://"):l] + if self.countries.has_key(country): + # TRANSLATORS: %s is a country + return _("Server for %s") % \ + gettext.dgettext("iso_3166", + self.countries[country].rstrip()).rstrip() + else: + return("%s" % server.rstrip("/ ")) + + def get_server_list(self): + ''' Return a list of used and suggested servers ''' + + def compare_mirrors(mir1, mir2): + ''' Helper function that handles comaprision of mirror urls + that could contain trailing slashes''' + return re.match(mir1.strip("/ "), mir2.rstrip("/ ")) + + # Store all available servers: + # Name, URI, active + mirrors = [] + if len(self.used_servers) < 1 or \ + (len(self.used_servers) == 1 and \ + compare_mirrors(self.used_servers[0], self.main_server)): + mirrors.append([_("Main server"), self.main_server, True]) mirrors.append([self._get_mirror_name(self.nearest_server), self.nearest_server, False]) - mirrors.append([self._get_mirror_name(server), server, True]) - - elif len(self.used_servers) > 1: - # More than one server is used. Since we don't handle this case - # in the user interface we set "custom servers" to true and - # append a list of all used servers - mirrors.append([_("Main server"), self.main_server, False]) - mirrors.append([self._get_mirror_name(self.nearest_server), - self.nearest_server, False]) - mirrors.append([_("Custom servers"), None, True]) - for server in self.used_servers: - if compare_mirrors(server, self.nearest_server) or\ - compare_mirrors(server, self.main_server): - continue - elif not [self._get_mirror_name(server), server, False] in mirrors: - mirrors.append([self._get_mirror_name(server), server, False]) - - return mirrors - - def add_source(self, type=None, + elif len(self.used_servers) == 1 and not \ + compare_mirrors(self.used_servers[0], self.main_server): + mirrors.append([_("Main server"), self.main_server, False]) + # Only one server is used + server = self.used_servers[0] + + # Append the nearest server if it's not already used + if not compare_mirrors(server, self.nearest_server): + mirrors.append([self._get_mirror_name(self.nearest_server), + self.nearest_server, False]) + mirrors.append([self._get_mirror_name(server), server, True]) + + elif len(self.used_servers) > 1: + # More than one server is used. Since we don't handle this case + # in the user interface we set "custom servers" to true and + # append a list of all used servers + mirrors.append([_("Main server"), self.main_server, False]) + mirrors.append([self._get_mirror_name(self.nearest_server), + self.nearest_server, False]) + mirrors.append([_("Custom servers"), None, True]) + for server in self.used_servers: + if compare_mirrors(server, self.nearest_server) or\ + compare_mirrors(server, self.main_server): + continue + elif not [self._get_mirror_name(server), server, False] in mirrors: + mirrors.append([self._get_mirror_name(server), server, False]) + + return mirrors + + def add_source(self, type=None, uri=None, dist=None, comps=None, comment=""): - """ - Add distribution specific sources - """ - if uri == None: - # FIXME: Add support for the server selector - uri = self.default_server - if dist == None: - dist = self.codename - if comps == None: - comps = list(self.enabled_comps) - if type == None: - type = self.binary_type - new_source = self.sourceslist.add(type, uri, dist, comps, comment) - # if source code is enabled add a deb-src line after the new - # source - if self.get_source_code == True and type == self.binary_type: - self.sourceslist.add(self.source_type, uri, dist, comps, comment, - file=new_source.file, - pos=self.sourceslist.list.index(new_source)+1) - - def enable_component(self, comp): - """ - Enable a component in all main, child and source code sources - (excluding cdrom based sources) - - comp: the component that should be enabled - """ - - def add_component_only_once(source, comps_per_dist): """ - Check if we already added the component to the repository, since - a repository could be splitted into different apt lines. If not - add the component + Add distribution specific sources """ - # if we don't that distro, just reutnr (can happen for e.g. - # dapper-update only in deb-src - if not comps_per_dist.has_key(source.dist): - return - # if we have seen this component already for this distro, - # return (nothing to do - if comp in comps_per_dist[source.dist]: - return - # add it - source.comps.append(comp) - comps_per_dist[source.dist].add(comp) - - sources = [] - sources.extend(self.main_sources) - sources.extend(self.child_sources) - # store what comps are enabled already per distro (where distro is - # e.g. "dapper", "dapper-updates") - comps_per_dist = {} - comps_per_sdist = {} - for s in sources: - if s.type == self.binary_type: - if not comps_per_dist.has_key(s.dist): - comps_per_dist[s.dist] = set() - map(comps_per_dist[s.dist].add, s.comps) - for s in self.source_code_sources: - if s.type == self.source_type: - if not comps_per_sdist.has_key(s.dist): - comps_per_sdist[s.dist] = set() - map(comps_per_sdist[s.dist].add, s.comps) - - # check if there is a main source at all - if len(self.main_sources) < 1: - # create a new main source - self.add_source(comps=["%s"%comp]) - else: - # add the comp to all main, child and source code sources - for source in sources: - add_component_only_once(source, comps_per_dist) + if uri == None: + # FIXME: Add support for the server selector + uri = self.default_server + if dist == None: + dist = self.codename + if comps == None: + comps = list(self.enabled_comps) + if type == None: + type = self.binary_type + new_source = self.sourceslist.add(type, uri, dist, comps, comment) + # if source code is enabled add a deb-src line after the new + # source + if self.get_source_code == True and type == self.binary_type: + self.sourceslist.add(self.source_type, uri, dist, comps, comment, + file=new_source.file, + pos=self.sourceslist.list.index(new_source)+1) + + def enable_component(self, comp): + """ + Enable a component in all main, child and source code sources + (excluding cdrom based sources) - # check if there is a main source code source at all - if self.get_source_code == True: - if len(self.source_code_sources) < 1: - # create a new main source - self.add_source(type=self.source_type, comps=["%s"%comp]) - else: - # add the comp to all main, child and source code sources - for source in self.source_code_sources: - add_component_only_once(source, comps_per_sdist) - - def disable_component(self, comp): - """ - Disable a component in all main, child and source code sources - (excluding cdrom based sources) - """ - sources = [] - sources.extend(self.main_sources) - sources.extend(self.child_sources) - sources.extend(self.source_code_sources) - if comp in self.cdrom_comps: + comp: the component that should be enabled + """ + + def add_component_only_once(source, comps_per_dist): + """ + Check if we already added the component to the repository, since + a repository could be splitted into different apt lines. If not + add the component + """ + # if we don't that distro, just reutnr (can happen for e.g. + # dapper-update only in deb-src + if not comps_per_dist.has_key(source.dist): + return + # if we have seen this component already for this distro, + # return (nothing to do + if comp in comps_per_dist[source.dist]: + return + # add it + source.comps.append(comp) + comps_per_dist[source.dist].add(comp) + + sources = [] + sources.extend(self.main_sources) + sources.extend(self.child_sources) + # store what comps are enabled already per distro (where distro is + # e.g. "dapper", "dapper-updates") + comps_per_dist = {} + comps_per_sdist = {} + for s in sources: + if s.type == self.binary_type: + if not comps_per_dist.has_key(s.dist): + comps_per_dist[s.dist] = set() + map(comps_per_dist[s.dist].add, s.comps) + for s in self.source_code_sources: + if s.type == self.source_type: + if not comps_per_sdist.has_key(s.dist): + comps_per_sdist[s.dist] = set() + map(comps_per_sdist[s.dist].add, s.comps) + + # check if there is a main source at all + if len(self.main_sources) < 1: + # create a new main source + self.add_source(comps=["%s"%comp]) + else: + # add the comp to all main, child and source code sources + for source in sources: + add_component_only_once(source, comps_per_dist) + + # check if there is a main source code source at all + if self.get_source_code == True: + if len(self.source_code_sources) < 1: + # create a new main source + self.add_source(type=self.source_type, comps=["%s"%comp]) + else: + # add the comp to all main, child and source code sources + for source in self.source_code_sources: + add_component_only_once(source, comps_per_sdist) + + def disable_component(self, comp): + """ + Disable a component in all main, child and source code sources + (excluding cdrom based sources) + """ sources = [] sources.extend(self.main_sources) - for source in sources: - if comp in source.comps: - source.comps.remove(comp) + sources.extend(self.child_sources) + sources.extend(self.source_code_sources) + if comp in self.cdrom_comps: + sources = [] + sources.extend(self.main_sources) + for source in sources: + if comp in source.comps: + source.comps.remove(comp) + if len(source.comps) < 1: + self.sourceslist.remove(source) + + def change_server(self, uri): + ''' Change the server of all distro specific sources to + a given host ''' + + def change_server_of_source(source, uri, seen): + # Avoid creating duplicate entries + source.uri = uri + for comp in source.comps: + if [source.uri, source.dist, comp] in seen: + source.comps.remove(comp) + else: + seen.append([source.uri, source.dist, comp]) if len(source.comps) < 1: - self.sourceslist.remove(source) - - def change_server(self, uri): - ''' Change the server of all distro specific sources to - a given host ''' + self.sourceslist.remove(source) - def change_server_of_source(source, uri, seen): - # Avoid creating duplicate entries - source.uri = uri - for comp in source.comps: - if [source.uri, source.dist, comp] in seen: - source.comps.remove(comp) - else: - seen.append([source.uri, source.dist, comp]) - if len(source.comps) < 1: - self.sourceslist.remove(source) - - seen_binary = [] - seen_source = [] - self.default_server = uri - for source in self.main_sources: - change_server_of_source(source, uri, seen_binary) - for source in self.child_sources: - # Do not change the forces server of a child source - if source.template.base_uri == None or \ - source.template.base_uri != source.uri: + seen_binary = [] + seen_source = [] + self.default_server = uri + for source in self.main_sources: change_server_of_source(source, uri, seen_binary) - for source in self.source_code_sources: - change_server_of_source(source, uri, seen_source) - - def is_codename(self, name): - ''' Compare a given name with the release codename. ''' - if name == self.codename: - return True - else: - return False + for source in self.child_sources: + # Do not change the forces server of a child source + if source.template.base_uri == None or \ + source.template.base_uri != source.uri: + change_server_of_source(source, uri, seen_binary) + for source in self.source_code_sources: + change_server_of_source(source, uri, seen_source) + + def is_codename(self, name): + ''' Compare a given name with the release codename. ''' + if name == self.codename: + return True + else: + return False class DebianDistribution(Distribution): - ''' Class to support specific Debian features ''' + ''' Class to support specific Debian features ''' - def is_codename(self, name): - ''' Compare a given name with the release codename and check if - if it can be used as a synonym for a development releases ''' - if name == self.codename or self.release in ("testing", "unstable"): - return True - else: - return False - - def _get_mirror_name(self, server): - ''' Try to get a human readable name for the main mirror of a country - Debian specific ''' - country = None - i = server.find("://ftp.") - l = server.find(".debian.org") - if i != -1 and l != -1: - country = server[i+len("://ftp."):l] - if self.countries.has_key(country): - # TRANSLATORS: %s is a country - return _("Server for %s") % \ - gettext.dgettext("iso_3166", - self.countries[country].rstrip()).rstrip() - else: - return("%s" % server.rstrip("/ ")) - - def get_mirrors(self): - Distribution.get_mirrors(self, - mirror_template="http://ftp.%s.debian.org/debian/") + def is_codename(self, name): + ''' Compare a given name with the release codename and check if + if it can be used as a synonym for a development releases ''' + if name == self.codename or self.release in ("testing", "unstable"): + return True + else: + return False + + def _get_mirror_name(self, server): + ''' Try to get a human readable name for the main mirror of a country + Debian specific ''' + country = None + i = server.find("://ftp.") + l = server.find(".debian.org") + if i != -1 and l != -1: + country = server[i+len("://ftp."):l] + if self.countries.has_key(country): + # TRANSLATORS: %s is a country + return _("Server for %s") % \ + gettext.dgettext("iso_3166", + self.countries[country].rstrip()).rstrip() + else: + return("%s" % server.rstrip("/ ")) + + def get_mirrors(self): + Distribution.get_mirrors(self, + mirror_template="http://ftp.%s.debian.org/debian/") class UbuntuDistribution(Distribution): - ''' Class to support specific Ubuntu features ''' + ''' Class to support specific Ubuntu features ''' - def get_mirrors(self): - Distribution.get_mirrors(self, - mirror_template="http://%s.archive.ubuntu.com/ubuntu/") + def get_mirrors(self): + Distribution.get_mirrors(self, + mirror_template="http://%s.archive.ubuntu.com/ubuntu/") def get_distro(): diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index a8a772a0..57be2a68 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -41,409 +41,409 @@ from distinfo import DistInfo def is_mirror(master_uri, compare_uri): - """check if the given add_url is idential or a mirror of orig_uri - e.g. master_uri = archive.ubuntu.com - compare_uri = de.archive.ubuntu.com - -> True - """ - # remove traling spaces and "/" - compare_uri = compare_uri.rstrip("/ ") - master_uri = master_uri.rstrip("/ ") - # uri is identical - if compare_uri == master_uri: - #print "Identical" - return True - # add uri is a master site and orig_uri has the from "XX.mastersite" - # (e.g. de.archive.ubuntu.com) - try: - compare_srv = compare_uri.split("//")[1] - master_srv = master_uri.split("//")[1] - #print "%s == %s " % (add_srv, orig_srv) - except IndexError: # ok, somethings wrong here - #print "IndexError" + """ check if the given add_url is idential or a mirror of orig_uri + e.g. master_uri = archive.ubuntu.com + compare_uri = de.archive.ubuntu.com + -> True + """ + # remove traling spaces and "/" + compare_uri = compare_uri.rstrip("/ ") + master_uri = master_uri.rstrip("/ ") + # uri is identical + if compare_uri == master_uri: + #print "Identical" + return True + # add uri is a master site and orig_uri has the from "XX.mastersite" + # (e.g. de.archive.ubuntu.com) + try: + compare_srv = compare_uri.split("//")[1] + master_srv = master_uri.split("//")[1] + #print "%s == %s " % (add_srv, orig_srv) + except IndexError: # ok, somethings wrong here + #print "IndexError" + return False + # remove the leading "." (if any) and see if that helps + if "." in compare_srv and \ + compare_srv[compare_srv.index(".")+1:] == master_srv: + #print "Mirror" + return True return False - # remove the leading "." (if any) and see if that helps - if "." in compare_srv and \ - compare_srv[compare_srv.index(".")+1:] == master_srv: - #print "Mirror" - return True - return False def uniq(s): - """ simple and efficient way to return uniq list """ - return list(set(s)) + """ simple and efficient way to return uniq list """ + return list(set(s)) class SourceEntry: - """ single sources.list entry """ - - def __init__(self, line,file=None): - self.invalid = False # is the source entry valid - self.disabled = False # is it disabled ('#' in front) - self.type = "" # what type (deb, deb-src) - self.uri = "" # base-uri - self.dist = "" # distribution (dapper, edgy, etc) - self.comps = [] # list of available componetns (may empty) - self.comment = "" # (optional) comment - self.line = line # the original sources.list line - if file == None: - file = apt_pkg.Config.FindDir("Dir::Etc")+apt_pkg.Config.Find("Dir::Etc::sourcelist") - self.file = file # the file that the entry is located in - self.parse(line) - self.template = None # type DistInfo.Suite - self.children = [] - - def __eq__(self, other): - """ equal operator for two sources.list entries """ - return (self.disabled == other.disabled and - self.type == other.type and - self.uri == other.uri and - self.dist == other.dist and - self.comps == other.comps) - - def mysplit(self, line): - """ a split() implementation that understands the sources.list - format better and takes [] into account (for e.g. cdroms) """ - line = string.strip(line) - pieces = [] - tmp = "" - # we are inside a [..] block - p_found = False - space_found = False - for i in range(len(line)): - if line[i] == "[": - p_found=True - tmp += line[i] - elif line[i] == "]": - p_found=False - tmp += line[i] - elif space_found and not line[i].isspace(): # we skip one or more space + """ single sources.list entry """ + + def __init__(self, line,file=None): + self.invalid = False # is the source entry valid + self.disabled = False # is it disabled ('#' in front) + self.type = "" # what type (deb, deb-src) + self.uri = "" # base-uri + self.dist = "" # distribution (dapper, edgy, etc) + self.comps = [] # list of available componetns (may empty) + self.comment = "" # (optional) comment + self.line = line # the original sources.list line + if file == None: + file = apt_pkg.Config.FindDir("Dir::Etc")+apt_pkg.Config.Find("Dir::Etc::sourcelist") + self.file = file # the file that the entry is located in + self.parse(line) + self.template = None # type DistInfo.Suite + self.children = [] + + def __eq__(self, other): + """ equal operator for two sources.list entries """ + return (self.disabled == other.disabled and + self.type == other.type and + self.uri == other.uri and + self.dist == other.dist and + self.comps == other.comps) + + def mysplit(self, line): + """ a split() implementation that understands the sources.list + format better and takes [] into account (for e.g. cdroms) """ + line = string.strip(line) + pieces = [] + tmp = "" + # we are inside a [..] block + p_found = False space_found = False - pieces.append(tmp) - tmp = line[i] - elif line[i].isspace() and not p_found: # found a whitespace - space_found = True - else: - tmp += line[i] - # append last piece - if len(tmp) > 0: - pieces.append(tmp) - return pieces - - def parse(self,line): - """ parse a given sources.list (textual) line and break it up - into the field we have """ - line = string.strip(self.line) - #print line - # check if the source is enabled/disabled - if line == "" or line == "#": # empty line - self.invalid = True - return - if line[0] == "#": - self.disabled = True - pieces = string.split(line[1:]) - # if it looks not like a disabled deb line return - if not pieces[0] in ("rpm", "rpm-src", "deb", "deb-src"): - self.invalid = True - return - else: - line = line[1:] - # check for another "#" in the line (this is treated as a comment) - i = line.find("#") - if i > 0: - self.comment = line[i+1:] - line = line[:i] - # source is ok, split it and see what we have - pieces = self.mysplit(line) - # Sanity check - if len(pieces) < 3: - self.invalid = True - return - # Type, deb or deb-src - self.type = string.strip(pieces[0]) - # Sanity check - if self.type not in ("deb", "deb-src", "rpm", "rpm-src"): - self.invalid = True - return - # URI - self.uri = string.strip(pieces[1]) - if len(self.uri) < 1: - self.invalid = True - # distro and components (optional) - # Directory or distro - self.dist = string.strip(pieces[2]) - if len(pieces) > 3: - # List of components - self.comps = pieces[3:] - else: - self.comps = [] - - def set_enabled(self, new_value): - """ set a line to enabled or disabled """ - self.disabled = not new_value - # enable, remove all "#" from the start of the line - if new_value == True: - i=0 - self.line = string.lstrip(self.line) - while self.line[i] == "#": - i += 1 - self.line = self.line[i:] - else: - # disabled, add a "#" - if string.strip(self.line)[0] != "#": - self.line = "#" + self.line - - def __str__(self): - """ debug helper """ - return self.str().strip() - - def str(self): - """ return the current line as string """ - if self.invalid: - return self.line - line = "" - if self.disabled: - line = "# " - line += "%s %s %s" % (self.type, self.uri, self.dist) - if len(self.comps) > 0: - line += " " + " ".join(self.comps) - if self.comment != "": - line += " #"+self.comment - line += "\n" - return line + for i in range(len(line)): + if line[i] == "[": + p_found=True + tmp += line[i] + elif line[i] == "]": + p_found=False + tmp += line[i] + elif space_found and not line[i].isspace(): # we skip one or more space + space_found = False + pieces.append(tmp) + tmp = line[i] + elif line[i].isspace() and not p_found: # found a whitespace + space_found = True + else: + tmp += line[i] + # append last piece + if len(tmp) > 0: + pieces.append(tmp) + return pieces + + def parse(self,line): + """ parse a given sources.list (textual) line and break it up + into the field we have """ + line = string.strip(self.line) + #print line + # check if the source is enabled/disabled + if line == "" or line == "#": # empty line + self.invalid = True + return + if line[0] == "#": + self.disabled = True + pieces = string.split(line[1:]) + # if it looks not like a disabled deb line return + if not pieces[0] in ("rpm", "rpm-src", "deb", "deb-src"): + self.invalid = True + return + else: + line = line[1:] + # check for another "#" in the line (this is treated as a comment) + i = line.find("#") + if i > 0: + self.comment = line[i+1:] + line = line[:i] + # source is ok, split it and see what we have + pieces = self.mysplit(line) + # Sanity check + if len(pieces) < 3: + self.invalid = True + return + # Type, deb or deb-src + self.type = string.strip(pieces[0]) + # Sanity check + if self.type not in ("deb", "deb-src", "rpm", "rpm-src"): + self.invalid = True + return + # URI + self.uri = string.strip(pieces[1]) + if len(self.uri) < 1: + self.invalid = True + # distro and components (optional) + # Directory or distro + self.dist = string.strip(pieces[2]) + if len(pieces) > 3: + # List of components + self.comps = pieces[3:] + else: + self.comps = [] + + def set_enabled(self, new_value): + """ set a line to enabled or disabled """ + self.disabled = not new_value + # enable, remove all "#" from the start of the line + if new_value == True: + i=0 + self.line = string.lstrip(self.line) + while self.line[i] == "#": + i += 1 + self.line = self.line[i:] + else: + # disabled, add a "#" + if string.strip(self.line)[0] != "#": + self.line = "#" + self.line + + def __str__(self): + """ debug helper """ + return self.str().strip() + + def str(self): + """ return the current line as string """ + if self.invalid: + return self.line + line = "" + if self.disabled: + line = "# " + line += "%s %s %s" % (self.type, self.uri, self.dist) + if len(self.comps) > 0: + line += " " + " ".join(self.comps) + if self.comment != "": + line += " #"+self.comment + line += "\n" + return line class NullMatcher(object): - """ a Matcher that does nothing """ + """ a Matcher that does nothing """ - def match(self, s): - return True + def match(self, s): + return True class SourcesList: - """ represents the full sources.list + sources.list.d file """ - - def __init__(self, - withMatcher=True, - matcherPath="/usr/share/python-apt/templates/"): - self.list = [] # the actual SourceEntries Type - if withMatcher: - self.matcher = SourceEntryMatcher(matcherPath) - else: - self.matcher = NullMatcher() - self.refresh() - - def refresh(self): - """ update the list of known entries """ - self.list = [] - # read sources.list - dir = apt_pkg.Config.FindDir("Dir::Etc") - file = apt_pkg.Config.Find("Dir::Etc::sourcelist") - self.load(dir+file) - # read sources.list.d - partsdir = apt_pkg.Config.FindDir("Dir::Etc::sourceparts") - for file in glob.glob("%s/*.list" % partsdir): - self.load(file) - # check if the source item fits a predefined template - for source in self.list: - if source.invalid == False: - self.matcher.match(source) - - def __iter__(self): - """ simple iterator to go over self.list, returns SourceEntry - types """ - for entry in self.list: - yield entry - raise StopIteration - - def add(self, type, uri, dist, orig_comps, comment="", pos=-1, file=None): - """ - Add a new source to the sources.list. - The method will search for existing matching repos and will try to - reuse them as far as possible - """ - # create a working copy of the component list so that - # we can modify it later - comps = orig_comps[:] - # check if we have this source already in the sources.list - for source in self.list: - if source.disabled == False and source.invalid == False and \ - source.type == type and uri == source.uri and \ - source.dist == dist: - for new_comp in comps: - if new_comp in source.comps: - # we have this component already, delete it from the new_comps - # list - del comps[comps.index(new_comp)] - if len(comps) == 0: - return source - for source in self.list: - # if there is a repo with the same (type, uri, dist) just add the - # components - if source.disabled == False and source.invalid == False and \ - source.type == type and uri == source.uri and \ - source.dist == dist: - comps = uniq(source.comps + comps) - source.comps = comps - return source - # if there is a corresponding repo which is disabled, enable it - elif source.disabled == True and source.invalid == False and \ - source.type == type and uri == source.uri and \ - source.dist == dist and \ - len(set(source.comps) & set(comps)) == len(comps): - source.disabled = False - return source - # there isn't any matching source, so create a new line and parse it - line = "%s %s %s" % (type,uri,dist) - for c in comps: - line = line + " " + c; - if comment != "": - line = "%s #%s\n" %(line,comment) - line = line + "\n" - new_entry = SourceEntry(line) - if file != None: - new_entry.file = file - self.matcher.match(new_entry) - self.list.insert(pos, new_entry) - return new_entry - - def remove(self, source_entry): - """ remove the specified entry from the sources.list """ - self.list.remove(source_entry) - - def restoreBackup(self, backup_ext): - " restore sources.list files based on the backup extension " - dir = apt_pkg.Config.FindDir("Dir::Etc") - file = apt_pkg.Config.Find("Dir::Etc::sourcelist") - if os.path.exists(dir+file+backup_ext) and \ - os.path.exists(dir+file): - shutil.copy(dir+file+backup_ext,dir+file) - # now sources.list.d - partsdir = apt_pkg.Config.FindDir("Dir::Etc::sourceparts") - for file in glob.glob("%s/*.list" % partsdir): - if os.path.exists(file+backup_ext): - shutil.copy(file+backup_ext,file) - - def backup(self, backup_ext=None): - """ make a backup of the current source files, if no backup extension - is given, the current date/time is used (and returned) """ - already_backuped = set() - if backup_ext == None: - backup_ext = time.strftime("%y%m%d.%H%M") - for source in self.list: - if not source.file in already_backuped and os.path.exists(source.file): - shutil.copy(source.file,"%s%s" % (source.file,backup_ext)) - return backup_ext - - def load(self,file): - """ (re)load the current sources """ - try: - f = open(file, "r") - lines = f.readlines() - for line in lines: - source = SourceEntry(line,file) - self.list.append(source) - except: - print "could not open file '%s'" % file - else: - f.close() - - def save(self): - """ save the current sources """ - files = {} - # write an empty default config file if there aren't any sources - if len(self.list) == 0: - path = "%s%s" % (apt_pkg.Config.FindDir("Dir::Etc"), - apt_pkg.Config.Find("Dir::Etc::sourcelist")) - header = ("## See sources.list(5) for more information, especialy\n" - "# Remember that you can only use http, ftp or file URIs\n" - "# CDROMs are managed through the apt-cdrom tool.\n") - open(path,"w").write(header) - return - for source in self.list: - if not files.has_key(source.file): - files[source.file]=open(source.file,"w") - files[source.file].write(source.str()) - for f in files: - files[f].close() - - def check_for_relations(self, sources_list): - """get all parent and child channels in the sources list""" - parents = [] - used_child_templates = {} - for source in sources_list: - # try to avoid checking uninterressting sources - if source.template == None: - continue - # set up a dict with all used child templates and corresponding - # source entries - if source.template.child == True: - key = source.template - if not used_child_templates.has_key(key): - used_child_templates[key] = [] - temp = used_child_templates[key] - temp.append(source) - else: - # store each source with children aka. a parent :) - if len(source.template.children) > 0: - parents.append(source) - #print self.used_child_templates - #print self.parents - return (parents, used_child_templates) + """ represents the full sources.list + sources.list.d file """ + + def __init__(self, + withMatcher=True, + matcherPath="/usr/share/python-apt/templates/"): + self.list = [] # the actual SourceEntries Type + if withMatcher: + self.matcher = SourceEntryMatcher(matcherPath) + else: + self.matcher = NullMatcher() + self.refresh() + + def refresh(self): + """ update the list of known entries """ + self.list = [] + # read sources.list + dir = apt_pkg.Config.FindDir("Dir::Etc") + file = apt_pkg.Config.Find("Dir::Etc::sourcelist") + self.load(dir+file) + # read sources.list.d + partsdir = apt_pkg.Config.FindDir("Dir::Etc::sourceparts") + for file in glob.glob("%s/*.list" % partsdir): + self.load(file) + # check if the source item fits a predefined template + for source in self.list: + if source.invalid == False: + self.matcher.match(source) + + def __iter__(self): + """ simple iterator to go over self.list, returns SourceEntry + types """ + for entry in self.list: + yield entry + raise StopIteration + + def add(self, type, uri, dist, orig_comps, comment="", pos=-1, file=None): + """ + Add a new source to the sources.list. + The method will search for existing matching repos and will try to + reuse them as far as possible + """ + # create a working copy of the component list so that + # we can modify it later + comps = orig_comps[:] + # check if we have this source already in the sources.list + for source in self.list: + if source.disabled == False and source.invalid == False and \ + source.type == type and uri == source.uri and \ + source.dist == dist: + for new_comp in comps: + if new_comp in source.comps: + # we have this component already, delete it from the new_comps + # list + del comps[comps.index(new_comp)] + if len(comps) == 0: + return source + for source in self.list: + # if there is a repo with the same (type, uri, dist) just add the + # components + if source.disabled == False and source.invalid == False and \ + source.type == type and uri == source.uri and \ + source.dist == dist: + comps = uniq(source.comps + comps) + source.comps = comps + return source + # if there is a corresponding repo which is disabled, enable it + elif source.disabled == True and source.invalid == False and \ + source.type == type and uri == source.uri and \ + source.dist == dist and \ + len(set(source.comps) & set(comps)) == len(comps): + source.disabled = False + return source + # there isn't any matching source, so create a new line and parse it + line = "%s %s %s" % (type,uri,dist) + for c in comps: + line = line + " " + c; + if comment != "": + line = "%s #%s\n" %(line,comment) + line = line + "\n" + new_entry = SourceEntry(line) + if file != None: + new_entry.file = file + self.matcher.match(new_entry) + self.list.insert(pos, new_entry) + return new_entry + + def remove(self, source_entry): + """ remove the specified entry from the sources.list """ + self.list.remove(source_entry) + + def restoreBackup(self, backup_ext): + " restore sources.list files based on the backup extension " + dir = apt_pkg.Config.FindDir("Dir::Etc") + file = apt_pkg.Config.Find("Dir::Etc::sourcelist") + if os.path.exists(dir+file+backup_ext) and \ + os.path.exists(dir+file): + shutil.copy(dir+file+backup_ext,dir+file) + # now sources.list.d + partsdir = apt_pkg.Config.FindDir("Dir::Etc::sourceparts") + for file in glob.glob("%s/*.list" % partsdir): + if os.path.exists(file+backup_ext): + shutil.copy(file+backup_ext,file) + + def backup(self, backup_ext=None): + """ make a backup of the current source files, if no backup extension + is given, the current date/time is used (and returned) """ + already_backuped = set() + if backup_ext == None: + backup_ext = time.strftime("%y%m%d.%H%M") + for source in self.list: + if not source.file in already_backuped and os.path.exists(source.file): + shutil.copy(source.file,"%s%s" % (source.file,backup_ext)) + return backup_ext + + def load(self,file): + """ (re)load the current sources """ + try: + f = open(file, "r") + lines = f.readlines() + for line in lines: + source = SourceEntry(line,file) + self.list.append(source) + except: + print "could not open file '%s'" % file + else: + f.close() + + def save(self): + """ save the current sources """ + files = {} + # write an empty default config file if there aren't any sources + if len(self.list) == 0: + path = "%s%s" % (apt_pkg.Config.FindDir("Dir::Etc"), + apt_pkg.Config.Find("Dir::Etc::sourcelist")) + header = ("## See sources.list(5) for more information, especialy\n" + "# Remember that you can only use http, ftp or file URIs\n" + "# CDROMs are managed through the apt-cdrom tool.\n") + open(path,"w").write(header) + return + for source in self.list: + if not files.has_key(source.file): + files[source.file]=open(source.file,"w") + files[source.file].write(source.str()) + for f in files: + files[f].close() + + def check_for_relations(self, sources_list): + """get all parent and child channels in the sources list""" + parents = [] + used_child_templates = {} + for source in sources_list: + # try to avoid checking uninterressting sources + if source.template == None: + continue + # set up a dict with all used child templates and corresponding + # source entries + if source.template.child == True: + key = source.template + if not used_child_templates.has_key(key): + used_child_templates[key] = [] + temp = used_child_templates[key] + temp.append(source) + else: + # store each source with children aka. a parent :) + if len(source.template.children) > 0: + parents.append(source) + #print self.used_child_templates + #print self.parents + return (parents, used_child_templates) class SourceEntryMatcher: - """ matcher class to make a source entry look nice - lots of predefined matchers to make it i18n/gettext friendly - """ - - def __init__(self, matcherPath): - self.templates = [] - # Get the human readable channel and comp names from the channel .infos - spec_files = glob.glob("%s/*.info" % matcherPath) - for f in spec_files: - f = os.path.basename(f) - i = f.find(".info") - f = f[0:i] - dist = DistInfo(f,base_dir=matcherPath) - for template in dist.templates: - if template.match_uri != None: - self.templates.append(template) - return - - def match(self, source): - """Add a matching template to the source""" - _ = gettext.gettext - found = False - for template in self.templates: - if (re.search(template.match_uri, source.uri) and - re.match(template.match_name, source.dist)): - found = True - source.template = template - break - elif (template.is_mirror(source.uri) and - re.match(template.match_name, source.dist)): - found = True - source.template = template - break - return found + """ matcher class to make a source entry look nice + lots of predefined matchers to make it i18n/gettext friendly + """ + + def __init__(self, matcherPath): + self.templates = [] + # Get the human readable channel and comp names from the channel .infos + spec_files = glob.glob("%s/*.info" % matcherPath) + for f in spec_files: + f = os.path.basename(f) + i = f.find(".info") + f = f[0:i] + dist = DistInfo(f,base_dir=matcherPath) + for template in dist.templates: + if template.match_uri != None: + self.templates.append(template) + return + + def match(self, source): + """Add a matching template to the source""" + _ = gettext.gettext + found = False + for template in self.templates: + if (re.search(template.match_uri, source.uri) and + re.match(template.match_name, source.dist)): + found = True + source.template = template + break + elif (template.is_mirror(source.uri) and + re.match(template.match_name, source.dist)): + found = True + source.template = template + break + return found # some simple tests if __name__ == "__main__": - apt_pkg.InitConfig() - sources = SourcesList() + apt_pkg.InitConfig() + sources = SourcesList() - for entry in sources: - print entry.str() - #print entry.uri + for entry in sources: + print entry.str() + #print entry.uri - mirror = is_mirror("http://archive.ubuntu.com/ubuntu/", - "http://de.archive.ubuntu.com/ubuntu/") - print "is_mirror(): %s" % mirror + mirror = is_mirror("http://archive.ubuntu.com/ubuntu/", + "http://de.archive.ubuntu.com/ubuntu/") + print "is_mirror(): %s" % mirror - print is_mirror("http://archive.ubuntu.com/ubuntu", - "http://de.archive.ubuntu.com/ubuntu/") - print is_mirror("http://archive.ubuntu.com/ubuntu/", - "http://de.archive.ubuntu.com/ubuntu") + print is_mirror("http://archive.ubuntu.com/ubuntu", + "http://de.archive.ubuntu.com/ubuntu/") + print is_mirror("http://archive.ubuntu.com/ubuntu/", + "http://de.archive.ubuntu.com/ubuntu") diff --git a/doc/examples/acquire.py b/doc/examples/acquire.py index 07f8da0e..7bf7d646 100644 --- a/doc/examples/acquire.py +++ b/doc/examples/acquire.py @@ -6,25 +6,25 @@ import tempfile def get_file(fetcher, uri, destFile): - cwd = os.getcwd() - # create a temp dir - dir = tempfile.mkdtemp() - os.chdir(dir) - # get the file - af = apt_pkg.GetPkgAcqFile(fetcher, - uri=uri, - descr="sample descr") - res = fetcher.Run() - if res != fetcher.ResultContinue: - os.rmdir(dir) - os.chdir(cwd) - return False - filename = os.path.basename(uri) - os.rename(dir+"/"+filename,destFile) - # cleanup - os.rmdir(dir) - os.chdir(cwd) - return True + cwd = os.getcwd() + # create a temp dir + dir = tempfile.mkdtemp() + os.chdir(dir) + # get the file + af = apt_pkg.GetPkgAcqFile(fetcher, + uri=uri, + descr="sample descr") + res = fetcher.Run() + if res != fetcher.ResultContinue: + os.rmdir(dir) + os.chdir(cwd) + return False + filename = os.path.basename(uri) + os.rename(dir+"/"+filename,destFile) + # cleanup + os.rmdir(dir) + os.chdir(cwd) + return True apt_pkg.init() diff --git a/doc/examples/build-deps.py b/doc/examples/build-deps.py index 2d83a54f..dc1a6f4e 100755 --- a/doc/examples/build-deps.py +++ b/doc/examples/build-deps.py @@ -7,17 +7,17 @@ import sets # only needed for python2.3, python2.4 supports this naively def get_source_pkg(pkg, records, depcache): - """ get the source package name of a given package """ - version = depcache.GetCandidateVer(pkg) - if not version: - return None - file, index = version.FileList.pop(0) - records.Lookup((file, index)) - if records.SourcePkg != "": - srcpkg = records.SourcePkg - else: - srcpkg = pkg.Name - return srcpkg + """ get the source package name of a given package """ + version = depcache.GetCandidateVer(pkg) + if not version: + return None + file, index = version.FileList.pop(0) + records.Lookup((file, index)) + if records.SourcePkg != "": + srcpkg = records.SourcePkg + else: + srcpkg = pkg.Name + return srcpkg # main @@ -30,45 +30,45 @@ srcrecords = apt_pkg.GetPkgSrcRecords() # base package that we use for build-depends calculation if len(sys.argv) < 2: - print "need a package name as argument" - sys.exit(1) + print "need a package name as argument" + sys.exit(1) try: - base = cache[sys.argv[1]] + base = cache[sys.argv[1]] except KeyError: - print "No package %s found" % sys.argv[1] - sys.exit(1) + print "No package %s found" % sys.argv[1] + sys.exit(1) all_build_depends = sets.Set() # get the build depdends for the package itself srcpkg_name = get_source_pkg(base, records, depcache) print "srcpkg_name: %s " % srcpkg_name if not srcpkg_name: - print "Can't find source package for '%s'" % pkg.Name + print "Can't find source package for '%s'" % pkg.Name srcrec = srcrecords.Lookup(srcpkg_name) if srcrec: - print "Files:" - print srcrecords.Files - bd = srcrecords.BuildDepends - print "build-depends of the package: %s " % bd - for b in bd: - all_build_depends.add(b[0]) + print "Files:" + print srcrecords.Files + bd = srcrecords.BuildDepends + print "build-depends of the package: %s " % bd + for b in bd: + all_build_depends.add(b[0]) # calculate the build depends for all dependencies depends = depcache.GetCandidateVer(base).DependsList for dep in depends["Depends"]: # FIXME: do we need to consider PreDepends? - pkg = dep[0].TargetPkg - srcpkg_name = get_source_pkg(pkg, records, depcache) - if not srcpkg_name: - print "Can't find source package for '%s'" % pkg.Name - continue - srcrec = srcrecords.Lookup(srcpkg_name) - if srcrec: - #print srcrecords.Package - #print srcrecords.Binaries - bd = srcrecords.BuildDepends - #print "%s: %s " % (srcpkg_name, bd) - for b in bd: - all_build_depends.add(b[0]) + pkg = dep[0].TargetPkg + srcpkg_name = get_source_pkg(pkg, records, depcache) + if not srcpkg_name: + print "Can't find source package for '%s'" % pkg.Name + continue + srcrec = srcrecords.Lookup(srcpkg_name) + if srcrec: + #print srcrecords.Package + #print srcrecords.Binaries + bd = srcrecords.BuildDepends + #print "%s: %s " % (srcpkg_name, bd) + for b in bd: + all_build_depends.add(b[0]) print "\n".join(all_build_depends) diff --git a/doc/examples/checkstate.py b/doc/examples/checkstate.py index 2986872f..3368d500 100755 --- a/doc/examples/checkstate.py +++ b/doc/examples/checkstate.py @@ -14,23 +14,23 @@ packages = cache.Packages uninstalled, updated, upgradable = {}, {}, {} for package in packages: - versions = package.VersionList - if not versions: - continue - version = versions[0] - for other_version in versions: - if apt_pkg.VersionCompare(version.VerStr, other_version.VerStr)<0: - version = other_version - if package.CurrentVer: - current = package.CurrentVer - if apt_pkg.VersionCompare(current.VerStr, version.VerStr)<0: - upgradable[package.Name] = version - break - else: - updated[package.Name] = current - else: - uninstalled[package.Name] = version + versions = package.VersionList + if not versions: + continue + version = versions[0] + for other_version in versions: + if apt_pkg.VersionCompare(version.VerStr, other_version.VerStr)<0: + version = other_version + if package.CurrentVer: + current = package.CurrentVer + if apt_pkg.VersionCompare(current.VerStr, version.VerStr)<0: + upgradable[package.Name] = version + break + else: + updated[package.Name] = current + else: + uninstalled[package.Name] = version for l in (uninstalled, updated, upgradable): - print l.items()[0] + print l.items()[0] diff --git a/doc/examples/config.py b/doc/examples/config.py index 222c1331..337899f0 100755 --- a/doc/examples/config.py +++ b/doc/examples/config.py @@ -25,31 +25,31 @@ print "Command line is",sys.argv # Load the default configuration file, InitConfig() does this better.. Cnf.Set("config-file","/etc/apt/apt.conf"); # or Cnf["config-file"] = ".."; if posixpath.exists(Cnf.FindFile("config-file")): - apt_pkg.ReadConfigFile(Cnf,"/etc/apt/apt.conf"); + apt_pkg.ReadConfigFile(Cnf,"/etc/apt/apt.conf"); # Merge the command line arguments into the configuration space Arguments = [('h',"help","help"), ('v',"version","version"), ('q',"quiet","quiet","IntLevel"), ('c',"config-file","","ConfigFile"), - ('o',"option","","ArbItem")] + ('o',"option","","ArbItem")] print "FileNames",apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv); print "Quiet level selected is",Cnf.FindI("quiet",0); # Do some stuff with it if Cnf.FindB("version",0) == 1: - print "Version selected - 1.1"; + print "Version selected - 1.1"; if Cnf.FindB("help",0) == 1: - print apt_pkg.Package,apt_pkg.Version,"for",apt_pkg.Architecture, \ - "compiled on",apt_pkg.Date,apt_pkg.Time; - print "Hi, I am the help text for this program"; - sys.exit(0); + print apt_pkg.Package,apt_pkg.Version,"for",apt_pkg.Architecture, \ + "compiled on",apt_pkg.Date,apt_pkg.Time; + print "Hi, I am the help text for this program"; + sys.exit(0); print "No help for you, try -h"; # Print the configuration space print "The Configuration space looks like:"; for I in Cnf.keys(): - print "%s \"%s\";"%(I,Cnf[I]); + print "%s \"%s\";"%(I,Cnf[I]); diff --git a/doc/examples/configisc.py b/doc/examples/configisc.py index 1773a919..45a9c7f6 100755 --- a/doc/examples/configisc.py +++ b/doc/examples/configisc.py @@ -13,8 +13,8 @@ import apt_pkg,sys,posixpath; ConfigFile = apt_pkg.ParseCommandLine(apt_pkg.Config,[],sys.argv); if len(ConfigFile) != 1: - print "Must have exactly 1 file name"; - sys.exit(0); + print "Must have exactly 1 file name"; + sys.exit(0); Cnf = apt_pkg.newConfiguration(); apt_pkg.ReadConfigFileISC(Cnf,ConfigFile[0]); @@ -26,14 +26,14 @@ apt_pkg.ReadConfigFileISC(Cnf,ConfigFile[0]); # bind8 config file.. if Cnf.has_key("Zone"): - print "Zones: ",Cnf.SubTree("zone").List(); - for I in Cnf.List("zone"): - SubCnf = Cnf.SubTree(I); - if SubCnf.Find("type") == "slave": - print "Masters for %s: %s"%(SubCnf.MyTag(),SubCnf.ValueList("masters")); + print "Zones: ",Cnf.SubTree("zone").List(); + for I in Cnf.List("zone"): + SubCnf = Cnf.SubTree(I); + if SubCnf.Find("type") == "slave": + print "Masters for %s: %s"%(SubCnf.MyTag(),SubCnf.ValueList("masters")); else: - print "Tree definitions:"; - for I in Cnf.List("tree"): - SubCnf = Cnf.SubTree(I); - # This could use Find which would eliminate the possibility of exceptions. - print "Subtree %s with sections '%s' and architectures '%s'"%(SubCnf.MyTag(),SubCnf["Sections"],SubCnf["Architectures"]); + print "Tree definitions:"; + for I in Cnf.List("tree"): + SubCnf = Cnf.SubTree(I); + # This could use Find which would eliminate the possibility of exceptions. + print "Subtree %s with sections '%s' and architectures '%s'"%(SubCnf.MyTag(),SubCnf["Sections"],SubCnf["Architectures"]); diff --git a/doc/examples/dependant-pkgs.py b/doc/examples/dependant-pkgs.py index 2de420a5..bb10ce70 100755 --- a/doc/examples/dependant-pkgs.py +++ b/doc/examples/dependant-pkgs.py @@ -6,27 +6,27 @@ import sys pkgs = set() cache = apt.Cache() for pkg in cache: - candver = cache._depcache.GetCandidateVer(pkg._pkg) - if candver == None: - continue - dependslist = candver.DependsList - for dep in dependslist.keys(): - # get the list of each dependency object - for depVerList in dependslist[dep]: - for z in depVerList: - # get all TargetVersions of - # the dependency object - for tpkg in z.AllTargets(): - if sys.argv[1] == tpkg.ParentPkg.Name: - pkgs.add(pkg.name) + candver = cache._depcache.GetCandidateVer(pkg._pkg) + if candver == None: + continue + dependslist = candver.DependsList + for dep in dependslist.keys(): + # get the list of each dependency object + for depVerList in dependslist[dep]: + for z in depVerList: + # get all TargetVersions of + # the dependency object + for tpkg in z.AllTargets(): + if sys.argv[1] == tpkg.ParentPkg.Name: + pkgs.add(pkg.name) main = set() universe = set() for pkg in pkgs: - if "universe" in cache[pkg].section: - universe.add(cache[pkg].sourcePackageName) - else: - main.add(cache[pkg].sourcePackageName) + if "universe" in cache[pkg].section: + universe.add(cache[pkg].sourcePackageName) + else: + main.add(cache[pkg].sourcePackageName) print "main:" print "\n".join(main) diff --git a/doc/examples/gui-inst.py b/doc/examples/gui-inst.py index 28887d34..edaec455 100755 --- a/doc/examples/gui-inst.py +++ b/doc/examples/gui-inst.py @@ -22,51 +22,51 @@ from apt.progress import OpProgress, FetchProgress, InstallProgress class GuiFetchProgress(gtk.Window, FetchProgress): def __init__(self): - gtk.Window.__init__(self) - self.vbox = gtk.VBox() - self.vbox.show() - self.add(self.vbox) - self.progress = gtk.ProgressBar() - self.progress.show() - self.label = gtk.Label() - self.label.show() - self.vbox.pack_start(self.progress) - self.vbox.pack_start(self.label) - self.resize(300,100) + gtk.Window.__init__(self) + self.vbox = gtk.VBox() + self.vbox.show() + self.add(self.vbox) + self.progress = gtk.ProgressBar() + self.progress.show() + self.label = gtk.Label() + self.label.show() + self.vbox.pack_start(self.progress) + self.vbox.pack_start(self.label) + self.resize(300,100) def start(self): print "start" - self.progress.set_fraction(0.0) + self.progress.set_fraction(0.0) self.show() def stop(self): - self.hide() + self.hide() def pulse(self): FetchProgress.pulse(self) self.label.set_text("Speed: %s/s" % apt_pkg.SizeToStr(self.currentCPS)) - #self.progressbar.set_fraction(self.currentBytes/self.totalBytes) - while gtk.events_pending(): - gtk.main_iteration() + #self.progressbar.set_fraction(self.currentBytes/self.totalBytes) + while gtk.events_pending(): + gtk.main_iteration() return True class TermInstallProgress(InstallProgress, gtk.Window): def __init__(self): - gtk.Window.__init__(self) + gtk.Window.__init__(self) InstallProgress.__init__(self) - self.show() + self.show() box = gtk.VBox() box.show() self.add(box) - self.term = vte.Terminal() - self.term.show() + self.term = vte.Terminal() + self.term.show() # check for the child self.reaper = vte.reaper_get() self.reaper.connect("child-exited",self.child_exited) self.finished = False - box.pack_start(self.term) + box.pack_start(self.term) self.progressbar = gtk.ProgressBar() self.progressbar.show() box.pack_start(self.progressbar) @@ -115,16 +115,16 @@ iprogress = TermInstallProgress() # show the interface while gtk.events_pending(): - gtk.main_iteration() + gtk.main_iteration() pkg = cache["3dchess"] print "\n%s"%pkg.name # install or remove, the importend thing is to keep us busy :) if pkg.isInstalled: - pkg.markDelete() + pkg.markDelete() else: - pkg.markInstall() + pkg.markInstall() cache.commit(fprogress, iprogress) print "Exiting" diff --git a/doc/examples/inst.py b/doc/examples/inst.py index d1e2ff99..b37ab4cd 100644 --- a/doc/examples/inst.py +++ b/doc/examples/inst.py @@ -11,23 +11,23 @@ from apt.progress import InstallProgress class TextInstallProgress(InstallProgress): - def __init__(self): - apt.progress.InstallProgress.__init__(self) - self.last = 0.0 + def __init__(self): + apt.progress.InstallProgress.__init__(self) + self.last = 0.0 - def updateInterface(self): - InstallProgress.updateInterface(self) - if self.last >= self.percent: - return - sys.stdout.write("\r[%s] %s\n" %(self.percent, self.status)) - sys.stdout.flush() - self.last = self.percent + def updateInterface(self): + InstallProgress.updateInterface(self) + if self.last >= self.percent: + return + sys.stdout.write("\r[%s] %s\n" %(self.percent, self.status)) + sys.stdout.flush() + self.last = self.percent - def conffile(self,current,new): - print "conffile prompt: %s %s" % (current,new) + def conffile(self,current,new): + print "conffile prompt: %s %s" % (current,new) - def error(self, errorstr): - print "got dpkg error: '%s'" % errorstr + def error(self, errorstr): + print "got dpkg error: '%s'" % errorstr cache = apt.Cache(apt.progress.OpTextProgress()) @@ -39,11 +39,11 @@ pkg = cache["3dchess"] # install or remove, the importend thing is to keep us busy :) if pkg.isInstalled: - print "Going to delete %s" % pkg.name - pkg.markDelete() + print "Going to delete %s" % pkg.name + pkg.markDelete() else: - print "Going to install %s" % pkg.name - pkg.markInstall() + print "Going to install %s" % pkg.name + pkg.markInstall() res = cache.commit(fprogress, iprogress) print res diff --git a/doc/examples/print_uris.py b/doc/examples/print_uris.py index c8a64223..3c93a668 100755 --- a/doc/examples/print_uris.py +++ b/doc/examples/print_uris.py @@ -12,11 +12,11 @@ upgradable = filter(lambda p: p.isUpgradable, cache) for pkg in upgradable: - pkg._lookupRecord(True) - path = apt_pkg.ParseSection(pkg._records.Record)["Filename"] - cand = pkg._depcache.GetCandidateVer(pkg._pkg) - for (packagefile,i) in cand.FileList: - indexfile = cache._list.FindIndex(packagefile) - if indexfile: - uri = indexfile.ArchiveURI(path) - print uri + pkg._lookupRecord(True) + path = apt_pkg.ParseSection(pkg._records.Record)["Filename"] + cand = pkg._depcache.GetCandidateVer(pkg._pkg) + for (packagefile,i) in cand.FileList: + indexfile = cache._list.FindIndex(packagefile) + if indexfile: + uri = indexfile.ArchiveURI(path) + print uri diff --git a/doc/examples/progress.py b/doc/examples/progress.py index 39e73e70..d8f00a52 100644 --- a/doc/examples/progress.py +++ b/doc/examples/progress.py @@ -41,8 +41,8 @@ class TextFetchProgress(apt.FetchProgress): return True def mediaChange(self, medium, drive): - print "Please insert medium %s in drive %s" % (medium, drive) - sys.stdin.readline() + print "Please insert medium %s in drive %s" % (medium, drive) + sys.stdin.readline() #return False diff --git a/doc/examples/recommends.py b/doc/examples/recommends.py index 03d46068..f0b3b1be 100755 --- a/doc/examples/recommends.py +++ b/doc/examples/recommends.py @@ -8,32 +8,32 @@ cache = apt_pkg.GetCache() class Wanted: - def __init__(self, name): - self.name = name - self.recommended = [] - self.suggested = [] + def __init__(self, name): + self.name = name + self.recommended = [] + self.suggested = [] wanted = {} for package in cache.Packages: - current = package.CurrentVer - if not current: - continue - depends = current.DependsList - for (key, attr) in (('Suggests', 'suggested'), - ('Recommends', 'recommended')): - list = depends.get(key, []) - for dependency in list: - name = dependency[0].TargetPkg.Name - dep = cache[name] - if dep.CurrentVer: - continue - getattr(wanted.setdefault(name, Wanted(name)), - attr).append(package.Name) + current = package.CurrentVer + if not current: + continue + depends = current.DependsList + for (key, attr) in (('Suggests', 'suggested'), + ('Recommends', 'recommended')): + list = depends.get(key, []) + for dependency in list: + name = dependency[0].TargetPkg.Name + dep = cache[name] + if dep.CurrentVer: + continue + getattr(wanted.setdefault(name, Wanted(name)), + attr).append(package.Name) ks = wanted.keys() ks.sort() for want in ks: - print want, wanted[want].recommended, wanted[want].suggested + print want, wanted[want].recommended, wanted[want].suggested diff --git a/doc/examples/records.py b/doc/examples/records.py index ef04b555..9dfc460b 100755 --- a/doc/examples/records.py +++ b/doc/examples/records.py @@ -5,8 +5,8 @@ import apt cache = apt.Cache() for pkg in cache: - if not pkg.candidateRecord: - continue - if pkg.candidateRecord.has_key("Task"): - print "Pkg %s is part of '%s'" % (pkg.name, pkg.candidateRecord["Task"].split()) - #print pkg.candidateRecord + if not pkg.candidateRecord: + continue + if pkg.candidateRecord.has_key("Task"): + print "Pkg %s is part of '%s'" % (pkg.name, pkg.candidateRecord["Task"].split()) + #print pkg.candidateRecord diff --git a/doc/examples/sources.py b/doc/examples/sources.py index b48c0ba5..8d807f4c 100644 --- a/doc/examples/sources.py +++ b/doc/examples/sources.py @@ -10,6 +10,6 @@ apt_pkg.init() sources = apt_pkg.GetPkgSrcRecords() sources.Restart() while sources.Lookup('hello'): - print sources.Package, sources.Version, sources.Maintainer, sources.Section, `sources.Binaries` - print sources.Files - print sources.Index.ArchiveURI(sources.Files[0][2]) + print sources.Package, sources.Version, sources.Maintainer, sources.Section, `sources.Binaries` + print sources.Files + print sources.Index.ArchiveURI(sources.Files[0][2]) diff --git a/doc/examples/tagfile.py b/doc/examples/tagfile.py index 653c0a71..aeba34d2 100755 --- a/doc/examples/tagfile.py +++ b/doc/examples/tagfile.py @@ -4,5 +4,5 @@ import apt_pkg Parse = apt_pkg.ParseTagFile(open("/var/lib/dpkg/status","r")); while Parse.Step() == 1: - print Parse.Section.get("Package"); - print apt_pkg.ParseDepends(Parse.Section.get("Depends","")); + print Parse.Section.get("Package"); + print apt_pkg.ParseDepends(Parse.Section.get("Depends","")); diff --git a/doc/examples/versiontest.py b/doc/examples/versiontest.py index c4e5f44d..8f18f6c8 100755 --- a/doc/examples/versiontest.py +++ b/doc/examples/versiontest.py @@ -7,30 +7,30 @@ apt_pkg.InitSystem(); TestFile = apt_pkg.ParseCommandLine(apt_pkg.Config,[],sys.argv); if len(TestFile) != 1: - print "Must have exactly 1 file name"; - sys.exit(0); + print "Must have exactly 1 file name"; + sys.exit(0); # Go over the file.. List = open(TestFile[0],"r"); CurLine = 0; while(1): - Line = List.readline(); - CurLine = CurLine + 1; - if Line == "": - break; - Line = string.strip(Line); - if len(Line) == 0 or Line[0] == '#': - continue; + Line = List.readline(); + CurLine = CurLine + 1; + if Line == "": + break; + Line = string.strip(Line); + if len(Line) == 0 or Line[0] == '#': + continue; - Split = re.split("[ \n]",Line); + Split = re.split("[ \n]",Line); - # Check forward - if apt_pkg.VersionCompare(Split[0],Split[1]) != int(Split[2]): - print "Comparision failed on line %u. '%s' ? '%s' %i != %i"%(CurLine, - Split[0],Split[1],apt_pkg.VersionCompare(Split[0],Split[1]), - int(Split[2])); - # Check reverse - if apt_pkg.VersionCompare(Split[1],Split[0]) != -1*int(Split[2]): - print "Comparision failed on line %u. '%s' ? '%s' %i != %i"%(CurLine, - Split[1],Split[0],apt_pkg.VersionCompare(Split[1],Split[0]), - -1*int(Split[2])); + # Check forward + if apt_pkg.VersionCompare(Split[0],Split[1]) != int(Split[2]): + print "Comparision failed on line %u. '%s' ? '%s' %i != %i"%(CurLine, + Split[0],Split[1],apt_pkg.VersionCompare(Split[0],Split[1]), + int(Split[2])); + # Check reverse + if apt_pkg.VersionCompare(Split[1],Split[0]) != -1*int(Split[2]): + print "Comparision failed on line %u. '%s' ? '%s' %i != %i"%(CurLine, + Split[1],Split[0],apt_pkg.VersionCompare(Split[1],Split[0]), + -1*int(Split[2])); diff --git a/tests/cache.py b/tests/cache.py index 34535e68..24732578 100644 --- a/tests/cache.py +++ b/tests/cache.py @@ -8,44 +8,44 @@ import sys def main(): - apt_pkg.init() - cache = apt_pkg.GetCache() - depcache = apt_pkg.GetDepCache(cache) - depcache.Init() - i=0 - all=cache.PackageCount - print "Running Cache test on all packages:" - # first, get all pkgs - for pkg in cache.Packages: - i += 1 - x = pkg.Name - # then get each version - for ver in pkg.VersionList: - # get some version information - a = ver.FileList - b = ver.VerStr - c = ver.Arch - d = ver.DependsListStr - dl = ver.DependsList - # get all dependencies (a dict of string->list, - # e.g. "depends:" -> [ver1,ver2,..] - for dep in dl.keys(): - # get the list of each dependency object - for depVerList in dl[dep]: - for z in depVerList: - # get all TargetVersions of - # the dependency object - for j in z.AllTargets(): - f = j.FileList - g = ver.VerStr - h = ver.Arch - k = ver.DependsListStr - j = ver.DependsList - pass + apt_pkg.init() + cache = apt_pkg.GetCache() + depcache = apt_pkg.GetDepCache(cache) + depcache.Init() + i=0 + all=cache.PackageCount + print "Running Cache test on all packages:" + # first, get all pkgs + for pkg in cache.Packages: + i += 1 + x = pkg.Name + # then get each version + for ver in pkg.VersionList: + # get some version information + a = ver.FileList + b = ver.VerStr + c = ver.Arch + d = ver.DependsListStr + dl = ver.DependsList + # get all dependencies (a dict of string->list, + # e.g. "depends:" -> [ver1,ver2,..] + for dep in dl.keys(): + # get the list of each dependency object + for depVerList in dl[dep]: + for z in depVerList: + # get all TargetVersions of + # the dependency object + for j in z.AllTargets(): + f = j.FileList + g = ver.VerStr + h = ver.Arch + k = ver.DependsListStr + j = ver.DependsList + pass - print "\r%i/%i=%.3f%% " % (i,all,(float(i)/float(all)*100)), + print "\r%i/%i=%.3f%% " % (i,all,(float(i)/float(all)*100)), if __name__ == "__main__": - main() - sys.exit(0) + main() + sys.exit(0) diff --git a/tests/depcache.py b/tests/depcache.py index 635fea14..32c510f0 100644 --- a/tests/depcache.py +++ b/tests/depcache.py @@ -8,46 +8,46 @@ import sys def main(): - apt_pkg.init() - cache = apt_pkg.GetCache() - depcache = apt_pkg.GetDepCache(cache) - depcache.Init() - i=0 - all=cache.PackageCount - print "Running DepCache test on all packages" - print "(trying to install each and then mark it keep again):" - # first, get all pkgs - for pkg in cache.Packages: - i += 1 - x = pkg.Name - # then get each version - ver =depcache.GetCandidateVer(pkg) - if ver != None: - depcache.MarkInstall(pkg) - if depcache.InstCount == 0: - if depcache.IsUpgradable(pkg): - print "Error marking %s for install" % x - for p in cache.Packages: - if depcache.MarkedInstall(p): - depcache.MarkKeep(p) - if depcache.InstCount != 0: - print "Error undoing the selection for %s (InstCount: %s)" % (x,depcache.InstCount) - print "\r%i/%i=%.3f%% " % (i,all,(float(i)/float(all)*100)), + apt_pkg.init() + cache = apt_pkg.GetCache() + depcache = apt_pkg.GetDepCache(cache) + depcache.Init() + i=0 + all=cache.PackageCount + print "Running DepCache test on all packages" + print "(trying to install each and then mark it keep again):" + # first, get all pkgs + for pkg in cache.Packages: + i += 1 + x = pkg.Name + # then get each version + ver =depcache.GetCandidateVer(pkg) + if ver != None: + depcache.MarkInstall(pkg) + if depcache.InstCount == 0: + if depcache.IsUpgradable(pkg): + print "Error marking %s for install" % x + for p in cache.Packages: + if depcache.MarkedInstall(p): + depcache.MarkKeep(p) + if depcache.InstCount != 0: + print "Error undoing the selection for %s (InstCount: %s)" % (x,depcache.InstCount) + print "\r%i/%i=%.3f%% " % (i,all,(float(i)/float(all)*100)), - print - print "Trying Upgrade:" - depcache.Upgrade() - print "To install: %s " % depcache.InstCount - print "To remove: %s " % depcache.DelCount - print "Kept back: %s " % depcache.KeepCount + print + print "Trying Upgrade:" + depcache.Upgrade() + print "To install: %s " % depcache.InstCount + print "To remove: %s " % depcache.DelCount + print "Kept back: %s " % depcache.KeepCount - print "Trying DistUpgrade:" - depcache.Upgrade(True) - print "To install: %s " % depcache.InstCount - print "To remove: %s " % depcache.DelCount - print "Kept back: %s " % depcache.KeepCount + print "Trying DistUpgrade:" + depcache.Upgrade(True) + print "To install: %s " % depcache.InstCount + print "To remove: %s " % depcache.DelCount + print "Kept back: %s " % depcache.KeepCount if __name__ == "__main__": - main() - sys.exit(0) + main() + sys.exit(0) diff --git a/tests/lock.py b/tests/lock.py index a3d962d7..aeab804b 100644 --- a/tests/lock.py +++ b/tests/lock.py @@ -21,7 +21,7 @@ if __name__ == "__main__": apt_pkg.PkgSystemLock() except SystemError, s: print "Can't get lock: (error text:\n%s)" % s - sys.exit(0) + sys.exit(0) apt_pkg.PkgSystemUnLock() @@ -35,7 +35,7 @@ if __name__ == "__main__": # child fd = apt_pkg.GetLock(lock,False) print "Lockfile fd (child): %s" % fd - sys.exit(0) + sys.exit(0) # try to get lock with error flag pid = os.fork() @@ -43,4 +43,4 @@ if __name__ == "__main__": # child fd = apt_pkg.GetLock(lock,True) print "Lockfile fd (child): %s" % fd - sys.exit(0) + sys.exit(0) diff --git a/tests/memleak.py b/tests/memleak.py index 58a2f886..6eece9d4 100755 --- a/tests/memleak.py +++ b/tests/memleak.py @@ -11,36 +11,36 @@ cache = apt.Cache() # memleak for i in range(100): - cache.open(None) - print cache["apt"].name - time.sleep(1) - gc.collect() - f = open("%s" % i,"w") - for obj in gc.get_objects(): - f.write("%s\n" % str(obj)) - f.close() + cache.open(None) + print cache["apt"].name + time.sleep(1) + gc.collect() + f = open("%s" % i,"w") + for obj in gc.get_objects(): + f.write("%s\n" % str(obj)) + f.close() # memleak #for i in range(100): -# cache = apt.Cache() -# time.sleep(1) -# cache = None -# gc.collect() +# cache = apt.Cache() +# time.sleep(1) +# cache = None +# gc.collect() # no memleak, but more or less the apt.Cache.open() code for i in range(100): - cache = apt_pkg.GetCache() - depcache = apt_pkg.GetDepCache(cache) - records = apt_pkg.GetPkgRecords(cache) - list = apt_pkg.GetPkgSourceList() - list.ReadMainList() - dict = {} - for pkg in cache.Packages: - if len(pkg.VersionList) > 0: - dict[pkg.Name] = apt.Package(cache,depcache, - records, list, None, pkg) - - print cache["apt"] - time.sleep(1) - - gc.collect() + cache = apt_pkg.GetCache() + depcache = apt_pkg.GetDepCache(cache) + records = apt_pkg.GetPkgRecords(cache) + list = apt_pkg.GetPkgSourceList() + list.ReadMainList() + dict = {} + for pkg in cache.Packages: + if len(pkg.VersionList) > 0: + dict[pkg.Name] = apt.Package(cache,depcache, + records, list, None, pkg) + + print cache["apt"] + time.sleep(1) + + gc.collect() diff --git a/tests/pkgproblemresolver.py b/tests/pkgproblemresolver.py index 546e2f16..82186d40 100644 --- a/tests/pkgproblemresolver.py +++ b/tests/pkgproblemresolver.py @@ -8,63 +8,63 @@ import sys def main(): - apt_pkg.init() - cache = apt_pkg.GetCache() - depcache = apt_pkg.GetDepCache(cache) - depcache.Init() - i=0 - all=cache.PackageCount - print "Running DepCache test on all packages" - print "(trying to install each and then mark it keep again):" - # first, get all pkgs - for pkg in cache.Packages: - i += 1 - x = pkg.Name - # then get each version - ver =depcache.GetCandidateVer(pkg) - if ver != None: - depcache.MarkInstall(pkg) - if depcache.BrokenCount > 0: - fixer = apt_pkg.GetPkgProblemResolver(depcache) - fixer.Clear(pkg) - fixer.Protect(pkg) - # we first try to resolve the problem - # with the package that should be installed - # protected - try: - fixer.Resolve(True) - except SystemError: - # the pkg seems to be broken, the - # returns a exception - fixer.Clear(pkg) - fixer.Resolve(True) - if not depcache.MarkedInstall(pkg): - print "broken in archive: %s " % pkg.Name - fixer = None - if depcache.InstCount == 0: - if depcache.IsUpgradable(pkg): - print "Error marking %s for install" % x - for p in cache.Packages: - if depcache.MarkedInstall(p) or depcache.MarkedUpgrade(p): - depcache.MarkKeep(p) - if depcache.InstCount != 0: - print "Error undoing the selection for %s" % x - print "\r%i/%i=%.3f%% " % (i,all,(float(i)/float(all)*100)), + apt_pkg.init() + cache = apt_pkg.GetCache() + depcache = apt_pkg.GetDepCache(cache) + depcache.Init() + i=0 + all=cache.PackageCount + print "Running DepCache test on all packages" + print "(trying to install each and then mark it keep again):" + # first, get all pkgs + for pkg in cache.Packages: + i += 1 + x = pkg.Name + # then get each version + ver =depcache.GetCandidateVer(pkg) + if ver != None: + depcache.MarkInstall(pkg) + if depcache.BrokenCount > 0: + fixer = apt_pkg.GetPkgProblemResolver(depcache) + fixer.Clear(pkg) + fixer.Protect(pkg) + # we first try to resolve the problem + # with the package that should be installed + # protected + try: + fixer.Resolve(True) + except SystemError: + # the pkg seems to be broken, the + # returns a exception + fixer.Clear(pkg) + fixer.Resolve(True) + if not depcache.MarkedInstall(pkg): + print "broken in archive: %s " % pkg.Name + fixer = None + if depcache.InstCount == 0: + if depcache.IsUpgradable(pkg): + print "Error marking %s for install" % x + for p in cache.Packages: + if depcache.MarkedInstall(p) or depcache.MarkedUpgrade(p): + depcache.MarkKeep(p) + if depcache.InstCount != 0: + print "Error undoing the selection for %s" % x + print "\r%i/%i=%.3f%% " % (i,all,(float(i)/float(all)*100)), - print - print "Trying Upgrade:" - depcache.Upgrade() - print "To install: %s " % depcache.InstCount - print "To remove: %s " % depcache.DelCount - print "Kept back: %s " % depcache.KeepCount + print + print "Trying Upgrade:" + depcache.Upgrade() + print "To install: %s " % depcache.InstCount + print "To remove: %s " % depcache.DelCount + print "Kept back: %s " % depcache.KeepCount - print "Trying DistUpgrade:" - depcache.Upgrade(True) - print "To install: %s " % depcache.InstCount - print "To remove: %s " % depcache.DelCount - print "Kept back: %s " % depcache.KeepCount + print "Trying DistUpgrade:" + depcache.Upgrade(True) + print "To install: %s " % depcache.InstCount + print "To remove: %s " % depcache.DelCount + print "Kept back: %s " % depcache.KeepCount if __name__ == "__main__": - main() - sys.exit(0) + main() + sys.exit(0) diff --git a/tests/pkgrecords.py b/tests/pkgrecords.py index 308505f7..72096463 100644 --- a/tests/pkgrecords.py +++ b/tests/pkgrecords.py @@ -9,30 +9,30 @@ import sys def main(): - apt_pkg.init() - cache = apt_pkg.GetCache() - depcache = apt_pkg.GetDepCache(cache) - depcache.Init() - i=0 - print "Running PkgRecords test on all packages:" - for pkg in cache.Packages: - i += 1 - records = apt_pkg.GetPkgRecords(cache) - if len(pkg.VersionList) == 0: - #print "no available version, cruft" - continue - version = depcache.GetCandidateVer(pkg) - if not version: - continue - file, index = version.FileList.pop(0) - if records.Lookup((file,index)): - #print records.FileName - x = records.FileName - y = records.LongDesc - pass - print "\r%i/%i=%.3f%% " % (i,cache.PackageCount, (float(i)/float(cache.PackageCount)*100)), + apt_pkg.init() + cache = apt_pkg.GetCache() + depcache = apt_pkg.GetDepCache(cache) + depcache.Init() + i=0 + print "Running PkgRecords test on all packages:" + for pkg in cache.Packages: + i += 1 + records = apt_pkg.GetPkgRecords(cache) + if len(pkg.VersionList) == 0: + #print "no available version, cruft" + continue + version = depcache.GetCandidateVer(pkg) + if not version: + continue + file, index = version.FileList.pop(0) + if records.Lookup((file,index)): + #print records.FileName + x = records.FileName + y = records.LongDesc + pass + print "\r%i/%i=%.3f%% " % (i,cache.PackageCount, (float(i)/float(cache.PackageCount)*100)), if __name__ == "__main__": - main() - sys.exit(0) + main() + sys.exit(0) diff --git a/tests/pkgsrcrecords.py b/tests/pkgsrcrecords.py index 410140c8..3eb0fcab 100644 --- a/tests/pkgsrcrecords.py +++ b/tests/pkgsrcrecords.py @@ -9,19 +9,19 @@ import sys def main(): - apt_pkg.init() - cache = apt_pkg.GetCache() - i=0 - print "Running PkgSrcRecords test on all packages:" - for x in cache.Packages: - i += 1 - src = apt_pkg.GetPkgSrcRecords() - if src.Lookup(x.Name): - #print src.Package - pass - print "\r%i/%i=%.3f%% " % (i,cache.PackageCount, (float(i)/float(cache.PackageCount)*100)), + apt_pkg.init() + cache = apt_pkg.GetCache() + i=0 + print "Running PkgSrcRecords test on all packages:" + for x in cache.Packages: + i += 1 + src = apt_pkg.GetPkgSrcRecords() + if src.Lookup(x.Name): + #print src.Package + pass + print "\r%i/%i=%.3f%% " % (i,cache.PackageCount, (float(i)/float(cache.PackageCount)*100)), if __name__ == "__main__": - main() - sys.exit(0) + main() + sys.exit(0) diff --git a/utils/get_ubuntu_mirrors.py b/utils/get_ubuntu_mirrors.py index 8482615d..ddd1e369 100755 --- a/utils/get_ubuntu_mirrors.py +++ b/utils/get_ubuntu_mirrors.py @@ -42,10 +42,10 @@ try: uri=urllib2.urlopen(req) p = re.compile('^.*((http|ftp):\/\/[A-Za-z0-9-.:\/_]+).*\n*$') for line in uri.readlines(): - if r"[[Anchor(dvd-images)]]" in line: - break - if "http://" in line or "ftp://" in line: - mirrors.append(p.sub(r"\1", line)) + if r"[[Anchor(dvd-images)]]" in line: + break + if "http://" in line or "ftp://" in line: + mirrors.append(p.sub(r"\1", line)) uri.close() except: print "Failed to download or extract the mirrors list!" -- cgit v1.2.3 From 0d12af28d4de2745f8831abf0224ceabec693b76 Mon Sep 17 00:00:00 2001 From: Ben Finney Date: Fri, 16 May 2008 18:04:01 +1000 Subject: Fix spaces adjacent to commas and operators, to conform with PEP 8. --- apt/cache.py | 4 ++-- apt/cdrom.py | 2 +- apt/debfile.py | 4 ++-- apt/package.py | 24 ++++++++++++------------ apt/progress.py | 30 +++++++++++++++--------------- aptsources/distinfo.py | 16 ++++++++-------- aptsources/distro.py | 2 +- aptsources/sourceslist.py | 28 ++++++++++++++-------------- doc/examples/acquire.py | 8 ++++---- doc/examples/all_deps.py | 4 ++-- doc/examples/cdrom.py | 2 +- doc/examples/config.py | 32 ++++++++++++++++---------------- doc/examples/configisc.py | 14 +++++++------- doc/examples/deb_inspect.py | 8 ++++---- doc/examples/desc.py | 6 +++--- doc/examples/gui-inst.py | 8 ++++---- doc/examples/indexfile.py | 2 +- doc/examples/inst.py | 4 ++-- doc/examples/metaindex.py | 6 +++--- doc/examples/print_uris.py | 2 +- doc/examples/progress.py | 4 ++-- doc/examples/tagfile.py | 6 +++--- doc/examples/update.py | 2 +- doc/examples/versiontest.py | 24 ++++++++++++------------ setup.py | 35 ++++++++++++++++++----------------- tests/apt-test.py | 2 +- tests/cache.py | 2 +- tests/depcache.py | 4 ++-- tests/lock.py | 6 +++--- tests/memleak.py | 4 ++-- tests/pkgproblemresolver.py | 2 +- tests/pkgrecords.py | 4 ++-- tests/pkgsrcrecords.py | 2 +- tests/refcount.py | 2 +- tests/test_aptsources.py | 18 +++++++++--------- 35 files changed, 162 insertions(+), 161 deletions(-) (limited to 'apt') diff --git a/apt/cache.py b/apt/cache.py index 35da7970..3c3a25e5 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -153,7 +153,7 @@ class Cache(object): if item.StatIdle: transient = True continue - errMsg += "Failed to fetch %s %s\n" % (item.DescURI,item.ErrorText) + errMsg += "Failed to fetch %s %s\n" % (item.DescURI, item.ErrorText) failed = True # we raise a exception if the download failed or it was cancelt @@ -371,7 +371,7 @@ if __name__ == "__main__": for d in ["/tmp/pytest", "/tmp/pytest/partial"]: if not os.path.exists(d): os.mkdir(d) - apt_pkg.Config.Set("Dir::Cache::Archives","/tmp/pytest") + apt_pkg.Config.Set("Dir::Cache::Archives", "/tmp/pytest") pm = apt_pkg.GetPackageManager(c._depcache) fetcher = apt_pkg.GetAcquire(apt.progress.TextFetchProgress()) c._fetchArchives(fetcher, pm) diff --git a/apt/cdrom.py b/apt/cdrom.py index 7f9b4776..d6f098db 100644 --- a/apt/cdrom.py +++ b/apt/cdrom.py @@ -18,7 +18,7 @@ class Cdrom(object): self._progress = progress # see if we have a alternative mountpoint if mountpoint is not None: - apt_pkg.Config.Set("Acquire::cdrom::mount",mountpoint) + apt_pkg.Config.Set("Acquire::cdrom::mount", mountpoint) # do not mess with mount points by default if nomount is True: apt_pkg.Config.Set("APT::CDROM::NoMount", "true") diff --git a/apt/debfile.py b/apt/debfile.py index 365847d7..1a64b833 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -34,9 +34,9 @@ class DebPackage(object): """ return the list of files in the deb """ files = [] - def extract_cb(What,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor): + def extract_cb(What, Name, Link, Mode, UID, GID, Size, MTime, Major, Minor): #print "%s '%s','%s',%u,%u,%u,%u,%u,%u,%u"\ - # % (What,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor) + # % (What, Name, Link, Mode, UID, GID, Size, MTime, Major, Minor) files.append(Name) for member in self._supported_data_members: diff --git a/apt/package.py b/apt/package.py index b771c677..eef598af 100644 --- a/apt/package.py +++ b/apt/package.py @@ -102,7 +102,7 @@ class Package(object): print "No FileList for: %s " % self._pkg.Name() return False f, index = ver.FileList.pop(0) - self._records.Lookup((f,index)) + self._records.Lookup((f, index)) return True @@ -259,11 +259,11 @@ class Package(object): self._records.Lookup(desc_iter.FileList.pop(0)) desc = "" try: - s = unicode(self._records.LongDesc,"utf-8") - except UnicodeDecodeError,e: + s = unicode(self._records.LongDesc, "utf-8") + except UnicodeDecodeError, e: s = _("Invalid unicode in description for '%s' (%s). " - "Please report.") % (self.name,e) - for line in string.split(s,"\n"): + "Please report.") % (self.name, e) + for line in string.split(s, "\n"): tmp = string.strip(line) if tmp == ".": desc += "\n" @@ -380,7 +380,7 @@ class Package(object): def __repr__(self): return "component: '%s' archive: '%s' origin: '%s' label: '%s' " \ - "site '%s' isTrusted: '%s'"% (self.component, self.archive, + "site '%s' isTrusted: '%s'" % (self.component, self.archive, self.origin, self.label, self.site, self.trusted) @@ -389,7 +389,7 @@ class Package(object): if not ver: return None origins = [] - for (verFileIter,index) in ver.FileList: + for (verFileIter, index) in ver.FileList: origins.append(self.Origin(self, verFileIter)) return origins candidateOrigin = property(candidateOrigin) @@ -440,7 +440,7 @@ class Package(object): self.markInstall() else: # FIXME: we may want to throw a exception here - sys.stderr.write("MarkUpgrade() called on a non-upgrable pkg: '%s'\n" %self._pkg.Name) + sys.stderr.write("MarkUpgrade() called on a non-upgrable pkg: '%s'\n" % self._pkg.Name) def commit(self, fprogress, iprogress): """ commit the changes, need a FetchProgress and InstallProgress @@ -477,10 +477,10 @@ if __name__ == "__main__": print "PackageSize: %s " % pkg.packageSize print "Dependencies: %s" % pkg.installedDependencies for dep in pkg.candidateDependencies: - print ",".join(["%s (%s) (%s) (%s)" % (o.name,o.version,o.relation, o.preDepend) for o in dep.or_dependencies]) + print ",".join(["%s (%s) (%s) (%s)" % (o.name, o.version, o.relation, o.preDepend) for o in dep.or_dependencies]) print "arch: %s" % pkg.architecture print "homepage: %s" % pkg.homepage - print "rec: ",pkg.candidateRecord + print "rec: ", pkg.candidateRecord # now test install/remove import apt @@ -491,7 +491,7 @@ if __name__ == "__main__": for name in cache.keys(): pkg = cache[name] if pkg.isUpgradable: - if random.randint(0,1) == 1: + if random.randint(0, 1) == 1: pkg.markInstall(i) print "Broken: %s " % cache._depcache.BrokenCount print "InstCount: %s " % cache._depcache.InstCount @@ -502,7 +502,7 @@ if __name__ == "__main__": print "Randomly remove some packages with AutoFix: %s" % i cache = apt.Cache(progress) for name in cache.keys(): - if random.randint(0,1) == 1: + if random.randint(0, 1) == 1: try: cache[name].markDelete(i) except SystemError: diff --git a/apt/progress.py b/apt/progress.py index 6f72197e..dbad8050 100644 --- a/apt/progress.py +++ b/apt/progress.py @@ -53,7 +53,7 @@ class OpTextProgress(OpProgress): OpProgress.__init__(self) def update(self, percent): - sys.stdout.write("\r%s: %.2i " % (self.subOp,percent)) + sys.stdout.write("\r%s: %.2i " % (self.subOp, percent)) sys.stdout.flush() def done(self): @@ -71,11 +71,11 @@ class FetchProgress(object): dlFailed = 2 dlHit = 3 dlIgnored = 4 - dlStatusStr = {dlDone : "Done", - dlQueued : "Queued", - dlFailed : "Failed", - dlHit : "Hit", - dlIgnored : "Ignored"} + dlStatusStr = {dlDone: "Done", + dlQueued: "Queued", + dlFailed: "Failed", + dlHit: "Hit", + dlIgnored: "Ignored"} def __init__(self): self.eta = 0.0 @@ -134,7 +134,7 @@ class TextFetchProgress(FetchProgress): """ react to media change events """ res = True; print "Media change: please insert the disc labeled \ - '%s' in the drive '%s' and press enter" % (medium,drive) + '%s' in the drive '%s' and press enter" % (medium, drive) s = sys.stdin.readline() if(s == 'c' or s == 'C'): res = false; @@ -174,7 +174,7 @@ class InstallProgress(DumbInstallProgress): (read, write) = os.pipe() self.writefd=write self.statusfd = os.fdopen(read, "r") - fcntl.fcntl(self.statusfd.fileno(), fcntl.F_SETFL,os.O_NONBLOCK) + fcntl.fcntl(self.statusfd.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) self.read = "" self.percent = 0.0 self.status = "" @@ -183,7 +183,7 @@ class InstallProgress(DumbInstallProgress): " called when a error is detected during the install " pass - def conffile(self,current,new): + def conffile(self, current, new): " called when a conffile question from dpkg is detected " pass @@ -195,8 +195,8 @@ class InstallProgress(DumbInstallProgress): if self.statusfd != None: try: while not self.read.endswith("\n"): - self.read += os.read(self.statusfd.fileno(),1) - except OSError, (errno,errstr): + self.read += os.read(self.statusfd.fileno(), 1) + except OSError, (errno, errstr): # resource temporarly unavailable is ignored if errno != EAGAIN and errnor != EWOULDBLOCK: print errstr @@ -204,14 +204,14 @@ class InstallProgress(DumbInstallProgress): s = self.read #print s try: - (status, pkg, percent, status_str) = string.split(s, ":",3) + (status, pkg, percent, status_str) = string.split(s, ":", 3) except ValueError, e: # silently ignore lines that can't be parsed self.read = "" return #print "percent: %s %s" % (pkg, float(percent)/100.0) if status == "pmerror": - self.error(pkg,status_str) + self.error(pkg, status_str) elif status == "pmconffile": # we get a string like this: # 'current-conffile' 'new-conffile' useredited distedited @@ -231,9 +231,9 @@ class InstallProgress(DumbInstallProgress): def waitChild(self): while True: - select.select([self.statusfd],[],[], self.selectTimeout) + select.select([self.statusfd], [], [], self.selectTimeout) self.updateInterface() - (pid, res) = os.waitpid(self.child_pid,os.WNOHANG) + (pid, res) = os.waitpid(self.child_pid, os.WNOHANG) if pid == self.child_pid: break return os.WEXITSTATUS(res) diff --git a/aptsources/distinfo.py b/aptsources/distinfo.py index 4a601be3..57266a49 100644 --- a/aptsources/distinfo.py +++ b/aptsources/distinfo.py @@ -139,8 +139,8 @@ class Repository: def split_url(url): ''' split a given URL into the protocoll, the hostname and the dir part ''' - return map(lambda a,b: a, re.split(":*\/+", url, maxsplit=2), - [None, None, None]) + return map(lambda a, b: a, re.split(":*\/+", url, maxsplit=2), + [None, None, None]) class DistInfo: @@ -167,17 +167,17 @@ class DistInfo: map_mirror_sets = {} dist_fname = "%s/%s.info" % (base_dir, dist) - dist_file = open (dist_fname) + dist_file = open(dist_fname) if not dist_file: return template = None component = None for line in dist_file: - tokens = line.split (':', 1) - if len (tokens) < 2: + tokens = line.split(':', 1) + if len(tokens) < 2: continue - field = tokens[0].strip () - value = tokens[1].strip () + field = tokens[0].strip() + value = tokens[1].strip() if field == 'ChangelogURI': self.changelogs_uri = _(value) elif field == 'MetaReleaseURI': @@ -251,7 +251,7 @@ class DistInfo: template = None if __name__ == "__main__": - d = DistInfo ("Ubuntu", "/usr/share/python-apt/templates") + d = DistInfo("Ubuntu", "/usr/share/python-apt/templates") print d.changelogs_uri for template in d.templates: print "\nSuite: %s" % template.name diff --git a/aptsources/distro.py b/aptsources/distro.py index 962c57bc..f39f6748 100644 --- a/aptsources/distro.py +++ b/aptsources/distro.py @@ -108,7 +108,7 @@ class Distribution: elif source.uri.startswith("cdrom:") and \ source.disabled == True: self.cdrom_sources.append(source) - elif source.type == self.binary_type and \ + elif source.type == self.binary_type and \ source.disabled == False: self.main_sources.append(source) comps.extend(source.comps) diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index 57be2a68..dfc0ccb6 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -78,7 +78,7 @@ def uniq(s): class SourceEntry: """ single sources.list entry """ - def __init__(self, line,file=None): + def __init__(self, line, file=None): self.invalid = False # is the source entry valid self.disabled = False # is it disabled ('#' in front) self.type = "" # what type (deb, deb-src) @@ -131,10 +131,10 @@ class SourceEntry: pieces.append(tmp) return pieces - def parse(self,line): + def parse(self, line): """ parse a given sources.list (textual) line and break it up into the field we have """ - line = string.strip(self.line) + line = string.strip(self.line) #print line # check if the source is enabled/disabled if line == "" or line == "#": # empty line @@ -295,11 +295,11 @@ class SourcesList: source.disabled = False return source # there isn't any matching source, so create a new line and parse it - line = "%s %s %s" % (type,uri,dist) + line = "%s %s %s" % (type, uri, dist) for c in comps: line = line + " " + c; if comment != "": - line = "%s #%s\n" %(line,comment) + line = "%s #%s\n" % (line, comment) line = line + "\n" new_entry = SourceEntry(line) if file != None: @@ -317,13 +317,13 @@ class SourcesList: dir = apt_pkg.Config.FindDir("Dir::Etc") file = apt_pkg.Config.Find("Dir::Etc::sourcelist") if os.path.exists(dir+file+backup_ext) and \ - os.path.exists(dir+file): - shutil.copy(dir+file+backup_ext,dir+file) + os.path.exists(dir+file): + shutil.copy(dir+file+backup_ext, dir+file) # now sources.list.d partsdir = apt_pkg.Config.FindDir("Dir::Etc::sourceparts") for file in glob.glob("%s/*.list" % partsdir): if os.path.exists(file+backup_ext): - shutil.copy(file+backup_ext,file) + shutil.copy(file+backup_ext, file) def backup(self, backup_ext=None): """ make a backup of the current source files, if no backup extension @@ -333,16 +333,16 @@ class SourcesList: backup_ext = time.strftime("%y%m%d.%H%M") for source in self.list: if not source.file in already_backuped and os.path.exists(source.file): - shutil.copy(source.file,"%s%s" % (source.file,backup_ext)) + shutil.copy(source.file, "%s%s" % (source.file, backup_ext)) return backup_ext - def load(self,file): + def load(self, file): """ (re)load the current sources """ try: f = open(file, "r") lines = f.readlines() for line in lines: - source = SourceEntry(line,file) + source = SourceEntry(line, file) self.list.append(source) except: print "could not open file '%s'" % file @@ -359,11 +359,11 @@ class SourcesList: header = ("## See sources.list(5) for more information, especialy\n" "# Remember that you can only use http, ftp or file URIs\n" "# CDROMs are managed through the apt-cdrom tool.\n") - open(path,"w").write(header) + open(path, "w").write(header) return for source in self.list: if not files.has_key(source.file): - files[source.file]=open(source.file,"w") + files[source.file] = open(source.file, "w") files[source.file].write(source.str()) for f in files: files[f].close() @@ -406,7 +406,7 @@ class SourceEntryMatcher: f = os.path.basename(f) i = f.find(".info") f = f[0:i] - dist = DistInfo(f,base_dir=matcherPath) + dist = DistInfo(f, base_dir=matcherPath) for template in dist.templates: if template.match_uri != None: self.templates.append(template) diff --git a/doc/examples/acquire.py b/doc/examples/acquire.py index 7bf7d646..e42a9401 100644 --- a/doc/examples/acquire.py +++ b/doc/examples/acquire.py @@ -20,7 +20,7 @@ def get_file(fetcher, uri, destFile): os.chdir(cwd) return False filename = os.path.basename(uri) - os.rename(dir+"/"+filename,destFile) + os.rename(dir+"/"+filename, destFile) # cleanup os.rmdir(dir) os.chdir(cwd) @@ -44,7 +44,7 @@ depcache.Upgrade(True) progress = apt.progress.TextFetchProgress() fetcher = apt_pkg.GetAcquire(progress) pm = apt_pkg.GetPackageManager(depcache) -pm.GetArchives(fetcher,list,recs) +pm.GetArchives(fetcher, list, recs) print "%s (%s)" % (apt_pkg.SizeToStr(fetcher.FetchNeeded), fetcher.FetchNeeded) actiongroup = apt_pkg.GetPkgActionGroup(depcache) for pkg in cache.Packages: @@ -55,7 +55,7 @@ try: os.mkdir("/tmp/pyapt-test/partial") except OSError: pass -apt_pkg.Config.Set("Dir::Cache::archives","/tmp/pyapt-test") +apt_pkg.Config.Set("Dir::Cache::archives", "/tmp/pyapt-test") pkg = cache["3ddesktop"] depcache.MarkInstall(pkg) @@ -70,7 +70,7 @@ print fetcher get_file(fetcher, "ftp://ftp.debian.org/debian/dists/README", "/tmp/lala") -pm.GetArchives(fetcher,list,recs) +pm.GetArchives(fetcher, list, recs) for item in fetcher.Items: print item diff --git a/doc/examples/all_deps.py b/doc/examples/all_deps.py index f4f1741c..37222463 100644 --- a/doc/examples/all_deps.py +++ b/doc/examples/all_deps.py @@ -26,9 +26,9 @@ pkg = c[pkgname] deps = set() -deps = dependencies(c,pkg, deps, "Depends") +deps = dependencies(c, pkg, deps, "Depends") print " ".join(deps) preDeps = set() -preDeps = dependencies(c,pkg, preDeps, "PreDepends") +preDeps = dependencies(c, pkg, preDeps, "PreDepends") print " ".join(preDeps) diff --git a/doc/examples/cdrom.py b/doc/examples/cdrom.py index e54eb763..289b10f1 100644 --- a/doc/examples/cdrom.py +++ b/doc/examples/cdrom.py @@ -16,7 +16,7 @@ print cdrom progress = CdromProgress() -(res,ident) = cdrom.Ident(progress) +(res, ident) = cdrom.Ident(progress) print "ident result is: %s (%s) " % (res, ident) apt_pkg.Config.Set("APT::CDROM::Rename", "True") diff --git a/doc/examples/config.py b/doc/examples/config.py index 337899f0..cd7bcae0 100755 --- a/doc/examples/config.py +++ b/doc/examples/config.py @@ -12,7 +12,7 @@ # This shows how to use the system for configuration and option control. # The other varient is for ISC object config files. See configisc.py. -import apt_pkg,sys,posixpath; +import apt_pkg, sys, posixpath # Create a new empty Configuration object - there is also the system global # configuration object apt_pkg.Config which is used interally by apt-pkg @@ -20,30 +20,30 @@ import apt_pkg,sys,posixpath; # whenever possible.. Cnf = apt_pkg.newConfiguration(); -print "Command line is",sys.argv +print "Command line is", sys.argv # Load the default configuration file, InitConfig() does this better.. -Cnf.Set("config-file","/etc/apt/apt.conf"); # or Cnf["config-file"] = ".."; +Cnf.Set("config-file", "/etc/apt/apt.conf") # or Cnf["config-file"] = ".." if posixpath.exists(Cnf.FindFile("config-file")): - apt_pkg.ReadConfigFile(Cnf,"/etc/apt/apt.conf"); + apt_pkg.ReadConfigFile(Cnf, "/etc/apt/apt.conf") # Merge the command line arguments into the configuration space -Arguments = [('h',"help","help"), - ('v',"version","version"), - ('q',"quiet","quiet","IntLevel"), - ('c',"config-file","","ConfigFile"), - ('o',"option","","ArbItem")] -print "FileNames",apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv); +Arguments = [('h', "help", "help"), + ('v', "version", "version"), + ('q', "quiet", "quiet", "IntLevel"), + ('c', "config-file", "", "ConfigFile"), + ('o', "option", "", "ArbItem")] +print "FileNames", apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv) -print "Quiet level selected is",Cnf.FindI("quiet",0); +print "Quiet level selected is", Cnf.FindI("quiet", 0) # Do some stuff with it -if Cnf.FindB("version",0) == 1: +if Cnf.FindB("version", 0) == 1: print "Version selected - 1.1"; -if Cnf.FindB("help",0) == 1: - print apt_pkg.Package,apt_pkg.Version,"for",apt_pkg.Architecture, \ - "compiled on",apt_pkg.Date,apt_pkg.Time; +if Cnf.FindB("help", 0) == 1: + print apt_pkg.Package, apt_pkg.Version, "for", apt_pkg.Architecture, \ + "compiled on", apt_pkg.Date, apt_pkg.Time print "Hi, I am the help text for this program"; sys.exit(0); @@ -52,4 +52,4 @@ print "No help for you, try -h"; # Print the configuration space print "The Configuration space looks like:"; for I in Cnf.keys(): - print "%s \"%s\";"%(I,Cnf[I]); + print "%s \"%s\";" % (I, Cnf[I]) diff --git a/doc/examples/configisc.py b/doc/examples/configisc.py index 45a9c7f6..4d0d33d4 100755 --- a/doc/examples/configisc.py +++ b/doc/examples/configisc.py @@ -8,32 +8,32 @@ # doc/examples/ftp-archive.conf # or a bind8 config file.. -import apt_pkg,sys,posixpath; +import apt_pkg, sys, posixpath -ConfigFile = apt_pkg.ParseCommandLine(apt_pkg.Config,[],sys.argv); +ConfigFile = apt_pkg.ParseCommandLine(apt_pkg.Config, [], sys.argv) if len(ConfigFile) != 1: print "Must have exactly 1 file name"; sys.exit(0); Cnf = apt_pkg.newConfiguration(); -apt_pkg.ReadConfigFileISC(Cnf,ConfigFile[0]); +apt_pkg.ReadConfigFileISC(Cnf, ConfigFile[0]) # Print the configuration space #print "The Configuration space looks like:"; #for I in Cnf.keys(): -# print "%s \"%s\";"%(I,Cnf[I]); +# print "%s \"%s\";" % (I, Cnf[I]) # bind8 config file.. if Cnf.has_key("Zone"): - print "Zones: ",Cnf.SubTree("zone").List(); + print "Zones: ", Cnf.SubTree("zone").List() for I in Cnf.List("zone"): SubCnf = Cnf.SubTree(I); if SubCnf.Find("type") == "slave": - print "Masters for %s: %s"%(SubCnf.MyTag(),SubCnf.ValueList("masters")); + print "Masters for %s: %s" % (SubCnf.MyTag(), SubCnf.ValueList("masters")) else: print "Tree definitions:"; for I in Cnf.List("tree"): SubCnf = Cnf.SubTree(I); # This could use Find which would eliminate the possibility of exceptions. - print "Subtree %s with sections '%s' and architectures '%s'"%(SubCnf.MyTag(),SubCnf["Sections"],SubCnf["Architectures"]); + print "Subtree %s with sections '%s' and architectures '%s'" % (SubCnf.MyTag(), SubCnf["Sections"], SubCnf["Architectures"]) diff --git a/doc/examples/deb_inspect.py b/doc/examples/deb_inspect.py index 68219d6d..f3e5ae2b 100755 --- a/doc/examples/deb_inspect.py +++ b/doc/examples/deb_inspect.py @@ -7,11 +7,11 @@ import sys import os.path -def Callback(What,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor): +def Callback(What, Name, Link, Mode, UID, GID, Size, MTime, Major, Minor): """ callback for debExtract """ - print "%s '%s','%s',%u,%u,%u,%u,%u,%u,%u"\ - % (What,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor); + print "%s '%s','%s',%u,%u,%u,%u,%u,%u,%u" \ + % (What, Name, Link, Mode, UID, GID, Size, MTime, Major, Minor) if __name__ == "__main__": @@ -40,7 +40,7 @@ if __name__ == "__main__": print "extracting archive" dir = "/tmp/deb" os.mkdir(dir) - apt_inst.debExtractArchive(open(file),dir) + apt_inst.debExtractArchive(open(file), dir) def visit(arg, dirname, names): print "%s/" % dirname diff --git a/doc/examples/desc.py b/doc/examples/desc.py index 1d43f2f9..f47517cf 100644 --- a/doc/examples/desc.py +++ b/doc/examples/desc.py @@ -3,7 +3,7 @@ import apt_pkg apt_pkg.init() -apt_pkg.Config.Set("APT::Acquire::Translation","de") +apt_pkg.Config.Set("APT::Acquire::Translation", "de") cache = apt_pkg.GetCache() depcache = apt_pkg.GetDepCache(cache) @@ -15,10 +15,10 @@ print cand desc = cand.TranslatedDescription print desc print desc.FileList -(f,index) = desc.FileList.pop(0) +(f, index) = desc.FileList.pop(0) records = apt_pkg.GetPkgRecords(cache) -records.Lookup((f,index)) +records.Lookup((f, index)) desc = records.LongDesc print len(desc) print desc diff --git a/doc/examples/gui-inst.py b/doc/examples/gui-inst.py index edaec455..61db63f8 100755 --- a/doc/examples/gui-inst.py +++ b/doc/examples/gui-inst.py @@ -32,7 +32,7 @@ class GuiFetchProgress(gtk.Window, FetchProgress): self.label.show() self.vbox.pack_start(self.progress) self.vbox.pack_start(self.label) - self.resize(300,100) + self.resize(300, 100) def start(self): print "start" @@ -64,15 +64,15 @@ class TermInstallProgress(InstallProgress, gtk.Window): self.term.show() # check for the child self.reaper = vte.reaper_get() - self.reaper.connect("child-exited",self.child_exited) + self.reaper.connect("child-exited", self.child_exited) self.finished = False box.pack_start(self.term) self.progressbar = gtk.ProgressBar() self.progressbar.show() box.pack_start(self.progressbar) - def child_exited(self,term, pid, status): - print "child_exited: %s %s %s %s" % (self,term,pid,status) + def child_exited(self, term, pid, status): + print "child_exited: %s %s %s %s" % (self, term, pid, status) self.apt_status = posix.WEXITSTATUS(status) self.finished = True diff --git a/doc/examples/indexfile.py b/doc/examples/indexfile.py index d383fd61..22d0b635 100644 --- a/doc/examples/indexfile.py +++ b/doc/examples/indexfile.py @@ -10,7 +10,7 @@ cache = apt_pkg.GetCache() depcache = apt_pkg.GetDepCache(cache) pkg = cache["libimlib2"] cand = depcache.GetCandidateVer(pkg) -for (f,i) in cand.FileList: +for (f, i) in cand.FileList: index = sources.FindIndex(f) print index if index: diff --git a/doc/examples/inst.py b/doc/examples/inst.py index b37ab4cd..723038c1 100644 --- a/doc/examples/inst.py +++ b/doc/examples/inst.py @@ -23,8 +23,8 @@ class TextInstallProgress(InstallProgress): sys.stdout.flush() self.last = self.percent - def conffile(self,current,new): - print "conffile prompt: %s %s" % (current,new) + def conffile(self, current, new): + print "conffile prompt: %s %s" % (current, new) def error(self, errorstr): print "got dpkg error: '%s'" % errorstr diff --git a/doc/examples/metaindex.py b/doc/examples/metaindex.py index 1bce0dba..f00a7e01 100644 --- a/doc/examples/metaindex.py +++ b/doc/examples/metaindex.py @@ -9,7 +9,7 @@ sources.ReadMainList() for metaindex in sources.List: print metaindex - print "URI: ",metaindex.URI - print "Dist: ",metaindex.Dist - print "IndexFiles: ","\n".join([str(i) for i in metaindex.IndexFiles]) + print "URI: ", metaindex.URI + print "Dist: ", metaindex.Dist + print "IndexFiles: ", "\n".join([str(i) for i in metaindex.IndexFiles]) print diff --git a/doc/examples/print_uris.py b/doc/examples/print_uris.py index 3c93a668..3b678e83 100755 --- a/doc/examples/print_uris.py +++ b/doc/examples/print_uris.py @@ -15,7 +15,7 @@ for pkg in upgradable: pkg._lookupRecord(True) path = apt_pkg.ParseSection(pkg._records.Record)["Filename"] cand = pkg._depcache.GetCandidateVer(pkg._pkg) - for (packagefile,i) in cand.FileList: + for (packagefile, i) in cand.FileList: indexfile = cache._list.FindIndex(packagefile) if indexfile: uri = indexfile.ArchiveURI(path) diff --git a/doc/examples/progress.py b/doc/examples/progress.py index d8f00a52..70fc92f3 100644 --- a/doc/examples/progress.py +++ b/doc/examples/progress.py @@ -34,7 +34,7 @@ class TextFetchProgress(apt.FetchProgress): pass def updateStatus(self, uri, descr, shortDescr, status): - print "UpdateStatus: '%s' '%s' '%s' '%i'" % (uri,descr,shortDescr, status) + print "UpdateStatus: '%s' '%s' '%s' '%i'" % (uri, descr, shortDescr, status) def pulse(self): print "Pulse: CPS: %s/s; Bytes: %s/%s; Item: %s/%s" % (SizeToStr(self.currentCPS), SizeToStr(self.currentBytes), SizeToStr(self.totalBytes), self.currentItems, self.totalItems) @@ -86,7 +86,7 @@ class TextCdromProgress(apt.CdromProgress): def changeCdrom(self): print "Please insert cdrom and press " - answer = sys.stdin.readline() + answer = sys.stdin.readline() return True diff --git a/doc/examples/tagfile.py b/doc/examples/tagfile.py index aeba34d2..4faf08ac 100755 --- a/doc/examples/tagfile.py +++ b/doc/examples/tagfile.py @@ -1,8 +1,8 @@ #!/usr/bin/env python import apt_pkg -Parse = apt_pkg.ParseTagFile(open("/var/lib/dpkg/status","r")); +Parse = apt_pkg.ParseTagFile(open("/var/lib/dpkg/status", "r")) while Parse.Step() == 1: - print Parse.Section.get("Package"); - print apt_pkg.ParseDepends(Parse.Section.get("Depends","")); + print Parse.Section.get("Package") + print apt_pkg.ParseDepends(Parse.Section.get("Depends", "")) diff --git a/doc/examples/update.py b/doc/examples/update.py index be7bb679..364fa1c9 100755 --- a/doc/examples/update.py +++ b/doc/examples/update.py @@ -9,5 +9,5 @@ if __name__ == "__main__": "touch /tmp/update-was-run") c = apt.Cache() res = c.update(apt.progress.TextFetchProgress()) - print "res: ",res + print "res: ", res assert(os.path.exists("/tmp/update-about-to-run")) diff --git a/doc/examples/versiontest.py b/doc/examples/versiontest.py index 8f18f6c8..29da3b8f 100755 --- a/doc/examples/versiontest.py +++ b/doc/examples/versiontest.py @@ -1,17 +1,17 @@ #!/usr/bin/python # This is a simple clone of tests/versiontest.cc -import apt_pkg,sys,re,string; +import apt_pkg, sys, re, string apt_pkg.InitConfig(); apt_pkg.InitSystem(); -TestFile = apt_pkg.ParseCommandLine(apt_pkg.Config,[],sys.argv); +TestFile = apt_pkg.ParseCommandLine(apt_pkg.Config, [], sys.argv) if len(TestFile) != 1: print "Must have exactly 1 file name"; sys.exit(0); # Go over the file.. -List = open(TestFile[0],"r"); +List = open(TestFile[0], "r") CurLine = 0; while(1): Line = List.readline(); @@ -22,15 +22,15 @@ while(1): if len(Line) == 0 or Line[0] == '#': continue; - Split = re.split("[ \n]",Line); + Split = re.split("[ \n]", Line) # Check forward - if apt_pkg.VersionCompare(Split[0],Split[1]) != int(Split[2]): - print "Comparision failed on line %u. '%s' ? '%s' %i != %i"%(CurLine, - Split[0],Split[1],apt_pkg.VersionCompare(Split[0],Split[1]), - int(Split[2])); + if apt_pkg.VersionCompare(Split[0], Split[1]) != int(Split[2]): + print "Comparision failed on line %u. '%s' ? '%s' %i != %i" % (CurLine, + Split[0], Split[1], apt_pkg.VersionCompare(Split[0], Split[1]), + int(Split[2])) # Check reverse - if apt_pkg.VersionCompare(Split[1],Split[0]) != -1*int(Split[2]): - print "Comparision failed on line %u. '%s' ? '%s' %i != %i"%(CurLine, - Split[1],Split[0],apt_pkg.VersionCompare(Split[1],Split[0]), - -1*int(Split[2])); + if apt_pkg.VersionCompare(Split[1], Split[0]) != -1 * int(Split[2]): + print "Comparision failed on line %u. '%s' ? '%s' %i != %i" % (CurLine, + Split[1], Split[0], apt_pkg.VersionCompare(Split[1], Split[0]), + -1 * int(Split[2])) diff --git a/setup.py b/setup.py index 72fada77..2c11d9d3 100755 --- a/setup.py +++ b/setup.py @@ -14,7 +14,7 @@ apt_pkg = Extension("apt_pkg", files, libraries=["apt-pkg"]); # The apt_inst module files = map(lambda source: "python/"+source, string.split(parse_makefile("python/makefile")["APT_INST_SRC"])) -apt_inst = Extension("apt_inst", files, libraries=["apt-pkg","apt-inst"]); +apt_inst = Extension("apt_inst", files, libraries=["apt-pkg", "apt-inst"]); # Replace the leading _ that is used in the templates for translation templates = [] @@ -29,19 +29,20 @@ for template in glob.glob('data/templates/*.info.in'): source.close() build.close() -setup(name="python-apt", - version="0.6.17", - description="Python bindings for APT", - author="APT Development Team", - author_email="deity@lists.debian.org", - ext_modules=[apt_pkg,apt_inst], - packages=['apt', 'aptsources'], - data_files = [('share/python-apt/templates', - glob.glob('build/data/templates/*.info')), - ('share/python-apt/templates', - glob.glob('data/templates/*.mirrors'))], - cmdclass = { "build" : build_extra.build_extra, - "build_i18n" : build_i18n.build_i18n }, - license = 'GNU GPL', - platforms = 'posix' - ) +setup( + name="python-apt", + version="0.6.17", + description="Python bindings for APT", + author="APT Development Team", + author_email="deity@lists.debian.org", + ext_modules=[apt_pkg, apt_inst], + packages=['apt', 'aptsources'], + data_files=[('share/python-apt/templates', + glob.glob('build/data/templates/*.info')), + ('share/python-apt/templates', + glob.glob('data/templates/*.mirrors'))], + cmdclass={"build": build_extra.build_extra, + "build_i18n": build_i18n.build_i18n}, + license='GNU GPL', + platforms='posix', + ) diff --git a/tests/apt-test.py b/tests/apt-test.py index 6205cf60..fac2ff43 100644 --- a/tests/apt-test.py +++ b/tests/apt-test.py @@ -20,7 +20,7 @@ if __name__ == "__main__": cache = apt.Cache(progress) for name in cache.keys(): import random - if random.randint(0,1) == 1: + if random.randint(0, 1) == 1: cache[name].markDelete() print "Broken: %s " % cache._depcache.BrokenCount print "DelCount: %s " % cache._depcache.DelCount diff --git a/tests/cache.py b/tests/cache.py index 24732578..4e79eb3e 100644 --- a/tests/cache.py +++ b/tests/cache.py @@ -43,7 +43,7 @@ def main(): j = ver.DependsList pass - print "\r%i/%i=%.3f%% " % (i,all,(float(i)/float(all)*100)), + print "\r%i/%i=%.3f%% " % (i, all, (float(i) / float(all) * 100)), if __name__ == "__main__": diff --git a/tests/depcache.py b/tests/depcache.py index 32c510f0..5ed54895 100644 --- a/tests/depcache.py +++ b/tests/depcache.py @@ -31,8 +31,8 @@ def main(): if depcache.MarkedInstall(p): depcache.MarkKeep(p) if depcache.InstCount != 0: - print "Error undoing the selection for %s (InstCount: %s)" % (x,depcache.InstCount) - print "\r%i/%i=%.3f%% " % (i,all,(float(i)/float(all)*100)), + print "Error undoing the selection for %s (InstCount: %s)" % (x, depcache.InstCount) + print "\r%i/%i=%.3f%% " % (i, all, (float(i) / float(all) * 100)), print print "Trying Upgrade:" diff --git a/tests/lock.py b/tests/lock.py index aeab804b..8bd5619f 100644 --- a/tests/lock.py +++ b/tests/lock.py @@ -26,14 +26,14 @@ if __name__ == "__main__": apt_pkg.PkgSystemUnLock() # low-level lock - fd = apt_pkg.GetLock(lock,True) + fd = apt_pkg.GetLock(lock, True) print "Lockfile fd: %s" % fd # try to get lock without error flag pid = os.fork() if pid == 0: # child - fd = apt_pkg.GetLock(lock,False) + fd = apt_pkg.GetLock(lock, False) print "Lockfile fd (child): %s" % fd sys.exit(0) @@ -41,6 +41,6 @@ if __name__ == "__main__": pid = os.fork() if pid == 0: # child - fd = apt_pkg.GetLock(lock,True) + fd = apt_pkg.GetLock(lock, True) print "Lockfile fd (child): %s" % fd sys.exit(0) diff --git a/tests/memleak.py b/tests/memleak.py index 6eece9d4..659091fc 100755 --- a/tests/memleak.py +++ b/tests/memleak.py @@ -15,7 +15,7 @@ for i in range(100): print cache["apt"].name time.sleep(1) gc.collect() - f = open("%s" % i,"w") + f = open("%s" % i, "w") for obj in gc.get_objects(): f.write("%s\n" % str(obj)) f.close() @@ -37,7 +37,7 @@ for i in range(100): dict = {} for pkg in cache.Packages: if len(pkg.VersionList) > 0: - dict[pkg.Name] = apt.Package(cache,depcache, + dict[pkg.Name] = apt.Package(cache, depcache, records, list, None, pkg) print cache["apt"] diff --git a/tests/pkgproblemresolver.py b/tests/pkgproblemresolver.py index 82186d40..7d5ae682 100644 --- a/tests/pkgproblemresolver.py +++ b/tests/pkgproblemresolver.py @@ -49,7 +49,7 @@ def main(): depcache.MarkKeep(p) if depcache.InstCount != 0: print "Error undoing the selection for %s" % x - print "\r%i/%i=%.3f%% " % (i,all,(float(i)/float(all)*100)), + print "\r%i/%i=%.3f%% " % (i, all, (float(i) / float(all) * 100)), print print "Trying Upgrade:" diff --git a/tests/pkgrecords.py b/tests/pkgrecords.py index 72096463..e128237b 100644 --- a/tests/pkgrecords.py +++ b/tests/pkgrecords.py @@ -25,12 +25,12 @@ def main(): if not version: continue file, index = version.FileList.pop(0) - if records.Lookup((file,index)): + if records.Lookup((file, index)): #print records.FileName x = records.FileName y = records.LongDesc pass - print "\r%i/%i=%.3f%% " % (i,cache.PackageCount, (float(i)/float(cache.PackageCount)*100)), + print "\r%i/%i=%.3f%% " % (i, cache.PackageCount, (float(i) / float(cache.PackageCount) * 100)), if __name__ == "__main__": diff --git a/tests/pkgsrcrecords.py b/tests/pkgsrcrecords.py index 3eb0fcab..6e78858b 100644 --- a/tests/pkgsrcrecords.py +++ b/tests/pkgsrcrecords.py @@ -19,7 +19,7 @@ def main(): if src.Lookup(x.Name): #print src.Package pass - print "\r%i/%i=%.3f%% " % (i,cache.PackageCount, (float(i)/float(cache.PackageCount)*100)), + print "\r%i/%i=%.3f%% " % (i, cache.PackageCount, (float(i) / float(cache.PackageCount) * 100)), if __name__ == "__main__": diff --git a/tests/refcount.py b/tests/refcount.py index f3230bd3..a29744ae 100755 --- a/tests/refcount.py +++ b/tests/refcount.py @@ -1,6 +1,6 @@ #!/usr/bin/python-dbg -from pprint import pprint,pformat +from pprint import pprint, pformat import apt import sys import gc diff --git a/tests/test_aptsources.py b/tests/test_aptsources.py index 08c8194a..9019aa2d 100644 --- a/tests/test_aptsources.py +++ b/tests/test_aptsources.py @@ -13,7 +13,7 @@ class TestAptSources(unittest.TestCase): unittest.TestCase.__init__(self, methodName) apt_pkg.init() apt_pkg.Config.Set("Dir::Etc", os.getcwd()) - apt_pkg.Config.Set("Dir::Etc::sourceparts",".") + apt_pkg.Config.Set("Dir::Etc::sourceparts", ".") def testIsMirror(self): self.assertTrue(aptsources.is_mirror("http://archive.ubuntu.com", @@ -22,7 +22,7 @@ class TestAptSources(unittest.TestCase): "http://ftp.debian.org")) def testSourcesListReading(self): - apt_pkg.Config.Set("Dir::Etc::sourcelist","data/sources.list") + apt_pkg.Config.Set("Dir::Etc::sourcelist", "data/sources.list") sources = aptsources.SourcesList() self.assertEqual(len(sources.list), 6) # test load @@ -31,22 +31,22 @@ class TestAptSources(unittest.TestCase): self.assertEqual(len(sources.list), 6) def testSourcesListAdding(self): - apt_pkg.Config.Set("Dir::Etc::sourcelist","data/sources.list") + apt_pkg.Config.Set("Dir::Etc::sourcelist", "data/sources.list") sources = aptsources.SourcesList() # test to add something that is already there (main) before = copy.deepcopy(sources) - sources.add("deb","http://de.archive.ubuntu.com/ubuntu/", + sources.add("deb", "http://de.archive.ubuntu.com/ubuntu/", "edgy", ["main"]) self.assertTrue(sources.list == before.list) # test to add something that is already there (restricted) before = copy.deepcopy(sources) - sources.add("deb","http://de.archive.ubuntu.com/ubuntu/", + sources.add("deb", "http://de.archive.ubuntu.com/ubuntu/", "edgy", ["restricted"]) self.assertTrue(sources.list == before.list) # test to add something new: multiverse - sources.add("deb","http://de.archive.ubuntu.com/ubuntu/", + sources.add("deb", "http://de.archive.ubuntu.com/ubuntu/", "edgy", ["multiverse"]) found = False @@ -60,7 +60,7 @@ class TestAptSources(unittest.TestCase): # test to add something new: multiverse *and* # something that is already there before = copy.deepcopy(sources) - sources.add("deb","http://de.archive.ubuntu.com/ubuntu/", + sources.add("deb", "http://de.archive.ubuntu.com/ubuntu/", "edgy", ["universe", "something"]) found_universe = 0 @@ -79,7 +79,7 @@ class TestAptSources(unittest.TestCase): self.assertEqual(found_universe, 1) def testDistribution(self): - apt_pkg.Config.Set("Dir::Etc::sourcelist","data/sources.list.testDistribution") + apt_pkg.Config.Set("Dir::Etc::sourcelist", "data/sources.list.testDistribution") sources = aptsources.SourcesList() distro = aptsources.Distribution() distro.get_sources(sources) @@ -89,7 +89,7 @@ class TestAptSources(unittest.TestCase): if s.template: dist_templates.add(s.template.name) #print dist_templates - for d in ["edgy","edgy-security","edgy-updates","hoary","breezy", "breezy-backports"]: + for d in ["edgy", "edgy-security", "edgy-updates", "hoary", "breezy", "breezy-backports"]: self.assertTrue(d in dist_templates) # test enable comp = "restricted" -- cgit v1.2.3 From 04dfb70356fc46a1b4e75f3370a4d64b5cc2d9b4 Mon Sep 17 00:00:00 2001 From: Ben Finney Date: Fri, 16 May 2008 19:27:02 +1000 Subject: Remove redundant semicolons from statements. --- apt/progress.py | 4 ++-- aptsources/sourceslist.py | 2 +- doc/examples/config.py | 12 ++++++------ doc/examples/configisc.py | 14 +++++++------- doc/examples/versiontest.py | 20 ++++++++++---------- setup.py | 4 ++-- 6 files changed, 28 insertions(+), 28 deletions(-) (limited to 'apt') diff --git a/apt/progress.py b/apt/progress.py index dbad8050..1f2d4e7c 100644 --- a/apt/progress.py +++ b/apt/progress.py @@ -132,12 +132,12 @@ class TextFetchProgress(FetchProgress): def mediaChange(self, medium, drive): """ react to media change events """ - res = True; + res = True print "Media change: please insert the disc labeled \ '%s' in the drive '%s' and press enter" % (medium, drive) s = sys.stdin.readline() if(s == 'c' or s == 'C'): - res = false; + res = false return res diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index dfc0ccb6..6eb69f6e 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -297,7 +297,7 @@ class SourcesList: # there isn't any matching source, so create a new line and parse it line = "%s %s %s" % (type, uri, dist) for c in comps: - line = line + " " + c; + line = line + " " + c if comment != "": line = "%s #%s\n" % (line, comment) line = line + "\n" diff --git a/doc/examples/config.py b/doc/examples/config.py index cd7bcae0..3a77301b 100755 --- a/doc/examples/config.py +++ b/doc/examples/config.py @@ -18,7 +18,7 @@ import apt_pkg, sys, posixpath # configuration object apt_pkg.Config which is used interally by apt-pkg # routines to control unusual situations. I recommend using the sytem global # whenever possible.. -Cnf = apt_pkg.newConfiguration(); +Cnf = apt_pkg.newConfiguration() print "Command line is", sys.argv @@ -39,17 +39,17 @@ print "Quiet level selected is", Cnf.FindI("quiet", 0) # Do some stuff with it if Cnf.FindB("version", 0) == 1: - print "Version selected - 1.1"; + print "Version selected - 1.1" if Cnf.FindB("help", 0) == 1: print apt_pkg.Package, apt_pkg.Version, "for", apt_pkg.Architecture, \ "compiled on", apt_pkg.Date, apt_pkg.Time - print "Hi, I am the help text for this program"; - sys.exit(0); + print "Hi, I am the help text for this program" + sys.exit(0) -print "No help for you, try -h"; +print "No help for you, try -h" # Print the configuration space -print "The Configuration space looks like:"; +print "The Configuration space looks like:" for I in Cnf.keys(): print "%s \"%s\";" % (I, Cnf[I]) diff --git a/doc/examples/configisc.py b/doc/examples/configisc.py index 4d0d33d4..9a858657 100755 --- a/doc/examples/configisc.py +++ b/doc/examples/configisc.py @@ -13,14 +13,14 @@ import apt_pkg, sys, posixpath ConfigFile = apt_pkg.ParseCommandLine(apt_pkg.Config, [], sys.argv) if len(ConfigFile) != 1: - print "Must have exactly 1 file name"; - sys.exit(0); + print "Must have exactly 1 file name" + sys.exit(0) -Cnf = apt_pkg.newConfiguration(); +Cnf = apt_pkg.newConfiguration() apt_pkg.ReadConfigFileISC(Cnf, ConfigFile[0]) # Print the configuration space -#print "The Configuration space looks like:"; +#print "The Configuration space looks like:" #for I in Cnf.keys(): # print "%s \"%s\";" % (I, Cnf[I]) @@ -28,12 +28,12 @@ apt_pkg.ReadConfigFileISC(Cnf, ConfigFile[0]) if Cnf.has_key("Zone"): print "Zones: ", Cnf.SubTree("zone").List() for I in Cnf.List("zone"): - SubCnf = Cnf.SubTree(I); + SubCnf = Cnf.SubTree(I) if SubCnf.Find("type") == "slave": print "Masters for %s: %s" % (SubCnf.MyTag(), SubCnf.ValueList("masters")) else: - print "Tree definitions:"; + print "Tree definitions:" for I in Cnf.List("tree"): - SubCnf = Cnf.SubTree(I); + SubCnf = Cnf.SubTree(I) # This could use Find which would eliminate the possibility of exceptions. print "Subtree %s with sections '%s' and architectures '%s'" % (SubCnf.MyTag(), SubCnf["Sections"], SubCnf["Architectures"]) diff --git a/doc/examples/versiontest.py b/doc/examples/versiontest.py index 29da3b8f..732eafac 100755 --- a/doc/examples/versiontest.py +++ b/doc/examples/versiontest.py @@ -2,25 +2,25 @@ # This is a simple clone of tests/versiontest.cc import apt_pkg, sys, re, string -apt_pkg.InitConfig(); -apt_pkg.InitSystem(); +apt_pkg.InitConfig() +apt_pkg.InitSystem() TestFile = apt_pkg.ParseCommandLine(apt_pkg.Config, [], sys.argv) if len(TestFile) != 1: - print "Must have exactly 1 file name"; - sys.exit(0); + print "Must have exactly 1 file name" + sys.exit(0) # Go over the file.. List = open(TestFile[0], "r") -CurLine = 0; +CurLine = 0 while(1): - Line = List.readline(); - CurLine = CurLine + 1; + Line = List.readline() + CurLine = CurLine + 1 if Line == "": - break; - Line = string.strip(Line); + break + Line = string.strip(Line) if len(Line) == 0 or Line[0] == '#': - continue; + continue Split = re.split("[ \n]", Line) diff --git a/setup.py b/setup.py index 2c11d9d3..eef54773 100755 --- a/setup.py +++ b/setup.py @@ -9,12 +9,12 @@ import glob, os, string # The apt_pkg module files = map(lambda source: "python/"+source, string.split(parse_makefile("python/makefile")["APT_PKG_SRC"])) -apt_pkg = Extension("apt_pkg", files, libraries=["apt-pkg"]); +apt_pkg = Extension("apt_pkg", files, libraries=["apt-pkg"]) # The apt_inst module files = map(lambda source: "python/"+source, string.split(parse_makefile("python/makefile")["APT_INST_SRC"])) -apt_inst = Extension("apt_inst", files, libraries=["apt-pkg", "apt-inst"]); +apt_inst = Extension("apt_inst", files, libraries=["apt-pkg", "apt-inst"]) # Replace the leading _ that is used in the templates for translation templates = [] -- cgit v1.2.3 From 97c3c24b3060e8280fffed68ed60a68e04f382ca Mon Sep 17 00:00:00 2001 From: Ben Finney Date: Fri, 16 May 2008 19:36:09 +1000 Subject: Statements on separate lines, to conform with PEP 8. --- apt/package.py | 3 ++- aptsources/distinfo.py | 3 ++- aptsources/distro.py | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) (limited to 'apt') diff --git a/apt/package.py b/apt/package.py index eef598af..51986874 100644 --- a/apt/package.py +++ b/apt/package.py @@ -28,7 +28,8 @@ import string import gettext -def _(s): return gettext.dgettext("python-apt", s) +def _(s): + return gettext.dgettext("python-apt", s) class BaseDependency(object): diff --git a/aptsources/distinfo.py b/aptsources/distinfo.py index 57266a49..ce90faac 100644 --- a/aptsources/distinfo.py +++ b/aptsources/distinfo.py @@ -34,7 +34,8 @@ import re import gettext -def _(s): return gettext.dgettext("python-apt", s) +def _(s): + return gettext.dgettext("python-apt", s) class Template: diff --git a/aptsources/distro.py b/aptsources/distro.py index f39f6748..888e6e06 100644 --- a/aptsources/distro.py +++ b/aptsources/distro.py @@ -30,7 +30,8 @@ import sys import gettext -def _(s): return gettext.dgettext("python-apt", s) +def _(s): + return gettext.dgettext("python-apt", s) class NoDistroTemplateException(Exception): -- cgit v1.2.3 From f264f62b7602f960bc35f3f68b1ed14c61bbfdd5 Mon Sep 17 00:00:00 2001 From: Ben Finney Date: Fri, 16 May 2008 20:12:36 +1000 Subject: Limit code lines to maximum 79 characters, to conform with PEP 8. --- apt/__init__.py | 3 +- apt/cache.py | 6 ++-- apt/debfile.py | 18 ++++++++---- apt/package.py | 16 ++++++++--- apt/progress.py | 71 ++++++++++++++++++++++++++--------------------- aptsources/distinfo.py | 10 +++++-- aptsources/distro.py | 33 ++++++++++++---------- aptsources/sourceslist.py | 26 ++++++++++------- doc/examples/action.py | 3 +- doc/examples/all_deps.py | 6 ++-- doc/examples/config.py | 3 +- doc/examples/configisc.py | 9 ++++-- doc/examples/depcache.py | 3 +- doc/examples/progress.py | 7 +++-- doc/examples/records.py | 3 +- doc/examples/sources.py | 3 +- tests/depcache.py | 3 +- tests/pkgrecords.py | 4 ++- tests/pkgsrcrecords.py | 4 ++- tests/test_aptsources.py | 7 +++-- 20 files changed, 149 insertions(+), 89 deletions(-) (limited to 'apt') diff --git a/apt/__init__.py b/apt/__init__.py index c6a2ff39..05407aff 100644 --- a/apt/__init__.py +++ b/apt/__init__.py @@ -6,7 +6,8 @@ import os # import some fancy classes from apt.package import Package from apt.cache import Cache -from apt.progress import OpProgress, FetchProgress, InstallProgress, CdromProgress +from apt.progress import ( + OpProgress, FetchProgress, InstallProgress, CdromProgress) from apt.cdrom import Cdrom from apt_pkg import SizeToStr, TimeToStr, VersionCompare diff --git a/apt/cache.py b/apt/cache.py index 3c3a25e5..a43bd5d7 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -51,7 +51,8 @@ class Cache(object): self._callbacks = {} if rootdir: apt_pkg.Config.Set("Dir", rootdir) - apt_pkg.Config.Set("Dir::State::status", rootdir + "/var/lib/dpkg/status") + apt_pkg.Config.Set( + "Dir::State::status", rootdir + "/var/lib/dpkg/status") self.open(progress) def _runCallbacks(self, name): @@ -153,7 +154,8 @@ class Cache(object): if item.StatIdle: transient = True continue - errMsg += "Failed to fetch %s %s\n" % (item.DescURI, item.ErrorText) + errMsg += "Failed to fetch %s %s\n" % ( + item.DescURI, item.ErrorText) failed = True # we raise a exception if the download failed or it was cancelt diff --git a/apt/debfile.py b/apt/debfile.py index 1a64b833..ca82bbdb 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -22,7 +22,9 @@ class DebPackage(object): " open given debfile " self.filename = filename if not arCheckMember(open(self.filename), "debian-binary"): - raise NoDebArchiveException, _("This is not a valid DEB archive, missing '%s' member" % "debian-binary") + raise NoDebArchiveException, _( + "This is not a valid DEB archive, missing '%s' member" + % "debian-binary") control = apt_inst.debExtractControl(open(self.filename)) self._sections = apt_pkg.ParseSection(control) self.pkgname = self._sections["Package"] @@ -34,18 +36,22 @@ class DebPackage(object): """ return the list of files in the deb """ files = [] - def extract_cb(What, Name, Link, Mode, UID, GID, Size, MTime, Major, Minor): - #print "%s '%s','%s',%u,%u,%u,%u,%u,%u,%u"\ - # % (What, Name, Link, Mode, UID, GID, Size, MTime, Major, Minor) + def extract_cb( + What, Name, Link, Mode, UID, GID, Size, MTime, Major, Minor): + #print "%s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % ( + # What, Name, Link, Mode, UID, GID, Size, MTime, Major, Minor) files.append(Name) for member in self._supported_data_members: if arCheckMember(open(self.filename), member): try: - apt_inst.debExtract(open(self.filename), extract_cb, member) + apt_inst.debExtract( + open(self.filename), extract_cb, member) break except SystemError, e: - return [_("List of files for '%s'could not be read" % self.filename)] + return [_( + "List of files for '%s'could not be read" + % self.filename)] return files filelist = property(filelist) diff --git a/apt/package.py b/apt/package.py index 51986874..e51ab98f 100644 --- a/apt/package.py +++ b/apt/package.py @@ -96,7 +96,8 @@ class Package(object): # check if we found a version if ver == None: - #print "No version for: %s (Candidate: %s)" % (self._pkg.Name, UseCandidate) + #print "No version for: %s (Candidate: %s)" % ( + # self._pkg.Name, UseCandidate) return False if ver.FileList == None: @@ -150,7 +151,10 @@ class Package(object): for depVerList in depends[t]: base_deps = [] for depOr in depVerList: - base_deps.append(BaseDependency(depOr.TargetPkg.Name, depOr.CompType, depOr.TargetVer, (t == "PreDepends"))) + base_deps.append( + BaseDependency( + depOr.TargetPkg.Name, depOr.CompType, + depOr.TargetVer, (t == "PreDepends"))) depends_list.append(Dependency(base_deps)) return depends_list @@ -441,7 +445,9 @@ class Package(object): self.markInstall() else: # FIXME: we may want to throw a exception here - sys.stderr.write("MarkUpgrade() called on a non-upgrable pkg: '%s'\n" % self._pkg.Name) + sys.stderr.write( + "MarkUpgrade() called on a non-upgrable pkg: '%s'\n" + % self._pkg.Name) def commit(self, fprogress, iprogress): """ commit the changes, need a FetchProgress and InstallProgress @@ -478,7 +484,9 @@ if __name__ == "__main__": print "PackageSize: %s " % pkg.packageSize print "Dependencies: %s" % pkg.installedDependencies for dep in pkg.candidateDependencies: - print ",".join(["%s (%s) (%s) (%s)" % (o.name, o.version, o.relation, o.preDepend) for o in dep.or_dependencies]) + print ",".join( + ["%s (%s) (%s) (%s)" % (o.name, o.version, o.relation, o.preDepend) + for o in dep.or_dependencies]) print "arch: %s" % pkg.architecture print "homepage: %s" % pkg.homepage print "rec: ", pkg.candidateRecord diff --git a/apt/progress.py b/apt/progress.py index 1f2d4e7c..96112d73 100644 --- a/apt/progress.py +++ b/apt/progress.py @@ -95,9 +95,13 @@ class FetchProgress(object): """ called periodically (to update the gui), importend to return True to continue or False to cancel """ - self.percent = ((self.currentBytes + self.currentItems)*100.0)/float(self.totalBytes+self.totalItems) + self.percent = ( + ((self.currentBytes + self.currentItems) * 100.0) + / float(self.totalBytes+self.totalItems)) if self.currentCPS > 0: - self.eta = (self.totalBytes-self.currentBytes)/float(self.currentCPS) + self.eta = ( + (self.totalBytes - self.currentBytes) + / float(self.currentCPS)) return True def mediaChange(self, medium, drive): @@ -193,38 +197,41 @@ class InstallProgress(DumbInstallProgress): def updateInterface(self): if self.statusfd != None: + try: + while not self.read.endswith("\n"): + self.read += os.read(self.statusfd.fileno(), 1) + except OSError, (errno, errstr): + # resource temporarly unavailable is ignored + if errno != EAGAIN and errnor != EWOULDBLOCK: + print errstr + if self.read.endswith("\n"): + s = self.read + #print s try: - while not self.read.endswith("\n"): - self.read += os.read(self.statusfd.fileno(), 1) - except OSError, (errno, errstr): - # resource temporarly unavailable is ignored - if errno != EAGAIN and errnor != EWOULDBLOCK: - print errstr - if self.read.endswith("\n"): - s = self.read - #print s - try: - (status, pkg, percent, status_str) = string.split(s, ":", 3) - except ValueError, e: - # silently ignore lines that can't be parsed - self.read = "" - return - #print "percent: %s %s" % (pkg, float(percent)/100.0) - if status == "pmerror": - self.error(pkg, status_str) - elif status == "pmconffile": - # we get a string like this: - # 'current-conffile' 'new-conffile' useredited distedited - match = re.compile("\s*\'(.*)\'\s*\'(.*)\'.*").match(status_str) - if match: - self.conffile(match.group(1), match.group(2)) - elif status == "pmstatus": - if float(percent) != self.percent or \ - status_str != self.status: - self.statusChange(pkg, float(percent), status_str.strip()) - self.percent = float(percent) - self.status = string.strip(status_str) + (status, pkg, percent, status_str) = string.split( + s, ":", 3) + except ValueError, e: + # silently ignore lines that can't be parsed self.read = "" + return + #print "percent: %s %s" % (pkg, float(percent)/100.0) + if status == "pmerror": + self.error(pkg, status_str) + elif status == "pmconffile": + # we get a string like this: + # 'current-conffile' 'new-conffile' useredited distedited + match = re.compile( + "\s*\'(.*)\'\s*\'(.*)\'.*").match(status_str) + if match: + self.conffile(match.group(1), match.group(2)) + elif status == "pmstatus": + if float(percent) != self.percent or \ + status_str != self.status: + self.statusChange( + pkg, float(percent), status_str.strip()) + self.percent = float(percent) + self.status = string.strip(status_str) + self.read = "" def fork(self): return os.fork() diff --git a/aptsources/distinfo.py b/aptsources/distinfo.py index ce90faac..3bdbd653 100644 --- a/aptsources/distinfo.py +++ b/aptsources/distinfo.py @@ -154,7 +154,9 @@ class DistInfo: location = None match_loc = re.compile(r"^#LOC:(.+)$") - match_mirror_line = re.compile(r"^(#LOC:.+)|(((http)|(ftp)|(rsync)|(file)|(https))://[A-Za-z/\.:\-_]+)$") + match_mirror_line = re.compile( + r"^(#LOC:.+)|(((http)|(ftp)|(rsync)|(file)|(https))://" + r"[A-Za-z/\.:\-_]+)$") #match_mirror_line = re.compile(r".+") if not dist: @@ -185,7 +187,8 @@ class DistInfo: self.metarelease_uri = value elif field == 'Suite': if template: - if component and not template.has_component(component.name): + if component \ + and not template.has_component(component.name): template.components.append(component) component = None self.templates.append(template) @@ -231,7 +234,8 @@ class DistInfo: if mirror_set.has_key(hostname): mirror_set[hostname].add_repository(proto, dir) else: - mirror_set[hostname] = Mirror(proto, hostname, dir, location) + mirror_set[hostname] = Mirror( + proto, hostname, dir, location) map_mirror_sets[value] = mirror_set template.mirror_set = map_mirror_sets[value] elif field == 'Description': diff --git a/aptsources/distro.py b/aptsources/distro.py index 888e6e06..f631e285 100644 --- a/aptsources/distro.py +++ b/aptsources/distro.py @@ -82,7 +82,8 @@ class Distribution: if self.is_codename(template.name) and\ template.distribution == self.id: #print "yeah! found a template for %s" % self.description - #print template.description, template.base_uri, template.components + #print template.description, template.base_uri, \ + # template.components self.source_template = template break if self.source_template == None: @@ -117,15 +118,19 @@ class Distribution: elif source.type == self.binary_type and \ source.disabled == True: self.disabled_sources.append(source) - elif source.type == self.source_type and source.disabled == False: + elif source.type == self.source_type \ + and source.disabled == False: self.source_code_sources.append(source) - elif source.type == self.source_type and source.disabled == True: + elif source.type == self.source_type \ + and source.disabled == True: self.disabled_sources.append(source) if source.invalid == False and\ source.template in self.source_template.children: - if source.disabled == False and source.type == self.binary_type: + if source.disabled == False \ + and source.type == self.binary_type: self.child_sources.append(source) - elif source.disabled == False and source.type == self.source_type: + elif source.disabled == False \ + and source.type == self.source_type: self.source_code_sources.append(source) else: self.disabled_sources.append(source) @@ -240,11 +245,12 @@ class Distribution: self.nearest_server, False]) mirrors.append([_("Custom servers"), None, True]) for server in self.used_servers: + mirror_entry = [self._get_mirror_name(server), server, False] if compare_mirrors(server, self.nearest_server) or\ compare_mirrors(server, self.main_server): continue - elif not [self._get_mirror_name(server), server, False] in mirrors: - mirrors.append([self._get_mirror_name(server), server, False]) + elif not mirror_entry in mirrors: + mirrors.append(mirror_entry) return mirrors @@ -408,23 +414,22 @@ class DebianDistribution(Distribution): country = server[i+len("://ftp."):l] if self.countries.has_key(country): # TRANSLATORS: %s is a country - return _("Server for %s") % \ - gettext.dgettext("iso_3166", - self.countries[country].rstrip()).rstrip() + return _("Server for %s") % gettext.dgettext( + "iso_3166", self.countries[country].rstrip()).rstrip() else: return("%s" % server.rstrip("/ ")) def get_mirrors(self): - Distribution.get_mirrors(self, - mirror_template="http://ftp.%s.debian.org/debian/") + Distribution.get_mirrors( + self, mirror_template="http://ftp.%s.debian.org/debian/") class UbuntuDistribution(Distribution): ''' Class to support specific Ubuntu features ''' def get_mirrors(self): - Distribution.get_mirrors(self, - mirror_template="http://%s.archive.ubuntu.com/ubuntu/") + Distribution.get_mirrors( + self, mirror_template="http://%s.archive.ubuntu.com/ubuntu/") def get_distro(): diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index 6eb69f6e..be17cd1f 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -84,11 +84,13 @@ class SourceEntry: self.type = "" # what type (deb, deb-src) self.uri = "" # base-uri self.dist = "" # distribution (dapper, edgy, etc) - self.comps = [] # list of available componetns (may empty) + self.comps = [] # list of available componetns + # (may empty) self.comment = "" # (optional) comment self.line = line # the original sources.list line if file == None: - file = apt_pkg.Config.FindDir("Dir::Etc")+apt_pkg.Config.Find("Dir::Etc::sourcelist") + file = apt_pkg.Config.FindDir( + "Dir::Etc")+apt_pkg.Config.Find("Dir::Etc::sourcelist") self.file = file # the file that the entry is located in self.parse(line) self.template = None # type DistInfo.Suite @@ -118,11 +120,13 @@ class SourceEntry: elif line[i] == "]": p_found=False tmp += line[i] - elif space_found and not line[i].isspace(): # we skip one or more space + elif space_found and not line[i].isspace(): + # we skip one or more space space_found = False pieces.append(tmp) tmp = line[i] - elif line[i].isspace() and not p_found: # found a whitespace + elif line[i].isspace() and not p_found: + # found a whitespace space_found = True else: tmp += line[i] @@ -273,8 +277,8 @@ class SourcesList: source.dist == dist: for new_comp in comps: if new_comp in source.comps: - # we have this component already, delete it from the new_comps - # list + # we have this component already, delete it + # from the new_comps list del comps[comps.index(new_comp)] if len(comps) == 0: return source @@ -332,7 +336,8 @@ class SourcesList: if backup_ext == None: backup_ext = time.strftime("%y%m%d.%H%M") for source in self.list: - if not source.file in already_backuped and os.path.exists(source.file): + if not source.file in already_backuped \ + and os.path.exists(source.file): shutil.copy(source.file, "%s%s" % (source.file, backup_ext)) return backup_ext @@ -356,9 +361,10 @@ class SourcesList: if len(self.list) == 0: path = "%s%s" % (apt_pkg.Config.FindDir("Dir::Etc"), apt_pkg.Config.Find("Dir::Etc::sourcelist")) - header = ("## See sources.list(5) for more information, especialy\n" - "# Remember that you can only use http, ftp or file URIs\n" - "# CDROMs are managed through the apt-cdrom tool.\n") + header = ( + "## See sources.list(5) for more information, especialy\n" + "# Remember that you can only use http, ftp or file URIs\n" + "# CDROMs are managed through the apt-cdrom tool.\n") open(path, "w").write(header) return for source in self.list: diff --git a/doc/examples/action.py b/doc/examples/action.py index 9277129e..7153292c 100644 --- a/doc/examples/action.py +++ b/doc/examples/action.py @@ -86,7 +86,8 @@ print "UsrSize: %s " % apt_pkg.SizeToStr(depcache.UsrSize) print "DebSize: %s " % apt_pkg.SizeToStr(depcache.DebSize) for pkg in cache.Packages: - if pkg.CurrentVer != None and not depcache.MarkedInstall(pkg) and depcache.IsUpgradable(pkg): + if pkg.CurrentVer != None and not depcache.MarkedInstall(pkg) \ + and depcache.IsUpgradable(pkg): print "Upgrade didn't upgrade (kept): %s" % pkg.Name print "\nPerforming DistUpgrade" diff --git a/doc/examples/all_deps.py b/doc/examples/all_deps.py index 37222463..2feeb125 100644 --- a/doc/examples/all_deps.py +++ b/doc/examples/all_deps.py @@ -14,9 +14,11 @@ def dependencies(cache, pkg, deps, key="Depends"): for depVerList in dependslist[key]: for dep in depVerList: if cache.has_key(dep.TargetPkg.Name): - if pkg.name != dep.TargetPkg.Name and not dep.TargetPkg.Name in deps: + if pkg.name != dep.TargetPkg.Name and \ + not dep.TargetPkg.Name in deps: deps.add(dep.TargetPkg.Name) - dependencies(cache, cache[dep.TargetPkg.Name], deps, key) + dependencies( + cache, cache[dep.TargetPkg.Name], deps, key) return deps diff --git a/doc/examples/config.py b/doc/examples/config.py index d0895690..cc1aae44 100755 --- a/doc/examples/config.py +++ b/doc/examples/config.py @@ -6,7 +6,8 @@ # config.py -no-h --no-help --help=no ; Turn off help # config.py -qqq -q=3 ; verbosity to 3 # config.py -c /etc/apt/apt.conf ; include that config file] -# config.py -o help=true ; Turn on help by giving a config file string +# config.py -o help=true ; Turn on help by giving a +# ; config file string # config.py -no-h -- -help ; Turn off help, specify the file '-help' # -c and -o are standard APT-program options. diff --git a/doc/examples/configisc.py b/doc/examples/configisc.py index 03fa2cad..1d5965f5 100755 --- a/doc/examples/configisc.py +++ b/doc/examples/configisc.py @@ -32,10 +32,13 @@ if Cnf.has_key("Zone"): for I in Cnf.List("zone"): SubCnf = Cnf.SubTree(I) if SubCnf.Find("type") == "slave": - print "Masters for %s: %s" % (SubCnf.MyTag(), SubCnf.ValueList("masters")) + print "Masters for %s: %s" % ( + SubCnf.MyTag(), SubCnf.ValueList("masters")) else: print "Tree definitions:" for I in Cnf.List("tree"): SubCnf = Cnf.SubTree(I) - # This could use Find which would eliminate the possibility of exceptions. - print "Subtree %s with sections '%s' and architectures '%s'" % (SubCnf.MyTag(), SubCnf["Sections"], SubCnf["Architectures"]) + # This could use Find which would eliminate the possibility of + # exceptions. + print "Subtree %s with sections '%s' and architectures '%s'" % ( + SubCnf.MyTag(), SubCnf["Sections"], SubCnf["Architectures"]) diff --git a/doc/examples/depcache.py b/doc/examples/depcache.py index 556c954b..ad884fe7 100644 --- a/doc/examples/depcache.py +++ b/doc/examples/depcache.py @@ -84,7 +84,8 @@ print "UsrSize: %s " % apt_pkg.SizeToStr(depcache.UsrSize) print "DebSize: %s " % apt_pkg.SizeToStr(depcache.DebSize) for pkg in cache.Packages: - if pkg.CurrentVer != None and not depcache.MarkedInstall(pkg) and depcache.IsUpgradable(pkg): + if pkg.CurrentVer != None and not depcache.MarkedInstall(pkg) \ + and depcache.IsUpgradable(pkg): print "Upgrade didn't upgrade (kept): %s" % pkg.Name diff --git a/doc/examples/progress.py b/doc/examples/progress.py index 70fc92f3..c56734b7 100644 --- a/doc/examples/progress.py +++ b/doc/examples/progress.py @@ -34,10 +34,13 @@ class TextFetchProgress(apt.FetchProgress): pass def updateStatus(self, uri, descr, shortDescr, status): - print "UpdateStatus: '%s' '%s' '%s' '%i'" % (uri, descr, shortDescr, status) + print "UpdateStatus: '%s' '%s' '%s' '%i'" % ( + uri, descr, shortDescr, status) def pulse(self): - print "Pulse: CPS: %s/s; Bytes: %s/%s; Item: %s/%s" % (SizeToStr(self.currentCPS), SizeToStr(self.currentBytes), SizeToStr(self.totalBytes), self.currentItems, self.totalItems) + print "Pulse: CPS: %s/s; Bytes: %s/%s; Item: %s/%s" % ( + SizeToStr(self.currentCPS), SizeToStr(self.currentBytes), + SizeToStr(self.totalBytes), self.currentItems, self.totalItems) return True def mediaChange(self, medium, drive): diff --git a/doc/examples/records.py b/doc/examples/records.py index 9dfc460b..a7a87727 100755 --- a/doc/examples/records.py +++ b/doc/examples/records.py @@ -8,5 +8,6 @@ for pkg in cache: if not pkg.candidateRecord: continue if pkg.candidateRecord.has_key("Task"): - print "Pkg %s is part of '%s'" % (pkg.name, pkg.candidateRecord["Task"].split()) + print "Pkg %s is part of '%s'" % ( + pkg.name, pkg.candidateRecord["Task"].split()) #print pkg.candidateRecord diff --git a/doc/examples/sources.py b/doc/examples/sources.py index 8d807f4c..49652982 100644 --- a/doc/examples/sources.py +++ b/doc/examples/sources.py @@ -10,6 +10,7 @@ apt_pkg.init() sources = apt_pkg.GetPkgSrcRecords() sources.Restart() while sources.Lookup('hello'): - print sources.Package, sources.Version, sources.Maintainer, sources.Section, `sources.Binaries` + print sources.Package, sources.Version, sources.Maintainer, \ + sources.Section, `sources.Binaries` print sources.Files print sources.Index.ArchiveURI(sources.Files[0][2]) diff --git a/tests/depcache.py b/tests/depcache.py index 5ed54895..b199c812 100644 --- a/tests/depcache.py +++ b/tests/depcache.py @@ -31,7 +31,8 @@ def main(): if depcache.MarkedInstall(p): depcache.MarkKeep(p) if depcache.InstCount != 0: - print "Error undoing the selection for %s (InstCount: %s)" % (x, depcache.InstCount) + print "Error undoing the selection for %s (InstCount: %s)" % ( + x, depcache.InstCount) print "\r%i/%i=%.3f%% " % (i, all, (float(i) / float(all) * 100)), print diff --git a/tests/pkgrecords.py b/tests/pkgrecords.py index e128237b..5866847d 100644 --- a/tests/pkgrecords.py +++ b/tests/pkgrecords.py @@ -30,7 +30,9 @@ def main(): x = records.FileName y = records.LongDesc pass - print "\r%i/%i=%.3f%% " % (i, cache.PackageCount, (float(i) / float(cache.PackageCount) * 100)), + print "\r%i/%i=%.3f%% " % ( + i, cache.PackageCount, + (float(i) / float(cache.PackageCount) * 100)), if __name__ == "__main__": diff --git a/tests/pkgsrcrecords.py b/tests/pkgsrcrecords.py index 6e78858b..77670540 100644 --- a/tests/pkgsrcrecords.py +++ b/tests/pkgsrcrecords.py @@ -19,7 +19,9 @@ def main(): if src.Lookup(x.Name): #print src.Package pass - print "\r%i/%i=%.3f%% " % (i, cache.PackageCount, (float(i) / float(cache.PackageCount) * 100)), + print "\r%i/%i=%.3f%% " % ( + i, cache.PackageCount, + (float(i) / float(cache.PackageCount) * 100)), if __name__ == "__main__": diff --git a/tests/test_aptsources.py b/tests/test_aptsources.py index 9019aa2d..3e2f7ac5 100644 --- a/tests/test_aptsources.py +++ b/tests/test_aptsources.py @@ -79,7 +79,8 @@ class TestAptSources(unittest.TestCase): self.assertEqual(found_universe, 1) def testDistribution(self): - apt_pkg.Config.Set("Dir::Etc::sourcelist", "data/sources.list.testDistribution") + apt_pkg.Config.Set( + "Dir::Etc::sourcelist", "data/sources.list.testDistribution") sources = aptsources.SourcesList() distro = aptsources.Distribution() distro.get_sources(sources) @@ -89,7 +90,9 @@ class TestAptSources(unittest.TestCase): if s.template: dist_templates.add(s.template.name) #print dist_templates - for d in ["edgy", "edgy-security", "edgy-updates", "hoary", "breezy", "breezy-backports"]: + for d in [ + "edgy", "edgy-security", "edgy-updates", + "hoary", "breezy", "breezy-backports"]: self.assertTrue(d in dist_templates) # test enable comp = "restricted" -- cgit v1.2.3 From 08fa9a44bc90b88f05cd8aa14d50892fadda9049 Mon Sep 17 00:00:00 2001 From: Ben Finney Date: Sat, 21 Jun 2008 01:13:50 +1000 Subject: Fix whitespace in changes from 0.7.6. --- apt/cache.py | 2 +- aptsources/distinfo.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'apt') diff --git a/apt/cache.py b/apt/cache.py index 36e3df8e..340b5696 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -51,7 +51,7 @@ class Cache(object): self._callbacks = {} if memonly: # force apt to build its caches in memory - apt_pkg.Config.Set("Dir::Cache::pkgcache","") + apt_pkg.Config.Set("Dir::Cache::pkgcache", "") if rootdir: apt_pkg.Config.Set("Dir", rootdir) apt_pkg.Config.Set( diff --git a/aptsources/distinfo.py b/aptsources/distinfo.py index d7dfd970..a309a548 100644 --- a/aptsources/distinfo.py +++ b/aptsources/distinfo.py @@ -222,7 +222,7 @@ class DistInfo: template.match_uri = value elif field == 'MatchURI-%s' % self.arch: template.match_uri = value - elif (field == 'MirrorsFile' or + elif (field == 'MirrorsFile' or field == 'MirrorsFile-%s' % self.arch): if not map_mirror_sets.has_key(value): mirror_set = {} -- cgit v1.2.3 From 75676866d4bf394b3ba1ddef06e0c93f6da03242 Mon Sep 17 00:00:00 2001 From: Ben Finney Date: Fri, 8 Aug 2008 10:27:33 +1000 Subject: 'mapping.has_key' is deprecated, use current Python 'key in mapping' idiom. --- apt/cache.py | 16 ++++++++-------- apt/package.py | 10 ++++------ aptsources/distinfo.py | 6 +++--- aptsources/distro.py | 12 ++++++------ aptsources/sourceslist.py | 4 ++-- doc/examples/all_deps.py | 4 ++-- doc/examples/configisc.py | 2 +- doc/examples/records.py | 2 +- tests/test_aptsources.py | 4 ++-- utils/get_ubuntu_mirrors_from_lp.py | 2 +- 10 files changed, 30 insertions(+), 32 deletions(-) (limited to 'apt') diff --git a/apt/cache.py b/apt/cache.py index 340b5696..576ef8c6 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -60,7 +60,7 @@ class Cache(object): def _runCallbacks(self, name): """ internal helper to run a callback """ - if self._callbacks.has_key(name): + if name in self._callbacks: for callback in self._callbacks[name]: callback() @@ -105,8 +105,8 @@ class Cache(object): yield self._dict[pkgname] raise StopIteration - def has_key(self, key): - return self._dict.has_key(key) + def __contains__(self, key): + return (key in self._dict) def __len__(self): return len(self._dict) @@ -251,7 +251,7 @@ class Cache(object): def connect(self, name, callback): """ connect to a signal, currently only used for cache_{post,pre}_{changed,open} """ - if not self._callbacks.has_key(name): + if name not in self._callbacks: self._callbacks[name] = [] self._callbacks[name].append(callback) @@ -304,8 +304,8 @@ class FilteredCache(object): def keys(self): return self._filtered.keys() - def has_key(self, key): - return self._filtered.has_key(key) + def __contains__(self, key): + return (key in self._filtered) def _reapplyFilter(self): " internal helper to refilter " @@ -335,7 +335,7 @@ class FilteredCache(object): def __getattr__(self, key): " we try to look exactly like a real cache " #print "getattr: %s " % key - if self.__dict__.has_key(key): + if key in self.__dict__: return self.__dict__[key] else: return getattr(self.cache, key) @@ -356,7 +356,7 @@ if __name__ == "__main__": c = Cache(apt.progress.OpTextProgress()) c.connect("cache_pre_change", cache_pre_changed) c.connect("cache_post_change", cache_post_changed) - print c.has_key("aptitude") + print ("aptitude" in c) p = c["aptitude"] print p.name print len(c) diff --git a/apt/package.py b/apt/package.py index 7f060b04..445b36ad 100644 --- a/apt/package.py +++ b/apt/package.py @@ -66,8 +66,8 @@ class Record(object): raise KeyError return k - def has_key(self, key): - return self._rec.has_key(key) + def __contains__(self, key): + return (key in self._rec) class Package(object): @@ -146,7 +146,7 @@ class Package(object): depends_list = [] depends = ver.DependsList for t in ["PreDepends", "Depends"]: - if not depends.has_key(t): + if t not in depends: continue for depVerList in depends[t]: base_deps = [] @@ -178,9 +178,7 @@ class Package(object): if not self._lookupRecord(): return None sec = apt_pkg.ParseSection(self._records.Record) - if sec.has_key("Architecture"): - return sec["Architecture"] - return None + return sec.get("Architecture", None) architecture = property(architecture) def _downloadable(self, useCandidate=True): diff --git a/aptsources/distinfo.py b/aptsources/distinfo.py index a309a548..74a280ae 100644 --- a/aptsources/distinfo.py +++ b/aptsources/distinfo.py @@ -61,7 +61,7 @@ class Template: def is_mirror(self, url): ''' Check if a given url of a repository is a valid mirror ''' proto, hostname, dir = split_url(url) - if self.mirror_set.has_key(hostname): + if hostname in self.mirror_set: return self.mirror_set[hostname].has_repository(proto, dir) else: return False @@ -224,7 +224,7 @@ class DistInfo: template.match_uri = value elif (field == 'MirrorsFile' or field == 'MirrorsFile-%s' % self.arch): - if not map_mirror_sets.has_key(value): + if value not in map_mirror_sets: mirror_set = {} try: mirror_data = filter(match_mirror_line.match, @@ -237,7 +237,7 @@ class DistInfo: location = match_loc.sub(r"\1", line) continue (proto, hostname, dir) = split_url(line) - if mirror_set.has_key(hostname): + if hostname in mirror_set: mirror_set[hostname].add_repository(proto, dir) else: mirror_set[hostname] = Mirror( diff --git a/aptsources/distro.py b/aptsources/distro.py index 0bf8aba9..350feb65 100644 --- a/aptsources/distro.py +++ b/aptsources/distro.py @@ -187,7 +187,7 @@ class Distribution: if mirror_template: self.nearest_server = mirror_template % country_code - if self.countries.has_key(country_code): + if country_code in self.countries: self.country = self.countries[country_code] self.country_code = country_code @@ -199,7 +199,7 @@ class Distribution: l = server.find(".archive.ubuntu.com") if i != -1 and l != -1: country = server[i+len("://"):l] - if self.countries.has_key(country): + if country in self.countries: # TRANSLATORS: %s is a country return _("Server for %s") % \ gettext.dgettext("iso_3166", @@ -292,7 +292,7 @@ class Distribution: """ # if we don't that distro, just reutnr (can happen for e.g. # dapper-update only in deb-src - if not comps_per_dist.has_key(source.dist): + if source.dist not in comps_per_dist: return # if we have seen this component already for this distro, # return (nothing to do @@ -311,12 +311,12 @@ class Distribution: comps_per_sdist = {} for s in sources: if s.type == self.binary_type: - if not comps_per_dist.has_key(s.dist): + if s.dist not in comps_per_dist: comps_per_dist[s.dist] = set() map(comps_per_dist[s.dist].add, s.comps) for s in self.source_code_sources: if s.type == self.source_type: - if not comps_per_sdist.has_key(s.dist): + if s.dist not in comps_per_sdist: comps_per_sdist[s.dist] = set() map(comps_per_sdist[s.dist].add, s.comps) @@ -412,7 +412,7 @@ class DebianDistribution(Distribution): l = server.find(".debian.org") if i != -1 and l != -1: country = server[i+len("://ftp."):l] - if self.countries.has_key(country): + if country in self.countries: # TRANSLATORS: %s is a country return _("Server for %s") % gettext.dgettext( "iso_3166", self.countries[country].rstrip()).rstrip() diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index be17cd1f..a0346267 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -368,7 +368,7 @@ class SourcesList: open(path, "w").write(header) return for source in self.list: - if not files.has_key(source.file): + if source.file not in files: files[source.file] = open(source.file, "w") files[source.file].write(source.str()) for f in files: @@ -386,7 +386,7 @@ class SourcesList: # source entries if source.template.child == True: key = source.template - if not used_child_templates.has_key(key): + if key not in used_child_templates: used_child_templates[key] = [] temp = used_child_templates[key] temp.append(source) diff --git a/doc/examples/all_deps.py b/doc/examples/all_deps.py index 2feeb125..2ed0207f 100644 --- a/doc/examples/all_deps.py +++ b/doc/examples/all_deps.py @@ -10,10 +10,10 @@ def dependencies(cache, pkg, deps, key="Depends"): if candver == None: return deps dependslist = candver.DependsList - if dependslist.has_key(key): + if key in dependslist: for depVerList in dependslist[key]: for dep in depVerList: - if cache.has_key(dep.TargetPkg.Name): + if TargetPkg.Name in cache: if pkg.name != dep.TargetPkg.Name and \ not dep.TargetPkg.Name in deps: deps.add(dep.TargetPkg.Name) diff --git a/doc/examples/configisc.py b/doc/examples/configisc.py index 1d5965f5..dc3c2f33 100755 --- a/doc/examples/configisc.py +++ b/doc/examples/configisc.py @@ -27,7 +27,7 @@ apt_pkg.ReadConfigFileISC(Cnf, ConfigFile[0]) # print "%s \"%s\";" % (I, Cnf[I]) # bind8 config file.. -if Cnf.has_key("Zone"): +if "Zone" in Cnf: print "Zones: ", Cnf.SubTree("zone").List() for I in Cnf.List("zone"): SubCnf = Cnf.SubTree(I) diff --git a/doc/examples/records.py b/doc/examples/records.py index a7a87727..a0fc8dc4 100755 --- a/doc/examples/records.py +++ b/doc/examples/records.py @@ -7,7 +7,7 @@ cache = apt.Cache() for pkg in cache: if not pkg.candidateRecord: continue - if pkg.candidateRecord.has_key("Task"): + if "Task" in pkg.candidateRecord: print "Pkg %s is part of '%s'" % ( pkg.name, pkg.candidateRecord["Task"].split()) #print pkg.candidateRecord diff --git a/tests/test_aptsources.py b/tests/test_aptsources.py index 3e2f7ac5..9f439899 100644 --- a/tests/test_aptsources.py +++ b/tests/test_aptsources.py @@ -104,7 +104,7 @@ class TestAptSources(unittest.TestCase): "edgy" in entry.dist): for c in entry.comps: if c == comp: - if not found.has_key(entry.dist): + if entry.dist not in found: found[entry.dist] = 0 found[entry.dist] += 1 #print "".join([s.str() for s in sources]) @@ -121,7 +121,7 @@ class TestAptSources(unittest.TestCase): entry.template.name == "edgy"): for c in entry.comps: if c == comp: - if not found.has_key(entry.dist): + if entry.dist not in found: found[entry.dist] = 0 found[entry.dist] += 1 #print "".join([s.str() for s in sources]) diff --git a/utils/get_ubuntu_mirrors_from_lp.py b/utils/get_ubuntu_mirrors_from_lp.py index 59ddd84e..b912f28d 100755 --- a/utils/get_ubuntu_mirrors_from_lp.py +++ b/utils/get_ubuntu_mirrors_from_lp.py @@ -70,7 +70,7 @@ def find(split): country = re.search(r"(.+?)", split) if not country: return - if countries.has_key(country.group(1)): + if country.group(1) in countries: lines.append("#LOC:%s" % countries[country.group(1)].upper()) else: lines.append("#LOC:%s" % country.group(1)) -- cgit v1.2.3 From 9358b351e8f1637ff87c9f9195a4b5e546ca2a79 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 9 Jan 2009 21:47:44 +0100 Subject: Cleanup: Remove whitespace at the end of line in all python codes. --- apt/cache.py | 42 +++++++++++++++--------------- apt/cdrom.py | 2 +- apt/debfile.py | 34 ++++++++++++------------ apt/gtk/widgets.py | 52 ++++++++++++++++++------------------- apt/package.py | 38 +++++++++++++-------------- apt/progress.py | 26 +++++++++---------- aptsources/__init__.py | 2 +- aptsources/distinfo.py | 22 ++++++++-------- aptsources/distro.py | 52 ++++++++++++++++++------------------- aptsources/sourceslist.py | 38 +++++++++++++-------------- doc/examples/acquire.py | 4 +-- doc/examples/build-deps.py | 2 +- doc/examples/deb_inspect.py | 2 +- doc/examples/gui-inst.py | 2 +- doc/examples/progress.py | 6 ++--- doc/examples/recommends.py | 2 +- doc/examples/versiontest.py | 6 ++--- setup.py | 2 +- tests/cache.py | 4 +-- tests/depcache.py | 2 +- tests/lock.py | 6 ++--- tests/pkgproblemresolver.py | 4 +-- tests/pkgrecords.py | 2 +- tests/pkgsrcrecords.py | 2 +- tests/test_aptsources.py | 4 +-- tests/test_debextract.py | 2 +- utils/get_debian_mirrors.py | 12 ++++----- utils/get_ubuntu_mirrors.py | 10 +++---- utils/get_ubuntu_mirrors_from_lp.py | 10 +++---- 29 files changed, 196 insertions(+), 196 deletions(-) (limited to 'apt') diff --git a/apt/cache.py b/apt/cache.py index 79e58282..530d56a0 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -1,19 +1,19 @@ # cache.py - apt cache abstraction -# +# # Copyright (c) 2005 Canonical -# +# # Author: Michael Vogt -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 @@ -36,7 +36,7 @@ class LockFailedException(IOError): pass class Cache(object): - """ Dictionary-like package cache + """ Dictionary-like package cache This class has all the packages that are available in it's dictionary """ @@ -56,7 +56,7 @@ class Cache(object): if self._callbacks.has_key(name): for callback in self._callbacks[name]: callback() - + def open(self, progress): """ Open the package cache, after that it can be used like a dictionary @@ -83,12 +83,12 @@ class Cache(object): self._dict[pkg.Name] = Package(self._cache, self._depcache, self._records, self._list, self, pkg) - + i += 1 if progress != None: progress.done() self._runCallbacks("cache_post_open") - + def __getitem__(self, key): """ look like a dictionary (get key) """ return self._dict[key] @@ -112,7 +112,7 @@ class Cache(object): def getChanges(self): """ Get the marked changes """ - changes = [] + changes = [] for name in self._dict.keys(): p = self._dict[name] if p.markedUpgrade or p.markedInstall or p.markedDelete or \ @@ -144,7 +144,7 @@ class Cache(object): " return the packages not downloadable packages in reqreinst state " reqreinst = set() for pkg in self: - if (not pkg.candidateDownloadable and + if (not pkg.candidateDownloadable and (pkg._pkg.InstState == apt_pkg.InstStateReInstReq or pkg._pkg.InstState == apt_pkg.InstStateHoldReInstReq)): reqreinst.add(pkg.name) @@ -153,7 +153,7 @@ class Cache(object): def _runFetcher(self, fetcher): # do the actual fetching res = fetcher.Run() - + # now check the result (this is the code from apt-get.cc) failed = False transient = False @@ -228,13 +228,13 @@ class Cache(object): return self._cache.Update(fetchProgress, self._list) finally: os.close(lock) - + def installArchives(self, pm, installProgress): installProgress.startUpdate() res = installProgress.run(pm) installProgress.finishUpdate() return res - + def commit(self, fetchProgress=None, installProgress=None): """ Apply the marked changes to the cache """ # FIXME: @@ -319,7 +319,7 @@ class FilteredCache(object): self._filters = [] def __len__(self): return len(self._filtered) - + def __getitem__(self, key): return self.cache._dict[key] @@ -337,7 +337,7 @@ class FilteredCache(object): if f.apply(self.cache._dict[pkg]): self._filtered[pkg] = 1 break - + def setFilter(self, filter): " set the current active filter " self._filters = [] @@ -361,7 +361,7 @@ class FilteredCache(object): return self.__dict__[key] else: return getattr(self.cache, key) - + def cache_pre_changed(): print "cache pre changed" @@ -413,7 +413,7 @@ if __name__ == "__main__": for pkg in f.keys(): #print c[pkg].name x = f[pkg].name - + print len(f) print "Testing filtered cache (no argument)" @@ -426,5 +426,5 @@ if __name__ == "__main__": for pkg in f.keys(): #print c[pkg].name x = f[pkg].name - + print len(f) diff --git a/apt/cdrom.py b/apt/cdrom.py index 9d4b62cb..c0e57094 100644 --- a/apt/cdrom.py +++ b/apt/cdrom.py @@ -44,4 +44,4 @@ class Cdrom(object): if not line.startswith("#") and cdid in line: return True return False - + diff --git a/apt/debfile.py b/apt/debfile.py index b1d436cd..33785ea0 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -32,7 +32,7 @@ from gettext import gettext as _ VERSION_OUTDATED, VERSION_SAME, VERSION_NEWER) = range(4) - + class NoDebArchiveException(IOError): pass @@ -63,7 +63,7 @@ class DebPackage(object): def __getitem__(self, key): return self._sections[key] - + def filelist(self): """ return the list of files in the deb """ files = [] @@ -105,7 +105,7 @@ class DebPackage(object): if instver != None and apt_pkg.CheckDep(instver,oper,ver) == True: return True return False - + def _satisfyOrGroup(self, or_group): """ try to satisfy the or_group """ @@ -128,7 +128,7 @@ class DebPackage(object): if len(providers) != 1: continue depname = providers[0].name - + # now check if we can satisfy the deps with the candidate(s) # in the cache cand = self._cache[depname] @@ -168,7 +168,7 @@ class DebPackage(object): #print "ver: %s" % ver #print "pkgver: %s " % pkgver #print "oper: %s " % oper - if (pkgver and apt_pkg.CheckDep(pkgver,oper,ver) and + if (pkgver and apt_pkg.CheckDep(pkgver,oper,ver) and not self.replacesRealPkg(pkgname, oper, ver)): self._failureString += _("Conflicts with the installed package '%s'" % cand.name) return True @@ -188,7 +188,7 @@ class DebPackage(object): # check conflicts with virtual pkgs if not self._cache.has_key(depname): - # FIXME: we have to check for virtual replaces here as + # FIXME: we have to check for virtual replaces here as # well (to pass tests/gdebi-test8.deb) if self._cache.isVirtualPackage(depname): for pkg in self._cache.getProvidingPackages(depname): @@ -208,7 +208,7 @@ class DebPackage(object): """ Return list of package names conflicting with this package. - WARNING: This method will is deprecated. Please use the + WARNING: This method will is deprecated. Please use the attribute DebPackage.depends instead. """ return self.conflicts @@ -228,7 +228,7 @@ class DebPackage(object): """ Return list of package names on which this package depends on. - WARNING: This method will is deprecated. Please use the + WARNING: This method will is deprecated. Please use the attribute DebPackage.depends instead. """ return self.depends @@ -249,7 +249,7 @@ class DebPackage(object): """ Return list of virtual packages which are provided by this package. - WARNING: This method will is deprecated. Please use the + WARNING: This method will is deprecated. Please use the attribute DebPackage.provides instead. """ return self.provides @@ -269,7 +269,7 @@ class DebPackage(object): """ Return list of packages which are replaced by this package. - WARNING: This method will is deprecated. Please use the + WARNING: This method will is deprecated. Please use the attribute DebPackage.replaces instead. """ return self.replaces @@ -286,9 +286,9 @@ class DebPackage(object): replaces = property(replaces) def replacesRealPkg(self, pkgname, oper, ver): - """ + """ return True if the deb packages replaces a real (not virtual) - packages named pkgname, oper, ver + packages named pkgname, oper, ver """ self._dbg(3, "replacesPkg() %s %s %s" % (pkgname,oper,ver)) pkgver = None @@ -299,7 +299,7 @@ class DebPackage(object): pkgver = cand.candidateVersion for or_group in self.getReplaces(): for (name, ver, oper) in or_group: - if (name == pkgname and + if (name == pkgname and apt_pkg.CheckDep(pkgver,oper,ver)): self._dbg(3, "we have a replaces in our package for the conflict against '%s'" % (pkgname)) return True @@ -316,7 +316,7 @@ class DebPackage(object): res = False return res - + def compareToVersionInCache(self, useInstalled=True): """ checks if the pkg is already installed or availabe in the cache and if so in what version, returns if the version of the deb @@ -485,14 +485,14 @@ class DscSrcPackage(DebPackage): self.binaries = [pkg.strip() for pkg in line[len("Binary:"):].split(",")] if line.startswith("Version:"): self._sections["Version"] = line[len("Version:"):].strip() - # we are at the end + # we are at the end if line.startswith("-----BEGIN PGP SIGNATURE-"): break s = _("Install Build-Dependencies for " "source package '%s' that builds %s\n" ) % (self.pkgName, " ".join(self.binaries)) self._sections["Description"] = s - + def checkDeb(self): if not self.checkConflicts(): for pkgname in self._installedConflicts: @@ -515,7 +515,7 @@ if __name__ == "__main__": print "Providers for %s :" % vp for pkg in providers: print " %s" % pkg.name - + d = DebPackage(sys.argv[1], cache) print "Deb: %s" % d.pkgname if not d.checkDeb(): diff --git a/apt/gtk/widgets.py b/apt/gtk/widgets.py index 3a15258f..968e2a77 100644 --- a/apt/gtk/widgets.py +++ b/apt/gtk/widgets.py @@ -8,8 +8,8 @@ Copyright (c) 2004,2005 Canonical Ltd. Authors: Michael Vogt Sebastian Heinlein -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License as +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. @@ -17,7 +17,7 @@ his program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 @@ -44,9 +44,9 @@ class GOpProgress(gobject.GObject, apt.progress.OpProgress): __gsignals__ = {"status-changed":(gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (gobject.TYPE_STRING, gobject.TYPE_INT)), - "status-started":(gobject.SIGNAL_RUN_FIRST, + "status-started":(gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()), - "status-finished":(gobject.SIGNAL_RUN_FIRST, + "status-finished":(gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ())} def __init__(self): @@ -70,15 +70,15 @@ class GInstallProgress(gobject.GObject, apt.progress.InstallProgress): __gsignals__ = {"status-changed":(gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (gobject.TYPE_STRING, gobject.TYPE_INT)), - "status-started":(gobject.SIGNAL_RUN_FIRST, + "status-started":(gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()), - "status-timeout":(gobject.SIGNAL_RUN_FIRST, + "status-timeout":(gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()), - "status-error":(gobject.SIGNAL_RUN_FIRST, + "status-error":(gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()), - "status-conffile":(gobject.SIGNAL_RUN_FIRST, + "status-conffile":(gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()), - "status-finished":(gobject.SIGNAL_RUN_FIRST, + "status-finished":(gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ())} def __init__(self, term): @@ -146,9 +146,9 @@ class GFetchProgress(gobject.GObject, apt.progress.FetchProgress): __gsignals__ = {"status-changed":(gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (gobject.TYPE_STRING, gobject.TYPE_INT)), - "status-started":(gobject.SIGNAL_RUN_FIRST, + "status-started":(gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()), - "status-finished":(gobject.SIGNAL_RUN_FIRST, + "status-finished":(gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ())} def __init__(self): @@ -206,7 +206,7 @@ class GtkAptProgress(gtk.VBox): win.add(progress) progress.show() win.show() - + cache = apt.cache.Cache(progress.open)) cache["xterm"].markDelete() progress.show_terminal(expanded=True) @@ -243,33 +243,33 @@ class GtkAptProgress(gtk.VBox): self._progress_fetch = GFetchProgress() self._progress_fetch.connect("status-changed", self._on_status_changed) self._progress_fetch.connect("status-started", self._on_status_started) - self._progress_fetch.connect("status-finished", + self._progress_fetch.connect("status-finished", self._on_status_finished) self._progress_install = GInstallProgress(self._terminal) self._progress_install.connect("status-changed", self._on_status_changed) - self._progress_install.connect("status-started", + self._progress_install.connect("status-started", self._on_status_started) - self._progress_install.connect("status-finished", + self._progress_install.connect("status-finished", self._on_status_finished) - self._progress_install.connect("status-timeout", + self._progress_install.connect("status-timeout", self._on_status_timeout) - self._progress_install.connect("status-error", + self._progress_install.connect("status-error", self._on_status_timeout) - self._progress_install.connect("status-conffile", + self._progress_install.connect("status-conffile", self._on_status_timeout) self._progress_dpkg_install = GDpkgInstallProgress(self._terminal) self._progress_dpkg_install.connect("status-changed", self._on_status_changed) - self._progress_dpkg_install.connect("status-started", + self._progress_dpkg_install.connect("status-started", self._on_status_started) - self._progress_dpkg_install.connect("status-finished", + self._progress_dpkg_install.connect("status-finished", self._on_status_finished) - self._progress_dpkg_install.connect("status-timeout", + self._progress_dpkg_install.connect("status-timeout", self._on_status_timeout) - self._progress_dpkg_install.connect("status-error", + self._progress_dpkg_install.connect("status-error", self._on_status_timeout) - self._progress_dpkg_install.connect("status-conffile", + self._progress_dpkg_install.connect("status-conffile", self._on_status_timeout) def clear(self): @@ -300,7 +300,7 @@ class GtkAptProgress(gtk.VBox): Return the install progress handler for dpkg """ return self._dpkg_progress_install - + @property def fetch(self): """ @@ -382,7 +382,7 @@ if __name__ == "__main__": pkg.markInstall() apt_progress.show_terminal(True) try: - cache.commit(apt_progress.get_fetch_progress(), + cache.commit(apt_progress.get_fetch_progress(), apt_progress.get_install_progress()) except: pass diff --git a/apt/package.py b/apt/package.py index 70ddbb1a..9e69a6ec 100644 --- a/apt/package.py +++ b/apt/package.py @@ -1,19 +1,19 @@ # package.py - apt package abstraction -# +# # Copyright (c) 2005 Canonical -# +# # Author: Michael Vogt -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 @@ -92,7 +92,7 @@ class Package(object): if ver == None: #print "No version for: %s (Candidate: %s)" % (self._pkg.Name, UseCandidate) return False - + if ver.FileList == None: print "No FileList for: %s " % self._pkg.Name() return False @@ -147,7 +147,7 @@ class Package(object): base_deps.append(BaseDependency(depOr.TargetPkg.Name, depOr.CompType, depOr.TargetVer, (t == "PreDepends"))) depends_list.append(Dependency(base_deps)) return depends_list - + def candidateDependencies(self): """ return a list of candidate dependencies """ candver = self._depcache.GetCandidateVer(self._pkg) @@ -155,7 +155,7 @@ class Package(object): return [] return self._getDependencies(candver) candidateDependencies = property(candidateDependencies) - + def installedDependencies(self): """ return a list of installed dependencies """ ver = self._pkg.CurrentVer @@ -304,7 +304,7 @@ class Package(object): return "" return self._records.LongDesc rawDescription = property(rawDescription) - + def candidateRecord(self): " return the full pkgrecord as string of the candidate version " if not self._lookupRecord(True): @@ -333,7 +333,7 @@ class Package(object): def markedDelete(self): """ Package is marked for delete """ return self._depcache.MarkedDelete(self._pkg) - markedDelete = property(markedDelete) + markedDelete = property(markedDelete) def markedKeep(self): """ Package is marked for keep """ @@ -356,12 +356,12 @@ class Package(object): isInstalled = property(isInstalled) def isUpgradable(self): - """ Package is upgradable """ + """ Package is upgradable """ return self.isInstalled and self._depcache.IsUpgradable(self._pkg) isUpgradable = property(isUpgradable) def isAutoRemovable(self): - """ + """ Package is installed as a automatic dependency and is no longer required """ @@ -411,7 +411,7 @@ class Package(object): def getChangelog(self, uri=None, cancel_lock=None): """ - Download the changelog of the package and return it as unicode + Download the changelog of the package and return it as unicode string uri: Is the uri to the changelog file. The following named variables @@ -442,7 +442,7 @@ class Package(object): # get the src package name src_pkg = self.sourcePackageName - # assume "main" section + # assume "main" section src_section = "main" # use the section of the candidate as a starting point section = self._depcache.GetCandidateVer(self._pkg).Section @@ -454,7 +454,7 @@ class Package(object): try: # try to get the source version of the pkg, this differs # for some (e.g. libnspr4 on ubuntu) - # this feature only works if the correct deb-src are in the + # this feature only works if the correct deb-src are in the # sources.list # otherwise we fall back to the binary version number src_records = apt_pkg.GetPkgSrcRecords() @@ -563,7 +563,7 @@ class Package(object): "site '%s' isTrusted: '%s'"% (self.component, self.archive, self.origin, self.label, self.site, self.trusted) - + def candidateOrigin(self): ver = self._depcache.GetCandidateVer(self._pkg) if not ver: @@ -623,7 +623,7 @@ class Package(object): object as argument """ self._depcache.Commit(fprogress, iprogress) - + # self-test if __name__ == "__main__": diff --git a/apt/progress.py b/apt/progress.py index a8ab76b6..5a7d1a86 100644 --- a/apt/progress.py +++ b/apt/progress.py @@ -1,19 +1,19 @@ # Progress.py - progress reporting classes -# +# # Copyright (c) 2005 Canonical -# +# # Author: Michael Vogt -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 @@ -69,18 +69,18 @@ class FetchProgress(object): dlFailed : "Failed", dlHit : "Hit", dlIgnored : "Ignored"} - + def __init__(self): self.eta = 0.0 self.percent = 0.0 pass - + def start(self): pass - + def stop(self): pass - + def updateStatus(self, uri, descr, shortDescr, status): pass @@ -115,7 +115,7 @@ class TextFetchProgress(FetchProgress): sys.stdout.flush() return True def stop(self): - print "\rDone downloading " + print "\rDone downloading " def mediaChange(self, medium, drive): """ react to media change events """ res = True; @@ -144,7 +144,7 @@ class DumbInstallProgress(object): class InstallProgress(DumbInstallProgress): """ A InstallProgress that is pretty useful. It supports the attributes 'percent' 'status' and callbacks - for the dpkg errors and conffiles and status changes + for the dpkg errors and conffiles and status changes """ def __init__(self): DumbInstallProgress.__init__(self) diff --git a/aptsources/__init__.py b/aptsources/__init__.py index d6b3605c..ddec2bd9 100644 --- a/aptsources/__init__.py +++ b/aptsources/__init__.py @@ -1,5 +1,5 @@ import apt_pkg - + # init the package system apt_pkg.init() diff --git a/aptsources/distinfo.py b/aptsources/distinfo.py index a6c0faf8..42395bc5 100644 --- a/aptsources/distinfo.py +++ b/aptsources/distinfo.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# +# # distinfo.py - provide meta information for distro repositories # # Copyright (c) 2005 Gustavo Noronha Silva @@ -7,17 +7,17 @@ # # Author: Gustavo Noronha Silva # Sebastian Heinlein -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 @@ -55,7 +55,7 @@ class Template: def has_component(self, comp): ''' Check if the distribution provides the given component ''' return comp in map(lambda c: c.name, self.components) - + def is_mirror(self, url): ''' Check if a given url of a repository is a valid mirror ''' proto, hostname, dir = split_url(url) @@ -190,7 +190,7 @@ class DistInfo: template.match_uri = value elif field == 'MatchURI-%s' % self.arch: template.match_uri = value - elif (field == 'MirrorsFile' or + elif (field == 'MirrorsFile' or field == 'MirrorsFile-%s' % self.arch): if not map_mirror_sets.has_key(value): mirror_set = {} @@ -243,7 +243,7 @@ class DistInfo: if component and not template.has_component(component.name): template.components.append(component) component = None - self.templates.append(template) + self.templates.append(template) if __name__ == "__main__": @@ -257,8 +257,8 @@ if __name__ == "__main__": if template.mirror_set != {}: print "Mirrors: %s" % template.mirror_set.keys() for comp in template.components: - print " %s -%s -%s" % (comp.name, - comp.description, + print " %s -%s -%s" % (comp.name, + comp.description, comp.description_long) for child in template.children: print " %s" % child.description diff --git a/aptsources/distro.py b/aptsources/distro.py index f271bbc4..a94d88ef 100644 --- a/aptsources/distro.py +++ b/aptsources/distro.py @@ -2,20 +2,20 @@ # # Copyright (c) 2004-2007 Canonical Ltd. # 2006-2007 Sebastian Heinlein -# +# # Authors: Sebastian Heinlein # Michael Vogt -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 @@ -48,8 +48,8 @@ class Distribution: def get_sources(self, sourceslist): """ - Find the corresponding template, main and child sources - for the distribution + Find the corresponding template, main and child sources + for the distribution """ self.sourceslist = sourceslist @@ -132,7 +132,7 @@ class Distribution: self.used_media = set(media) self.get_mirrors() - + def get_mirrors(self, mirror_template=None): """ Provide a set of mirrors where you can get the distribution from @@ -203,34 +203,34 @@ class Distribution: '''Helper function that handles comaprision of mirror urls that could contain trailing slashes''' return re.match(mir1.strip("/ "), mir2.rstrip("/ ")) - + # Store all available servers: # Name, URI, active mirrors = [] if len(self.used_servers) < 1 or \ (len(self.used_servers) == 1 and \ compare_mirrors(self.used_servers[0], self.main_server)): - mirrors.append([_("Main server"), self.main_server, True]) - mirrors.append([self._get_mirror_name(self.nearest_server), + mirrors.append([_("Main server"), self.main_server, True]) + mirrors.append([self._get_mirror_name(self.nearest_server), self.nearest_server, False]) elif len(self.used_servers) == 1 and not \ compare_mirrors(self.used_servers[0], self.main_server): - mirrors.append([_("Main server"), self.main_server, False]) + mirrors.append([_("Main server"), self.main_server, False]) # Only one server is used server = self.used_servers[0] - # Append the nearest server if it's not already used + # Append the nearest server if it's not already used if not compare_mirrors(server, self.nearest_server): - mirrors.append([self._get_mirror_name(self.nearest_server), + mirrors.append([self._get_mirror_name(self.nearest_server), self.nearest_server, False]) mirrors.append([self._get_mirror_name(server), server, True]) elif len(self.used_servers) > 1: # More than one server is used. Since we don't handle this case - # in the user interface we set "custom servers" to true and - # append a list of all used servers + # in the user interface we set "custom servers" to true and + # append a list of all used servers mirrors.append([_("Main server"), self.main_server, False]) - mirrors.append([self._get_mirror_name(self.nearest_server), + mirrors.append([self._get_mirror_name(self.nearest_server), self.nearest_server, False]) mirrors.append([_("Custom servers"), None, True]) for server in self.used_servers: @@ -242,7 +242,7 @@ class Distribution: return mirrors - def add_source(self, type=None, + def add_source(self, type=None, uri=None, dist=None, comps=None, comment=""): """ Add distribution specific sources @@ -297,7 +297,7 @@ class Distribution: comps_per_dist = {} comps_per_sdist = {} for s in sources: - if s.type == self.binary_type: + if s.type == self.binary_type: if not comps_per_dist.has_key(s.dist): comps_per_dist[s.dist] = set() map(comps_per_dist[s.dist].add, s.comps) @@ -339,9 +339,9 @@ class Distribution: sources = [] sources.extend(self.main_sources) for source in sources: - if comp in source.comps: + if comp in source.comps: source.comps.remove(comp) - if len(source.comps) < 1: + if len(source.comps) < 1: self.sourceslist.remove(source) def change_server(self, uri): @@ -415,10 +415,10 @@ class UbuntuDistribution(Distribution): mirror_template="http://%s.archive.ubuntu.com/ubuntu/") def get_distro(id=None,codename=None,description=None,release=None): - """ + """ Check the currently used distribution and return the corresponding - distriubtion class that supports distro specific features. - + distriubtion class that supports distro specific features. + If no paramter are given the distro will be auto detected via a call to lsb-release """ @@ -431,7 +431,7 @@ def get_distro(id=None,codename=None,description=None,release=None): del pipe (id, codename, description, release) = lsb_info if id == "Ubuntu": - return UbuntuDistribution(id, codename, description, + return UbuntuDistribution(id, codename, description, release) elif id == "Debian": return DebianDistribution(id, codename, description, release) diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index e0f32f8d..4067920a 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -1,28 +1,28 @@ # aptsource.py - Provide an abstraction of the sources.list -# +# # Copyright (c) 2004-2007 Canonical Ltd. # 2004 Michiel Sikkes # 2006-2007 Sebastian Heinlein -# +# # Author: Michiel Sikkes # Michael Vogt # Sebastian Heinlein -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA - + import string import gettext import re @@ -81,14 +81,14 @@ class SourceEntry: self.comps = [] # list of available componetns (may empty) self.comment = "" # (optional) comment self.line = line # the original sources.list line - if file == None: + if file == None: file = apt_pkg.Config.FindDir("Dir::Etc")+apt_pkg.Config.Find("Dir::Etc::sourcelist") self.file = file # the file that the entry is located in self.parse(line) self.template = None # type DistInfo.Suite self.children = [] - def __eq__(self, other): + def __eq__(self, other): """ equal operator for two sources.list entries """ return (self.disabled == other.disabled and self.type == other.type and @@ -138,7 +138,7 @@ class SourceEntry: if line[0] == "#": self.disabled = True pieces = string.split(line[1:]) - # if it looks not like a disabled deb line return + # if it looks not like a disabled deb line return if not pieces[0] in ("rpm", "rpm-src", "deb", "deb-src"): self.invalid = True return @@ -185,7 +185,7 @@ class SourceEntry: i += 1 self.line = self.line[i:] else: - # disabled, add a "#" + # disabled, add a "#" if string.strip(self.line)[0] != "#": self.line = "#" + self.line @@ -207,7 +207,7 @@ class SourceEntry: line += " #"+self.comment line += "\n" return line - + class NullMatcher(object): """ a Matcher that does nothing """ def match(self, s): @@ -218,7 +218,7 @@ class SourcesList: def __init__(self, withMatcher=True, matcherPath="/usr/share/python-apt/templates/"): - self.list = [] # the actual SourceEntries Type + self.list = [] # the actual SourceEntries Type if withMatcher: self.matcher = SourceEntryMatcher(matcherPath) else: @@ -251,7 +251,7 @@ class SourcesList: def add(self, type, uri, dist, orig_comps, comment="", pos=-1, file=None): """ Add a new source to the sources.list. - The method will search for existing matching repos and will try to + The method will search for existing matching repos and will try to reuse them as far as possible """ # create a working copy of the component list so that @@ -367,7 +367,7 @@ class SourcesList: # try to avoid checking uninterressting sources if source.template == None: continue - # set up a dict with all used child templates and corresponding + # set up a dict with all used child templates and corresponding # source entries if source.template.child == True: key = source.template @@ -405,12 +405,12 @@ class SourceEntryMatcher: _ = gettext.gettext found = False for template in self.templates: - if (re.search(template.match_uri, source.uri) and + if (re.search(template.match_uri, source.uri) and re.match(template.match_name, source.dist)): found = True source.template = template break - elif (template.is_mirror(source.uri) and + elif (template.is_mirror(source.uri) and re.match(template.match_name, source.dist)): found = True source.template = template @@ -430,7 +430,7 @@ if __name__ == "__main__": mirror = is_mirror("http://archive.ubuntu.com/ubuntu/", "http://de.archive.ubuntu.com/ubuntu/") print "is_mirror(): %s" % mirror - + print is_mirror("http://archive.ubuntu.com/ubuntu", "http://de.archive.ubuntu.com/ubuntu/") print is_mirror("http://archive.ubuntu.com/ubuntu/", diff --git a/doc/examples/acquire.py b/doc/examples/acquire.py index eef6c1f7..939c33a2 100644 --- a/doc/examples/acquire.py +++ b/doc/examples/acquire.py @@ -27,7 +27,7 @@ recs = apt_pkg.GetPkgRecords(cache) list = apt_pkg.GetPkgSourceList() list.ReadMainList() -# show the amount fetch needed for a dist-upgrade +# show the amount fetch needed for a dist-upgrade depcache.Upgrade(True) progress = apt.progress.TextFetchProgress() fetcher = apt_pkg.GetAcquire(progress) @@ -67,7 +67,7 @@ for item in fetcher.Items: if item.Complete == False: print "No error, still nothing downloaded (%s)" % item.ErrorText print - + res = fetcher.Run() print "fetcher.Run() returned: %s" % res diff --git a/doc/examples/build-deps.py b/doc/examples/build-deps.py index 65e35f3d..81a8b408 100755 --- a/doc/examples/build-deps.py +++ b/doc/examples/build-deps.py @@ -3,7 +3,7 @@ import apt_pkg import sys -import sets # only needed for python2.3, python2.4 supports this naively +import sets # only needed for python2.3, python2.4 supports this naively def get_source_pkg(pkg, records, depcache): """ get the source package name of a given package """ diff --git a/doc/examples/deb_inspect.py b/doc/examples/deb_inspect.py index 0befd2bb..b57526c6 100755 --- a/doc/examples/deb_inspect.py +++ b/doc/examples/deb_inspect.py @@ -8,7 +8,7 @@ import os.path def Callback(What,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor): """ callback for debExtract """ - + print "%s '%s','%s',%u,%u,%u,%u,%u,%u,%u"\ % (What,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor); diff --git a/doc/examples/gui-inst.py b/doc/examples/gui-inst.py index feefd6ed..9a3b007f 100755 --- a/doc/examples/gui-inst.py +++ b/doc/examples/gui-inst.py @@ -23,7 +23,7 @@ if __name__ == "__main__": win.add(progress) progress.show() win.show() - + cache = apt.cache.Cache(progress.open) if cache["2vcard"].isInstalled: cache["2vcard"].markDelete() diff --git a/doc/examples/progress.py b/doc/examples/progress.py index 2723c382..b90253cb 100644 --- a/doc/examples/progress.py +++ b/doc/examples/progress.py @@ -23,13 +23,13 @@ class TextProgress(apt.OpProgress): class TextFetchProgress(apt.FetchProgress): def __init__(self): pass - + def start(self): pass - + def stop(self): pass - + def updateStatus(self, uri, descr, shortDescr, status): print "UpdateStatus: '%s' '%s' '%s' '%i'" % (uri,descr,shortDescr, status) def pulse(self): diff --git a/doc/examples/recommends.py b/doc/examples/recommends.py index b1094aee..c1a7eb2e 100755 --- a/doc/examples/recommends.py +++ b/doc/examples/recommends.py @@ -19,7 +19,7 @@ for package in cache.Packages: if not current: continue depends = current.DependsList - for (key, attr) in (('Suggests', 'suggested'), + for (key, attr) in (('Suggests', 'suggested'), ('Recommends', 'recommended')): list = depends.get(key, []) for dependency in list: diff --git a/doc/examples/versiontest.py b/doc/examples/versiontest.py index 95f887f2..c4e5f44d 100755 --- a/doc/examples/versiontest.py +++ b/doc/examples/versiontest.py @@ -10,7 +10,7 @@ if len(TestFile) != 1: print "Must have exactly 1 file name"; sys.exit(0); -# Go over the file.. +# Go over the file.. List = open(TestFile[0],"r"); CurLine = 0; while(1): @@ -21,10 +21,10 @@ while(1): Line = string.strip(Line); if len(Line) == 0 or Line[0] == '#': continue; - + Split = re.split("[ \n]",Line); - # Check forward + # Check forward if apt_pkg.VersionCompare(Split[0],Split[1]) != int(Split[2]): print "Comparision failed on line %u. '%s' ? '%s' %i != %i"%(CurLine, Split[0],Split[1],apt_pkg.VersionCompare(Split[0],Split[1]), diff --git a/setup.py b/setup.py index 7024f81e..bdb59ff2 100755 --- a/setup.py +++ b/setup.py @@ -56,7 +56,7 @@ for template in glob.glob('data/templates/*.info.in'): if sys.argv[1] == "build": build_docs() -setup(name="python-apt", +setup(name="python-apt", version="0.6.17", description="Python bindings for APT", author="APT Development Team", diff --git a/tests/cache.py b/tests/cache.py index 47d9a3b4..afcad00d 100644 --- a/tests/cache.py +++ b/tests/cache.py @@ -1,7 +1,7 @@ #!/usr/bin/env python2.4 # # Test for the pkgCache code -# +# import apt_pkg import sys @@ -26,7 +26,7 @@ def main(): c = ver.Arch d = ver.DependsListStr dl = ver.DependsList - # get all dependencies (a dict of string->list, + # get all dependencies (a dict of string->list, # e.g. "depends:" -> [ver1,ver2,..] for dep in dl.keys(): # get the list of each dependency object diff --git a/tests/depcache.py b/tests/depcache.py index f4821b4f..5c78c3a1 100644 --- a/tests/depcache.py +++ b/tests/depcache.py @@ -1,7 +1,7 @@ #!/usr/bin/env python2.4 # # Test for the DepCache code -# +# import apt_pkg import sys diff --git a/tests/lock.py b/tests/lock.py index 5d2697f1..86d704ea 100644 --- a/tests/lock.py +++ b/tests/lock.py @@ -1,7 +1,7 @@ #!/usr/bin/env python2.4 # # Test for the pkgCache code -# +# import apt_pkg import sys, os @@ -9,7 +9,7 @@ import sys, os if __name__ == "__main__": lock = "/tmp/test.lck" - + apt_pkg.init() # system-lock @@ -44,4 +44,4 @@ if __name__ == "__main__": fd = apt_pkg.GetLock(lock,True) print "Lockfile fd (child): %s" % fd sys.exit(0) - + diff --git a/tests/pkgproblemresolver.py b/tests/pkgproblemresolver.py index 27747e43..0ed32ea6 100644 --- a/tests/pkgproblemresolver.py +++ b/tests/pkgproblemresolver.py @@ -1,7 +1,7 @@ #!/usr/bin/env python2.4 # # Test for the DepCache code -# +# import apt_pkg import sys @@ -29,7 +29,7 @@ def main(): fixer.Protect(pkg) # we first try to resolve the problem # with the package that should be installed - # protected + # protected try: fixer.Resolve(True) except SystemError: diff --git a/tests/pkgrecords.py b/tests/pkgrecords.py index d0616d29..43723569 100644 --- a/tests/pkgrecords.py +++ b/tests/pkgrecords.py @@ -2,7 +2,7 @@ # # Test for the PkgSrcRecords code # it segfaults for python-apt < 0.5.37 -# +# import apt_pkg import sys diff --git a/tests/pkgsrcrecords.py b/tests/pkgsrcrecords.py index 28df3f7c..06c4a1ef 100644 --- a/tests/pkgsrcrecords.py +++ b/tests/pkgsrcrecords.py @@ -2,7 +2,7 @@ # # Test for the PkgSrcRecords code # it segfaults for python-apt < 0.5.37 -# +# import apt_pkg import sys diff --git a/tests/test_aptsources.py b/tests/test_aptsources.py index 49fe6afa..c8d84395 100644 --- a/tests/test_aptsources.py +++ b/tests/test_aptsources.py @@ -60,7 +60,7 @@ class TestAptSources(unittest.TestCase): "multiverse" in entry.comps): found = True self.assertTrue(found) - # test to add something new: multiverse *and* + # test to add something new: multiverse *and* # something that is already there before = copy.deepcopy(sources) sources.add("deb","http://de.archive.ubuntu.com/ubuntu/", @@ -105,7 +105,7 @@ class TestAptSources(unittest.TestCase): #print dist_templates for d in ["hardy","hardy-security","hardy-updates","intrepid","hardy-backports"]: self.assertTrue(d in dist_templates) - # test enable + # test enable comp = "restricted" distro.enable_component(comp) found = {} diff --git a/tests/test_debextract.py b/tests/test_debextract.py index 53241e92..c080b26e 100755 --- a/tests/test_debextract.py +++ b/tests/test_debextract.py @@ -7,7 +7,7 @@ def Callback(What,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor): print "%s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % ( What,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor) -member = "data.tar.lzma" +member = "data.tar.lzma" if len(sys.argv) > 2: member = sys.argv[2] apt_inst.debExtract(open(sys.argv[1]), Callback, member) diff --git a/utils/get_debian_mirrors.py b/utils/get_debian_mirrors.py index ccddf8ed..512731ed 100755 --- a/utils/get_debian_mirrors.py +++ b/utils/get_debian_mirrors.py @@ -2,23 +2,23 @@ # # get_debian_mirrors.py # -# Download the latest list with available mirrors from the Debian +# Download the latest list with available mirrors from the Debian # website and extract the hosts from the raw page # # Copyright (c) 2006 Free Software Foundation Europe # # Author: Sebastian Heinlein -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 diff --git a/utils/get_ubuntu_mirrors.py b/utils/get_ubuntu_mirrors.py index 62b18ba6..605edcf5 100755 --- a/utils/get_ubuntu_mirrors.py +++ b/utils/get_ubuntu_mirrors.py @@ -8,17 +8,17 @@ # Copyright (c) 2006 Free Software Foundation Europe # # Author: Sebastian Heinlein -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 diff --git a/utils/get_ubuntu_mirrors_from_lp.py b/utils/get_ubuntu_mirrors_from_lp.py index 7d9116f2..1f41e34b 100755 --- a/utils/get_ubuntu_mirrors_from_lp.py +++ b/utils/get_ubuntu_mirrors_from_lp.py @@ -8,17 +8,17 @@ # Copyright (c) 2006 Free Software Foundation Europe # # Author: Sebastian Heinlein -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -- cgit v1.2.3 From 48af5526d2b8b85fc7f244a471fb58683e70d156 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 9 Jan 2009 21:48:16 +0100 Subject: * apt/debfile.py, apt/package.py: Use @property Use @property instead of x = property(x), where x is the function name. --- apt/debfile.py | 15 +++++------ apt/package.py | 78 +++++++++++++++++++++++++++++----------------------------- 2 files changed, 47 insertions(+), 46 deletions(-) (limited to 'apt') diff --git a/apt/debfile.py b/apt/debfile.py index 33785ea0..49826f6b 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -64,6 +64,7 @@ class DebPackage(object): def __getitem__(self, key): return self._sections[key] + @property def filelist(self): """ return the list of files in the deb """ files = [] @@ -79,7 +80,6 @@ class DebPackage(object): except SystemError, e: return [_("List of files for '%s'could not be read" % self.filename)] return files - filelist = property(filelist) def _isOrGroupSatisfied(self, or_group): """ this function gets a 'or_group' and analyzes if @@ -213,6 +213,7 @@ class DebPackage(object): """ return self.conflicts + @property def conflicts(self): """ List of package names conflicting with this package @@ -222,7 +223,6 @@ class DebPackage(object): if self._sections.has_key(key): conflicts = apt_pkg.ParseDepends(self._sections[key]) return conflicts - conflicts = property(conflicts) def getDepends(self): """ @@ -233,6 +233,7 @@ class DebPackage(object): """ return self.depends + @property def depends(self): """ List of package names on which this package depends on @@ -243,7 +244,6 @@ class DebPackage(object): if self._sections.has_key(key): depends.extend(apt_pkg.ParseDepends(self._sections[key])) return depends - depends = property(depends) def getProvides(self): """ @@ -254,6 +254,7 @@ class DebPackage(object): """ return self.provides + @property def provides(self): """ List of virtual packages which are provided by this package @@ -263,7 +264,6 @@ class DebPackage(object): if self._sections.has_key(key): provides = apt_pkg.ParseDepends(self._sections[key]) return provides - provides = property(provides) def getReplaces(self): """ @@ -274,6 +274,7 @@ class DebPackage(object): """ return self.replaces + @property def replaces(self): """ List of packages which are replaced by this package @@ -283,7 +284,6 @@ class DebPackage(object): if self._sections.has_key(key): replaces = apt_pkg.ParseDepends(self._sections[key]) return replaces - replaces = property(replaces) def replacesRealPkg(self, pkgname, oper, ver): """ @@ -408,13 +408,14 @@ class DebPackage(object): return False return True + @property def missingDeps(self): self._dbg(1, "Installing: %s" % self._needPkgs) if self._needPkgs == None: self.checkDeb() return self._needPkgs - missingDeps = property(missingDeps) + @property def requiredChanges(self): """ gets the required changes to satisfy the depends. returns a tuple with (install, remove, unauthenticated) @@ -435,7 +436,7 @@ class DebPackage(object): if pkg.markedDelete: remove.append(pkg.name) return (install,remove, unauthenticated) - requiredChanges = property(requiredChanges) + def _dbg(self, level, msg): """Write debugging output to sys.stderr. diff --git a/apt/package.py b/apt/package.py index 9e69a6ec..a4840e35 100644 --- a/apt/package.py +++ b/apt/package.py @@ -101,22 +101,18 @@ class Package(object): return True - # basic information (implemented as properties) - - # FIXME once python2.3 is dropped we can use @property instead - # of name = property(name) - + @property def name(self): """ Return the name of the package """ return self._pkg.Name - name = property(name) + @property def id(self): """ Return a uniq ID for the pkg, can be used to store additional information about the pkg """ return self._pkg.ID - id = property(id) + @property def installedVersion(self): """ Return the installed version as string """ ver = self._pkg.CurrentVer @@ -124,8 +120,8 @@ class Package(object): return ver.VerStr else: return None - installedVersion = property(installedVersion) + @property def candidateVersion(self): """ Return the candidate version as string """ ver = self._depcache.GetCandidateVer(self._pkg) @@ -133,7 +129,6 @@ class Package(object): return ver.VerStr else: return None - candidateVersion = property(candidateVersion) def _getDependencies(self, ver): depends_list = [] @@ -148,22 +143,23 @@ class Package(object): depends_list.append(Dependency(base_deps)) return depends_list + @property def candidateDependencies(self): """ return a list of candidate dependencies """ candver = self._depcache.GetCandidateVer(self._pkg) if candver == None: return [] return self._getDependencies(candver) - candidateDependencies = property(candidateDependencies) + @property def installedDependencies(self): """ return a list of installed dependencies """ ver = self._pkg.CurrentVer if ver == None: return [] return self._getDependencies(ver) - installedDependencies = property(installedDependencies) + @property def architecture(self): if not self._lookupRecord(): return None @@ -171,7 +167,6 @@ class Package(object): if sec.has_key("Architecture"): return sec["Architecture"] return None - architecture = property(architecture) def _downloadable(self, useCandidate=True): """ helper, return if the version is downloadable """ @@ -182,16 +177,18 @@ class Package(object): if ver == None: return False return ver.Downloadable + + @property def candidateDownloadable(self): " returns if the canidate is downloadable " return self._downloadable(useCandidate=True) - candidateDownloadable = property(candidateDownloadable) + @property def installedDownloadable(self): " returns if the installed version is downloadable " return self._downloadable(useCandidate=False) - installedDownloadable = property(installedDownloadable) + @property def sourcePackageName(self): """ Return the source package name as string """ if not self._lookupRecord(): @@ -202,20 +199,20 @@ class Package(object): return src else: return self._pkg.Name - sourcePackageName = property(sourcePackageName) + @property def homepage(self): """ Return the homepage field as string """ if not self._lookupRecord(): return None return self._records.Homepage - homepage = property(homepage) + @property def section(self): """ Return the section of the package""" return self._pkg.Section - section = property(section) + @property def priority(self): """ Return the priority (of the candidate version)""" ver = self._depcache.GetCandidateVer(self._pkg) @@ -223,8 +220,8 @@ class Package(object): return ver.PriorityStr else: return None - priority = property(priority) + @property def installedPriority(self): """ Return the priority (of the installed version)""" ver = self._depcache.GetCandidateVer(self._pkg) @@ -232,8 +229,8 @@ class Package(object): return ver.PriorityStr else: return None - installedPriority = property(installedPriority) + @property def summary(self): """ Return the short description (one line summary) """ if not self._lookupRecord(): @@ -242,8 +239,8 @@ class Package(object): desc_iter = ver.TranslatedDescription self._records.Lookup(desc_iter.FileList.pop(0)) return self._records.ShortDesc - summary = property(summary) + @property def description(self, format=True, useDots=False): """ Return the formated long description according to the Debian policy @@ -296,104 +293,105 @@ class Package(object): # Add current line to the description desc += line return desc - description = property(description) + @property def rawDescription(self): """ return the long description (raw)""" if not self._lookupRecord(): return "" return self._records.LongDesc - rawDescription = property(rawDescription) + @property def candidateRecord(self): " return the full pkgrecord as string of the candidate version " if not self._lookupRecord(True): return None return Record(self._records.Record) - candidateRecord = property(candidateRecord) + @property def installedRecord(self): " return the full pkgrecord as string of the installed version " if not self._lookupRecord(False): return None return Record(self._records.Record) - installedRecord = property(installedRecord) # depcache states + @property def markedInstall(self): """ Package is marked for install """ return self._depcache.MarkedInstall(self._pkg) - markedInstall = property(markedInstall) + @property def markedUpgrade(self): """ Package is marked for upgrade """ return self._depcache.MarkedUpgrade(self._pkg) - markedUpgrade = property(markedUpgrade) + @property def markedDelete(self): """ Package is marked for delete """ return self._depcache.MarkedDelete(self._pkg) - markedDelete = property(markedDelete) + @property def markedKeep(self): """ Package is marked for keep """ return self._depcache.MarkedKeep(self._pkg) - markedKeep = property(markedKeep) + @property def markedDowngrade(self): """ Package is marked for downgrade """ return self._depcache.MarkedDowngrade(self._pkg) - markedDowngrade = property(markedDowngrade) + @property def markedReinstall(self): """ Package is marked for reinstall """ return self._depcache.MarkedReinstall(self._pkg) - markedReinstall = property(markedReinstall) + @property def isInstalled(self): """ Package is installed """ return (self._pkg.CurrentVer != None) - isInstalled = property(isInstalled) + @property def isUpgradable(self): """ Package is upgradable """ return self.isInstalled and self._depcache.IsUpgradable(self._pkg) - isUpgradable = property(isUpgradable) + @property def isAutoRemovable(self): """ Package is installed as a automatic dependency and is no longer required """ return self.isInstalled and self._depcache.IsGarbage(self._pkg) - isAutoRemovable = property(isAutoRemovable) + # size + @property def packageSize(self): """ The size of the candidate deb package """ ver = self._depcache.GetCandidateVer(self._pkg) return ver.Size - packageSize = property(packageSize) + @property def installedPackageSize(self): """ The size of the installed deb package """ ver = self._pkg.CurrentVer return ver.Size - installedPackageSize = property(installedPackageSize) + @property def candidateInstalledSize(self, UseCandidate=True): """ The size of the candidate installed package """ ver = self._depcache.GetCandidateVer(self._pkg) - candidateInstalledSize = property(candidateInstalledSize) + @property def installedSize(self): """ The size of the currently installed package """ ver = self._pkg.CurrentVer if ver is None: return 0 return ver.InstalledSize - installedSize = property(installedSize) + @property def installedFiles(self): """ Return the list of unicode names of the files which have @@ -407,7 +405,6 @@ class Package(object): except: return [] return files - installedFiles = property(installedFiles) def getChangelog(self, uri=None, cancel_lock=None): """ @@ -564,6 +561,7 @@ class Package(object): self.origin, self.label, self.site, self.trusted) + @property def candidateOrigin(self): ver = self._depcache.GetCandidateVer(self._pkg) if not ver: @@ -572,7 +570,6 @@ class Package(object): for (verFileIter,index) in ver.FileList: origins.append(self.Origin(self, verFileIter)) return origins - candidateOrigin = property(candidateOrigin) # depcache actions def markKeep(self): @@ -580,6 +577,7 @@ class Package(object): self._pcache.cachePreChange() self._depcache.MarkKeep(self._pkg) self._pcache.cachePostChange() + def markDelete(self, autoFix=True, purge=False): """ mark a package for delete. Run the resolver if autoFix is set. Mark the package as purge (remove with configuration) if 'purge' @@ -596,6 +594,7 @@ class Package(object): Fix.InstallProtect() Fix.Resolve() self._pcache.cachePostChange() + def markInstall(self, autoFix=True, autoInst=True, fromUser=True): """ mark a package for install. Run the resolver if autoFix is set, automatically install required dependencies if autoInst is set @@ -610,6 +609,7 @@ class Package(object): fixer.Protect(self._pkg) fixer.Resolve(True) self._pcache.cachePostChange() + def markUpgrade(self): """ mark a package for upgrade """ if self.isUpgradable: -- cgit v1.2.3 From 47feb903a8bc9b5ac4d93167b4c316ca82caa1b8 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 9 Jan 2009 21:48:57 +0100 Subject: * apt/progress.py: Cleanup This is the first part of a cleanup series. The code has been changed in terms of indentation at some places, the lines have all been shortened to 79 chars or less, everything has been documented, the (non-functional) testing code has been removed, and more... --- apt/progress.py | 352 ++++++++++++++++++++++++++++++++------------------------ 1 file changed, 204 insertions(+), 148 deletions(-) (limited to 'apt') diff --git a/apt/progress.py b/apt/progress.py index 5a7d1a86..51eb2426 100644 --- a/apt/progress.py +++ b/apt/progress.py @@ -18,44 +18,65 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA +"""progress reporting classes. -import sys +This module provides classes for progress reporting. They can be used with +e.g., for reporting progress on the cache opening process, the cache update +progress, or the package install progress. +""" + +import errno +import fcntl import os import re -import fcntl -import string -from errno import * import select +import sys + import apt_pkg -import apt + +__all__ = ('CdromProgress', 'DpkgInstallProgress', 'DumbInstallProgress', + 'FetchProgress', 'InstallProgress', 'OpProgress', 'OpTextProgress', + 'TextFetchProgress') + class OpProgress(object): - """ Abstract class to implement reporting on cache opening - Subclass this class to implement simple Operation progress reporting + """Abstract class to implement reporting on cache opening. + + Subclass this class to implement simple Operation progress reporting. """ + def __init__(self): - pass + self.op = None + self.subOp = None + def update(self, percent): - pass + """Called periodically to update the user interface.""" + def done(self): - pass + """Called once an operation has been completed.""" + class OpTextProgress(OpProgress): - """ A simple text based cache open reporting class """ + """A simple text based cache open reporting class.""" + def __init__(self): OpProgress.__init__(self) + def update(self, percent): - sys.stdout.write("\r%s: %.2i " % (self.subOp,percent)) + """Called periodically to update the user interface.""" + sys.stdout.write("\r%s: %.2i " % (self.subOp, percent)) sys.stdout.flush() + def done(self): + """Called once an operation has been completed.""" sys.stdout.write("\r%s: Done\n" % self.op) - class FetchProgress(object): - """ Report the download/fetching progress - Subclass this class to implement fetch progress reporting + """Report the download/fetching progress. + + Subclass this class to implement fetch progress reporting """ # download status constants @@ -64,46 +85,71 @@ class FetchProgress(object): dlFailed = 2 dlHit = 3 dlIgnored = 4 - dlStatusStr = {dlDone : "Done", - dlQueued : "Queued", - dlFailed : "Failed", - dlHit : "Hit", - dlIgnored : "Ignored"} + dlStatusStr = {dlDone: "Done", + dlQueued: "Queued", + dlFailed: "Failed", + dlHit: "Hit", + dlIgnored: "Ignored"} def __init__(self): self.eta = 0.0 self.percent = 0.0 - pass + # Make checking easier + self.currentBytes = 0 + self.currentItems = 0 + self.totalBytes = 0 + self.totalItems = 0 + self.currentCPS = 0 def start(self): - pass + """Called when the fetching starts.""" def stop(self): - pass + """Called when all files have been fetched.""" def updateStatus(self, uri, descr, shortDescr, status): - pass + """Called when the status of an item changes. + + This happens eg. when the downloads fails or is completed. + """ def pulse(self): - """ called periodically (to update the gui), importend to - return True to continue or False to cancel + """Called periodically to update the user interface. + + Return True to continue or False to cancel. """ - self.percent = ((self.currentBytes + self.currentItems)*100.0)/float(self.totalBytes+self.totalItems) + self.percent = (((self.currentBytes + self.currentItems) * 100.0) / + float(self.totalBytes + self.totalItems)) if self.currentCPS > 0: - self.eta = (self.totalBytes-self.currentBytes)/float(self.currentCPS) + self.eta = ((self.totalBytes - self.currentBytes) / + float(self.currentCPS)) return True + def mediaChange(self, medium, drive): - pass + """react to media change events.""" + class TextFetchProgress(FetchProgress): """ Ready to use progress object for terminal windows """ + def __init__(self): + FetchProgress.__init__(self) self.items = {} + def updateStatus(self, uri, descr, shortDescr, status): + """Called when the status of an item changes. + + This happens eg. when the downloads fails or is completed. + """ if status != self.dlQueued: print "\r%s %s" % (self.dlStatusStr[status], descr) self.items[uri] = status + def pulse(self): + """Called periodically to update the user interface. + + Return True to continue or False to cancel. + """ FetchProgress.pulse(self) if self.currentCPS > 0: s = "[%2.f%%] %sB/s %s" % (self.percent, @@ -114,102 +160,121 @@ class TextFetchProgress(FetchProgress): print "\r%s" % (s), sys.stdout.flush() return True + def stop(self): + """Called when all files have been fetched.""" print "\rDone downloading " + def mediaChange(self, medium, drive): - """ react to media change events """ - res = True; - print "Media change: please insert the disc labeled \ - '%s' in the drive '%s' and press enter" % (medium,drive) - s = sys.stdin.readline() - if(s == 'c' or s == 'C'): - res = false; - return res + """react to media change events.""" + print ("Media change: please insert the disc labeled " + "'%s' in the drive '%s' and press enter") % (medium, drive) + + return raw_input() not in ('c', 'C') + class DumbInstallProgress(object): - """ Report the install progress - Subclass this class to implement install progress reporting + """Report the install progress. + + Subclass this class to implement install progress reporting. """ - def __init__(self): - pass + def startUpdate(self): - pass + """Start update.""" + def run(self, pm): + """Start installation.""" return pm.DoInstall() + def finishUpdate(self): - pass + """Called when update has finished.""" + def updateInterface(self): - pass + """Called periodically to update the user interface""" + class InstallProgress(DumbInstallProgress): - """ A InstallProgress that is pretty useful. - It supports the attributes 'percent' 'status' and callbacks - for the dpkg errors and conffiles and status changes - """ + """An InstallProgress that is pretty useful. + + It supports the attributes 'percent' 'status' and callbacks for the dpkg + errors and conffiles and status changes. + """ + def __init__(self): DumbInstallProgress.__init__(self) self.selectTimeout = 0.1 (read, write) = os.pipe() - self.writefd=write + self.writefd = write self.statusfd = os.fdopen(read, "r") - fcntl.fcntl(self.statusfd.fileno(), fcntl.F_SETFL,os.O_NONBLOCK) + fcntl.fcntl(self.statusfd.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) self.read = "" self.percent = 0.0 self.status = "" + def error(self, pkg, errormsg): - " called when a error is detected during the install " - pass - def conffile(self,current,new): - " called when a conffile question from dpkg is detected " - pass + """Called when a error is detected during the install.""" + + def conffile(self, current, new): + """Called when a conffile question from dpkg is detected.""" + def statusChange(self, pkg, percent, status): - " called when the status changed " - pass + """Called when the status changed.""" + def updateInterface(self): - if self.statusfd != None: - try: - while not self.read.endswith("\n"): - self.read += os.read(self.statusfd.fileno(),1) - except OSError, (errno,errstr): - # resource temporarly unavailable is ignored - if errno != EAGAIN and errnor != EWOULDBLOCK: - print errstr - if self.read.endswith("\n"): - s = self.read - #print s - try: - (status, pkg, percent, status_str) = string.split(s, ":",3) - except ValueError, e: - # silently ignore lines that can't be parsed - self.read = "" - return - #print "percent: %s %s" % (pkg, float(percent)/100.0) - if status == "pmerror": - self.error(pkg,status_str) - elif status == "pmconffile": - # we get a string like this: - # 'current-conffile' 'new-conffile' useredited distedited - match = re.compile("\s*\'(.*)\'\s*\'(.*)\'.*").match(status_str) - if match: - self.conffile(match.group(1), match.group(2)) - elif status == "pmstatus": - if float(percent) != self.percent or \ - status_str != self.status: - self.statusChange(pkg, float(percent), status_str.strip()) - self.percent = float(percent) - self.status = string.strip(status_str) - self.read = "" + """Called periodically to update the interface.""" + if self.statusfd is None: + return + try: + while not self.read.endswith("\n"): + self.read += os.read(self.statusfd.fileno(), 1) + except OSError, (errno_, errstr): + # resource temporarly unavailable is ignored + if errno_ != errno.EAGAIN and errno_ != errno.EWOULDBLOCK: + print errstr + if not self.read.endswith("\n"): + return + + s = self.read + #print s + try: + (status, pkg, percent, status_str) = s.split(":", 3) + except ValueError: + # silently ignore lines that can't be parsed + self.read = "" + return + #print "percent: %s %s" % (pkg, float(percent)/100.0) + if status == "pmerror": + self.error(pkg, status_str) + elif status == "pmconffile": + # we get a string like this: + # 'current-conffile' 'new-conffile' useredited distedited + match = re.match("\s*\'(.*)\'\s*\'(.*)\'.*", status_str) + if match: + self.conffile(match.group(1), match.group(2)) + elif status == "pmstatus": + if float(percent) != self.percent or status_str != self.status: + self.statusChange(pkg, float(percent), + status_str.strip()) + self.percent = float(percent) + self.status = status_str.strip() + self.read = "" + def fork(self): + """Fork.""" return os.fork() + def waitChild(self): + """Wait for child progress to exit.""" while True: - select.select([self.statusfd],[],[], self.selectTimeout) + select.select([self.statusfd], [], [], self.selectTimeout) self.updateInterface() - (pid, res) = os.waitpid(self.child_pid,os.WNOHANG) + (pid, res) = os.waitpid(self.child_pid, os.WNOHANG) if pid == self.child_pid: break return res + def run(self, pm): + """Start installing.""" pid = self.fork() if pid == 0: # child @@ -219,29 +284,31 @@ class InstallProgress(DumbInstallProgress): res = self.waitChild() return os.WEXITSTATUS(res) -class CdromProgress: - """ Report the cdrom add progress - Subclass this class to implement cdrom add progress reporting + +class CdromProgress(object): + """Report the cdrom add progress. + + Subclass this class to implement cdrom add progress reporting. """ + def __init__(self): pass + def update(self, text, step): - """ update is called regularly so that the gui can be redrawn """ - pass + """Called periodically to update the user interface.""" + def askCdromName(self): - pass + """Called to ask for the name of the cdrom.""" + def changeCdrom(self): - pass + """Called to ask for the cdrom to be changed.""" class DpkgInstallProgress(InstallProgress): - """ - Progress handler for a local Debian package installation - """ + """Progress handler for a local Debian package installation.""" + def run(self, debfile): - """ - Start installing the given Debian package - """ + """Start installing the given Debian package.""" self.debfile = debfile self.debname = os.path.basename(debfile).split("_")[0] pid = self.fork() @@ -255,46 +322,35 @@ class DpkgInstallProgress(InstallProgress): return res def updateInterface(self): - """ - Process status messages from dpkg - """ - if self.statusfd != None: - while True: - try: - self.read += os.read(self.statusfd.fileno(),1) - except OSError, (errno,errstr): - # resource temporarly unavailable is ignored - if errno != 11: - print errstr - break - if self.read.endswith("\n"): - statusl = string.split(self.read, ":") - if len(statusl) < 3: - print "got garbage from dpkg: '%s'" % read - self.read = "" - break - status = statusl[2].strip() - #print status - if status == "error": - self.error(self.debname, status) - elif status == "conffile-prompt": - # we get a string like this: - # 'current-conffile' 'new-conffile' useredited distedited - match = re.compile("\s*\'(.*)\'\s*\'(.*)\'.*").match(status_str) - if match: - self.conffile(match.group(1), match.group(2)) - else: - self.status = status - self.read = "" - -# module test code -if __name__ == "__main__": - import apt_pkg - apt_pkg.init() - progress = OpTextProgress() - cache = apt_pkg.GetCache(progress) - depcache = apt_pkg.GetDepCache(cache) - depcache.Init(progress) - - fprogress = TextFetchProgress() - cache.Update(fprogress) + """Process status messages from dpkg.""" + if self.statusfd is None: + return + while True: + try: + self.read += os.read(self.statusfd.fileno(), 1) + except OSError, (errno_, errstr): + # resource temporarly unavailable is ignored + if errno_ != 11: + print errstr + break + if not self.read.endswith("\n"): + continue + + statusl = self.read.split(":") + if len(statusl) < 3: + print "got garbage from dpkg: '%s'" % self.read + self.read = "" + break + status = statusl[2].strip() + #print status + if status == "error": + self.error(self.debname, status) + elif status == "conffile-prompt": + # we get a string like this: + # 'current-conffile' 'new-conffile' useredited distedited + match = re.match("\s*\'(.*)\'\s*\'(.*)\'.*", statusl[3]) + if match: + self.conffile(match.group(1), match.group(2)) + else: + self.status = status + self.read = "" -- cgit v1.2.3 From 9c0e4ac3ec3657c5b77ec4a50b47af08625d3985 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 9 Jan 2009 21:49:42 +0100 Subject: * apt/package.py: Cleanup, move Origin to module-level, enhance Record This commit includes multiple changes: First of all, the code has been adjusted to follow PEP 8 and the documentation has been improved. Secondly, the Origin class has been moved out of the Package class into the module, and its __repr__ has been changed. Thirdly, the Record class has been enhances with some new methods, and the attribute containing the string has been removed, as we can reproduce the string using the TagSection in the _rec attribute. The methods added are __contains__(), __iter__(), get() and iteritems(). Fourthly, the method getChangelog() has been fixed in some areas, especially in the exception handling. The method/property installedFiles() is now enclosing its file access into a try/finally block. All the testing code has been moved into a _test() function for now, until the new testing functionality is implemented. --- apt/package.py | 442 ++++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 277 insertions(+), 165 deletions(-) (limited to 'apt') diff --git a/apt/package.py b/apt/package.py index a4840e35..7817c64c 100644 --- a/apt/package.py +++ b/apt/package.py @@ -18,56 +18,136 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA - +"""Functionality related to packages.""" +import gettext import httplib import sys -import random import re import socket -import string import urllib2 import apt_pkg + +__all__ = 'BaseDependency', 'Dependency', 'Origin', 'Package', 'Record' + + # Set a timeout for the changelog download socket.setdefaulttimeout(2) -#from gettext import gettext as _ -import gettext -def _(s): return gettext.dgettext("python-apt", s) + +def _(string): + """Return the translation of the string.""" + return gettext.dgettext("python-apt", string) + class BaseDependency(object): - " a single dependency " + """A single dependency. + + Attributes defined here: + name - The name of the dependency + relation - The relation (>>,>=,==,<<,<=,) + version - The version depended on + preDepend - Boolean value whether this is a pre-dependency. + """ + def __init__(self, name, rel, ver, pre): self.name = name self.relation = rel self.version = ver self.preDepend = pre + class Dependency(object): + """Represent an Or-group of dependencies. + + Attributes defined here: + or_dependencies - The possible choices + """ + def __init__(self, alternatives): self.or_dependencies = alternatives + +class Origin(object): + """The origin of a version. + + Attributes defined here: + archive - The archive (eg. unstable) + component - The component (eg. main) + label - The Label, as set in the Release file + origin - The Origin, as set in the Release file + site - The hostname of the site. + trusted - Boolean value whether this is trustworthy. + """ + + def __init__(self, pkg, VerFileIter): + self.archive = VerFileIter.Archive + self.component = VerFileIter.Component + self.label = VerFileIter.Label + self.origin = VerFileIter.Origin + self.site = VerFileIter.Site + # check the trust + indexfile = pkg._list.FindIndex(VerFileIter) + if indexfile and indexfile.IsTrusted: + self.trusted = True + else: + self.trusted = False + + def __repr__(self): + return ("") % (self.component, self.archive, + self.origin, self.label, + self.site, self.trusted) + + class Record(object): - """ represents a pkgRecord, can be accessed like a - dictionary and gives the original package record - if accessed as a string """ - def __init__(self, s): - self._str = s - self._rec = apt_pkg.ParseSection(s) + """Represent a pkgRecord. + + It can be accessed like a dictionary and can also give the original package + record if accessed as a string. + """ + + def __init__(self, record_str): + self._rec = apt_pkg.ParseSection(record_str) + def __str__(self): - return self._str + return str(self._rec) + def __getitem__(self, key): - k = self._rec.get(key) - if k is None: - raise KeyError - return k + return self._rec[key] + + def __contains__(self, key): + return self._rec.has_key(key) + + def __iter__(self): + return iter(self._rec.keys()) + + def iteritems(self): + """An iterator over the (key, value) items of the record.""" + for key in self._rec.keys(): + yield key, self._rec[key] + + def get(self, key, default=None): + """Return record[key] if key in record, else `default`. + + The parameter `default` must be either a string or None. + """ + return self._rec.get(key, default) + def has_key(self, key): + """deprecated form of 'key in x'.""" return self._rec.has_key(key) + class Package(object): - """ This class represents a package in the cache + """Representation of a package in a cache. + + This class provides methods and properties for working with a package. It + lets you mark the package for installation, check if it is installed, and + much more. """ + def __init__(self, cache, depcache, records, sourcelist, pcache, pkgiter): """ Init the Package object """ self._cache = cache # low level cache @@ -77,122 +157,135 @@ class Package(object): self._list = sourcelist # sourcelist self._pcache = pcache # python cache in cache.py self._changelog = "" # Cached changelog - pass - # helper def _lookupRecord(self, UseCandidate=True): - """ internal helper that moves the Records to the right - position, must be called before _records is accessed """ + """Internal helper that moves the Records to the right position. + + Must be called before _records is accessed. + """ if UseCandidate: ver = self._depcache.GetCandidateVer(self._pkg) else: ver = self._pkg.CurrentVer # check if we found a version - if ver == None: - #print "No version for: %s (Candidate: %s)" % (self._pkg.Name, UseCandidate) + if ver is None: + #print "No version for: %s (Candidate: %s)" % (self._pkg.Name, + # UseCandidate) return False - if ver.FileList == None: + if ver.FileList is None: print "No FileList for: %s " % self._pkg.Name() return False f, index = ver.FileList.pop(0) - self._records.Lookup((f,index)) + self._records.Lookup((f, index)) return True - @property def name(self): - """ Return the name of the package """ + """Return the name of the package.""" return self._pkg.Name @property def id(self): - """ Return a uniq ID for the pkg, can be used to store - additional information about the pkg """ + """Return a uniq ID for the package. + + This can be used eg. to store additional information about the pkg.""" + return self._pkg.ID + + def __hash__(self): + """Return the hash of the object. + + This returns the same value as ID, which is unique.""" return self._pkg.ID @property def installedVersion(self): - """ Return the installed version as string """ + """Return the installed version as string.""" ver = self._pkg.CurrentVer - if ver != None: + if ver is not None: return ver.VerStr else: return None @property def candidateVersion(self): - """ Return the candidate version as string """ + """Return the candidate version as string.""" ver = self._depcache.GetCandidateVer(self._pkg) - if ver != None: + if ver is not None: return ver.VerStr else: return None def _getDependencies(self, ver): + """Get the dependencies for a given version of a package.""" depends_list = [] depends = ver.DependsList for t in ["PreDepends", "Depends"]: - if not depends.has_key(t): - continue - for depVerList in depends[t]: - base_deps = [] - for depOr in depVerList: - base_deps.append(BaseDependency(depOr.TargetPkg.Name, depOr.CompType, depOr.TargetVer, (t == "PreDepends"))) - depends_list.append(Dependency(base_deps)) + try: + for depVerList in depends[t]: + base_deps = [] + for depOr in depVerList: + base_deps.append(BaseDependency(depOr.TargetPkg.Name, + depOr.CompType, depOr.TargetVer, + (t == "PreDepends"))) + depends_list.append(Dependency(base_deps)) + except KeyError: + pass return depends_list @property def candidateDependencies(self): - """ return a list of candidate dependencies """ + """Return a list of candidate dependencies.""" candver = self._depcache.GetCandidateVer(self._pkg) - if candver == None: + if candver is None: return [] return self._getDependencies(candver) @property def installedDependencies(self): - """ return a list of installed dependencies """ + """Return a list of installed dependencies.""" ver = self._pkg.CurrentVer - if ver == None: + if ver is None: return [] return self._getDependencies(ver) @property def architecture(self): + """Return the Architecture of the package""" if not self._lookupRecord(): return None sec = apt_pkg.ParseSection(self._records.Record) - if sec.has_key("Architecture"): + try: return sec["Architecture"] - return None + except KeyError: + return None def _downloadable(self, useCandidate=True): - """ helper, return if the version is downloadable """ + """Return True if the package is downloadable.""" if useCandidate: ver = self._depcache.GetCandidateVer(self._pkg) else: ver = self._pkg.CurrentVer - if ver == None: + if ver is None: return False return ver.Downloadable @property def candidateDownloadable(self): - " returns if the canidate is downloadable " - return self._downloadable(useCandidate=True) + """Return True if the candidate is downloadable.""" + return self._downloadable(True) @property def installedDownloadable(self): - " returns if the installed version is downloadable " - return self._downloadable(useCandidate=False) + """Return True if the installed version is downloadable.""" + return self._downloadable(False) @property def sourcePackageName(self): - """ Return the source package name as string """ + """Return the source package name as string.""" if not self._lookupRecord(): - if not self._lookupRecord(UseCandidate=False): + if not self._lookupRecord(False): return self._pkg.Name src = self._records.SourcePkg if src != "": @@ -202,19 +295,19 @@ class Package(object): @property def homepage(self): - """ Return the homepage field as string """ + """Return the homepage field as string.""" if not self._lookupRecord(): return None return self._records.Homepage @property def section(self): - """ Return the section of the package""" + """Return the section of the package.""" return self._pkg.Section @property def priority(self): - """ Return the priority (of the candidate version)""" + """Return the priority (of the candidate version).""" ver = self._depcache.GetCandidateVer(self._pkg) if ver: return ver.PriorityStr @@ -223,7 +316,7 @@ class Package(object): @property def installedPriority(self): - """ Return the priority (of the installed version)""" + """Return the priority (of the installed version).""" ver = self._depcache.GetCandidateVer(self._pkg) if ver: return ver.PriorityStr @@ -232,7 +325,7 @@ class Package(object): @property def summary(self): - """ Return the short description (one line summary) """ + """Return the short description (one line summary).""" if not self._lookupRecord(): return "" ver = self._depcache.GetCandidateVer(self._pkg) @@ -242,7 +335,8 @@ class Package(object): @property def description(self, format=True, useDots=False): - """ + """Return the formatted long description. + Return the formated long description according to the Debian policy (Chapter 5.6.13). See http://www.debian.org/doc/debian-policy/ch-controlfields.html @@ -258,14 +352,15 @@ class Package(object): self._records.Lookup(desc_iter.FileList.pop(0)) desc = "" try: - s = unicode(self._records.LongDesc,"utf-8") - except UnicodeDecodeError,e: - s = _("Invalid unicode in description for '%s' (%s). " - "Please report.") % (self.name,e) - lines = string.split(s, "\n") + dsc = unicode(self._records.LongDesc, "utf-8") + except UnicodeDecodeError, err: + dsc = _("Invalid unicode in description for '%s' (%s). " + "Please report.") % (self.name, err) + lines = dsc.split("\n") for i in range(len(lines)): # Skip the first line, since its a duplication of the summary - if i == 0: continue + if i == 0: + continue raw_line = lines[i] if raw_line.strip() == ".": # The line is just line break @@ -296,44 +391,45 @@ class Package(object): @property def rawDescription(self): - """ return the long description (raw)""" + """return the long description (raw).""" if not self._lookupRecord(): return "" return self._records.LongDesc @property def candidateRecord(self): - " return the full pkgrecord as string of the candidate version " + """Return the Record of the candidate version of the package.""" if not self._lookupRecord(True): return None return Record(self._records.Record) @property def installedRecord(self): - " return the full pkgrecord as string of the installed version " + """Return the Record of the candidate version of the package.""" if not self._lookupRecord(False): return None return Record(self._records.Record) # depcache states + @property def markedInstall(self): - """ Package is marked for install """ + """Return True if the package is marked for install.""" return self._depcache.MarkedInstall(self._pkg) @property def markedUpgrade(self): - """ Package is marked for upgrade """ + """Return True if the package is marked for upgrade.""" return self._depcache.MarkedUpgrade(self._pkg) @property def markedDelete(self): - """ Package is marked for delete """ + """Return True if the package is marked for delete.""" return self._depcache.MarkedDelete(self._pkg) @property def markedKeep(self): - """ Package is marked for keep """ + """Return True if the package is marked for keep.""" return self._depcache.MarkedKeep(self._pkg) @property @@ -343,49 +439,51 @@ class Package(object): @property def markedReinstall(self): - """ Package is marked for reinstall """ + """Return True if the package is marked for reinstall.""" return self._depcache.MarkedReinstall(self._pkg) @property def isInstalled(self): - """ Package is installed """ - return (self._pkg.CurrentVer != None) + """Return True if the package is installed.""" + return (self._pkg.CurrentVer is not None) @property def isUpgradable(self): - """ Package is upgradable """ + """Return True if the package is upgradable.""" return self.isInstalled and self._depcache.IsUpgradable(self._pkg) @property def isAutoRemovable(self): - """ - Package is installed as a automatic dependency and is - no longer required + """Return True if the package is no longer required. + + If the package has been installed automatically as a dependency of + another package, and if no packages depend on it anymore, the package + is no longer required. """ return self.isInstalled and self._depcache.IsGarbage(self._pkg) + # sizes - # size @property def packageSize(self): - """ The size of the candidate deb package """ + """Return the size of the candidate deb package.""" ver = self._depcache.GetCandidateVer(self._pkg) return ver.Size @property def installedPackageSize(self): - """ The size of the installed deb package """ + """Return the size of the installed deb package.""" ver = self._pkg.CurrentVer return ver.Size @property def candidateInstalledSize(self, UseCandidate=True): - """ The size of the candidate installed package """ + """Return the size of the candidate installed package.""" ver = self._depcache.GetCandidateVer(self._pkg) @property def installedSize(self): - """ The size of the currently installed package """ + """Return the size of the currently installed package.""" ver = self._pkg.CurrentVer if ver is None: return 0 @@ -393,38 +491,42 @@ class Package(object): @property def installedFiles(self): - """ - Return the list of unicode names of the files which have + """Return a list of files installed by the package. + + Return a list of unicode names of the files which have been installed by this package """ path = "/var/lib/dpkg/info/%s.list" % self.name try: - list = open(path) - files = list.read().decode().split("\n") - list.close() - except: + file_list = open(path) + try: + return file_list.read().decode().split("\n") + finally: + file_list.close() + except EnvironmentError: return [] - return files def getChangelog(self, uri=None, cancel_lock=None): """ Download the changelog of the package and return it as unicode - string - - uri: Is the uri to the changelog file. The following named variables - will be substituted: src_section, prefix, src_pkg and src_ver - For example the Ubuntu changelog: - uri = "http://changelogs.ubuntu.com/changelogs/pool" \\ - "/%(src_section)s/%(prefix)s/%(src_pkg)s" \\ - "/%(src_pkg)s_%(src_ver)s/changelog" - cancel_lock: If this threading.Lock() is set, the download will be - canceled + string. + + The parameter `uri` refers to the uri of the changelog file. It may + contain multiple named variables which will be substitued. These + variables are (src_section, prefix, src_pkg, src_ver). An example is + the Ubuntu changelog: + "http://changelogs.ubuntu.com/changelogs/pool" \\ + "/%(src_section)s/%(prefix)s/%(src_pkg)s" \\ + "/%(src_pkg)s_%(src_ver)s/changelog" + + The parameter `cancel_lock` refers to an instance of threading.Lock, + which if set, prevents the download. """ # Return a cached changelog if available if self._changelog != "": return self._changelog - if uri == None: + if uri is None: if self.candidateOrigin[0].origin == "Debian": uri = "http://packages.debian.org/changelogs/pool" \ "/%(src_section)s/%(prefix)s/%(src_pkg)s" \ @@ -449,6 +551,7 @@ class Package(object): src_ver = self.candidateVersion #print "bin: %s" % binver try: + # FIXME: This try-statement is too long ... # try to get the source version of the pkg, this differs # for some (e.g. libnspr4 on ubuntu) # this feature only works if the correct deb-src are in the @@ -468,7 +571,7 @@ class Package(object): else: # fail into the error handler raise SystemError - except SystemError, e: + except SystemError: src_ver = bin_ver l = section.split("/") @@ -481,26 +584,27 @@ class Package(object): prefix = "lib" + src_pkg[3] # stip epoch - l = string.split(src_ver,":") + l = src_ver.split(":") if len(l) > 1: src_ver = "".join(l[1:]) - uri = uri % {"src_section" : src_section, - "prefix" : prefix, - "src_pkg" : src_pkg, - "src_ver" : src_ver} + uri = uri % {"src_section": src_section, + "prefix": prefix, + "src_pkg": src_pkg, + "src_ver": src_ver} try: # Check if the download was canceled - if cancel_lock and cancel_lock.isSet(): return "" + if cancel_lock and cancel_lock.isSet(): + return "" changelog_file = urllib2.urlopen(uri) # do only get the lines that are new changelog = "" regexp = "^%s \((.*)\)(.*)$" % (re.escape(src_pkg)) - i=0 while True: # Check if the download was canceled - if cancel_lock and cancel_lock.isSet(): return "" + if cancel_lock and cancel_lock.isSet(): + return "" # Read changelog line by line line_raw = changelog_file.readline() if line_raw == "": @@ -516,7 +620,7 @@ class Package(object): # and from changelog too installed = self.installedVersion if installed and ":" in installed: - installed = installed.split(":",1)[1] + installed = installed.split(":", 1)[1] changelog_ver = match.group(1) if changelog_ver and ":" in changelog_ver: changelog_ver = changelog_ver.split(":", 1)[1] @@ -530,59 +634,47 @@ class Package(object): if len(changelog) == 0: changelog = _("The list of changes is not available") self._changelog = changelog - except urllib2.HTTPError,e: + + # FIXME: Ubuntu-specific part. + except urllib2.HTTPError: return _("The list of changes is not available yet.\n\n" "Please use http://launchpad.net/ubuntu/+source/%s/%s/" "+changelog\n" "until the changes become available or try again " - "later.") % (srcpkg, srcver), - except IOError, httplib.BadStatusLine: - return _("Failed to download the list of changes. \nPlease " - "check your Internet connection.") + "later.") % (src_pkg, src_ver) + except (IOError, httplib.BadStatusLine): + return _("Failed to download the list of changes. \nPlease " + "check your Internet connection.") return self._changelog - # canidate origin - class Origin: - def __init__(self, pkg, VerFileIter): - self.component = VerFileIter.Component - self.archive = VerFileIter.Archive - self.origin = VerFileIter.Origin - self.label = VerFileIter.Label - self.site = VerFileIter.Site - # check the trust - indexfile = pkg._list.FindIndex(VerFileIter) - if indexfile and indexfile.IsTrusted: - self.trusted = True - else: - self.trusted = False - def __repr__(self): - return "component: '%s' archive: '%s' origin: '%s' label: '%s' " \ - "site '%s' isTrusted: '%s'"% (self.component, self.archive, - self.origin, self.label, - self.site, self.trusted) - @property def candidateOrigin(self): + """Return the Origin() of the candidate version.""" ver = self._depcache.GetCandidateVer(self._pkg) if not ver: return None origins = [] - for (verFileIter,index) in ver.FileList: - origins.append(self.Origin(self, verFileIter)) + for (verFileIter, index) in ver.FileList: + origins.append(Origin(self, verFileIter)) return origins # depcache actions + def markKeep(self): - """ mark a package for keep """ + """Mark a package for keep.""" self._pcache.cachePreChange() self._depcache.MarkKeep(self._pkg) self._pcache.cachePostChange() def markDelete(self, autoFix=True, purge=False): - """ mark a package for delete. Run the resolver if autoFix is set. - Mark the package as purge (remove with configuration) if 'purge' - is set. - """ + """Mark a package for install. + + If autoFix is True, the resolver will be run, trying to fix broken + packages. This is the default. + + If purge is True, remove the configuration files of the package as + well. The default is to keep the configuration. + """ self._pcache.cachePreChange() self._depcache.MarkDelete(self._pkg, purge) # try to fix broken stuffsta @@ -596,9 +688,18 @@ class Package(object): self._pcache.cachePostChange() def markInstall(self, autoFix=True, autoInst=True, fromUser=True): - """ mark a package for install. Run the resolver if autoFix is set, - automatically install required dependencies if autoInst is set - record it as automatically installed when fromuser is set to false + """Mark a package for install. + + If autoFix is True, the resolver will be run, trying to fix broken + packages. This is the default. + + If autoInst is True, the dependencies of the packages will be installed + automatically. This is the default. + + If fromUser is True, this package will not be marked as automatically + installed. This is the default. Set it to False if you want to be able + to remove the package at a later stage if no other package depends on + it. """ self._pcache.cachePreChange() self._depcache.MarkInstall(self._pkg, autoInst, fromUser) @@ -611,23 +712,31 @@ class Package(object): self._pcache.cachePostChange() def markUpgrade(self): - """ mark a package for upgrade """ + """Mark a package for upgrade.""" if self.isUpgradable: self.markInstall() else: # FIXME: we may want to throw a exception here - sys.stderr.write("MarkUpgrade() called on a non-upgrable pkg: '%s'\n" %self._pkg.Name) + sys.stderr.write(("MarkUpgrade() called on a non-upgrable pkg: " + "'%s'\n") % self._pkg.Name) def commit(self, fprogress, iprogress): - """ commit the changes, need a FetchProgress and InstallProgress - object as argument + """Commit the changes. + + The parameter `fprogress` refers to a FetchProgress() object, as + found in apt.progress. + + The parameter `iprogress` refers to an InstallProgress() object, as + found in apt.progress. """ self._depcache.Commit(fprogress, iprogress) -# self-test -if __name__ == "__main__": +def _test(): + """Self-test.""" print "Self-test for the Package modul" + import random + import apt apt_pkg.init() cache = apt_pkg.GetCache() depcache = apt_pkg.GetDepCache(cache) @@ -653,35 +762,38 @@ if __name__ == "__main__": print "PackageSize: %s " % pkg.packageSize print "Dependencies: %s" % pkg.installedDependencies for dep in pkg.candidateDependencies: - print ",".join(["%s (%s) (%s) (%s)" % (o.name,o.version,o.relation, o.preDepend) for o in dep.or_dependencies]) + print ",".join("%s (%s) (%s) (%s)" % (o.name, o.version, o.relation, + o.preDepend) for o in dep.or_dependencies) print "arch: %s" % pkg.architecture print "homepage: %s" % pkg.homepage - print "rec: ",pkg.candidateRecord + print "rec: ", pkg.candidateRecord # now test install/remove - import apt progress = apt.progress.OpTextProgress() cache = apt.Cache(progress) - for i in [True, False]: + for i in True, False: print "Running install on random upgradable pkgs with AutoFix: %s " % i - for name in cache.keys(): - pkg = cache[name] + for pkg in cache: if pkg.isUpgradable: - if random.randint(0,1) == 1: + if random.randint(0, 1) == 1: pkg.markInstall(i) print "Broken: %s " % cache._depcache.BrokenCount print "InstCount: %s " % cache._depcache.InstCount print # get a new cache - for i in [True, False]: + for i in True, False: print "Randomly remove some packages with AutoFix: %s" % i cache = apt.Cache(progress) for name in cache.keys(): - if random.randint(0,1) == 1: + if random.randint(0, 1) == 1: try: cache[name].markDelete(i) except SystemError: print "Error trying to remove: %s " % name print "Broken: %s " % cache._depcache.BrokenCount print "DelCount: %s " % cache._depcache.DelCount + +# self-test +if __name__ == "__main__": + _test() -- cgit v1.2.3 From 91939209a22a0d2d3c807432edd3b8c504c45ebd Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 9 Jan 2009 21:50:26 +0100 Subject: * apt/cdrom.py: Cleanup, support sources.list.d --- apt/cdrom.py | 85 +++++++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 64 insertions(+), 21 deletions(-) (limited to 'apt') diff --git a/apt/cdrom.py b/apt/cdrom.py index c0e57094..797c644e 100644 --- a/apt/cdrom.py +++ b/apt/cdrom.py @@ -1,14 +1,49 @@ +# cdrom.py - CDROM handling +# +# Copyright (c) 2005 Canonical +# Copyright (c) 2009 Julian Andres Klode +# +# Author: Michael Vogt +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 2 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 +# USA +"""Classes related to cdrom handling.""" +import glob + import apt_pkg -from progress import CdromProgress +from apt.progress import CdromProgress + class Cdrom(object): + """Support for apt-cdrom like features. + + This class has several optional parameters for initialisation, which may + be used to influence the behaviour of the object: + + The optional parameter `progress` is a CdromProgress() subclass, which will + ask for the correct cdrom, etc. If not specified or None, a CdromProgress() + object will be used. + + The optional parameter `mountpoint` may be used to specify an alternative + mountpoint. + + If the optional parameter `nomount` is True, the cdroms will not be + mounted. This is the default behaviour. + """ + def __init__(self, progress=None, mountpoint=None, nomount=True): - """ Support for apt-cdrom like features. - Options: - - progress: optional progress.CdromProgress() subclass - - mountpoint: optional alternative mountpoint - - nomount: do not mess with mount/umount the CD - """ self._cdrom = apt_pkg.GetCdrom() if progress is None: self._progress = CdromProgress() @@ -16,32 +51,40 @@ class Cdrom(object): self._progress = progress # see if we have a alternative mountpoint if mountpoint is not None: - apt_pkg.Config.Set("Acquire::cdrom::mount",mountpoint) + apt_pkg.Config.Set("Acquire::cdrom::mount", mountpoint) # do not mess with mount points by default - if nomount is True: + if nomount: apt_pkg.Config.Set("APT::CDROM::NoMount", "true") else: apt_pkg.Config.Set("APT::CDROM::NoMount", "false") + def add(self): - " add cdrom to the sources.list " + """Add cdrom to the sources.list.""" return self._cdrom.Add(self._progress) + def ident(self): - " identify the cdrom " + """Identify the cdrom.""" (res, ident) = self._cdrom.Ident(self._progress) if res: return ident - return None + @property def inSourcesList(self): - " check if the cdrom is already in the current sources.list " - cdid = self.ident() - if cdid is None: + """Check if the cdrom is already in the current sources.list.""" + cd_id = self.ident() + if cd_id is None: # FIXME: throw exception instead return False - # FIXME: check sources.list.d/ as well - for line in open(apt_pkg.Config.FindFile("Dir::Etc::sourcelist")): - line = line.strip() - if not line.startswith("#") and cdid in line: - return True + # Get a list of files + src = glob.glob(apt_pkg.Config.FindDir("Dir::Etc::sourceparts") + '*') + src.append(apt_pkg.Config.FindFile("Dir::Etc::sourcelist")) + # Check each file + for fname in src: + fobj = open(fname) + try: + for line in fobj: + if not line.lstrip().startswith("#") and cd_id in line: + return True + finally: + fobj.close() return False - -- cgit v1.2.3 From 2aaecf61a8f464a78d62fee62941bfda7244b031 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 9 Jan 2009 21:50:43 +0100 Subject: * apt/gtk/widgets.py: Fix it and clean it up. Everything is now documented, we follow PEP 8 (except for naming conventions), etc. --- apt/gtk/widgets.py | 259 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 164 insertions(+), 95 deletions(-) (limited to 'apt') diff --git a/apt/gtk/widgets.py b/apt/gtk/widgets.py index 968e2a77..0becf994 100644 --- a/apt/gtk/widgets.py +++ b/apt/gtk/widgets.py @@ -1,28 +1,26 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- -""" -widgets - GTK widgets to show the progress and status of apt - -Copyright (c) 2004,2005 Canonical Ltd. - -Authors: Michael Vogt - Sebastian Heinlein - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License as -published by the Free Software Foundation; either version 2 of the -License, or (at your option) any later version. - -his program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA -""" +# +# Copyright (c) 2004-2005 Canonical +# +# Authors: Michael Vogt +# Sebastian Heinlein +# Julian Andres Klode +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 2 of the +# License, or (at your option) any later version. +# +# his program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 +# USA +"""GObject-powered progress classes and a GTK+ status widget.""" from gettext import gettext as _ import os @@ -39,15 +37,32 @@ import vte import apt import apt_pkg + +def mksig(params=(), run=gobject.SIGNAL_RUN_FIRST, rettype=gobject.TYPE_NONE): + """Simplified Create a gobject signal. + + This allows us to write signals easier, because we just need to define the + type of the parameters (in most cases). + + ``params`` is a tuple which defines the types of the arguments. + """ + return (run, rettype, params) + + class GOpProgress(gobject.GObject, apt.progress.OpProgress): + """Operation progress with GObject signals. + + Signals: - __gsignals__ = {"status-changed":(gobject.SIGNAL_RUN_FIRST, - gobject.TYPE_NONE, - (gobject.TYPE_STRING, gobject.TYPE_INT)), - "status-started":(gobject.SIGNAL_RUN_FIRST, - gobject.TYPE_NONE, ()), - "status-finished":(gobject.SIGNAL_RUN_FIRST, - gobject.TYPE_NONE, ())} + status-changed(str: operation, int: percent) + status-started() - Not Implemented yet + status-finished() + + """ + + __gsignals__ = {"status-changed": mksig((str, int)), + "status-started": mksig(), + "status-finished": mksig()} def __init__(self): apt.progress.OpProgress.__init__(self) @@ -55,31 +70,38 @@ class GOpProgress(gobject.GObject, apt.progress.OpProgress): self._context = glib.main_context_default() def update(self, percent): + """Called to update the percentage done""" self.emit("status-changed", self.op, percent) while self._context.pending(): self._context.iteration() def done(self): + """Called when all operation have finished.""" self.emit("status-finished") + class GInstallProgress(gobject.GObject, apt.progress.InstallProgress): + """Installation progress with GObject signals. + Signals: + + status-changed(str: status, int: percent) + status-started() + status-finished() + status-timeout() + status-error() + status-conffile() + + """ # Seconds until a maintainer script will be regarded as hanging INSTALL_TIMEOUT = 5 * 60 - __gsignals__ = {"status-changed":(gobject.SIGNAL_RUN_FIRST, - gobject.TYPE_NONE, - (gobject.TYPE_STRING, gobject.TYPE_INT)), - "status-started":(gobject.SIGNAL_RUN_FIRST, - gobject.TYPE_NONE, ()), - "status-timeout":(gobject.SIGNAL_RUN_FIRST, - gobject.TYPE_NONE, ()), - "status-error":(gobject.SIGNAL_RUN_FIRST, - gobject.TYPE_NONE, ()), - "status-conffile":(gobject.SIGNAL_RUN_FIRST, - gobject.TYPE_NONE, ()), - "status-finished":(gobject.SIGNAL_RUN_FIRST, - gobject.TYPE_NONE, ())} + __gsignals__ = {"status-changed": mksig((str, int)), + "status-started": mksig(), + "status-timeout": mksig(), + "status-error": mksig(), + "status-conffile": mksig(), + "status-finished": mksig()} def __init__(self, term): apt.progress.InstallProgress.__init__(self) @@ -89,32 +111,57 @@ class GInstallProgress(gobject.GObject, apt.progress.InstallProgress): self.term = term reaper = vte.reaper_get() reaper.connect("child-exited", self.childExited) - self.env = ["VTE_PTY_KEEP_FD=%s"% self.writefd, + self.env = ["VTE_PTY_KEEP_FD=%s" % self.writefd, "DEBIAN_FRONTEND=gnome", "APT_LISTCHANGES_FRONTEND=gtk"] self._context = glib.main_context_default() def childExited(self, term, pid, status): + """Called when a child process exits""" self.apt_status = os.WEXITSTATUS(status) self.finished = True def error(self, pkg, errormsg): + """Called when an error happens. + + Emits: status-error() + """ self.emit("status-error") def conffile(self, current, new): + """Called during conffile. + + Emits: status-conffile() + """ self.emit("status-conffile") def startUpdate(self): + """Called when the update starts. + + Emits: status-started() + """ self.emit("status-started") def finishUpdate(self): + """Called when the update finished. + + Emits: status-finished() + """ self.emit("status-finished") def statusChange(self, pkg, percent, status): + """Called when the status changed. + + Emits: status-changed(status, percent) + """ self.time_last_update = time.time() self.emit("status-changed", status, percent) def updateInterface(self): + """Called periodically to update the interface. + + Emits: status-timeout() [When a timeout happens] + """ apt.progress.InstallProgress.updateInterface(self) while self._context.pending(): self._context.iteration() @@ -122,34 +169,55 @@ class GInstallProgress(gobject.GObject, apt.progress.InstallProgress): self.emit("status-timeout") def fork(self): + """Fork the process.""" return self.term.forkpty(envv=self.env) def waitChild(self): + """Wait for the child process to exit.""" while not self.finished: self.updateInterface() return self.apt_status -class GDpkgInstallProgress(apt.progress.DpkgInstallProgress,GInstallProgress): +class GDpkgInstallProgress(apt.progress.DpkgInstallProgress, GInstallProgress): + """An InstallProgress for local installations. + + Signals: + + status-changed(str: status, int: percent) + status-started() - Not Implemented yet + status-finished() + status-timeout() - When the maintainer script hangs + status-error() - When an error happens + status-conffile() - On Conffile + """ def run(self, debfile): + """Install the given package.""" apt.progress.DpkgInstallProgress.run(self, debfile) def updateInterface(self): + """Called periodically to update the interface. + + Emits: status-timeout() [When a timeout happens]""" apt.progress.DpkgInstallProgress.updateInterface(self) if self.time_last_update + self.INSTALL_TIMEOUT < time.time(): self.emit("status-timeout") class GFetchProgress(gobject.GObject, apt.progress.FetchProgress): + """A Fetch Progress with GObject signals. + + Signals: - __gsignals__ = {"status-changed":(gobject.SIGNAL_RUN_FIRST, - gobject.TYPE_NONE, - (gobject.TYPE_STRING, gobject.TYPE_INT)), - "status-started":(gobject.SIGNAL_RUN_FIRST, - gobject.TYPE_NONE, ()), - "status-finished":(gobject.SIGNAL_RUN_FIRST, - gobject.TYPE_NONE, ())} + status-changed(str: description, int: percent) + status-started() + status-finished() + """ + + __gsignals__ = {"status-changed": mksig((str, int)), + "status-started": mksig(), + "status-finished": mksig()} def __init__(self): apt.progress.FetchProgress.__init__(self) @@ -170,17 +238,17 @@ class GFetchProgress(gobject.GObject, apt.progress.FetchProgress): apt.progress.FetchProgress.pulse(self) currentItem = self.currentItems + 1 if currentItem > self.totalItems: - currentItem = self.totalItems + currentItem = self.totalItems if self.currentCPS > 0: text = (_("Downloading file %(current)li of %(total)li with " "%(speed)s/s") % \ - {"current" : currentItem, - "total" : self.totalItems, - "speed" : humanize_size(self.currentCPS)}) + {"current": currentItem, + "total": self.totalItems, + "speed": apt_pkg.SizeToStr(self.currentCPS)}) else: text = (_("Downloading file %(current)li of %(total)li") % \ - {"current" : currentItem, - "total" : self.totalItems }) + {"current": currentItem, + "total": self.totalItems}) self.emit("status-changed", text, self.percent) while self._context.pending(): self._context.iteration() @@ -188,7 +256,8 @@ class GFetchProgress(gobject.GObject, apt.progress.FetchProgress): class GtkAptProgress(gtk.VBox): - """ + """Graphical progress for installation/fetch/operations. + This widget provides a progress bar, a terminal and a status bar for showing the progress of package manipulation tasks. @@ -215,6 +284,7 @@ class GtkAptProgress(gtk.VBox): gtk.main() """ + def __init__(self): gtk.VBox.__init__(self) self.set_spacing(6) @@ -226,7 +296,7 @@ class GtkAptProgress(gtk.VBox): self._progressbar = gtk.ProgressBar() # Setup the always italic status label self._label = gtk.Label() - attr_list = pango.AttrList() + attr_list = pango.AttrList() attr_list.insert(pango.AttrStyle(pango.STYLE_ITALIC, 0, -1)) self._label.set_attributes(attr_list) self._label.set_ellipsize(pango.ELLIPSIZE_END) @@ -239,7 +309,8 @@ class GtkAptProgress(gtk.VBox): self._progress_open = GOpProgress() self._progress_open.connect("status-changed", self._on_status_changed) self._progress_open.connect("status-started", self._on_status_started) - self._progress_open.connect("status-finished", self._on_status_finished) + self._progress_open.connect("status-finished", + self._on_status_finished) self._progress_fetch = GFetchProgress() self._progress_fetch.connect("status-changed", self._on_status_changed) self._progress_fetch.connect("status-started", self._on_status_started) @@ -273,52 +344,45 @@ class GtkAptProgress(gtk.VBox): self._on_status_timeout) def clear(self): - """ - Reset all status information - """ + """Reset all status information.""" self._label.set_label("") - self._progress.set_fraction(0) + self._progressbar.set_fraction(0) self._expander.set_expanded(False) @property def open(self): - """ - Return the cache opening progress handler. - """ + """Return the cache opening progress handler.""" return self._progress_open @property def install(self): - """ - Return the install progress handler - """ + """Return the install progress handler.""" return self._progress_install @property def dpkg_install(self): - """ - Return the install progress handler for dpkg - """ + """Return the install progress handler for dpkg.""" return self._dpkg_progress_install @property def fetch(self): - """ - Return the fetch progress handler - """ + """Return the fetch progress handler.""" return self._progress_fetch def _on_status_started(self, progress): + """Called when something starts.""" self._on_status_changed(progress, _("Starting..."), 0) while gtk.events_pending(): gtk.main_iteration() def _on_status_finished(self, progress): + """Called when something finished.""" self._on_status_changed(progress, _("Complete"), 100) while gtk.events_pending(): gtk.main_iteration() def _on_status_changed(self, progress, status, percent): + """Called when the status changed.""" self._label.set_text(status) if percent is None: self._progressbar.pulse() @@ -328,18 +392,18 @@ class GtkAptProgress(gtk.VBox): gtk.main_iteration() def _on_status_timeout(self, progress): - selt._expander.set_expanded(True) + """Called when timeout happens.""" + self._expander.set_expanded(True) while gtk.events_pending(): gtk.main_iteration() def cancel_download(self): - """ - Cancel a currently running download - """ + """Cancel a currently running download.""" self._progress_fetch.cancel() def show_terminal(self, expanded=False): - """ + """Show the expander for the terminal. + Show an expander with a terminal widget which provides a way to interact with dpkg """ @@ -350,31 +414,33 @@ class GtkAptProgress(gtk.VBox): gtk.main_iteration() def hide_terminal(self): - """ - Hide the expander with the terminal widget - """ + """Hide the expander with the terminal widget.""" self._expander.hide() while gtk.events_pending(): gtk.main_iteration() def show(self): + """Show the Box""" gtk.HBox.show(self) self._label.show() self._progressbar.show() while gtk.events_pending(): gtk.main_iteration() -if __name__ == "__main__": + +def _test(): + """Test function""" import sys - import debfile + + from apt.debfile import DebPackage win = gtk.Window() - apt_progress = GAptProgress() + apt_progress = GtkAptProgress() win.set_title("GtkAptProgress Demo") win.add(apt_progress) apt_progress.show() win.show() - cache = apt.cache.Cache(apt_progress.get_open_progress()) + cache = apt.cache.Cache(apt_progress.open) pkg = cache["xterm"] if pkg.isInstalled: pkg.markDelete() @@ -382,13 +448,16 @@ if __name__ == "__main__": pkg.markInstall() apt_progress.show_terminal(True) try: - cache.commit(apt_progress.get_fetch_progress(), - apt_progress.get_install_progress()) - except: - pass + cache.commit(apt_progress.fetch, apt_progress.install) + except Exception, exc: + print >> sys.stderr, "Exception happened:", exc if len(sys.argv) > 1: deb = DebPackage(sys.argv[1], cache) - deb.install(apt_progress.get_dpkg_install_progress()) + deb.install(apt_progress.dpkg_install) gtk.main() + +if __name__ == "__main__": + _test() + # vim: ts=4 et sts=4 -- cgit v1.2.3 From 5b0beca05b84919581e44af83824c47d7a49f02b Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 9 Jan 2009 21:51:09 +0100 Subject: * apt/debfile: Fix and cleanup This fixes various problems. Most things should work now. I have also removed the get*() methods, because we have not had these methods in a stable python-apt release yet, and they are deprecated. --- apt/debfile.py | 402 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 198 insertions(+), 204 deletions(-) (limited to 'apt') diff --git a/apt/debfile.py b/apt/debfile.py index 49826f6b..9730be35 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -19,24 +19,25 @@ # along with GDebi; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # - -import warnings -warnings.filterwarnings("ignore", "apt API not stable yet", FutureWarning) -import apt_inst, apt_pkg -import sys -import os +"""Classes for working with locally available Debian packages.""" from gettext import gettext as _ +import os +import sys + +import apt_inst +import apt_pkg + # Constants for comparing the local package file with the version in the cache -(VERSION_NONE, - VERSION_OUTDATED, - VERSION_SAME, - VERSION_NEWER) = range(4) +(VERSION_NONE, VERSION_OUTDATED, VERSION_SAME, VERSION_NEWER) = range(4) + class NoDebArchiveException(IOError): - pass + """Exception which is raised if a file is no Debian archive.""" + class DebPackage(object): + """A Debian Package (.deb file).""" _supported_data_members = ("data.tar.gz", "data.tar.bz2", "data.tar.lzma") @@ -56,7 +57,9 @@ class DebPackage(object): " open given debfile " self.filename = filename if not apt_inst.arCheckMember(open(self.filename), "debian-binary"): - raise NoDebArchiveException, _("This is not a valid DEB archive, missing '%s' member" % "debian-binary") + raise NoDebArchiveException(_("This is not a valid DEB archive, " + "missing '%s' member" % + "debian-binary")) control = apt_inst.debExtractControl(open(self.filename)) self._sections = apt_pkg.ParseSection(control) self.pkgname = self._sections["Package"] @@ -66,25 +69,30 @@ class DebPackage(object): @property def filelist(self): - """ return the list of files in the deb """ + """return the list of files in the deb.""" files = [] - def extract_cb(What,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor): - #print "%s '%s','%s',%u,%u,%u,%u,%u,%u,%u"\ - # % (What,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor) - files.append(Name) + + def extract_cb(what, name, *_): + files.append(name) + for member in self._supported_data_members: if apt_inst.arCheckMember(open(self.filename), member): try: - apt_inst.debExtract(open(self.filename), extract_cb, member) + apt_inst.debExtract(open(self.filename), extract_cb, + member) break - except SystemError, e: - return [_("List of files for '%s'could not be read" % self.filename)] + except SystemError: + return [_("List of files for '%s'could not be read" % + self.filename)] return files def _isOrGroupSatisfied(self, or_group): - """ this function gets a 'or_group' and analyzes if - at least one dependency of this group is already satisfied """ - self._dbg(2,"_checkOrGroup(): %s " % (or_group)) + """Return True if at least one dependency of the or-group is satisfied. + + This method gets an 'or_group' and analyzes if at least one dependency + of this group is already satisfied. + """ + self._dbg(2, "_checkOrGroup(): %s " % (or_group)) for dep in or_group: depname = dep[0] @@ -92,9 +100,10 @@ class DebPackage(object): oper = dep[2] # check for virtual pkgs - if not self._cache.has_key(depname): + if not depname in self._cache: if self._cache.isVirtualPackage(depname): - self._dbg(3,"_isOrGroupSatisfied(): %s is virtual dep" % depname) + self._dbg(3, "_isOrGroupSatisfied(): %s is virtual dep" % + depname) for pkg in self._cache.getProvidingPackages(depname): if pkg.isInstalled: return True @@ -102,24 +111,17 @@ class DebPackage(object): inst = self._cache[depname] instver = inst.installedVersion - if instver != None and apt_pkg.CheckDep(instver,oper,ver) == True: + if instver is not None and apt_pkg.CheckDep(instver, oper, ver): return True return False - def _satisfyOrGroup(self, or_group): - """ try to satisfy the or_group """ - - or_found = False - virtual_pkg = None - + """Try to satisfy the or_group.""" for dep in or_group: - depname = dep[0] - ver = dep[1] - oper = dep[2] + depname, ver, oper = dep # if we don't have it in the cache, it may be virtual - if not self._cache.has_key(depname): + if not depname in self._cache: if not self._cache.isVirtualPackage(depname): continue providers = self._cache.getProvidingPackages(depname) @@ -131,15 +133,15 @@ class DebPackage(object): # now check if we can satisfy the deps with the candidate(s) # in the cache - cand = self._cache[depname] - candver = self._cache._depcache.GetCandidateVer(cand._pkg) - if not candver: + pkg = self._cache[depname] + cand = self._cache._depcache.GetCandidateVer(pkg._pkg) + if not cand: continue - if not apt_pkg.CheckDep(candver.VerStr,oper,ver): + if not apt_pkg.CheckDep(cand.VerStr, oper, ver): continue # check if we need to install it - self._dbg(2,"Need to get: %s" % depname) + self._dbg(2, "Need to get: %s" % depname) self._needPkgs.append(depname) return True @@ -147,36 +149,40 @@ class DebPackage(object): or_str = "" for dep in or_group: or_str += dep[0] - if dep != or_group[len(or_group)-1]: + if dep != or_group[-1]: or_str += "|" - self._failureString += _("Dependency is not satisfiable: %s\n" % or_str) + self._failureString += _("Dependency is not satisfiable: %s\n" % + or_str) return False def _checkSinglePkgConflict(self, pkgname, ver, oper): - """ returns true if a pkg conflicts with a real installed/marked - pkg """ + """Return True if a pkg conflicts with a real installed/marked pkg.""" # FIXME: deal with conflicts against its own provides # (e.g. Provides: ftp-server, Conflicts: ftp-server) - self._dbg(3, "_checkSinglePkgConflict() pkg='%s' ver='%s' oper='%s'" % (pkgname, ver, oper)) - pkgver = None - cand = self._cache[pkgname] - if cand.isInstalled: - pkgver = cand.installedVersion - elif cand.markedInstall: - pkgver = cand.candidateVersion + self._dbg(3, "_checkSinglePkgConflict() pkg='%s' ver='%s' oper='%s'" % + (pkgname, ver, oper)) + + pkg = self._cache[pkgname] + if pkg.isInstalled: + pkgver = pkg.installedVersion + elif pkg.markedInstall: + pkgver = pkg.candidateVersion + else: + return False #print "pkg: %s" % pkgname #print "ver: %s" % ver #print "pkgver: %s " % pkgver #print "oper: %s " % oper - if (pkgver and apt_pkg.CheckDep(pkgver,oper,ver) and - not self.replacesRealPkg(pkgname, oper, ver)): - self._failureString += _("Conflicts with the installed package '%s'" % cand.name) + if (apt_pkg.CheckDep(pkgver, oper, ver) and not + self.replacesRealPkg(pkgname, oper, ver)): + self._failureString += _("Conflicts with the installed package " + "'%s'" % pkg.name) return True return False def _checkConflictsOrGroup(self, or_group): - """ check the or-group for conflicts with installed pkgs """ - self._dbg(2,"_checkConflictsOrGroup(): %s " % (or_group)) + """Check the or-group for conflicts with installed pkgs.""" + self._dbg(2, "_checkConflictsOrGroup(): %s " % (or_group)) or_found = False virtual_pkg = None @@ -187,152 +193,116 @@ class DebPackage(object): oper = dep[2] # check conflicts with virtual pkgs - if not self._cache.has_key(depname): + if not depname in self._cache: # FIXME: we have to check for virtual replaces here as # well (to pass tests/gdebi-test8.deb) if self._cache.isVirtualPackage(depname): for pkg in self._cache.getProvidingPackages(depname): self._dbg(3, "conflicts virtual check: %s" % pkg.name) # P/C/R on virtal pkg, e.g. ftpd - if self.pkgName == pkg.name: + if self.pkgname == pkg.name: self._dbg(3, "conflict on self, ignoring") continue - if self._checkSinglePkgConflict(pkg.name,ver,oper): + if self._checkSinglePkgConflict(pkg.name, ver, oper): self._installedConflicts.add(pkg.name) continue - if self._checkSinglePkgConflict(depname,ver,oper): + if self._checkSinglePkgConflict(depname, ver, oper): self._installedConflicts.add(depname) - return len(self._installedConflicts) != 0 - - def getConflicts(self): - """ - Return list of package names conflicting with this package. - - WARNING: This method will is deprecated. Please use the - attribute DebPackage.depends instead. - """ - return self.conflicts + return bool(self._installedConflicts) @property def conflicts(self): - """ - List of package names conflicting with this package - """ - conflicts = [] + """List of package names conflicting with this package.""" key = "Conflicts" - if self._sections.has_key(key): - conflicts = apt_pkg.ParseDepends(self._sections[key]) - return conflicts - - def getDepends(self): - """ - Return list of package names on which this package depends on. - - WARNING: This method will is deprecated. Please use the - attribute DebPackage.depends instead. - """ - return self.depends + try: + return apt_pkg.ParseDepends(self._sections[key]) + except KeyError: + return [] @property def depends(self): - """ - List of package names on which this package depends on - """ + """List of package names on which this package depends on.""" depends = [] # find depends - for key in ["Depends","PreDepends"]: - if self._sections.has_key(key): + for key in "Depends", "PreDepends": + try: depends.extend(apt_pkg.ParseDepends(self._sections[key])) + except KeyError: + pass return depends - def getProvides(self): - """ - Return list of virtual packages which are provided by this package. - - WARNING: This method will is deprecated. Please use the - attribute DebPackage.provides instead. - """ - return self.provides - @property def provides(self): - """ - List of virtual packages which are provided by this package - """ - provides = [] + """List of virtual packages which are provided by this package.""" key = "Provides" - if self._sections.has_key(key): - provides = apt_pkg.ParseDepends(self._sections[key]) - return provides - - def getReplaces(self): - """ - Return list of packages which are replaced by this package. - - WARNING: This method will is deprecated. Please use the - attribute DebPackage.replaces instead. - """ - return self.replaces + try: + return apt_pkg.ParseDepends(self._sections[key]) + except KeyError: + return [] @property def replaces(self): - """ - List of packages which are replaced by this package - """ - replaces = [] + """List of packages which are replaced by this package.""" key = "Replaces" - if self._sections.has_key(key): - replaces = apt_pkg.ParseDepends(self._sections[key]) - return replaces + try: + return apt_pkg.ParseDepends(self._sections[key]) + except KeyError: + return [] def replacesRealPkg(self, pkgname, oper, ver): + """Return True if a given non-virtual package is replaced. + + Return True if the deb packages replaces a real (not virtual) + packages named (pkgname, oper, ver). """ - return True if the deb packages replaces a real (not virtual) - packages named pkgname, oper, ver - """ - self._dbg(3, "replacesPkg() %s %s %s" % (pkgname,oper,ver)) - pkgver = None - cand = self._cache[pkgname] - if cand.isInstalled: - pkgver = cand.installedVersion - elif cand.markedInstall: - pkgver = cand.candidateVersion - for or_group in self.getReplaces(): + self._dbg(3, "replacesPkg() %s %s %s" % (pkgname, oper, ver)) + pkg = self._cache[pkgname] + if pkg.isInstalled: + pkgver = pkg.installedVersion + elif pkg.markedInstall: + pkgver = pkg.candidateVersion + else: + pkgver = None + for or_group in self.replaces: for (name, ver, oper) in or_group: - if (name == pkgname and - apt_pkg.CheckDep(pkgver,oper,ver)): - self._dbg(3, "we have a replaces in our package for the conflict against '%s'" % (pkgname)) + if (name == pkgname and apt_pkg.CheckDep(pkgver, oper, ver)): + self._dbg(3, "we have a replaces in our package for the " + "conflict against '%s'" % (pkgname)) return True return False def checkConflicts(self): - """ check if the pkg conflicts with a existing or to be installed - package. Return True if the pkg is ok """ + """Check if there are conflicts with existing or selected packages. + + Check if the package conflicts with a existing or to be installed + package. Return True if the pkg is OK. + """ res = True - for or_group in self.getConflicts(): + for or_group in self.conflicts: if self._checkConflictsOrGroup(or_group): #print "Conflicts with a exisiting pkg!" #self._failureString = "Conflicts with a exisiting pkg!" res = False return res - def compareToVersionInCache(self, useInstalled=True): - """ checks if the pkg is already installed or availabe in the cache - and if so in what version, returns if the version of the deb - is not available,older,same,newer + """Compare the package to the version available in the cache. + + Checks if the package is already installed or availabe in the cache + and if so in what version, returns one of (VERSION_NONE, + VERSION_OUTDATED, VERSION_SAME, VERSION_NEWER). """ - self._dbg(3,"compareToVersionInCache") + self._dbg(3, "compareToVersionInCache") pkgname = self._sections["Package"] debver = self._sections["Version"] - self._dbg(1,"debver: %s" % debver) - if self._cache.has_key(pkgname): + self._dbg(1, "debver: %s" % debver) + if pkgname in self._cache: if useInstalled: cachever = self._cache[pkgname].installedVersion else: cachever = self._cache[pkgname].candidateVersion - if cachever != None: - cmp = apt_pkg.VersionCompare(cachever,debver) + if cachever is not None: + cmp = apt_pkg.VersionCompare(cachever, debver) self._dbg(1, "CompareVersion(debver,instver): %s" % cmp) if cmp == 0: return VERSION_SAME @@ -343,12 +313,13 @@ class DebPackage(object): return VERSION_NONE def checkDeb(self): - self._dbg(3,"checkDepends") + """Check if the package is installable.""" + self._dbg(3, "checkDepends") # check arch arch = self._sections["Architecture"] if arch != "all" and arch != apt_pkg.Config.Find("APT::Architecture"): - self._dbg(1,"ERROR: Wrong architecture dude!") + self._dbg(1, "ERROR: Wrong architecture dude!") self._failureString = _("Wrong architecture '%s'" % arch) return False @@ -366,7 +337,7 @@ class DebPackage(object): return False # try to satisfy the dependencies - res = self._satisfyDepends(self.getDepends()) + res = self._satisfyDepends(self.depends) if not res: return False @@ -376,20 +347,23 @@ class DebPackage(object): return False if self._cache._depcache.BrokenCount > 0: - self._failureString = _("Failed to satisfy all dependencies (broken cache)") + self._failureString = _("Failed to satisfy all dependencies " + "(broken cache)") # clean the cache again self._cache.clear() return False return True def satisfyDependsStr(self, dependsstr): + """Satisfy the dependencies in the given string.""" return self._satisfyDepends(apt_pkg.ParseDepends(dependsstr)) def _satisfyDepends(self, depends): + """Satisfy the dependencies.""" # turn off MarkAndSweep via a action group (if available) try: _actiongroup = apt_pkg.GetPkgActionGroup(self._cache._depcache) - except AttributeError, e: + except AttributeError: pass # check depends for or_group in depends: @@ -410,15 +384,17 @@ class DebPackage(object): @property def missingDeps(self): + """Return missing dependencies.""" self._dbg(1, "Installing: %s" % self._needPkgs) - if self._needPkgs == None: + if self._needPkgs is None: self.checkDeb() return self._needPkgs @property def requiredChanges(self): - """ gets the required changes to satisfy the depends. - returns a tuple with (install, remove, unauthenticated) + """Get the changes required to satisfy the dependencies. + + Returns: a tuple with (install, remove, unauthenticated) """ install = [] remove = [] @@ -435,83 +411,98 @@ class DebPackage(object): unauthenticated.append(pkg.name) if pkg.markedDelete: remove.append(pkg.name) - return (install,remove, unauthenticated) - + return (install, remove, unauthenticated) def _dbg(self, level, msg): - """Write debugging output to sys.stderr. - """ + """Write debugging output to sys.stderr.""" if level <= self.debug: print >> sys.stderr, msg def install(self, installProgress=None): - """ Install the package """ - if installProgress == None: - res = os.system("/usr/sbin/dpkg -i %s" % self.filename) + """Install the package.""" + if installProgress is None: + return os.system("dpkg -i %s" % self.filename) else: installProgress.startUpdate() res = installProgress.run(self.filename) installProgress.finishUpdate() - return res + return res + class DscSrcPackage(DebPackage): + """A locally available source package.""" + def __init__(self, filename=None, cache=None): - DebPackage.__init__(self, filename, cache) - self.depends = [] - self.conflicts = [] - self.binaries = [] - if filename != None: + DebPackage.__init__(self, None, cache) + self._depends = [] + self._conflicts = [] + self._binaries = [] + if filename is not None: self.open(filename) - def getConflicts(self): - return self.conflicts - def getDepends(self): - return self.depends + + @property + def depends(self): + """Return the dependencies of the package""" + return self._depends + + @property + def conflicts(self): + """Return the dependencies of the package""" + return self._conflicts + def open(self, file): - depends_tags = ["Build-Depends:", "Build-Depends-Indep:"] - conflicts_tags = ["Build-Conflicts:", "Build-Conflicts-Indep:"] - for line in open(file): - # check b-d and b-c - for tag in depends_tags: - if line.startswith(tag): - key = line[len(tag):].strip() - self.depends.extend(apt_pkg.ParseSrcDepends(key)) - for tag in conflicts_tags: - if line.startswith(tag): - key = line[len(tag):].strip() - self.conflicts.extend(apt_pkg.ParseSrcDepends(key)) - # check binary and source and version - if line.startswith("Source:"): - self.pkgName = line[len("Source:"):].strip() - if line.startswith("Binary:"): - self.binaries = [pkg.strip() for pkg in line[len("Binary:"):].split(",")] - if line.startswith("Version:"): - self._sections["Version"] = line[len("Version:"):].strip() - # we are at the end - if line.startswith("-----BEGIN PGP SIGNATURE-"): - break + """Open the package.""" + depends_tags = ["Build-Depends", "Build-Depends-Indep"] + conflicts_tags = ["Build-Conflicts", "Build-Conflicts-Indep"] + + fobj = open(file) + tagfile = apt_pkg.ParseTagFile(fobj) + sec = tagfile.Section + try: + while tagfile.Step() == 1: + for tag in depends_tags: + if not sec.has_key(tag): + continue + self._depends.extend(apt_pkg.ParseSrcDepends(sec[tag])) + for tag in conflicts_tags: + if not sec.has_key(tag): + continue + self._conflicts.extend(apt_pkg.ParseSrcDepends(sec[tag])) + if sec.has_key('Source'): + self.pkgname = sec['Source'] + if sec.has_key('Binary'): + self.binaries = sec['Binary'].split(', ') + if sec.has_key('Version'): + self._sections['Version'] = sec['Version'] + finally: + fobj.close() + s = _("Install Build-Dependencies for " - "source package '%s' that builds %s\n" - ) % (self.pkgName, " ".join(self.binaries)) + "source package '%s' that builds %s\n") % (self.pkgname, + " ".join(self.binaries)) self._sections["Description"] = s def checkDeb(self): + """Check if the package is installable..""" if not self.checkConflicts(): for pkgname in self._installedConflicts: if self._cache[pkgname]._pkg.Essential: - raise Exception, _("A essential package would be removed") + raise Exception(_("A essential package would be removed")) self._cache[pkgname].markDelete() # FIXME: a additional run of the checkConflicts() # after _satisfyDepends() should probably be done return self._satisfyDepends(self.depends) -if __name__ == "__main__": - from cache import Cache - from progress import DpkgInstallProgress + +def _test(): + """Test function""" + from apt.cache import Cache + from apt.progress import DpkgInstallProgress cache = Cache() vp = "www-browser" - print "%s virtual: %s" % (vp,cache.isVirtualPackage(vp)) + #print "%s virtual: %s" % (vp, cache.isVirtualPackage(vp)) providers = cache.getProvidingPackages(vp) print "Providers for %s :" % vp for pkg in providers: @@ -537,3 +528,6 @@ if __name__ == "__main__": s = DscSrcPackage(cache=cache) d = "libc6 (>= 2.3.2), libaio (>= 0.3.96) | libaio1 (>= 0.3.96)" print s._satisfyDepends(apt_pkg.ParseDepends(d)) + +if __name__ == "__main__": + _test() -- cgit v1.2.3 From db05cdcf94ca8e746eb4e89cd81725b607f2ccbf Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 9 Jan 2009 21:51:34 +0100 Subject: * apt/gtk/widgets: Reformat docstrings a bit, for sphinx Sphinx autodoc requires reStructuredText in docstrings, we format the list of signals with light markup. --- apt/gtk/widgets.py | 59 +++++++++++++++++------------------------------------- 1 file changed, 18 insertions(+), 41 deletions(-) (limited to 'apt') diff --git a/apt/gtk/widgets.py b/apt/gtk/widgets.py index 0becf994..34cc2759 100644 --- a/apt/gtk/widgets.py +++ b/apt/gtk/widgets.py @@ -54,9 +54,9 @@ class GOpProgress(gobject.GObject, apt.progress.OpProgress): Signals: - status-changed(str: operation, int: percent) - status-started() - Not Implemented yet - status-finished() + * status-changed(str: operation, int: percent) + * status-started() - Not Implemented yet + * status-finished() """ @@ -85,12 +85,12 @@ class GInstallProgress(gobject.GObject, apt.progress.InstallProgress): Signals: - status-changed(str: status, int: percent) - status-started() - status-finished() - status-timeout() - status-error() - status-conffile() + * status-changed(str: status, int: percent) + * status-started() + * status-finished() + * status-timeout() + * status-error() + * status-conffile() """ # Seconds until a maintainer script will be regarded as hanging @@ -184,12 +184,12 @@ class GDpkgInstallProgress(apt.progress.DpkgInstallProgress, GInstallProgress): Signals: - status-changed(str: status, int: percent) - status-started() - Not Implemented yet - status-finished() - status-timeout() - When the maintainer script hangs - status-error() - When an error happens - status-conffile() - On Conffile + * status-changed(str: status, int: percent) + * status-started() - Not Implemented yet + * status-finished() + * status-timeout() - When the maintainer script hangs + * status-error() - When an error happens + * status-conffile() - On Conffile """ def run(self, debfile): @@ -210,9 +210,9 @@ class GFetchProgress(gobject.GObject, apt.progress.FetchProgress): Signals: - status-changed(str: description, int: percent) - status-started() - status-finished() + * status-changed(str: description, int: percent) + * status-started() + * status-finished() """ __gsignals__ = {"status-changed": mksig((str, int)), @@ -260,29 +260,6 @@ class GtkAptProgress(gtk.VBox): This widget provides a progress bar, a terminal and a status bar for showing the progress of package manipulation tasks. - - A simple example code snippet to install/remove a package: - - import pygtk - pygtk.require('2.0') - import gtk - - import apt.widgets - - win = gtk.Window() - progress = apt.widgets.GtkAptProgress() - win.set_title("GtkAptProgress Demo") - win.add(progress) - progress.show() - win.show() - - cache = apt.cache.Cache(progress.open)) - cache["xterm"].markDelete() - progress.show_terminal(expanded=True) - cache.commit(progress.fetch), - progress.install) - - gtk.main() """ def __init__(self): -- cgit v1.2.3 From 0cb387c7aa2f4b873bbd9202c875e66774b8918e Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 11 Jan 2009 18:32:34 +0100 Subject: * apt/cache.py: PEP 8 cleanup, no deprecated raise --- apt/cache.py | 98 +++++++++++++++++++++++++++++++++++++----------------------- 1 file changed, 61 insertions(+), 37 deletions(-) (limited to 'apt') diff --git a/apt/cache.py b/apt/cache.py index 530d56a0..303bb99f 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -19,41 +19,47 @@ # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA +import os +import sys + import apt_pkg from apt import Package import apt.progress -import os -import sys + class FetchCancelledException(IOError): - " Exception that is thrown when the user cancels a fetch operation " - pass + """Exception that is thrown when the user cancels a fetch operation.""" + + class FetchFailedException(IOError): - " Exception that is thrown when fetching fails " - pass + """Exception that is thrown when fetching fails.""" + + class LockFailedException(IOError): - " Exception that is thrown when locking fails " - pass + """Exception that is thrown when locking fails.""" + class Cache(object): - """ Dictionary-like package cache - This class has all the packages that are available in it's - dictionary + """Dictionary-like package cache. + + This class has all the packages that are available in it's + dictionary """ def __init__(self, progress=None, rootdir=None, memonly=False): self._callbacks = {} if memonly: # force apt to build its caches in memory - apt_pkg.Config.Set("Dir::Cache::pkgcache","") + apt_pkg.Config.Set("Dir::Cache::pkgcache", "") if rootdir: apt_pkg.Config.Set("Dir", rootdir) - apt_pkg.Config.Set("Dir::State::status", rootdir + "/var/lib/dpkg/status") + apt_pkg.Config.Set("Dir::State::status", + rootdir + "/var/lib/dpkg/status") self.open(progress) def _runCallbacks(self, name): """ internal helper to run a callback """ - if self._callbacks.has_key(name): + if name in self._callbacks: for callback in self._callbacks[name]: callback() @@ -99,7 +105,7 @@ class Cache(object): raise StopIteration def has_key(self, key): - return self._dict.has_key(key) + return key in self._dict def __contains__(self, key): return key in self._dict @@ -130,18 +136,20 @@ class Cache(object): @property def requiredDownload(self): - """ get the size of the packages that are required to download """ + """Get the size of the packages that are required to download.""" pm = apt_pkg.GetPackageManager(self._depcache) fetcher = apt_pkg.GetAcquire() pm.GetArchives(fetcher, self._list, self._records) return fetcher.FetchNeeded + @property def additionalRequiredSpace(self): - """ get the size of the additional required space on the fs """ + """Get the size of the additional required space on the fs.""" return self._depcache.UsrSize + @property def reqReinstallPkgs(self): - " return the packages not downloadable packages in reqreinst state " + """Return the packages not downloadable packages in reqreinst state.""" reqreinst = set() for pkg in self: if (not pkg.candidateDownloadable and @@ -164,14 +172,15 @@ class Cache(object): if item.StatIdle: transient = True continue - errMsg += "Failed to fetch %s %s\n" % (item.DescURI,item.ErrorText) + errMsg += "Failed to fetch %s %s\n" % (item.DescURI, + item.ErrorText) failed = True # we raise a exception if the download failed or it was cancelt if res == fetcher.ResultCancelled: - raise FetchCancelledException, errMsg + raise FetchCancelledException(errMsg) elif failed: - raise FetchFailedException, errMsg + raise FetchFailedException(errMsg) return res def _fetchArchives(self, fetcher, pm): @@ -181,7 +190,7 @@ class Cache(object): lockfile = apt_pkg.Config.FindDir("Dir::Cache::Archives") + "lock" lock = apt_pkg.GetLock(lockfile) if lock < 0: - raise LockFailedException, "Failed to lock %s" % lockfile + raise LockFailedException("Failed to lock %s" % lockfile) try: # this may as well throw a SystemError exception @@ -220,7 +229,7 @@ class Cache(object): lockfile = apt_pkg.Config.FindDir("Dir::State::Lists") + "lock" lock = apt_pkg.GetLock(lockfile) if lock < 0: - raise LockFailedException, "Failed to lock %s" % lockfile + raise LockFailedException("Failed to lock %s" % lockfile) try: if fetchProgress == None: @@ -260,16 +269,17 @@ class Cache(object): if res == pm.ResultCompleted: break if res == pm.ResultFailed: - raise SystemError, "installArchives() failed" + raise SystemError("installArchives() failed") # reload the fetcher for media swaping fetcher.Shutdown() return (res == pm.ResultCompleted) def clear(self): - """ Unmark all changes """ - self._depcache.Init() + """ Unmark all changes """ + self._depcache.Init() # cache changes + def cachePostChange(self): " called internally if the cache has changed, emit a signal then " self._runCallbacks("cache_post_change") @@ -282,32 +292,40 @@ class Cache(object): def connect(self, name, callback): """ connect to a signal, currently only used for cache_{post,pre}_{changed,open} """ - if not self._callbacks.has_key(name): + if not name in self._callbacks: self._callbacks[name] = [] self._callbacks[name].append(callback) + # ----------------------------- experimental interface + + class Filter(object): """ Filter base class """ + def apply(self, pkg): """ Filter function, return True if the package matchs a filter criteria and False otherwise """ return True + class MarkedChangesFilter(Filter): """ Filter that returns all marked changes """ + def apply(self, pkg): if pkg.markedInstall or pkg.markedDelete or pkg.markedUpgrade: return True else: return False + class FilteredCache(object): """ A package cache that is filtered. Can work on a existing cache or create a new one """ + def __init__(self, cache=None, progress=None): if cache == None: self.cache = Cache(progress) @@ -317,17 +335,25 @@ class FilteredCache(object): self.cache.connect("cache_post_open", self.filterCachePostChange) self._filtered = {} self._filters = [] + def __len__(self): return len(self._filtered) def __getitem__(self, key): return self.cache._dict[key] + def __iter__(self): + for pkgname in self._filtered: + yield self.cache[pkgname] + def keys(self): return self._filtered.keys() def has_key(self, key): - return self._filtered.has_key(key) + return key in self._filtered + + def __contains__(self, key): + return key in self._filtered def _reapplyFilter(self): " internal helper to refilter " @@ -339,7 +365,7 @@ class FilteredCache(object): break def setFilter(self, filter): - " set the current active filter " + """Set the current active filter.""" self._filters = [] self._filters.append(filter) #self._reapplyFilter() @@ -347,7 +373,7 @@ class FilteredCache(object): self.cache.cachePostChange() def filterCachePostChange(self): - " called internally if the cache changes, emit a signal then " + """Called internally if the cache changes, emit a signal then.""" #print "filterCachePostChange()" self._reapplyFilter() @@ -355,17 +381,15 @@ class FilteredCache(object): # self.cache.connect(name, callback) def __getattr__(self, key): - " we try to look exactly like a real cache " + """we try to look exactly like a real cache.""" #print "getattr: %s " % key - if self.__dict__.has_key(key): - return self.__dict__[key] - else: - return getattr(self.cache, key) + return getattr(self.cache, key) def cache_pre_changed(): print "cache pre changed" + def cache_post_changed(): print "cache post changed" @@ -377,7 +401,7 @@ if __name__ == "__main__": c = Cache(apt.progress.OpTextProgress()) c.connect("cache_pre_change", cache_pre_changed) c.connect("cache_post_change", cache_post_changed) - print c.has_key("aptitude") + print "aptitude" in c p = c["aptitude"] print p.name print len(c) @@ -397,7 +421,7 @@ if __name__ == "__main__": for d in ["/tmp/pytest", "/tmp/pytest/partial"]: if not os.path.exists(d): os.mkdir(d) - apt_pkg.Config.Set("Dir::Cache::Archives","/tmp/pytest") + apt_pkg.Config.Set("Dir::Cache::Archives", "/tmp/pytest") pm = apt_pkg.GetPackageManager(c._depcache) fetcher = apt_pkg.GetAcquire(apt.progress.TextFetchProgress()) c._fetchArchives(fetcher, pm) -- cgit v1.2.3 From 2e4443bbd9872f5599c9a8eb93a65d6c34c83ca2 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 12 Jan 2009 17:01:34 +0100 Subject: Cleanup: Comparisons to True/False, ==/!= None, deprecated modules --- apt/cache.py | 16 +++++------ aptsources/distinfo.py | 16 +++++------ aptsources/distro.py | 13 +++++---- aptsources/sourceslist.py | 54 +++++++++++++++++-------------------- doc/examples/action.py | 4 +-- doc/examples/all_deps.py | 4 +-- doc/examples/build-deps.py | 3 +-- doc/examples/depcache.py | 4 +-- doc/examples/dependant-pkgs.py | 2 +- doc/examples/gui-inst.py | 9 +------ doc/examples/progress.py | 9 +++---- doc/examples/versiontest.py | 3 +-- doc/source/conf.py | 18 +++++++------ doc/source/examples/missing-deps.py | 1 + setup.py | 9 +++---- tests/depcache.py | 2 +- tests/pkgproblemresolver.py | 2 +- tests/test_aptsources_ports.py | 18 ++++++++----- tests/test_debextract.py | 19 ++++++++----- 19 files changed, 98 insertions(+), 108 deletions(-) (limited to 'apt') diff --git a/apt/cache.py b/apt/cache.py index f134ab0a..ff3149f5 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -76,12 +76,12 @@ class Cache(object): self._dict = {} # build the packages dict - if progress != None: + if progress is not None: progress.Op = "Building data structures" i=last=0 size=len(self._cache.Packages) for pkg in self._cache.Packages: - if progress != None and last+100 < i: + if progress is not None and last+100 < i: progress.update(i/float(size)*100) last=i # drop stuff with no versions (cruft) @@ -91,7 +91,7 @@ class Cache(object): self, pkg) i += 1 - if progress != None: + if progress is not None: progress.done() self._runCallbacks("cache_post_open") @@ -216,7 +216,7 @@ class Cache(object): return providers for pkg in self: v = self._depcache.GetCandidateVer(pkg._pkg) - if v == None: + if v is None: continue for p in v.ProvidesList: if virtual == p[0]: @@ -232,7 +232,7 @@ class Cache(object): raise LockFailedException("Failed to lock %s" % lockfile) try: - if fetchProgress == None: + if fetchProgress is None: fetchProgress = apt.progress.FetchProgress() return self._cache.Update(fetchProgress, self._list) finally: @@ -253,9 +253,9 @@ class Cache(object): # Current a failed download will just display "error" # which is less than optimal! - if fetchProgress == None: + if fetchProgress is None: fetchProgress = apt.progress.FetchProgress() - if installProgress == None: + if installProgress is None: installProgress = apt.progress.InstallProgress() pm = apt_pkg.GetPackageManager(self._depcache) @@ -327,7 +327,7 @@ class FilteredCache(object): """ def __init__(self, cache=None, progress=None): - if cache == None: + if cache is None: self.cache = Cache(progress) else: self.cache = cache diff --git a/aptsources/distinfo.py b/aptsources/distinfo.py index 3c499b52..59fa7e02 100644 --- a/aptsources/distinfo.py +++ b/aptsources/distinfo.py @@ -27,11 +27,9 @@ import os import gettext from os import getenv import ConfigParser -import string -import apt_pkg +import re -#from gettext import gettext as _ -import gettext +import apt_pkg def _(s): @@ -76,9 +74,9 @@ class Component: self.description_long = long_desc def get_description(self): - if self.description_long != None: + if self.description_long is not None: return self.description_long - elif self.description != None: + elif self.description is not None: return self.description else: return None @@ -221,8 +219,8 @@ class DistInfo: mirror_set = {} try: mirror_data = filter(match_mirror_line.match, - map(string.strip, open(value))) - except: + [x.strip() for x in open(value)]) + except Exception: print "WARNING: Failed to read mirror file" mirror_data = [] for line in mirror_data: @@ -256,7 +254,7 @@ class DistInfo: if not template: return # reuse some properties of the parent template - if template.match_uri == None and template.child: + if template.match_uri is None and template.child: for t in template.parents: if t.match_uri: template.match_uri = t.match_uri diff --git a/aptsources/distro.py b/aptsources/distro.py index a8f1d0fd..d8f191d6 100644 --- a/aptsources/distro.py +++ b/aptsources/distro.py @@ -21,7 +21,6 @@ # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA -import string import gettext import re import os @@ -86,7 +85,7 @@ class Distribution: # template.components self.source_template = template break - if self.source_template == None: + if self.source_template is None: raise NoDistroTemplateException("Error: could not find a " "distribution template") @@ -259,14 +258,14 @@ class Distribution: """ Add distribution specific sources """ - if uri == None: + if uri is None: # FIXME: Add support for the server selector uri = self.default_server - if dist == None: + if dist is None: dist = self.codename - if comps == None: + if comps is None: comps = list(self.enabled_comps) - if type == None: + if type is None: type = self.binary_type new_source = self.sourceslist.add(type, uri, dist, comps, comment) # if source code is enabled add a deb-src line after the new @@ -379,7 +378,7 @@ class Distribution: change_server_of_source(source, uri, seen_binary) for source in self.child_sources: # Do not change the forces server of a child source - if source.template.base_uri == None or \ + if source.template.base_uri is None or \ source.template.base_uri != source.uri: change_server_of_source(source, uri, seen_binary) for source in self.source_code_sources: diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index a0346267..dc2a5d45 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -23,18 +23,16 @@ # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA -import string import gettext -import re -import apt_pkg import glob -import shutil -import time import os.path +import re +import shutil import sys +import time -#from UpdateManager.Common.DistInfo import DistInfo -from distinfo import DistInfo +import apt_pkg +from aptsources.distinfo import DistInfo # some global helpers @@ -88,7 +86,7 @@ class SourceEntry: # (may empty) self.comment = "" # (optional) comment self.line = line # the original sources.list line - if file == None: + if file is None: file = apt_pkg.Config.FindDir( "Dir::Etc")+apt_pkg.Config.Find("Dir::Etc::sourcelist") self.file = file # the file that the entry is located in @@ -107,7 +105,7 @@ class SourceEntry: def mysplit(self, line): """ a split() implementation that understands the sources.list format better and takes [] into account (for e.g. cdroms) """ - line = string.strip(line) + line = line.strip() pieces = [] tmp = "" # we are inside a [..] block @@ -138,7 +136,7 @@ class SourceEntry: def parse(self, line): """ parse a given sources.list (textual) line and break it up into the field we have """ - line = string.strip(self.line) + line = self.line.strip() #print line # check if the source is enabled/disabled if line == "" or line == "#": # empty line @@ -146,7 +144,7 @@ class SourceEntry: return if line[0] == "#": self.disabled = True - pieces = string.split(line[1:]) + pieces = line[1:].strip() # if it looks not like a disabled deb line return if not pieces[0] in ("rpm", "rpm-src", "deb", "deb-src"): self.invalid = True @@ -165,18 +163,18 @@ class SourceEntry: self.invalid = True return # Type, deb or deb-src - self.type = string.strip(pieces[0]) + self.type = pieces[0].strip() # Sanity check if self.type not in ("deb", "deb-src", "rpm", "rpm-src"): self.invalid = True return # URI - self.uri = string.strip(pieces[1]) + self.uri = pieces[1].strip() if len(self.uri) < 1: self.invalid = True # distro and components (optional) # Directory or distro - self.dist = string.strip(pieces[2]) + self.dist = pieces[2].strip() if len(pieces) > 3: # List of components self.comps = pieces[3:] @@ -187,15 +185,11 @@ class SourceEntry: """ set a line to enabled or disabled """ self.disabled = not new_value # enable, remove all "#" from the start of the line - if new_value == True: - i=0 - self.line = string.lstrip(self.line) - while self.line[i] == "#": - i += 1 - self.line = self.line[i:] + if new_value: + self.line = self.line.lstrip().lstrip('#') else: # disabled, add a "#" - if string.strip(self.line)[0] != "#": + if self.line.strip()[0] != "#": self.line = "#" + self.line def __str__(self): @@ -251,7 +245,7 @@ class SourcesList: self.load(file) # check if the source item fits a predefined template for source in self.list: - if source.invalid == False: + if not source.invalid: self.matcher.match(source) def __iter__(self): @@ -272,7 +266,7 @@ class SourcesList: comps = orig_comps[:] # check if we have this source already in the sources.list for source in self.list: - if source.disabled == False and source.invalid == False and \ + if not source.disabled and not source.invalid and \ source.type == type and uri == source.uri and \ source.dist == dist: for new_comp in comps: @@ -285,14 +279,14 @@ class SourcesList: for source in self.list: # if there is a repo with the same (type, uri, dist) just add the # components - if source.disabled == False and source.invalid == False and \ + if not source.disabled and not source.invalid and \ source.type == type and uri == source.uri and \ source.dist == dist: comps = uniq(source.comps + comps) source.comps = comps return source # if there is a corresponding repo which is disabled, enable it - elif source.disabled == True and source.invalid == False and \ + elif source.disabled and not source.invalid and \ source.type == type and uri == source.uri and \ source.dist == dist and \ len(set(source.comps) & set(comps)) == len(comps): @@ -306,7 +300,7 @@ class SourcesList: line = "%s #%s\n" % (line, comment) line = line + "\n" new_entry = SourceEntry(line) - if file != None: + if file is not None: new_entry.file = file self.matcher.match(new_entry) self.list.insert(pos, new_entry) @@ -333,7 +327,7 @@ class SourcesList: """ make a backup of the current source files, if no backup extension is given, the current date/time is used (and returned) """ already_backuped = set() - if backup_ext == None: + if backup_ext is None: backup_ext = time.strftime("%y%m%d.%H%M") for source in self.list: if not source.file in already_backuped \ @@ -380,11 +374,11 @@ class SourcesList: used_child_templates = {} for source in sources_list: # try to avoid checking uninterressting sources - if source.template == None: + if source.template is None: continue # set up a dict with all used child templates and corresponding # source entries - if source.template.child == True: + if source.template.child: key = source.template if key not in used_child_templates: used_child_templates[key] = [] @@ -414,7 +408,7 @@ class SourceEntryMatcher: f = f[0:i] dist = DistInfo(f, base_dir=matcherPath) for template in dist.templates: - if template.match_uri != None: + if template.match_uri is not None: self.templates.append(template) return diff --git a/doc/examples/action.py b/doc/examples/action.py index 7153292c..9b9d7dd3 100644 --- a/doc/examples/action.py +++ b/doc/examples/action.py @@ -86,7 +86,7 @@ print "UsrSize: %s " % apt_pkg.SizeToStr(depcache.UsrSize) print "DebSize: %s " % apt_pkg.SizeToStr(depcache.DebSize) for pkg in cache.Packages: - if pkg.CurrentVer != None and not depcache.MarkedInstall(pkg) \ + if pkg.CurrentVer is not None and not depcache.MarkedInstall(pkg) \ and depcache.IsUpgradable(pkg): print "Upgrade didn't upgrade (kept): %s" % pkg.Name @@ -101,7 +101,7 @@ print "DebSize: %s " % apt_pkg.SizeToStr(depcache.DebSize) # overview about what would happen for pkg in cache.Packages: if depcache.MarkedInstall(pkg): - if pkg.CurrentVer != None: + if pkg.CurrentVer is not None: print "Marked upgrade: %s " % pkg.Name else: print "Marked install: %s" % pkg.Name diff --git a/doc/examples/all_deps.py b/doc/examples/all_deps.py index 0a2f3157..992e98d8 100644 --- a/doc/examples/all_deps.py +++ b/doc/examples/all_deps.py @@ -1,13 +1,13 @@ #!/usr/bin/env python - import sys + import apt def dependencies(cache, pkg, deps, key="Depends"): #print "pkg: %s (%s)" % (pkg.name, deps) candver = cache._depcache.GetCandidateVer(pkg._pkg) - if candver == None: + if candver is None: return deps dependslist = candver.DependsList if key in dependslist: diff --git a/doc/examples/build-deps.py b/doc/examples/build-deps.py index dc1a6f4e..aeb5667c 100755 --- a/doc/examples/build-deps.py +++ b/doc/examples/build-deps.py @@ -3,7 +3,6 @@ import apt_pkg import sys -import sets # only needed for python2.3, python2.4 supports this naively def get_source_pkg(pkg, records, depcache): @@ -37,7 +36,7 @@ try: except KeyError: print "No package %s found" % sys.argv[1] sys.exit(1) -all_build_depends = sets.Set() +all_build_depends = set() # get the build depdends for the package itself srcpkg_name = get_source_pkg(base, records, depcache) diff --git a/doc/examples/depcache.py b/doc/examples/depcache.py index ad884fe7..790cc9d6 100644 --- a/doc/examples/depcache.py +++ b/doc/examples/depcache.py @@ -84,7 +84,7 @@ print "UsrSize: %s " % apt_pkg.SizeToStr(depcache.UsrSize) print "DebSize: %s " % apt_pkg.SizeToStr(depcache.DebSize) for pkg in cache.Packages: - if pkg.CurrentVer != None and not depcache.MarkedInstall(pkg) \ + if pkg.CurrentVer is not None and not depcache.MarkedInstall(pkg) \ and depcache.IsUpgradable(pkg): print "Upgrade didn't upgrade (kept): %s" % pkg.Name @@ -100,7 +100,7 @@ print "DebSize: %s " % apt_pkg.SizeToStr(depcache.DebSize) # overview about what would happen for pkg in cache.Packages: if depcache.MarkedInstall(pkg): - if pkg.CurrentVer != None: + if pkg.CurrentVer is not None: print "Marked upgrade: %s " % pkg.Name else: print "Marked install: %s" % pkg.Name diff --git a/doc/examples/dependant-pkgs.py b/doc/examples/dependant-pkgs.py index bb10ce70..5fbbc76d 100755 --- a/doc/examples/dependant-pkgs.py +++ b/doc/examples/dependant-pkgs.py @@ -7,7 +7,7 @@ pkgs = set() cache = apt.Cache() for pkg in cache: candver = cache._depcache.GetCandidateVer(pkg._pkg) - if candver == None: + if candver is None: continue dependslist = candver.DependsList for dep in dependslist.keys(): diff --git a/doc/examples/gui-inst.py b/doc/examples/gui-inst.py index cb49db3e..8138d922 100755 --- a/doc/examples/gui-inst.py +++ b/doc/examples/gui-inst.py @@ -1,20 +1,13 @@ #!/usr/bin/python # example how to install in a custom terminal widget # see also gnome bug: #169201 - -import apt -import apt_pkg -import sys, os, fcntl -import copy -import string -import fcntl - import pygtk pygtk.require('2.0') import gtk import apt.gtk.widgets + if __name__ == "__main__": win = gtk.Window() diff --git a/doc/examples/progress.py b/doc/examples/progress.py index c56734b7..83847598 100644 --- a/doc/examples/progress.py +++ b/doc/examples/progress.py @@ -1,8 +1,7 @@ -import apt -from apt import SizeToStr import sys import time -import string + +import apt class TextProgress(apt.OpProgress): @@ -39,8 +38,8 @@ class TextFetchProgress(apt.FetchProgress): def pulse(self): print "Pulse: CPS: %s/s; Bytes: %s/%s; Item: %s/%s" % ( - SizeToStr(self.currentCPS), SizeToStr(self.currentBytes), - SizeToStr(self.totalBytes), self.currentItems, self.totalItems) + apt.SizeToStr(self.currentCPS), SizeToStr(self.currentBytes), + apt.SizeToStr(self.totalBytes), self.currentItems, self.totalItems) return True def mediaChange(self, medium, drive): diff --git a/doc/examples/versiontest.py b/doc/examples/versiontest.py index dd881f6b..fa13cc1c 100755 --- a/doc/examples/versiontest.py +++ b/doc/examples/versiontest.py @@ -4,7 +4,6 @@ import apt_pkg import sys import re -import string apt_pkg.InitConfig() apt_pkg.InitSystem() @@ -22,7 +21,7 @@ while(1): CurLine = CurLine + 1 if Line == "": break - Line = string.strip(Line) + Line = Line.strip() if len(Line) == 0 or Line[0] == '#': continue diff --git a/doc/source/conf.py b/doc/source/conf.py index bb8056ad..8f71e3e3 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -3,18 +3,20 @@ # python-apt documentation build configuration file, created by # sphinx-quickstart on Wed Jan 7 17:04:36 2009. # -# This file is execfile()d with the current directory set to its containing dir. +# This file is execfile()d with the current directory set to its containing +# dir. # # The contents of this file are pickled, so don't put values in the namespace -# that aren't pickleable (module imports are okay, they're removed automatically). +# that aren't pickleable (module imports are okay, they're removed +# automatically). # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. - -import sys, os +import os +import sys # If your extensions are in another directory, add it here. If the directory # is relative to the documentation root, use os.path.abspath to make it @@ -28,8 +30,8 @@ if os.path.exists("../../build"): # General configuration # --------------------- -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo'] intersphinx_mapping = {'http://docs.python.org/': None} @@ -76,7 +78,7 @@ release = '0.7.9~exp2' # for source files. exclude_trees = [] -# The reST default role (used for this markup: `text`) to use for all documents. +# The reST default role (used for this markup: `text`) for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. @@ -172,7 +174,7 @@ htmlhelp_basename = 'python-aptdoc' #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, document class [howto/manual]). +# (source index, target name, title, author, document class [howto/manual]). latex_documents = [ ('index', 'python-apt.tex', ur'python-apt Documentation', ur'Julian Andres Klode ', 'manual'), diff --git a/doc/source/examples/missing-deps.py b/doc/source/examples/missing-deps.py index 0870eb98..3ca16e45 100644 --- a/doc/source/examples/missing-deps.py +++ b/doc/source/examples/missing-deps.py @@ -10,6 +10,7 @@ def fmt_dep(dep): ret += " (%s %s)" % (dep.CompType, dep.TargetVer) return ret + def check_version(pkgver): """Check the version of the package""" missing = [] diff --git a/setup.py b/setup.py index c9f940a4..6a22734d 100755 --- a/setup.py +++ b/setup.py @@ -3,24 +3,21 @@ from distutils.core import setup, Extension from distutils.sysconfig import parse_makefile -from DistUtilsExtra.command import * +from DistUtilsExtra.command import build_extra, build_i18n import glob import os -import os.path -import pydoc import shutil -import string import sys # The apt_pkg module files = map(lambda source: "python/"+source, - string.split(parse_makefile("python/makefile")["APT_PKG_SRC"])) + parse_makefile("python/makefile")["APT_PKG_SRC"].split()) apt_pkg = Extension("apt_pkg", files, libraries=["apt-pkg"]) # The apt_inst module files = map(lambda source: "python/"+source, - string.split(parse_makefile("python/makefile")["APT_INST_SRC"])) + parse_makefile("python/makefile")["APT_INST_SRC"].split()) apt_inst = Extension("apt_inst", files, libraries=["apt-pkg", "apt-inst"]) # Replace the leading _ that is used in the templates for translation diff --git a/tests/depcache.py b/tests/depcache.py index b199c812..19aba680 100644 --- a/tests/depcache.py +++ b/tests/depcache.py @@ -22,7 +22,7 @@ def main(): x = pkg.Name # then get each version ver =depcache.GetCandidateVer(pkg) - if ver != None: + if ver is not None: depcache.MarkInstall(pkg) if depcache.InstCount == 0: if depcache.IsUpgradable(pkg): diff --git a/tests/pkgproblemresolver.py b/tests/pkgproblemresolver.py index 7d5ae682..a21d8d9d 100644 --- a/tests/pkgproblemresolver.py +++ b/tests/pkgproblemresolver.py @@ -22,7 +22,7 @@ def main(): x = pkg.Name # then get each version ver =depcache.GetCandidateVer(pkg) - if ver != None: + if ver is not None: depcache.MarkInstall(pkg) if depcache.BrokenCount > 0: fixer = apt_pkg.GetPkgProblemResolver(depcache) diff --git a/tests/test_aptsources_ports.py b/tests/test_aptsources_ports.py index 203721c7..09d6e9d9 100644 --- a/tests/test_aptsources_ports.py +++ b/tests/test_aptsources_ports.py @@ -1,28 +1,32 @@ #!/usr/bin/env python import unittest -import apt_pkg + import os import copy - import sys + sys.path.insert(0, "../") +import apt_pkg import aptsources import aptsources.sourceslist import aptsources.distro + class TestAptSources(unittest.TestCase): + def __init__(self, methodName): unittest.TestCase.__init__(self, methodName) apt_pkg.init() - apt_pkg.Config.Set("APT::Architecture","powerpc") - apt_pkg.Config.Set("Dir::Etc", os.path.join(os.getcwd(),"test-data-ports")) - apt_pkg.Config.Set("Dir::Etc::sourceparts","/xxx") + apt_pkg.Config.Set("APT::Architecture", "powerpc") + apt_pkg.Config.Set("Dir::Etc", os.path.abspath("test-data-ports")) + apt_pkg.Config.Set("Dir::Etc::sourceparts", "/xxx") def testMatcher(self): - apt_pkg.Config.Set("Dir::Etc::sourcelist","sources.list") + apt_pkg.Config.Set("Dir::Etc::sourcelist", "sources.list") sources = aptsources.sourceslist.SourcesList() - distro = aptsources.distro.get_distro("Ubuntu","hardy","desc","8.04") + distro = aptsources.distro.get_distro("Ubuntu", "hardy", "desc", + "8.04") distro.get_sources(sources) # test if all suits of the current distro were detected correctly dist_templates = set() diff --git a/tests/test_debextract.py b/tests/test_debextract.py index c080b26e..4ba498ae 100755 --- a/tests/test_debextract.py +++ b/tests/test_debextract.py @@ -1,13 +1,18 @@ #!/usr/bin/python +import sys import apt_inst -import sys -def Callback(What,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor): + +def Callback(What, Name, Link, Mode, UID, GID, Size, MTime, Major, Minor): print "%s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % ( - What,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor) + What, Name, Link, Mode, UID, GID, Size, MTime, Major, Minor) + + +def main(): + member = "data.tar.lzma" + if len(sys.argv) > 2: + member = sys.argv[2] + apt_inst.debExtract(open(sys.argv[1]), Callback, member) -member = "data.tar.lzma" -if len(sys.argv) > 2: - member = sys.argv[2] -apt_inst.debExtract(open(sys.argv[1]), Callback, member) +main() -- cgit v1.2.3 From c48741a79cc4581ffb3890ceeef1420c0ccab830 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 12 Jan 2009 17:59:18 +0100 Subject: * apt/README.apt: Point to doc/source/coding.rst --- apt/README.apt | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) (limited to 'apt') diff --git a/apt/README.apt b/apt/README.apt index 30166a24..2a017bde 100644 --- a/apt/README.apt +++ b/apt/README.apt @@ -12,10 +12,4 @@ WARNING !!! The API is not 100% stable yet !!! Style Guides: ------------- - -Follow PEP08. - -Internal variables/methods are prefixed with a "_" (e.g. _foo). - - - +See ../doc/source/coding.rst -- cgit v1.2.3 From 0c5ef89b82b3a8a085f0b503b4a54be33d34e81c Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 12 Jan 2009 18:28:18 +0100 Subject: * apt/cache.py: Introduce isVirtualPackage() --- apt/cache.py | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'apt') diff --git a/apt/cache.py b/apt/cache.py index ff3149f5..0065d14c 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -202,6 +202,11 @@ class Cache(object): finally: os.close(lock) + def isVirtualPackage(self, pkgname): + """Return whether the package is a virtual package.""" + pkg = self._cache[pkgname] + return bool(pkg.ProvidesList and not pkg.VersionList) + def getProvidingPackages(self, virtual): """ Return a list of packages which provide the virtual package of the -- cgit v1.2.3 From 614897f798d9f16591fbd29ebe2a6c5674102d2d Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 12 Jan 2009 18:36:58 +0100 Subject: * apt/debfile.py: Do not use mixedCase anymore In accordance with the latest change of the guidelines, mixedCase names may not be used anymore for new modules. --- apt/debfile.py | 144 ++++++++++++++++++++++++++++++--------------------------- 1 file changed, 75 insertions(+), 69 deletions(-) (limited to 'apt') diff --git a/apt/debfile.py b/apt/debfile.py index 9730be35..f24f19f4 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -45,11 +45,10 @@ class DebPackage(object): def __init__(self, filename=None, cache=None): self._cache = cache - self.file = filename - self._needPkgs = [] + self._need_pkgs = [] self._sections = {} - self._installedConflicts = set() - self._failureString = "" + self._installed_conflicts = set() + self._failure_string = "" if filename: self.open(filename) @@ -86,7 +85,7 @@ class DebPackage(object): self.filename)] return files - def _isOrGroupSatisfied(self, or_group): + def _is_or_group_satisfied(self, or_group): """Return True if at least one dependency of the or-group is satisfied. This method gets an 'or_group' and analyzes if at least one dependency @@ -115,7 +114,7 @@ class DebPackage(object): return True return False - def _satisfyOrGroup(self, or_group): + def _satisfy_or_group(self, or_group): """Try to satisfy the or_group.""" for dep in or_group: depname, ver, oper = dep @@ -142,7 +141,7 @@ class DebPackage(object): # check if we need to install it self._dbg(2, "Need to get: %s" % depname) - self._needPkgs.append(depname) + self._need_pkgs.append(depname) return True # if we reach this point, we failed @@ -151,11 +150,11 @@ class DebPackage(object): or_str += dep[0] if dep != or_group[-1]: or_str += "|" - self._failureString += _("Dependency is not satisfiable: %s\n" % + self._failure_string += _("Dependency is not satisfiable: %s\n" % or_str) return False - def _checkSinglePkgConflict(self, pkgname, ver, oper): + def _check_single_pkg_conflict(self, pkgname, ver, oper): """Return True if a pkg conflicts with a real installed/marked pkg.""" # FIXME: deal with conflicts against its own provides # (e.g. Provides: ftp-server, Conflicts: ftp-server) @@ -174,15 +173,15 @@ class DebPackage(object): #print "pkgver: %s " % pkgver #print "oper: %s " % oper if (apt_pkg.CheckDep(pkgver, oper, ver) and not - self.replacesRealPkg(pkgname, oper, ver)): - self._failureString += _("Conflicts with the installed package " + self.replaces_real_pkg(pkgname, oper, ver)): + self._failure_string += _("Conflicts with the installed package " "'%s'" % pkg.name) return True return False - def _checkConflictsOrGroup(self, or_group): + def _check_conflicts_or_group(self, or_group): """Check the or-group for conflicts with installed pkgs.""" - self._dbg(2, "_checkConflictsOrGroup(): %s " % (or_group)) + self._dbg(2, "_check_conflicts_or_group(): %s " % (or_group)) or_found = False virtual_pkg = None @@ -203,12 +202,12 @@ class DebPackage(object): if self.pkgname == pkg.name: self._dbg(3, "conflict on self, ignoring") continue - if self._checkSinglePkgConflict(pkg.name, ver, oper): - self._installedConflicts.add(pkg.name) + if self._check_single_pkg_conflict(pkg.name, ver, oper): + self._installed_conflicts.add(pkg.name) continue - if self._checkSinglePkgConflict(depname, ver, oper): - self._installedConflicts.add(depname) - return bool(self._installedConflicts) + if self._check_single_pkg_conflict(depname, ver, oper): + self._installed_conflicts.add(depname) + return bool(self._installed_conflicts) @property def conflicts(self): @@ -249,7 +248,7 @@ class DebPackage(object): except KeyError: return [] - def replacesRealPkg(self, pkgname, oper, ver): + def replaces_real_pkg(self, pkgname, oper, ver): """Return True if a given non-virtual package is replaced. Return True if the deb packages replaces a real (not virtual) @@ -271,7 +270,7 @@ class DebPackage(object): return True return False - def checkConflicts(self): + def check_conflicts(self): """Check if there are conflicts with existing or selected packages. Check if the package conflicts with a existing or to be installed @@ -279,13 +278,13 @@ class DebPackage(object): """ res = True for or_group in self.conflicts: - if self._checkConflictsOrGroup(or_group): + if self._check_conflicts_or_group(or_group): #print "Conflicts with a exisiting pkg!" - #self._failureString = "Conflicts with a exisiting pkg!" + #self._failure_string = "Conflicts with a exisiting pkg!" res = False return res - def compareToVersionInCache(self, useInstalled=True): + def compare_to_version_in_cache(self, use_installed=True): """Compare the package to the version available in the cache. Checks if the package is already installed or availabe in the cache @@ -297,7 +296,7 @@ class DebPackage(object): debver = self._sections["Version"] self._dbg(1, "debver: %s" % debver) if pkgname in self._cache: - if useInstalled: + if use_installed: cachever = self._cache[pkgname].installedVersion else: cachever = self._cache[pkgname].candidateVersion @@ -312,7 +311,7 @@ class DebPackage(object): return VERSION_OUTDATED return VERSION_NONE - def checkDeb(self): + def check(self): """Check if the package is installable.""" self._dbg(3, "checkDepends") @@ -320,45 +319,44 @@ class DebPackage(object): arch = self._sections["Architecture"] if arch != "all" and arch != apt_pkg.Config.Find("APT::Architecture"): self._dbg(1, "ERROR: Wrong architecture dude!") - self._failureString = _("Wrong architecture '%s'" % arch) + self._failure_string = _("Wrong architecture '%s'" % arch) return False # check version - res = self.compareToVersionInCache() - if res == VERSION_OUTDATED: # the deb is older than the installed - self._failureString = _("A later version is already installed") + if self.compare_to_version_in_cache() == VERSION_OUTDATED: + # the deb is older than the installed + self._failure_string = _("A later version is already installed") return False # FIXME: this sort of error handling sux - self._failureString = "" + self._failure_string = "" # check conflicts - if not self.checkConflicts(): + if not self.check_conflicts(): return False # try to satisfy the dependencies - res = self._satisfyDepends(self.depends) - if not res: + if not self._satisfy_depends(self.depends): return False # check for conflicts again (this time with the packages that are # makeed for install) - if not self.checkConflicts(): + if not self.check_conflicts(): return False if self._cache._depcache.BrokenCount > 0: - self._failureString = _("Failed to satisfy all dependencies " + self._failure_string = _("Failed to satisfy all dependencies " "(broken cache)") # clean the cache again self._cache.clear() return False return True - def satisfyDependsStr(self, dependsstr): + def satisfy_depends_str(self, dependsstr): """Satisfy the dependencies in the given string.""" - return self._satisfyDepends(apt_pkg.ParseDepends(dependsstr)) + return self._satisfy_depends(apt_pkg.ParseDepends(dependsstr)) - def _satisfyDepends(self, depends): + def _satisfy_depends(self, depends): """Satisfy the dependencies.""" # turn off MarkAndSweep via a action group (if available) try: @@ -368,30 +366,30 @@ class DebPackage(object): # check depends for or_group in depends: #print "or_group: %s" % or_group - #print "or_group satified: %s" % self._isOrGroupSatisfied(or_group) - if not self._isOrGroupSatisfied(or_group): - if not self._satisfyOrGroup(or_group): + #print "or_group satified: %s" % self._is_or_group_satisfied(or_group) + if not self._is_or_group_satisfied(or_group): + if not self._satisfy_or_group(or_group): return False # now try it out in the cache - for pkg in self._needPkgs: - try: - self._cache[pkg].markInstall(fromUser=False) - except SystemError, e: - self._failureString = _("Cannot install '%s'" % pkg) - self._cache.clear() - return False + for pkg in self._need_pkgs: + try: + self._cache[pkg].markInstall(fromUser=False) + except SystemError, e: + self._failure_string = _("Cannot install '%s'" % pkg) + self._cache.clear() + return False return True @property - def missingDeps(self): + def missing_deps(self): """Return missing dependencies.""" - self._dbg(1, "Installing: %s" % self._needPkgs) - if self._needPkgs is None: - self.checkDeb() - return self._needPkgs + self._dbg(1, "Installing: %s" % self._need_pkgs) + if self._need_pkgs is None: + self.check() + return self._need_pkgs @property - def requiredChanges(self): + def required_changes(self): """Get the changes required to satisfy the dependencies. Returns: a tuple with (install, remove, unauthenticated) @@ -418,14 +416,20 @@ class DebPackage(object): if level <= self.debug: print >> sys.stderr, msg - def install(self, installProgress=None): + def install(self, install_progress=None): """Install the package.""" - if installProgress is None: + if install_progress is None: return os.system("dpkg -i %s" % self.filename) else: - installProgress.startUpdate() - res = installProgress.run(self.filename) - installProgress.finishUpdate() + try: + install_progress.start_update() + except AttributeError: + install_progress.startUpdate() + res = install_progress.run(self.filename) + try: + install_progress.finish_update() + except AttributeError: + install_progress.finishUpdate() return res @@ -475,6 +479,8 @@ class DscSrcPackage(DebPackage): if sec.has_key('Version'): self._sections['Version'] = sec['Version'] finally: + del sec + del tagfile fobj.close() s = _("Install Build-Dependencies for " @@ -482,16 +488,16 @@ class DscSrcPackage(DebPackage): " ".join(self.binaries)) self._sections["Description"] = s - def checkDeb(self): + def check(self): """Check if the package is installable..""" - if not self.checkConflicts(): - for pkgname in self._installedConflicts: + if not self.check_conflicts(): + for pkgname in self._installed_conflicts: if self._cache[pkgname]._pkg.Essential: - raise Exception(_("A essential package would be removed")) + raise Exception(_("An essential package would be removed")) self._cache[pkgname].markDelete() # FIXME: a additional run of the checkConflicts() # after _satisfyDepends() should probably be done - return self._satisfyDepends(self.depends) + return self._satisfy_depends(self.depends) def _test(): @@ -510,11 +516,11 @@ def _test(): d = DebPackage(sys.argv[1], cache) print "Deb: %s" % d.pkgname - if not d.checkDeb(): + if not d.check(): print "can't be satified" - print d._failureString - print "missing deps: %s" % d.missingDeps - print d.requiredChanges + print d._failure_string + print "missing deps: %s" % d.missing_deps + print d.required_changes print "Installing ..." ret = d.install(DpkgInstallProgress()) @@ -527,7 +533,7 @@ def _test(): s = DscSrcPackage(cache=cache) d = "libc6 (>= 2.3.2), libaio (>= 0.3.96) | libaio1 (>= 0.3.96)" - print s._satisfyDepends(apt_pkg.ParseDepends(d)) + print s._satisfy_depends(apt_pkg.ParseDepends(d)) if __name__ == "__main__": _test() -- cgit v1.2.3