From b3934f4303c419bb6b517f71cce59749cf13f9c4 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 26 Aug 2013 13:45:40 +0200 Subject: Completely remove deprecated stuff --- aptsources/sourceslist.py | 4 ---- 1 file changed, 4 deletions(-) (limited to 'aptsources') diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index f5a86ecb..48839d6e 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -34,7 +34,6 @@ import time import apt_pkg from .distinfo import DistInfo -from apt.deprecation import function_deprecated_by #from apt_pkg import gettext as _ @@ -352,9 +351,6 @@ class SourcesList(object): if os.path.exists(file+backup_ext): shutil.copy(file+backup_ext, file) - if apt_pkg._COMPAT_0_7: - restoreBackup = function_deprecated_by(restore_backup) - 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) """ -- cgit v1.2.3 From 328fd48b06f75e756a9adb15e2bdf408fba47da3 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 8 Oct 2013 20:32:46 +0200 Subject: aptsources/sourceslist.py: Fix uniq docstring and hide it (Closes: #723815) We accidentally exported this and people wrongly assumed that it was intended for SourcesList objects. --- aptsources/sourceslist.py | 10 +++++++++- debian/changelog | 2 ++ 2 files changed, 11 insertions(+), 1 deletion(-) (limited to 'aptsources') diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index 48839d6e..43729246 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -39,6 +39,9 @@ from .distinfo import DistInfo # some global helpers +__all__ = ['is_mirror', 'SourceEntry', 'NullMatcher', 'SourcesList', + 'SourceEntryMatcher'] + def is_mirror(master_uri, compare_uri): """ check if the given add_url is idential or a mirror of orig_uri @@ -71,7 +74,12 @@ def is_mirror(master_uri, compare_uri): def uniq(s): - """ simple and efficient way to return uniq list """ + """ simple and efficient way to return uniq collection + + This is not intended for use with a SourceList. It is provided + for internal use only. It does not have a leading underscore to + not break any old code that uses it; but it should not be used + in new code (and is not listed in __all__).""" return list(set(s)) diff --git a/debian/changelog b/debian/changelog index ca844f38..1d3bbaa5 100644 --- a/debian/changelog +++ b/debian/changelog @@ -8,6 +8,8 @@ python-apt (0.9.0) UNRELEASED; urgency=low [ Julian Andres Klode ] * Completely remove all old-API support code + * aptsources/sourceslist.py + - Document correct use of uniq and hide it using __all__ (Closes: #723815) [ Jeremy Bicha ] * data/templates/Ubuntu.info.in: add 'devel' series (Closes: #722961) -- cgit v1.2.3 From 1d62185fb1eb7b9523ec45666c3d96863b91e9af Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 10 Oct 2013 15:12:11 +0200 Subject: apt, aptsources: Only call init_config() if not already initialized Based on an idea by the bug reporter. Reported-by: Dominique Lasserre Closes: #686403 --- apt/__init__.py | 6 ++++-- aptsources/__init__.py | 7 +++++-- debian/changelog | 2 ++ 3 files changed, 11 insertions(+), 4 deletions(-) (limited to 'aptsources') diff --git a/apt/__init__.py b/apt/__init__.py index 4ded8e29..7b04befb 100644 --- a/apt/__init__.py +++ b/apt/__init__.py @@ -25,7 +25,9 @@ from apt.package import Package from apt.cache import Cache, ProblemResolver from apt.cdrom import Cdrom -# init the package system -apt_pkg.init() +# init the package system, but do not re-initialize config +if "APT" not in apt_pkg.config: + apt_pkg.init_config() +apt_pkg.init_system() __all__ = ['Cache', 'Cdrom', 'Package'] diff --git a/aptsources/__init__.py b/aptsources/__init__.py index c02341c2..0929e12b 100644 --- a/aptsources/__init__.py +++ b/aptsources/__init__.py @@ -1,4 +1,7 @@ import apt_pkg -# init the package system -apt_pkg.init() + +# init the package system, but do not re-initialize config +if "APT" not in apt_pkg.config: + apt_pkg.init_config() +apt_pkg.init_system() diff --git a/debian/changelog b/debian/changelog index 77c64d82..81e30b64 100644 --- a/debian/changelog +++ b/debian/changelog @@ -17,6 +17,8 @@ python-apt (0.9.0) UNRELEASED; urgency=low - Add a Package.has_config_files property (Closes: #712749) * tests: - Do not set dir::etc::sourceparts to /tmp + * apt, aptsources: + - Only call init_config() if not already initialized (Closes: #686403) [ Jeremy Bicha ] * data/templates/Ubuntu.info.in: add 'devel' series (Closes: #722961) -- cgit v1.2.3 From 8a67219266605b39a522aee08bf7cd3b0b6c3a8c Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 21 Oct 2013 20:20:22 +0200 Subject: aptsources: Correctly parse multiple options (LP: #1103200) It's still not optimal and we do not support the arch+ and arch- options, but it's a beginning. --- aptsources/sourceslist.py | 23 ++++++++++++++++++----- debian/changelog | 1 + tests/data/aptsources/sources.list | 1 + tests/test_aptsources.py | 21 +++++++++++++++++++-- 4 files changed, 39 insertions(+), 7 deletions(-) (limited to 'aptsources') diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index 43729246..69e7e107 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -91,6 +91,7 @@ class SourceEntry(object): self.disabled = False # is it disabled ('#' in front) self.type = "" # what type (deb, deb-src) self.architectures = [] # architectures + self.trusted = None # Trusted self.uri = "" # base-uri self.dist = "" # distribution (dapper, edgy, etc) self.comps = [] # list of available componetns @@ -123,9 +124,15 @@ class SourceEntry(object): p_found = False space_found = False for i in range(len(line)): - if line[i] == "[" and not space_found: - p_found=True - tmp += line[i] + if line[i] == "[": + if space_found: + space_found = False + p_found = True + pieces.append(tmp) + tmp = line[i] + else: + p_found=True + tmp += line[i] elif line[i] == "]": p_found=False tmp += line[i] @@ -181,7 +188,7 @@ class SourceEntry(object): return if pieces[1].strip()[0] == "[": - options = pieces.pop(1).strip("[]").split(";") + options = pieces.pop(1).strip("[]").split() for option in options: try: key, value = option.split("=", 1) @@ -190,6 +197,8 @@ class SourceEntry(object): else: if key == "arch": self.architectures = value.split(",") + elif key == "trusted": + self.trusted = apt_pkg.string_to_bool(value) else: self.invalid = True @@ -231,7 +240,11 @@ class SourceEntry(object): line += self.type - if self.architectures: + if self.architectures and self.trusted is not None: + line += " [arch=%s trusted=%s]" % (",".join(self.architectures), "yes" if self.trusted else "no") + elif self.trusted is not None: + line += " [trusted=%s]" % ("yes" if self.trusted else "no") + elif self.architectures: line += " [arch=%s]" % ",".join(self.architectures) line += " %s %s" % (self.uri, self.dist) if len(self.comps) > 0: diff --git a/debian/changelog b/debian/changelog index f1e40039..51f2b8b7 100644 --- a/debian/changelog +++ b/debian/changelog @@ -11,6 +11,7 @@ python-apt (0.9.0) UNRELEASED; urgency=low * Accept bytes object for file names (Closes: #680971) * aptsources/sourceslist.py - Document correct use of uniq and hide it using __all__ (Closes: #723815) + - Correctly parse multiple options (LP: #1103200) * python/apt_pkgmodule.cc: - Fix documentation of version_compare (Closes: #680891) * python/cache.cc: diff --git a/tests/data/aptsources/sources.list b/tests/data/aptsources/sources.list index 376d6961..8ca68075 100644 --- a/tests/data/aptsources/sources.list +++ b/tests/data/aptsources/sources.list @@ -7,3 +7,4 @@ deb http://de.archive.ubuntu.com/ubuntu/ edgy universe # multi-arch deb [arch=amd64,i386] http://de.archive.ubuntu.com/ubuntu/ natty main +deb [arch=amd64,i386 trusted=yes] http://de.archive.ubuntu.com/ubuntu/ natty main diff --git a/tests/test_aptsources.py b/tests/test_aptsources.py index 75dd91c1..5a174f3b 100644 --- a/tests/test_aptsources.py +++ b/tests/test_aptsources.py @@ -40,11 +40,11 @@ class TestAptSources(unittest.TestCase): apt_pkg.config.set("Dir::Etc::sourcelist", "data/aptsources/" "sources.list") sources = aptsources.sourceslist.SourcesList(True, self.templates) - self.assertEqual(len(sources.list), 9) + self.assertEqual(len(sources.list), 10) # test load sources.list = [] sources.load("data/aptsources/sources.list") - self.assertEqual(len(sources.list), 9) + self.assertEqual(len(sources.list), 10) def testSourcesListAdding(self): """aptsources: Test additions to sources.list""" @@ -159,6 +159,23 @@ class TestAptSources(unittest.TestCase): assert sources.list[8].dist == "natty" assert sources.list[8].comps == ["main"] assert sources.list[8].line.strip() == str(sources.list[8]) + assert sources.list[8].trusted is None + + def testMultipleOptions(self): + """aptsources: Test multi-arch parsing""" + + apt_pkg.config.set("Dir::Etc::sourcelist", "data/aptsources/" + "sources.list") + sources = aptsources.sourceslist.SourcesList(True, self.templates) + + assert sources.list[9].invalid == False + assert sources.list[9].type == "deb" + assert sources.list[9].architectures == ["amd64", "i386"] + self.assertEqual( sources.list[9].uri, "http://de.archive.ubuntu.com/ubuntu/") + assert sources.list[9].dist == "natty" + assert sources.list[9].comps == ["main"] + assert sources.list[9].trusted + assert sources.list[9].line.strip() == str(sources.list[9]) def test_enable_component(self): from subprocess import Popen, PIPE -- cgit v1.2.3 From 3bf9c3fe4d19ed4d985dc8b7747a737699f46a7e Mon Sep 17 00:00:00 2001 From: Michael Vogt Date: Tue, 31 Dec 2013 23:25:13 +0100 Subject: make test_pep8.py pass --- apt/auth.py | 39 +++++---- apt/debfile.py | 148 ++++++++++++++++++++++------------- apt/package.py | 12 +-- apt/progress/gtk2.py | 8 +- apt/progress/text.py | 9 ++- apt/utils.py | 2 +- aptsources/distinfo.py | 11 ++- aptsources/distro.py | 45 +++++------ aptsources/sourceslist.py | 38 ++++----- doc/examples/acquire.py | 7 +- doc/examples/action.py | 2 +- doc/examples/architecture.py | 2 +- doc/examples/build-deps-old.py | 2 +- doc/examples/checkstate.py | 4 +- doc/examples/deb_inspect.py | 4 +- doc/examples/depcache.py | 2 +- doc/examples/inst.py | 2 +- doc/examples/progress.py | 9 ++- doc/examples/sources.py | 2 +- doc/source/conf.py | 9 +-- doc/source/examples/cache-pkgfile.py | 2 +- setup.py | 16 ++-- tests/old/__init__.py | 1 - tests/old/cache.py | 4 +- tests/old/depcache.py | 6 +- tests/old/pkgproblemresolver.py | 6 +- tests/old/pkgrecords.py | 2 +- tests/old/pkgsrcrecords.py | 2 +- tests/old/refcount.py | 5 +- tests/test_all.py | 9 ++- tests/test_apt_cache.py | 43 +++++----- tests/test_aptsources.py | 12 ++- tests/test_auth.py | 11 ++- tests/test_configuration.py | 5 +- tests/test_debfile.py | 30 ++++--- tests/test_debfile_multiarch.py | 7 +- tests/test_group.py | 1 - tests/test_hashes.py | 2 +- tests/test_lp659438.py | 2 +- tests/test_paths.py | 10 ++- tests/test_pep8.py | 2 +- tests/test_policy.py | 2 +- tests/test_progress.py | 5 +- tests/test_size_to_str.py | 136 ++++++++++++++++---------------- tests/test_tagfile.py | 1 + tests/test_utils.py | 22 ++++-- utils/doclint.py | 21 +++-- utils/get_ubuntu_mirrors.py | 2 +- 48 files changed, 399 insertions(+), 325 deletions(-) (limited to 'aptsources') diff --git a/apt/auth.py b/apt/auth.py index d5a66b4a..acc612a9 100644 --- a/apt/auth.py +++ b/apt/auth.py @@ -67,7 +67,8 @@ def _call_apt_key_script(*args, **kwargs): # configuration from the chroot to the apt-key script by using # a temporary APT_CONFIG file. The apt-key script uses apt-config # shell internally - conf = tempfile.NamedTemporaryFile(prefix="apt-key", suffix=".conf") + conf = tempfile.NamedTemporaryFile( + prefix="apt-key", suffix=".conf") conf.write(apt_pkg.config.dump().encode("UTF-8")) conf.flush() env["APT_CONFIG"] = conf.name @@ -84,11 +85,12 @@ def _call_apt_key_script(*args, **kwargs): output, stderr = proc.communicate(content) if proc.returncode: - raise AptKeyError("The apt-key script failed with return code %s:\n" - "%s\n" - "stdout: %s\n" - "stderr: %s" % (proc.returncode, " ".join(cmd), - output,stderr)) + raise AptKeyError( + "The apt-key script failed with return code %s:\n" + "%s\n" + "stdout: %s\n" + "stderr: %s" % ( + proc.returncode, " ".join(cmd), output, stderr)) elif stderr: sys.stderr.write(stderr) # Forward stderr @@ -97,6 +99,7 @@ def _call_apt_key_script(*args, **kwargs): if conf is not None: conf.close() + def add_key_from_file(filename): """Import a GnuPG key file to trust repositores signed by it. @@ -109,6 +112,7 @@ def add_key_from_file(filename): raise AptKeyError("Key file cannot be accessed: %s" % filename) _call_apt_key_script("add", filename) + def add_key_from_keyserver(keyid, keyserver): """Import a GnuPG key file to trust repositores signed by it. @@ -125,8 +129,9 @@ def add_key_from_keyserver(keyid, keyserver): finally: shutil.rmtree(tmp_keyring_dir) + def _add_key_from_keyserver(keyid, keyserver, tmp_keyring_dir): - if len(keyid) < 160/8: + if len(keyid) < (160 / 8): raise AptKeyError("Only long keyids (v4, 160bit) are supported") # create a temp keyring dir tmp_secret_keyring = os.path.join(tmp_keyring_dir, "secring.gpg") @@ -136,14 +141,14 @@ def _add_key_from_keyserver(keyid, keyserver, tmp_keyring_dir): "gpg", "--no-default-keyring", "--no-options", "--homedir", tmp_keyring_dir, - ] + ] # download the key to a temp keyring first res = subprocess.call(gpg_default_options + [ "--secret-keyring", tmp_secret_keyring, "--keyring", tmp_keyring, "--keyserver", keyserver, "--recv", keyid, - ]) + ]) if res != 0: raise AptKeyError("recv from '%s' failed for '%s'" % ( keyserver, keyid)) @@ -154,7 +159,7 @@ def _add_key_from_keyserver(keyid, keyserver, tmp_keyring_dir): "--keyring", tmp_keyring, "--output", tmp_export_keyring, "--export", keyid, - ]) + ]) if res != 0: raise AptKeyError("export of '%s' failed", keyid) # now verify the fingerprint, this is probably redundant as we @@ -166,10 +171,10 @@ def _add_key_from_keyserver(keyid, keyserver, tmp_keyring_dir): "--fingerprint", "--batch", "--with-colons", - ], - stdout=subprocess.PIPE, - universal_newlines=True).communicate()[0] - got_fingerprint=None + ], + stdout=subprocess.PIPE, + universal_newlines=True).communicate()[0] + got_fingerprint = None for line in output.splitlines(): if line.startswith("fpr:"): got_fingerprint = line.split(":")[9] @@ -185,6 +190,7 @@ def _add_key_from_keyserver(keyid, keyserver, tmp_keyring_dir): # finally add it add_key_from_file(tmp_export_keyring) + def add_key(content): """Import a GnuPG key to trust repositores signed by it. @@ -194,6 +200,7 @@ def add_key(content): _call_apt_key_script("adv", "--quiet", "--batch", "--import", "-", stdin=content) + def remove_key(fingerprint): """Remove a GnuPG key to no longer trust repositores signed by it. @@ -202,6 +209,7 @@ def remove_key(fingerprint): """ _call_apt_key_script("rm", fingerprint) + def export_key(fingerprint): """Return the GnuPG key in text format. @@ -210,6 +218,7 @@ def export_key(fingerprint): """ return _call_apt_key_script("export", fingerprint) + def update(): """Update the local keyring with the archive keyring and remove from the local keyring the archive keys which are no longer valid. The @@ -218,6 +227,7 @@ def update(): """ return _call_apt_key_script("update") + def net_update(): """Work similar to the update command above, but get the archive keyring from an URI instead and validate it against a master key. @@ -228,6 +238,7 @@ def net_update(): """ return _call_apt_key_script("net-update") + def list_keys(): """Returns a list of TrustedKey instances for each key which is used to trust repositories. diff --git a/apt/debfile.py b/apt/debfile.py index c845b1f2..679c8468 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -27,17 +27,19 @@ import sys from apt_pkg import gettext as _ from StringIO import StringIO + class NoDebArchiveException(IOError): """Exception which is raised if a file is no Debian archive.""" + class DebPackage(object): """A Debian Package (.deb file).""" # Constants for comparing the local package file with the version # in the cache - (VERSION_NONE, - VERSION_OUTDATED, - VERSION_SAME, + (VERSION_NONE, + VERSION_OUTDATED, + VERSION_SAME, VERSION_NEWER) = range(4) debug = 0 @@ -68,7 +70,7 @@ class DebPackage(object): self._sections = apt_pkg.TagSection(control) self.pkgname = self._sections["Package"] self._check_was_run = False - + def __getitem__(self, key): return self._sections[key] @@ -91,15 +93,15 @@ class DebPackage(object): """ return the list of files in control.tar.gt """ control = [] try: - self._debfile.control.go(lambda item, data: control.append(item.name)) + self._debfile.control.go( + lambda item, data: control.append(item.name)) except SystemError: return [_("List of control files for '%s' could not be read") % self.filename] return sorted(control) - # helper that will return a pkgname with a multiarch suffix if needed - def _maybe_append_multiarch_suffix(self, pkgname, + def _maybe_append_multiarch_suffix(self, pkgname, in_conflict_checking=False): # trivial cases if ":" in pkgname: @@ -108,7 +110,7 @@ class DebPackage(object): return pkgname elif self._cache.is_virtual_package(pkgname): return pkgname - elif (pkgname in self._cache and + elif (pkgname in self._cache and self._cache[pkgname].candidate and self._cache[pkgname].candidate.architecture == "all"): return pkgname @@ -126,7 +128,7 @@ class DebPackage(object): return pkgname # for conflicts we need a special case here, any not multiarch enabled # package has a implicit conflict - if (in_conflict_checking and + if (in_conflict_checking and not (cand.multi_arch & cand.MULTI_ARCH_SAME)): return pkgname return multiarch_pkgname @@ -150,7 +152,9 @@ class DebPackage(object): # check for virtual pkgs if not depname in self._cache: if self._cache.is_virtual_package(depname): - self._dbg(3, "_is_or_group_satisfied(): %s is virtual dep" % depname) + self._dbg( + 3, "_is_or_group_satisfied(): %s is virtual dep" % + depname) for pkg in self._cache.get_providing_packages(depname): if pkg.is_installed: return True @@ -163,13 +167,15 @@ class DebPackage(object): # if no real dependency is installed, check if there is # a package installed that provides this dependency # (e.g. scrollkeeper dependecies are provided by rarian-compat) - # but only do that if there is no version required in the + # but only do that if there is no version required in the # dependency (we do not supprot versionized dependencies) if not oper: for ppkg in self._cache.get_providing_packages( depname, include_nonvirtual=True): if ppkg.is_installed: - self._dbg(3, "found installed '%s' that provides '%s'" % (ppkg.name, depname)) + self._dbg( + 3, "found installed '%s' that provides '%s'" % ( + ppkg.name, depname)) return True return False @@ -212,16 +218,19 @@ class DebPackage(object): or_str += dep[0] if ver and oper: or_str += " (%s %s)" % (dep[2], dep[1]) - if dep != or_group[len(or_group)-1]: + if dep != or_group[len(or_group) - 1]: or_str += "|" - self._failure_string += _("Dependency is not satisfiable: %s\n") % or_str + self._failure_string += _( + "Dependency is not satisfiable: %s\n") % or_str return False 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) - self._dbg(3, "_check_single_pkg_conflict() pkg='%s' ver='%s' oper='%s'" % (pkgname, ver, oper)) + self._dbg( + 3, "_check_single_pkg_conflict() pkg='%s' ver='%s' oper='%s'" % ( + pkgname, ver, oper)) pkg = self._cache[pkgname] if pkg.is_installed: pkgver = pkg.installed.version @@ -265,8 +274,8 @@ class DebPackage(object): if self.pkgname == pkg.name: self._dbg(3, "conflict on self, ignoring") continue - if self._check_single_pkg_conflict(pkg.name, ver, - oper): + if self._check_single_pkg_conflict( + pkg.name, ver, oper): self._installed_conflicts.add(pkg.name) continue if self._check_single_pkg_conflict(depname, ver, oper): @@ -289,7 +298,8 @@ class DebPackage(object): # find depends for key in "Depends", "Pre-Depends": try: - depends.extend(apt_pkg.parse_depends(self._sections[key], False)) + depends.extend( + apt_pkg.parse_depends(self._sections[key], False)) except KeyError: pass return depends @@ -349,22 +359,22 @@ class DebPackage(object): return res def check_breaks_existing_packages(self): - """ - check if installing the package would break exsisting + """ + check if installing the package would break exsisting package on the system, e.g. system has: smc depends on smc-data (= 1.4) and user tries to installs smc-data 1.6 """ # show progress information as this step may take some time size = float(len(self._cache)) - steps = max(int(size/50), 1) + steps = max(int(size / 50), 1) debver = self._sections["Version"] debarch = self._sections["Architecture"] # store what we provide so that we can later check against that - provides = [ x[0][0] for x in self.provides] + provides = [x[0][0] for x in self.provides] for (i, pkg) in enumerate(self._cache): - if i%steps == 0: - self._cache.op_progress.update(float(i)/size*100.0) + if i % steps == 0: + self._cache.op_progress.update(float(i) / size * 100.0) if not pkg.is_installed: continue # check if the exising dependencies are still satisfied @@ -373,14 +383,21 @@ class DebPackage(object): for dep_or in pkg.installed.dependencies: for dep in dep_or.or_dependencies: if dep.name == self.pkgname: - if not apt_pkg.check_dep(debver, dep.relation, dep.version): + if not apt_pkg.check_dep( + debver, dep.relation, dep.version): self._dbg(2, "would break (depends) %s" % pkg.name) - # TRANSLATORS: the first '%s' is the package that breaks, the second the dependency that makes it break, the third the relation (e.g. >=) and the latest the version for the releation - self._failure_string += _("Breaks existing package '%(pkgname)s' dependency %(depname)s (%(deprelation)s %(depversion)s)") % { - 'pkgname' : pkg.name, - 'depname' : dep.name, - 'deprelation' : dep.relation, - 'depversion' : dep.version} + # TRANSLATORS: the first '%s' is the package that + # breaks, the second the dependency that makes it + # break, the third the relation (e.g. >=) and the + # latest the version for the releation + self._failure_string += _( + "Breaks existing package '%(pkgname)s' " + "dependency %(depname)s " + "(%(deprelation)s %(depversion)s)") % { + 'pkgname': pkg.name, + 'depname': dep.name, + 'deprelation': dep.relation, + 'depversion': dep.version} self._cache.op_progress.done() return False # now check if there are conflicts against this package on @@ -388,25 +405,41 @@ class DebPackage(object): if "Conflicts" in ver.depends_list: for conflicts_ver_list in ver.depends_list["Conflicts"]: for c_or in conflicts_ver_list: - if c_or.target_pkg.name == self.pkgname and c_or.target_pkg.architecture == debarch: - if apt_pkg.check_dep(debver, c_or.comp_type, c_or.target_ver): - self._dbg(2, "would break (conflicts) %s" % pkg.name) - # TRANSLATORS: the first '%s' is the package that conflicts, the second the packagename that it conflicts with (so the name of the deb the user tries to install), the third is the relation (e.g. >=) and the last is the version for the relation - self._failure_string += _("Breaks existing package '%(pkgname)s' conflict: %(targetpkg)s (%(comptype)s %(targetver)s)") % { - 'pkgname' : pkg.name, - 'targetpkg' : c_or.target_pkg.name, - 'comptype' : c_or.comp_type, - 'targetver' : c_or.target_ver } + if (c_or.target_pkg.name == self.pkgname and + c_or.target_pkg.architecture == debarch): + if apt_pkg.check_dep( + debver, c_or.comp_type, c_or.target_ver): + self._dbg( + 2, "would break (conflicts) %s" % pkg.name) + # TRANSLATORS: the first '%s' is the package + # that conflicts, the second the packagename + # that it conflicts with (so the name of the + # deb the user tries to install), the third is + # the relation (e.g. >=) and the last is the + # version for the relation + self._failure_string += _( + "Breaks existing package '%(pkgname)s' " + "conflict: %(targetpkg)s " + "(%(comptype)s %(targetver)s)") % { + 'pkgname': pkg.name, + 'targetpkg': c_or.target_pkg.name, + 'comptype': c_or.comp_type, + 'targetver': c_or.target_ver} self._cache.op_progress.done() return False if (c_or.target_pkg.name in provides and self.pkgname != pkg.name): - self._dbg(2, "would break (conflicts) %s" % provides) - self._failure_string += _("Breaks existing package '%(pkgname)s' that conflict: '%(targetpkg)s'. But the '%(debfile)s' provides it via: '%(provides)s'") % { - 'provides' : ",".join(provides), - 'debfile' : self.filename, - 'targetpkg' : c_or.target_pkg.name, - 'pkgname' : pkg.name } + self._dbg( + 2, "would break (conflicts) %s" % provides) + self._failure_string += _( + "Breaks existing package '%(pkgname)s' " + "that conflict: '%(targetpkg)s'. But the " + "'%(debfile)s' provides it via: " + "'%(provides)s'") % { + 'provides': ",".join(provides), + 'debfile': self.filename, + 'targetpkg': c_or.target_pkg.name, + 'pkgname': pkg.name} self._cache.op_progress.done() return False self._cache.op_progress.done() @@ -453,7 +486,7 @@ class DebPackage(object): self._failure_string = _("No Architecture field in the package") return False arch = self._sections["Architecture"] - if arch != "all" and arch != apt_pkg.config.find("APT::Architecture"): + if arch != "all" and arch != apt_pkg.config.find("APT::Architecture"): if arch in apt_pkg.get_architectures(): self._multiarch = arch self.pkgname = "%s:%s" % (self.pkgname, self._multiarch) @@ -467,7 +500,8 @@ class DebPackage(object): if self.compare_to_version_in_cache() == self.VERSION_OUTDATED: if self._cache[self.pkgname].installed: # the deb is older than the installed - self._failure_string = _("A later version is already installed") + self._failure_string = _( + "A later version is already installed") return False # FIXME: this sort of error handling sux @@ -477,7 +511,7 @@ class DebPackage(object): if not self.check_conflicts(): return False - # check if installing it would break anything on the + # check if installing it would break anything on the # current system if not self.check_breaks_existing_packages(): return False @@ -513,8 +547,6 @@ class DebPackage(object): pass # check depends for or_group in depends: - #print "or_group: %s" % 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 @@ -533,7 +565,8 @@ class DebPackage(object): """Return missing dependencies.""" self._dbg(1, "Installing: %s" % self._need_pkgs) if not self._check_was_run: - raise AttributeError("property only available after check() was run") + raise AttributeError( + "property only available after check() was run") return self._need_pkgs @property @@ -546,7 +579,8 @@ class DebPackage(object): remove = [] unauthenticated = [] if not self._check_was_run: - raise AttributeError("property only available after check() was run") + raise AttributeError( + "property only available after check() was run") for pkg in self._cache: if pkg.marked_install or pkg.marked_upgrade: install.append(pkg.name) @@ -565,7 +599,7 @@ class DebPackage(object): def to_hex(in_data): hex = "" for (i, c) in enumerate(in_data): - if i%80 == 0: + if i % 80 == 0: hex += "\n" hex += "%2.2x " % ord(c) return hex @@ -588,7 +622,7 @@ class DebPackage(object): else: s += chr(b) return s - + def _get_content(self, part, name, auto_decompress=True, auto_hex=True): if name.startswith("./"): name = name[2:] @@ -643,6 +677,7 @@ class DebPackage(object): install_progress.finishUpdate() return res + class DscSrcPackage(DebPackage): """A locally available source package.""" @@ -698,7 +733,7 @@ class DscSrcPackage(DebPackage): " ".join(self.binaries)) self._sections["Description"] = s self._check_was_run = False - + def check(self): """Check if the package is installable..""" if not self.check_conflicts(): @@ -712,6 +747,7 @@ class DscSrcPackage(DebPackage): # after _satisfy_depends() should probably be done return self._satisfy_depends(self.depends) + def _test(): """Test function""" from apt.cache import Cache diff --git a/apt/package.py b/apt/package.py index 79dac71d..d4217195 100644 --- a/apt/package.py +++ b/apt/package.py @@ -26,16 +26,8 @@ import re import socket import subprocess import urllib2 -try: - from collections import Mapping, Sequence -except ImportError: - # (for Python < 2.6) pylint: disable-msg=C0103 - Sequence = Mapping = object - -try: - from collections import Sequence -except ImportError: - Sequence = object + +from collections import Mapping, Sequence import apt_pkg import apt.progress.text diff --git a/apt/progress/gtk2.py b/apt/progress/gtk2.py index 63e531fa..b978c34f 100644 --- a/apt/progress/gtk2.py +++ b/apt/progress/gtk2.py @@ -27,6 +27,7 @@ pygtk.require('2.0') import gtk try: import glib + glib # pyflakes except ImportError: import gobject as glib import gobject @@ -87,7 +88,6 @@ class GOpProgress(gobject.GObject, base.OpProgress): self.emit("status-finished") - class GInstallProgress(gobject.GObject, base.InstallProgress): """Installation progress with GObject signals. @@ -241,12 +241,12 @@ class GAcquireProgress(gobject.GObject, base.AcquireProgress): current_item = self.total_items if self.current_cps > 0: text = (_("Downloading file %(current)li of %(total)li with " - "%(speed)s/s") % \ + "%(speed)s/s") % {"current": current_item, "total": self.total_items, "speed": apt_pkg.size_to_str(self.current_cps)}) else: - text = (_("Downloading file %(current)li of %(total)li") % \ + text = (_("Downloading file %(current)li of %(total)li") % {"current": current_item, "total": self.total_items}) @@ -358,7 +358,7 @@ class GtkAptProgress(gtk.VBox): if percent is None or percent == -1: self._progressbar.pulse() else: - self._progressbar.set_fraction(percent/100.0) + self._progressbar.set_fraction(percent / 100.0) while gtk.events_pending(): gtk.main_iteration() diff --git a/apt/progress/text.py b/apt/progress/text.py index c5eec092..76a4309e 100644 --- a/apt/progress/text.py +++ b/apt/progress/text.py @@ -47,7 +47,7 @@ class TextProgress(object): # Fill remaining stuff with whitespace if self._width > len(msg): self._file.write((self._width - len(msg)) * ' ') - elif maximize: # Needed for OpProgress. + elif maximize: # Needed for OpProgress. self._width = max(self._width, len(msg)) if newline: self._file.write("\n") @@ -114,7 +114,7 @@ class AcquireProgress(base.AcquireProgress, TextProgress): import struct buf = fcntl.ioctl(self._file, termios.TIOCGWINSZ, 8 * ' ') dummy, col, dummy, dummy = struct.unpack('hhhh', buf) - self._width = col - 1 # 1 for the cursor + self._width = col - 1 # 1 for the cursor def ims_hit(self, item): """Called when an item is update (e.g. not modified on the server).""" @@ -188,8 +188,9 @@ class AcquireProgress(base.AcquireProgress, TextProgress): # Add the total size and percent if worker.total_size and not worker.current_item.owner.complete: - val += "/%sB %i%%" % (apt_pkg.size_to_str(worker.total_size), - worker.current_size*100.0/worker.total_size) + val += "/%sB %i%%" % ( + apt_pkg.size_to_str(worker.total_size), + worker.current_size * 100.0 / worker.total_size) val += ']' diff --git a/apt/utils.py b/apt/utils.py index 08140258..9451f4bc 100644 --- a/apt/utils.py +++ b/apt/utils.py @@ -32,7 +32,7 @@ def get_maintenance_end_date(release_date, m_months): years = m_months // 12 months = m_months % 12 support_end_year = (release_date.year + years + - (release_date.month + months)//12) + (release_date.month + months) // 12) support_end_month = (release_date.month + months) % 12 # special case: this happens when e.g. doing 2010-06 + 18 months if support_end_month == 0: diff --git a/aptsources/distinfo.py b/aptsources/distinfo.py index d80721e5..b03e68f8 100644 --- a/aptsources/distinfo.py +++ b/aptsources/distinfo.py @@ -33,6 +33,7 @@ import apt_pkg from apt_pkg import gettext as _ + class Template(object): def __init__(self): @@ -152,9 +153,7 @@ def split_url(url): class DistInfo(object): - def __init__(self, - dist = None, - base_dir = "/usr/share/python-apt/templates"): + def __init__(self, dist=None, base_dir="/usr/share/python-apt/templates"): self.metarelease_uri = '' self.templates = [] self.arch = apt_pkg.config.find("APT::Architecture") @@ -196,7 +195,7 @@ class DistInfo(object): self.metarelease_uri = value elif field == 'Suite': self.finish_template(template, component) - component=None + component = None template = Template() template.name = value template.distribution = dist @@ -265,8 +264,8 @@ class DistInfo(object): elif field == 'ParentComponent': component.set_parent_component(value) self.finish_template(template, component) - template=None - component=None + template = None + component = None def finish_template(self, template, component): " finish the current tempalte " diff --git a/aptsources/distro.py b/aptsources/distro.py index e9facbfb..a71d5af2 100644 --- a/aptsources/distro.py +++ b/aptsources/distro.py @@ -85,7 +85,7 @@ class Distribution(object): break if self.source_template is None: raise NoDistroTemplateException( - "Error: could not find a distribution template for %s/%s" % + "Error: could not find a distribution template for %s/%s" % (self.id, self.codename)) # find main and child sources @@ -95,40 +95,40 @@ class Distribution(object): enabled_comps = [] #source_code = [] for source in self.sourceslist.list: - if (source.invalid == False and + if (source.invalid is False and self.is_codename(source.dist) and source.template and - source.template.official == True and + source.template.official is True 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): + source.disabled is False): self.cdrom_sources.append(source) cdrom_comps.extend(source.comps) elif (source.uri.startswith("cdrom:") and - source.disabled == True): + source.disabled is True): self.cdrom_sources.append(source) elif (source.type == self.binary_type and - source.disabled == False): + source.disabled is False): self.main_sources.append(source) comps.extend(source.comps) media.append(source.uri) elif (source.type == self.binary_type and - source.disabled == True): + source.disabled is True): self.disabled_sources.append(source) elif (source.type == self.source_type - and source.disabled == False): + and source.disabled is False): self.source_code_sources.append(source) elif (source.type == self.source_type and - source.disabled == True): + source.disabled is True): self.disabled_sources.append(source) - if (source.invalid == False and + if (source.invalid is False and source.template in self.source_template.children): - if (source.disabled == False + if (source.disabled is False and source.type == self.binary_type): self.child_sources.append(source) - elif (source.disabled == False + elif (source.disabled is False and source.type == self.source_type): self.source_code_sources.append(source) else: @@ -189,7 +189,7 @@ class Distribution(object): z = locale.find(".") if z == -1: z = len(locale) - country_code = locale[a+1:z].lower() + country_code = locale[a + 1:z].lower() if mirror_template: self.nearest_server = mirror_template % country_code @@ -205,7 +205,7 @@ class Distribution(object): i = server.find("://") l = server.find(".archive.ubuntu.com") if i != -1 and l != -1: - country = server[i+len("://"):l] + country = server[i + len("://"):l] if country in self.countries: # TRANSLATORS: %s is a country return _("Server for %s") % self.countries[country] @@ -280,10 +280,11 @@ class Distribution(object): 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) + if self.get_source_code is 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): """ @@ -344,7 +345,7 @@ class Distribution(object): # 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]) + self.add_source(comps=["%s" % comp]) else: # add the comp to all main, child and source code sources for source in sources: @@ -354,10 +355,10 @@ class Distribution(object): add_component_only_once(source, comps_per_sdist) # check if there is a main source code source at all - if self.get_source_code == True: + if self.get_source_code is True: if len(self.source_code_sources) < 1: # create a new main source - self.add_source(type=self.source_type, comps=["%s"%comp]) + 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: @@ -435,7 +436,7 @@ class DebianDistribution(Distribution): i = server.find("://ftp.") l = server.find(".debian.org") if i != -1 and l != -1: - country = server[i+len("://ftp."):l] + country = server[i + len("://ftp."):l] if country in self.countries: # TRANSLATORS: %s is a country return _("Server for %s") % gettext.dgettext( diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index 69e7e107..1b68d52e 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -62,12 +62,12 @@ def is_mirror(master_uri, compare_uri): 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 + 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: + compare_srv[compare_srv.index(".") + 1:] == master_srv: #print "Mirror" return True return False @@ -100,7 +100,7 @@ class SourceEntry(object): self.line = line # the original sources.list line if file is None: file = apt_pkg.config.find_dir( - "Dir::Etc")+apt_pkg.config.find("Dir::Etc::sourcelist") + "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 @@ -131,10 +131,10 @@ class SourceEntry(object): pieces.append(tmp) tmp = line[i] else: - p_found=True + p_found = True tmp += line[i] elif line[i] == "]": - p_found=False + p_found = False tmp += line[i] elif space_found and not line[i].isspace(): # we skip one or more space @@ -157,7 +157,7 @@ class SourceEntry(object): line = self.line.strip() #print line # check if the source is enabled/disabled - if line == "" or line == "#": # empty line + if line == "" or line == "#": # empty line self.invalid = True return if line[0] == "#": @@ -172,7 +172,7 @@ class SourceEntry(object): # check for another "#" in the line (this is treated as a comment) i = line.find("#") if i > 0: - self.comment = line[i+1:] + self.comment = line[i + 1:] line = line[:i] # source is ok, split it and see what we have pieces = self.mysplit(line) @@ -201,7 +201,7 @@ class SourceEntry(object): self.trusted = apt_pkg.string_to_bool(value) else: self.invalid = True - + # URI self.uri = pieces[1].strip() if len(self.uri) < 1: @@ -241,7 +241,8 @@ class SourceEntry(object): line += self.type if self.architectures and self.trusted is not None: - line += " [arch=%s trusted=%s]" % (",".join(self.architectures), "yes" if self.trusted else "no") + line += " [arch=%s trusted=%s]" % ( + ",".join(self.architectures), "yes" if self.trusted else "no") elif self.trusted is not None: line += " [trusted=%s]" % ("yes" if self.trusted else "no") elif self.architectures: @@ -250,7 +251,7 @@ class SourceEntry(object): if len(self.comps) > 0: line += " " + " ".join(self.comps) if self.comment != "": - line += " #"+self.comment + line += " #" + self.comment line += "\n" return line @@ -303,7 +304,8 @@ class SourcesList(object): all(predicate(source) for predicate in predicates)): yield source - def add(self, type, uri, dist, orig_comps, comment="", pos=-1, file=None, architectures=[]): + def add(self, type, uri, dist, orig_comps, comment="", pos=-1, file=None, + architectures=[]): """ Add a new source to the sources.list. The method will search for existing matching repos and will try to @@ -315,8 +317,8 @@ class SourcesList(object): # we can modify it later comps = orig_comps[:] sources = self.__find(lambda s: set(s.architectures) == architectures, - disabled=False, invalid=False, type=type, uri=uri, - dist=dist) + disabled=False, invalid=False, type=type, + uri=uri, dist=dist) # check if we have this source already in the sources.list for source in sources: for new_comp in comps: @@ -329,7 +331,6 @@ class SourcesList(object): sources = self.__find(lambda s: set(s.architectures) == architectures, invalid=False, type=type, uri=uri, dist=dist) - for source in sources: # if there is a repo with the same (type, uri, dist) just add the # components @@ -363,14 +364,13 @@ class SourcesList(object): def restore_backup(self, backup_ext): " restore sources.list files based on the backup extension " file = apt_pkg.config.find_file("Dir::Etc::sourcelist") - if os.path.exists(file+backup_ext) and \ - os.path.exists(file): - shutil.copy(file+backup_ext, file) + if os.path.exists(file + backup_ext) and os.path.exists(file): + shutil.copy(file + backup_ext, file) # now sources.list.d partsdir = apt_pkg.config.find_dir("Dir::Etc::sourceparts") for file in glob.glob("%s/*.list" % partsdir): - if os.path.exists(file+backup_ext): - shutil.copy(file+backup_ext, file) + 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 diff --git a/doc/examples/acquire.py b/doc/examples/acquire.py index 7381ad68..1971ba2f 100644 --- a/doc/examples/acquire.py +++ b/doc/examples/acquire.py @@ -34,7 +34,8 @@ progress = apt.progress.text.AcquireProgress() fetcher = apt_pkg.Acquire(progress) pm = apt_pkg.PackageManager(depcache) pm.get_archives(fetcher, list, recs) -print "%s (%s)" % (apt_pkg.size_to_str(fetcher.fetch_needed), fetcher.fetch_needed) +print "%s (%s)" % ( + apt_pkg.size_to_str(fetcher.fetch_needed), fetcher.fetch_needed) actiongroup = apt_pkg.ActionGroup(depcache) for pkg in cache.packages: depcache.mark_keep(pkg) @@ -65,7 +66,7 @@ for item in fetcher.items: print item if item.status == item.STAT_ERROR: print "Some error ocured: '%s'" % item.error_text - if item.complete == False: + if item.complete is False: print "No error, still nothing downloaded (%s)" % item.error_text print @@ -75,4 +76,4 @@ print "fetcher.Run() returned: %s" % res print "now runing pm.DoInstall()" res = pm.do_install(1) -print "pm.DoInstall() returned: %s"% res +print "pm.DoInstall() returned: %s" % res diff --git a/doc/examples/action.py b/doc/examples/action.py index 0399bddc..41b55144 100644 --- a/doc/examples/action.py +++ b/doc/examples/action.py @@ -36,7 +36,7 @@ depcache.init(progress) #sys.exit() # get a canidate version -ver= depcache.get_candidate_ver(iter) +ver = depcache.get_candidate_ver(iter) print "Candidate version: %s " % ver print "\n\nQuerry interface" diff --git a/doc/examples/architecture.py b/doc/examples/architecture.py index 75afb2d1..421c79a7 100644 --- a/doc/examples/architecture.py +++ b/doc/examples/architecture.py @@ -6,7 +6,7 @@ def main(): print "Native architecture:", apt_pkg.config["APT::Architecture"] print "All architectures:", apt_pkg.config.value_list("APT::Architectures") - + if __name__ == '__main__': main() diff --git a/doc/examples/build-deps-old.py b/doc/examples/build-deps-old.py index cc41aa64..4e7e4350 100755 --- a/doc/examples/build-deps-old.py +++ b/doc/examples/build-deps-old.py @@ -54,7 +54,7 @@ if srcrec: # calculate the build depends for all dependencies depends = depcache.get_candidate_ver(base).depends_list -for dep in depends["Depends"]: # FIXME: do we need to consider PreDepends? +for dep in depends["Depends"]: # FIXME: do we need to consider PreDepends? pkg = dep[0].target_pkg srcpkg_name = get_source_pkg(pkg, records, depcache) if not srcpkg_name: diff --git a/doc/examples/checkstate.py b/doc/examples/checkstate.py index 7f046c5d..084fdb87 100755 --- a/doc/examples/checkstate.py +++ b/doc/examples/checkstate.py @@ -19,11 +19,11 @@ for package in packages: continue version = versions[0] for other_version in versions: - if apt_pkg.version_compare(version.ver_str, other_version.ver_str)<0: + if apt_pkg.version_compare(version.ver_str, other_version.ver_str) < 0: version = other_version if package.current_ver: current = package.current_ver - if apt_pkg.version_compare(current.ver_str, version.ver_str)<0: + if apt_pkg.version_compare(current.ver_str, version.ver_str) < 0: upgradable[package.name] = version break else: diff --git a/doc/examples/deb_inspect.py b/doc/examples/deb_inspect.py index 3261c734..f6e090a1 100755 --- a/doc/examples/deb_inspect.py +++ b/doc/examples/deb_inspect.py @@ -10,7 +10,8 @@ import os.path def Callback(member, data): """ callback for debExtract """ print "'%s','%s',%u,%u,%u,%u,%u,%u,%u" \ - % (member.name, member.linkname, member.mode, member.uid, member.gid, member.size, member.mtime, member.major, member.minor) + % (member.name, member.linkname, member.mode, member.uid, + member.gid, member.size, member.mtime, member.major, member.minor) if __name__ == "__main__": @@ -35,7 +36,6 @@ if __name__ == "__main__": depends = sections["Depends"] print apt_pkg.parse_depends(depends) - print "extracting archive" dir = "/tmp/deb" os.mkdir(dir) diff --git a/doc/examples/depcache.py b/doc/examples/depcache.py index 919de603..8e33e98b 100644 --- a/doc/examples/depcache.py +++ b/doc/examples/depcache.py @@ -31,7 +31,7 @@ depcache.init(progress) # get a canidate version -ver= depcache.get_candidate_ver(iter) +ver = depcache.get_candidate_ver(iter) print "Candidate version: %s " % ver print "\n\nQuerry interface" diff --git a/doc/examples/inst.py b/doc/examples/inst.py index dd39c25b..25658435 100644 --- a/doc/examples/inst.py +++ b/doc/examples/inst.py @@ -17,7 +17,7 @@ class TextInstallProgress(InstallProgress): InstallProgress.updateInterface(self) if self.last >= self.percent: return - sys.stdout.write("\r[%s] %s\n" %(self.percent, self.status)) + sys.stdout.write("\r[%s] %s\n" % (self.percent, self.status)) sys.stdout.flush() self.last = self.percent diff --git a/doc/examples/progress.py b/doc/examples/progress.py index d7c4fad8..32dac330 100644 --- a/doc/examples/progress.py +++ b/doc/examples/progress.py @@ -11,7 +11,7 @@ import apt.progress.base class TextProgress(apt.progress.base.OpProgress): def __init__(self): - self.last=0.0 + self.last = 0.0 def update(self, percent): if (self.last + 1.0) <= percent: @@ -47,8 +47,11 @@ class TextFetchProgress(apt.progress.base.AcquireProgress): def pulse(self, owner): print "pulse: CPS: %s/s; Bytes: %s/%s; Item: %s/%s" % ( - apt_pkg.size_to_str(self.current_cps), apt_pkg.size_to_str(self.current_bytes), - apt_pkg.size_to_str(self.total_bytes), self.current_items, self.total_items) + apt_pkg.size_to_str(self.current_cps), + apt_pkg.size_to_str(self.current_bytes), + apt_pkg.size_to_str(self.total_bytes), + self.current_items, + self.total_items) return True def media_change(self, medium, drive): diff --git a/doc/examples/sources.py b/doc/examples/sources.py index 238ca48c..aa783758 100644 --- a/doc/examples/sources.py +++ b/doc/examples/sources.py @@ -11,6 +11,6 @@ sources = apt_pkg.SourceRecords() sources.restart() while sources.lookup('hello'): print sources.package, sources.version, sources.maintainer, \ - sources.section, `sources.binaries` + sources.section, repr(sources.binaries) print sources.files print sources.index.archive_uri(sources.files[0][2]) diff --git a/doc/source/conf.py b/doc/source/conf.py index 163f5074..7a565e16 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -36,7 +36,6 @@ if os.path.exists("../../build"): break - # General configuration # --------------------- @@ -68,7 +67,7 @@ copyright = u'2009-2010, Julian Andres Klode ' # try: - release=os.environ['DEBVER'] + release = os.environ['DEBVER'] except KeyError: from subprocess import Popen, PIPE p1 = Popen(["dpkg-parsechangelog", "-l../../debian/changelog"], @@ -82,7 +81,7 @@ for c in release.split("~")[0].split(".")[2]: if not c.isdigit(): break release_raw += c - + if int(release_raw) >= 90: version_s = release.split("~")[0].split(".")[:3] # Set the version to 0.X.100 if the release is 0.X.9Y (0.7.90 => 0.7.100) @@ -212,8 +211,8 @@ htmlhelp_basename = 'python-aptdoc' # Grouping the document tree into LaTeX files. List of tuples # (source index, target name, title, author, document class [howto/manual]). latex_documents = [ - ('contents', 'python-apt.tex', ur'python-apt Documentation', - ur'Julian Andres Klode ', 'manual'), + ('contents', 'python-apt.tex', ur'python-apt Documentation', + ur'Julian Andres Klode ', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of diff --git a/doc/source/examples/cache-pkgfile.py b/doc/source/examples/cache-pkgfile.py index f4cc2e66..10216c19 100644 --- a/doc/source/examples/cache-pkgfile.py +++ b/doc/source/examples/cache-pkgfile.py @@ -8,7 +8,7 @@ def main(): cache = apt_pkg.Cache() for pkgfile in cache.file_list: print 'Package-File:', pkgfile.filename - print 'Index-Type:', pkgfile.index_type # 'Debian Package Index' + print 'Index-Type:', pkgfile.index_type # 'Debian Package Index' if pkgfile.not_source: print 'Source: None' else: diff --git a/setup.py b/setup.py index 0c4561c0..cfbbf44e 100644 --- a/setup.py +++ b/setup.py @@ -61,7 +61,7 @@ if len(sys.argv) > 1 and sys.argv[1] == "build": for template in glob.glob('data/templates/*.mirrors'): import shutil shutil.copy(template, os.path.join("build", template)) - + setup(name="python-apt", description="Python bindings for APT", @@ -70,10 +70,10 @@ setup(name="python-apt", author_email="deity@lists.debian.org", ext_modules=[apt_pkg, apt_inst], packages=['apt', 'apt.progress', 'aptsources'], - data_files = [('share/python-apt/templates', - glob.glob('build/data/templates/*.info')), - ('share/python-apt/templates', - glob.glob('data/templates/*.mirrors'))], - cmdclass = cmdclass, - license = 'GNU GPL', - platforms = 'posix') + data_files=[('share/python-apt/templates', + glob.glob('build/data/templates/*.info')), + ('share/python-apt/templates', + glob.glob('data/templates/*.mirrors'))], + cmdclass=cmdclass, + license='GNU GPL', + platforms='posix') diff --git a/tests/old/__init__.py b/tests/old/__init__.py index afd0f074..e93c0b65 100644 --- a/tests/old/__init__.py +++ b/tests/old/__init__.py @@ -2,7 +2,6 @@ import os import unittest - if __name__ == '__main__': os.chdir(os.path.dirname(__file__)) print os.getcwd() diff --git a/tests/old/cache.py b/tests/old/cache.py index 11156c00..5cbf19d9 100644 --- a/tests/old/cache.py +++ b/tests/old/cache.py @@ -12,8 +12,8 @@ def main(): cache = apt_pkg.Cache() depcache = apt_pkg.DepCache(cache) depcache.init() - i=0 - all=cache.package_count + i = 0 + all = cache.package_count print "Running Cache test on all packages:" # first, get all pkgs for pkg in cache.packages: diff --git a/tests/old/depcache.py b/tests/old/depcache.py index cc030ed0..67a47503 100644 --- a/tests/old/depcache.py +++ b/tests/old/depcache.py @@ -12,8 +12,8 @@ def main(): cache = apt_pkg.Cache() depcache = apt_pkg.DepCache(cache) depcache.init() - i=0 - all=cache.package_count + i = 0 + all = cache.package_count print "Running DepCache test on all packages" print "(trying to install each and then mark it keep again):" # first, get all pkgs @@ -21,7 +21,7 @@ def main(): i += 1 x = pkg.name # then get each version - ver =depcache.get_candidate_ver(pkg) + ver = depcache.get_candidate_ver(pkg) if ver is not None: depcache.mark_install(pkg) if depcache.inst_count == 0: diff --git a/tests/old/pkgproblemresolver.py b/tests/old/pkgproblemresolver.py index 7714c882..feaa3cb1 100644 --- a/tests/old/pkgproblemresolver.py +++ b/tests/old/pkgproblemresolver.py @@ -12,8 +12,8 @@ def main(): cache = apt_pkg.Cache() depcache = apt_pkg.DepCache(cache) depcache.init() - i=0 - all=cache.package_count + i = 0 + all = cache.package_count print "Running DepCache test on all packages" print "(trying to install each and then mark it keep again):" # first, get all pkgs @@ -21,7 +21,7 @@ def main(): i += 1 x = pkg.name # then get each version - ver =depcache.get_candidate_ver(pkg) + ver = depcache.get_candidate_ver(pkg) if ver is not None: depcache.mark_install(pkg) if depcache.broken_count > 0: diff --git a/tests/old/pkgrecords.py b/tests/old/pkgrecords.py index 9e06d44c..3f253bf3 100644 --- a/tests/old/pkgrecords.py +++ b/tests/old/pkgrecords.py @@ -13,7 +13,7 @@ def main(): cache = apt_pkg.Cache() depcache = apt_pkg.DepCache(cache) depcache.init() - i=0 + i = 0 print "Running PkgRecords test on all packages:" for pkg in cache.packages: i += 1 diff --git a/tests/old/pkgsrcrecords.py b/tests/old/pkgsrcrecords.py index 36790eff..42b545ed 100644 --- a/tests/old/pkgsrcrecords.py +++ b/tests/old/pkgsrcrecords.py @@ -11,7 +11,7 @@ import sys def main(): apt_pkg.init() cache = apt_pkg.Cache() - i=0 + i = 0 print "Running PkgSrcRecords test on all packages:" for x in cache.packages: i += 1 diff --git a/tests/old/refcount.py b/tests/old/refcount.py index a80595c9..70adc0c1 100755 --- a/tests/old/refcount.py +++ b/tests/old/refcount.py @@ -1,14 +1,13 @@ #!/usr/bin/python-dbg -from pprint import pprint, pformat +from pprint import pprint import apt import sys import gc -import difflib # get initial cache print sys.gettotalrefcount() -progress= apt.progress.OpTextProgress() +progress = apt.progress.OpTextProgress() c = apt.Cache(progress) print "refcount after first cache instance: ", sys.gettotalrefcount() diff --git a/tests/test_all.py b/tests/test_all.py index 25774617..de6cb0c0 100644 --- a/tests/test_all.py +++ b/tests/test_all.py @@ -11,19 +11,21 @@ import sys try: import unittest.runner import unittest + unittest # pyflakes except ImportError: # py2.6 compat import unittest2 as unittest # workaround for py3.2 that apparently does not have this anymore -# it has "abiflags" +# it has "abiflags" if not hasattr(sys, "pydebug"): if sys.abiflags.startswith("d"): sys.pydebug = True else: sys.pydebug = False + def get_library_dir(): # Find the path to the built apt_pkg and apt_inst extensions if not os.path.exists("../build"): @@ -40,14 +42,17 @@ def get_library_dir(): plat_specifier) return os.path.abspath(library_dir) + class MyTestRunner(unittest.runner.TextTestRunner): def __init__(self, *args, **kwargs): kwargs["stream"] = sys.stdout super(MyTestRunner, self).__init__(*args, **kwargs) + if __name__ == '__main__': if not os.access("/etc/apt/sources.list", os.R_OK): - sys.stdout.write("[tests] Skipping because sources.list is not readable\n") + sys.stdout.write( + "[tests] Skipping because sources.list is not readable\n") sys.exit(0) sys.stdout.write("[tests] Running on %s\n" % sys.version.replace("\n", "")) diff --git a/tests/test_apt_cache.py b/tests/test_apt_cache.py index 9940374f..ee4fc50b 100644 --- a/tests/test_apt_cache.py +++ b/tests/test_apt_cache.py @@ -18,6 +18,7 @@ import unittest if sys.version_info[0] == 2 and sys.version_info[1] == 6: from unittest2 import TestCase + TestCase # pyflakes else: from unittest import TestCase @@ -36,7 +37,8 @@ def if_sources_list_is_readable(f): if os.access("/etc/apt/sources.list", os.R_OK): f(*args, **kwargs) else: - logging.warning("skipping '%s' because sources.list is not readable" % f) + logging.warning( + "skipping '%s' because sources.list is not readable" % f) return wrapper @@ -124,20 +126,23 @@ class TestAptCache(TestCase): cache = apt.Cache(rootdir="./data/test-provides/") cache.open() if len(cache) == 0: - logging.warning("skipping test_get_provided_packages, cache empty?!?") + logging.warning( + "skipping test_get_provided_packages, cache empty?!?") return # a true virtual pkg l = cache.get_providing_packages("mail-transport-agent") self.assertTrue(len(l) > 0) self.assertTrue("postfix" in [p.name for p in l]) - self.assertTrue("mail-transport-agent" in cache["postfix"].candidate.provides) + self.assertTrue( + "mail-transport-agent" in cache["postfix"].candidate.provides) def test_low_level_pkg_provides(self): apt.apt_pkg.config.set("Apt::architecture", "i386") # create highlevel cache and get the lowlevel one from it highlevel_cache = apt.Cache(rootdir="./data/test-provides") if len(highlevel_cache) == 0: - logging.warning("skipping test_log_level_pkg_provides, cache empty?!?") + logging.warning( + "skipping test_log_level_pkg_provides, cache empty?!?") return # low level cache provides list of the pkg cache = highlevel_cache._cache @@ -150,24 +155,24 @@ class TestAptCache(TestCase): break else: self.assertNotReached() - + @if_sources_list_is_readable def test_dpkg_journal_dirty(self): # create tmp env tmpdir = tempfile.mkdtemp() - dpkg_dir = os.path.join(tmpdir,"var","lib","dpkg") - os.makedirs(os.path.join(dpkg_dir,"updates")) - open(os.path.join(dpkg_dir,"status"), "w").close() + dpkg_dir = os.path.join(tmpdir, "var", "lib", "dpkg") + os.makedirs(os.path.join(dpkg_dir, "updates")) + open(os.path.join(dpkg_dir, "status"), "w").close() apt_pkg.config.set("Dir::State::status", - os.path.join(dpkg_dir,"status")) + os.path.join(dpkg_dir, "status")) cache = apt.Cache() # test empty self.assertFalse(cache.dpkg_journal_dirty) # that is ok, only [0-9] are dpkg jounral entries - open(os.path.join(dpkg_dir,"updates","xxx"), "w").close() - self.assertFalse(cache.dpkg_journal_dirty) + open(os.path.join(dpkg_dir, "updates", "xxx"), "w").close() + self.assertFalse(cache.dpkg_journal_dirty) # that is a dirty journal - open(os.path.join(dpkg_dir,"updates","000"), "w").close() + open(os.path.join(dpkg_dir, "updates", "000"), "w").close() self.assertTrue(cache.dpkg_journal_dirty) @if_sources_list_is_readable @@ -209,29 +214,29 @@ class TestAptCache(TestCase): # update a single sources.list cache = apt.Cache() cache.update(sources_list=sources_list) - # verify we just got the excpected package file + # verify we just got the excpected package file needle_packages = glob.glob( - lists_dir+"/*tests_data_test-repo_Packages*") + lists_dir + "/*tests_data_test-repo_Packages*") self.assertEqual(len(needle_packages), 1) # verify that we *only* got the Packages file from a single source - all_packages = glob.glob(lists_dir+"/*_Packages*") + all_packages = glob.glob(lists_dir + "/*_Packages*") self.assertEqual(needle_packages, all_packages) # verify that the listcleaner was not run and the marker file is # still there self.assertTrue("marker" in os.listdir(lists_dir)) - # now run update again (without the "normal" sources.list that # contains test-repo2 and verify that we got the normal sources.list cache.update() - needle_packages = glob.glob(lists_dir+"/*tests_data_test-repo2_Packages*") + needle_packages = glob.glob( + lists_dir + "/*tests_data_test-repo2_Packages*") self.assertEqual(len(needle_packages), 1) - all_packages = glob.glob(lists_dir+"/*_Packages*") + all_packages = glob.glob(lists_dir + "/*_Packages*") self.assertEqual(needle_packages, all_packages) # and another update with a single source only cache = apt.Cache() cache.update(sources_list=sources_list) - all_packages = glob.glob(lists_dir+"/*_Packages*") + all_packages = glob.glob(lists_dir + "/*_Packages*") self.assertEqual(len(all_packages), 2) apt_pkg.config.set("dir::state", old_state) apt_pkg.config.set("dir::etc::sourcelist", old_source_list) diff --git a/tests/test_aptsources.py b/tests/test_aptsources.py index 0b74cb79..4539b2d1 100644 --- a/tests/test_aptsources.py +++ b/tests/test_aptsources.py @@ -70,7 +70,6 @@ class TestAptSources(unittest.TestCase): ["main"], architectures=["amd64", "i386"]) self.assertTrue(sources.list == before.list) - # test to add something new: multiverse sources.add("deb", "http://de.archive.ubuntu.com/ubuntu/", "edgy", @@ -150,8 +149,7 @@ class TestAptSources(unittest.TestCase): apt_pkg.config.set("Dir::Etc::sourcelist", "data/aptsources/" "sources.list") sources = aptsources.sourceslist.SourcesList(True, self.templates) - - assert sources.list[8].invalid == False + assert sources.list[8].invalid is False assert sources.list[8].type == "deb" assert sources.list[8].architectures == ["amd64", "i386"] assert sources.list[8].uri == "http://de.archive.ubuntu.com/ubuntu/" @@ -166,11 +164,11 @@ class TestAptSources(unittest.TestCase): apt_pkg.config.set("Dir::Etc::sourcelist", "data/aptsources/" "sources.list") sources = aptsources.sourceslist.SourcesList(True, self.templates) - - assert sources.list[9].invalid == False + assert sources.list[9].invalid is False assert sources.list[9].type == "deb" assert sources.list[9].architectures == ["amd64", "i386"] - self.assertEqual( sources.list[9].uri, "http://de.archive.ubuntu.com/ubuntu/") + self.assertEqual( + sources.list[9].uri, "http://de.archive.ubuntu.com/ubuntu/") assert sources.list[9].dist == "natty" assert sources.list[9].comps == ["main"] assert sources.list[9].trusted @@ -198,7 +196,7 @@ class TestAptSources(unittest.TestCase): comps = comps.union(set(entry.comps)) self.assertTrue("multiverse" in comps) self.assertTrue("universe" in comps) - + def testDistribution(self): """aptsources: Test distribution detection.""" apt_pkg.config.set("Dir::Etc::sourcelist", "data/aptsources/" diff --git a/tests/test_auth.py b/tests/test_auth.py index bc353427..a9cfe736 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -15,6 +15,8 @@ import unittest if sys.version_info[0] > 2: from http.server import HTTPServer from http.server import SimpleHTTPRequestHandler as HTTPRequestHandler + HTTPServer # pyflakes + HTTPRequestHandler # pyflakes else: from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler as HTTPRequestHandler @@ -22,6 +24,7 @@ else: if sys.version_info[0] == 2 and sys.version_info[1] == 6: from unittest2 import TestCase + TestCase # pyflakes else: from unittest import TestCase @@ -215,7 +218,8 @@ class TestAuthKeys(TestCase): def test_add_key_from_keyserver_too_short(self): """Ensure that short keyids are not imported""" with self.assertRaises(apt.auth.AptKeyError): - apt.auth.add_key_from_keyserver("46925553", "hkp://localhost:19191") + apt.auth.add_key_from_keyserver( + "46925553", "hkp://localhost:19191") def test_add_key_from_server_mitm(self): """Verify that the key fingerprint is verified after download""" @@ -227,7 +231,8 @@ class TestAuthKeys(TestCase): "0101010178F7FE5C3E65D8AF8B48AD6246925553", "hkp://localhost:%d" % self.keyserver_port) self.assertTrue( - str(cm.exception).startswith("Fingerprints do not match"), cm.exception) + str(cm.exception).startswith("Fingerprints do not match"), + cm.exception) def testAddKeyFromServer(self): """Install a GnuPG key from a remote server.""" @@ -236,7 +241,7 @@ class TestAuthKeys(TestCase): with self._discard_stderr(): apt.auth.add_key_from_keyserver( - "0xa1bD8E9D78F7FE5C3E65D8AF8B48AD6246925553", + "0xa1bD8E9D78F7FE5C3E65D8AF8B48AD6246925553", "hkp://localhost:%d" % self.keyserver_port) ret = apt.auth.list_keys() diff --git a/tests/test_configuration.py b/tests/test_configuration.py index 80509cff..adf33719 100644 --- a/tests/test_configuration.py +++ b/tests/test_configuration.py @@ -7,7 +7,6 @@ # notice and this notice are preserved. """Unit tests for verifying the correctness of apt_pkg.Configuration""" import unittest - import apt_pkg @@ -21,9 +20,9 @@ class TestConfiguration(unittest.TestCase): def test_lp707416(self): """configuration: Test empty arguments (LP: #707416)""" self.assertRaises(ValueError, apt_pkg.parse_commandline, - apt_pkg.config,[], []) + apt_pkg.config, [], []) self.assertRaises(SystemError, apt_pkg.parse_commandline, - apt_pkg.config,[], ["cmd", "--arg0"]) + apt_pkg.config, [], ["cmd", "--arg0"]) if __name__ == "__main__": diff --git a/tests/test_debfile.py b/tests/test_debfile.py index 9379884a..ec3bf518 100644 --- a/tests/test_debfile.py +++ b/tests/test_debfile.py @@ -19,6 +19,7 @@ if libdir: import apt_pkg import apt.debfile + class TestDebfile(unittest.TestCase): """ test the debfile """ @@ -32,31 +33,31 @@ class TestDebfile(unittest.TestCase): # Conflicts: apt (<= 0.1) ('gdebi-test4.deb', True), # Conflicts: apt (>= 0.1) - ('gdebi-test5.deb', False), + ('gdebi-test5.deb', False), # invalid unicode in descr ('gdebi-test6.deb', True), # provides/conflicts against "foobarbaz" ('gdebi-test7.deb', True), # provides/conflicts/replaces against "mail-transport-agent" # (should fails if mail-transport-agent is installed) - ('gdebi-test8.deb', False), + ('gdebi-test8.deb', False), # provides/conflicts against real pkg ('gdebi-test9.deb', True), - # provides debconf-tiny and the real debconf conflicts with + # provides debconf-tiny and the real debconf conflicts with ('gdebi-test10.deb', False), ] def setUp(self): apt_pkg.init_config() - apt_pkg.config.set("APT::Architecture","i386") + apt_pkg.config.set("APT::Architecture", "i386") # FIXME: When run via test_all.py, the tests fail without this if it # is set in the system. apt_pkg.config.clear("APT::Architectures") - apt_pkg.config.set("Dir::State::status", + apt_pkg.config.set("Dir::State::status", "./data/test_debs/var/lib/dpkg/status") - apt_pkg.config.set("Dir::State::lists", + apt_pkg.config.set("Dir::State::lists", "./data/test_debs/var/lib/apt/lists") - apt_pkg.config.set("Dir::Etc::sourcelist", + apt_pkg.config.set("Dir::Etc::sourcelist", "./data/test_debs/etc/apt/sources.list") apt_pkg.init_system() self.cache = apt.Cache() @@ -76,7 +77,8 @@ class TestDebfile(unittest.TestCase): def testDebFile(self): deb = apt.debfile.DebPackage(cache=self.cache) for (filename, expected_res) in self.TEST_DEBS: - logging.debug("testing %s, expecting %s" % (filename, expected_res)) + logging.debug("testing %s, expecting %s" % ( + filename, expected_res)) deb.open(os.path.join("data", "test_debs", filename)) res = deb.check() self.assertEqual(res, expected_res, @@ -85,7 +87,8 @@ class TestDebfile(unittest.TestCase): def test_utf8_sections(self): deb = apt.debfile.DebPackage(cache=self.cache) - deb.open(os.path.join("data","test_debs","utf8-package_1.0-1_all.deb")) + deb.open( + os.path.join("data", "test_debs", "utf8-package_1.0-1_all.deb")) self.assertEqual(deb["Maintainer"], "Samuel Lidén Borell ") @@ -99,7 +102,8 @@ class TestDebfile(unittest.TestCase): deb = apt.debfile.DebPackage(cache=self.cache) deb.open(os.path.join("data", "test_debs", "gdebi-test12.deb")) content = deb.data_content("usr/bin/binary") - self.assertTrue(content.startswith("Automatically converted to printable ascii:\n\x7fELF ")) + self.assertTrue(content.startswith( + "Automatically converted to printable ascii:\n\x7fELF ")) # control file needle = """Package: gdebi-test12 Version: 1.0 @@ -136,7 +140,8 @@ Description: testpackage for gdebi - contains usr/bin/binary for file reading apt_pkg.config["APT::Architecture"] = "amd64" apt_pkg.init_system() - allowed_any = apt.debfile.DebPackage("./data/test_debs/testdep-allowed-any_1.0-1_i386.deb") + allowed_any = apt.debfile.DebPackage( + "./data/test_debs/testdep-allowed-any_1.0-1_i386.deb") self.assertTrue(allowed_any.check(), allowed_any._failure_string) def test_multi_arch_same(self): @@ -144,7 +149,8 @@ Description: testpackage for gdebi - contains usr/bin/binary for file reading apt_pkg.config["APT::Architectures::"] = "amd64" apt_pkg.config["APT::Architecture"] = "amd64" apt_pkg.init_system() - same = apt.debfile.DebPackage("./data/test_debs/testdep-same-arch_1.0-1_i386.deb") + same = apt.debfile.DebPackage( + "./data/test_debs/testdep-same-arch_1.0-1_i386.deb") self.assertTrue(same.check(), same._failure_string) diff --git a/tests/test_debfile_multiarch.py b/tests/test_debfile_multiarch.py index cf6479b1..045daf72 100644 --- a/tests/test_debfile_multiarch.py +++ b/tests/test_debfile_multiarch.py @@ -18,13 +18,15 @@ import apt import apt_pkg import apt.debfile + class TestDebfileMultiarch(unittest.TestCase): """ test the multiarch debfile """ def test_multiarch_deb_check(self): if apt_pkg.get_architectures() != ["amd64", "i386"]: # TODO: use unittest.skip - #logging.warning("skipping test because running on a non-multiarch system") + #logging.warning("skipping test because running on a " + # "non-multiarch system") return deb = apt.debfile.DebPackage( "./data/test_debs/multiarch-test1_i386.deb") @@ -48,10 +50,9 @@ class TestDebfileMultiarch(unittest.TestCase): installable = deb.check() #print deb._failure_string self.assertFalse(installable) - self.assertEqual(deb._failure_string, + self.assertEqual(deb._failure_string, "Conflicts with the installed package 'lib3ds-1-3'") - if __name__ == "__main__": unittest.main() diff --git a/tests/test_group.py b/tests/test_group.py index 3c3a5b7a..e70d2479 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -22,7 +22,6 @@ class TestGroup(unittest.TestCase): list(group) == list(group) - def test_cache_groups(self): """group: Iterate over all groups""" assert len(list(self.cache.groups)) == self.cache.group_count diff --git a/tests/test_hashes.py b/tests/test_hashes.py index 660373cb..be817f88 100644 --- a/tests/test_hashes.py +++ b/tests/test_hashes.py @@ -90,7 +90,7 @@ class TestHashString(unittest.TestCase): def tearDown(self): """Cleanup, Close the file object used for the tests.""" - self.file.close() + self.file.close() def test_md5(self): """hashes: Test apt_pkg.HashString().md5""" diff --git a/tests/test_lp659438.py b/tests/test_lp659438.py index 334f574d..40943d10 100644 --- a/tests/test_lp659438.py +++ b/tests/test_lp659438.py @@ -20,7 +20,7 @@ # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # Licensed under the GNU General Public License Version 2 -__author__ = "Sebastian Heinlein " +__author__ = "Sebastian Heinlein " import os import shutil diff --git a/tests/test_paths.py b/tests/test_paths.py index 48f86c52..62ea1665 100644 --- a/tests/test_paths.py +++ b/tests/test_paths.py @@ -30,8 +30,10 @@ class TestPath(unittest.TestCase): def test_acquire(self): apt_pkg.AcquireFile(apt_pkg.Acquire(), "http://example.com", destdir=self.file_bytes, destfile=self.file_bytes) - apt_pkg.AcquireFile(apt_pkg.Acquire(), "http://example.com", - destdir=self.file_unicode, destfile=self.file_unicode) + apt_pkg.AcquireFile(apt_pkg.Acquire(), + "http://example.com", + destdir=self.file_unicode, + destfile=self.file_unicode) def test_ararchive(self): archive = apt_inst.ArArchive(u"data/test_debs/data-tar-xz.deb") @@ -65,7 +67,7 @@ class TestPath(unittest.TestCase): apt_inst.TarFile(os.path.join(self.dir_bytes, b"control.tar.gz")) def test_configuration(self): - with open(self.file_unicode, 'w' ) as config: + with open(self.file_unicode, 'w') as config: config.write("Hello { World 1; };") apt_pkg.read_config_file(apt_pkg.config, self.file_bytes) apt_pkg.read_config_file(apt_pkg.config, self.file_unicode) @@ -95,7 +97,7 @@ class TestPath(unittest.TestCase): self.assertEqual(size1, size2) self.assertEqual(str(hash1), str(hash2)) self.assertEqual(str(hash1), ("SHA256:fefed230e286d832ab6eb0fb7b72" - + "442165b50df23a68402ae6e9d265a31920a2")) + "442165b50df23a68402ae6e9d265a31920a2")) def test_lock(self): apt_pkg.get_lock(self.file_unicode, True) diff --git a/tests/test_pep8.py b/tests/test_pep8.py index e6a672cf..2e1f43fc 100755 --- a/tests/test_pep8.py +++ b/tests/test_pep8.py @@ -5,7 +5,7 @@ import unittest class PackagePep8TestCase(unittest.TestCase): - def test_all_code(self): + def test_pep8(self): res = 0 py_dir = os.path.join(os.path.dirname(__file__), "..") res += subprocess.call( diff --git a/tests/test_policy.py b/tests/test_policy.py index f7d41152..f15cf2d1 100644 --- a/tests/test_policy.py +++ b/tests/test_policy.py @@ -9,6 +9,7 @@ import apt import unittest + class TestAptPolicy(unittest.TestCase): def test_apt_policy_lowlevel(self): @@ -34,6 +35,5 @@ class TestAptPolicy(unittest.TestCase): pkg.candidate.policy_priority < 1001) - if __name__ == "__main__": unittest.main() diff --git a/tests/test_progress.py b/tests/test_progress.py index 508da7d4..01cd8a2d 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -12,6 +12,7 @@ import apt import apt_pkg import os + class TestAcquireProgress(apt.progress.base.AcquireProgress): def pulse(self, owner): self.pulsed = True @@ -19,6 +20,7 @@ class TestAcquireProgress(apt.progress.base.AcquireProgress): # but often this is forgoten (and causes odd error messages) # so the lib supports it. we test the lack of support value here + class TestProgress(unittest.TestCase): def setUp(self): @@ -35,7 +37,7 @@ class TestProgress(unittest.TestCase): apt_pkg.config.set("Dir::state::lists", "./tmp") # create artifical line deb_line = "deb file:%s/data/fake-packages/ /\n" % basedir - with open("fetch_sources.list","w") as fobj: + with open("fetch_sources.list", "w") as fobj: fobj.write(deb_line) apt_pkg.config.set("Dir::Etc::sourcelist", "fetch_sources.list") apt_pkg.config.clear("APT::Update::Post-Invoke") @@ -47,5 +49,6 @@ class TestProgress(unittest.TestCase): cache.update(progress) self.assertTrue(progress.pulsed) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_size_to_str.py b/tests/test_size_to_str.py index 2c2c372f..1d0e9232 100644 --- a/tests/test_size_to_str.py +++ b/tests/test_size_to_str.py @@ -1,6 +1,6 @@ #!/usr/bin/python -__author__ = "Barry Warsaw , James Hunt, Michael Vogt" +__author__ = "Barry Warsaw , James Hunt, Michael Vogt" import sys import unittest @@ -9,6 +9,7 @@ import apt_pkg if sys.version_info[0] == 2 and sys.version_info[1] == 6: from unittest2 import TestCase + TestCase # pyflakes else: from unittest import TestCase @@ -18,74 +19,71 @@ class SizeToStrTestCase(TestCase): DATA = { # XXX: note the trailing spaces for some of these entries! - 10 ** 1 : "10 ", - 10 ** 2 : "100 ", - 10 ** 3 : "1000 ", - 10 ** 4 : "10.0 k", - 10 ** 5 : "100 k", - 10 ** 6 : "1000 k", - 10 ** 7 : "10.0 M", - 10 ** 8 : "100 M", - 10 ** 9 : "1000 M", - 10 ** 10 : "10.0 G", - 10 ** 11 : "100 G", - 10 ** 12 : "1000 G", - 10 ** 13 : "10.0 T", - 10 ** 14 : "100 T", - 10 ** 15 : "1000 T", - 10 ** 16 : "10.0 P", - 10 ** 17 : "100 P", - 10 ** 18 : "1000 P", - 10 ** 19 : "10.0 E", - 10 ** 20 : "100 E", - 10 ** 21 : "1000 E", - 10 ** 22 : "10.0 Z", - 10 ** 23 : "100.0 Z", - 10 ** 24 : "1000 Z", -# 10 ** 25 : "10.0 Y", - 10 ** 26 : "100 Y", - 10 ** 27 : "1000 Y", - + 10 ** 1: "10 ", + 10 ** 2: "100 ", + 10 ** 3: "1000 ", + 10 ** 4: "10.0 k", + 10 ** 5: "100 k", + 10 ** 6: "1000 k", + 10 ** 7: "10.0 M", + 10 ** 8: "100 M", + 10 ** 9: "1000 M", + 10 ** 10: "10.0 G", + 10 ** 11: "100 G", + 10 ** 12: "1000 G", + 10 ** 13: "10.0 T", + 10 ** 14: "100 T", + 10 ** 15: "1000 T", + 10 ** 16: "10.0 P", + 10 ** 17: "100 P", + 10 ** 18: "1000 P", + 10 ** 19: "10.0 E", + 10 ** 20: "100 E", + 10 ** 21: "1000 E", + 10 ** 22: "10.0 Z", + 10 ** 23: "100.0 Z", + 10 ** 24: "1000 Z", + #10 ** 25: "10.0 Y", + 10 ** 26: "100 Y", + 10 ** 27: "1000 Y", # That's our limit :) - 10 ** 28 : "10000 Y", - - 0 : "0 ", - 1 : "1 ", - 1024 : "1024 ", - 10240 : "10.2 k", - 102400 : "102 k", - 1024000 : "1024 k", - 10240000 : "10.2 M", - 102400000 : "102 M", - 2147483647 : "2147 M", - 2147483648 : "2147 M", - 1024000000 : "1024 M", - 10240000000 : "10.2 G", - - 9 : "9 ", - 99 : "99 ", - 999 : "999 ", - 9999 : "9999 ", - 99999 : "100.0 k", - 999999 : "1000 k", - 9999999 : "10000 k", - 99999999 : "100.0 M", - 999999999 : "1000 M", - 9999999999 : "10000 M", - 99999999999 : "100.0 G", - 999999999999 : "1000 G", - 9999999999999 : "10000 G", - 99999999999999 : "100.0 T", - 999999999999999 : "1000 T", - 9999999999999999 : "10.0 P", - 99999999999999999 : "100 P", - 999999999999999999 : "1000 P", - 9999999999999999999 : "10.0 E", - 99999999999999999999 : "100 E", - 999999999999999999999 : "1000 E", - 9999999999999999999999 : "10.0 Z", - 999999999999999999999999 : "1000 Z", - } + 10 ** 28: "10000 Y", + 0: "0 ", + 1: "1 ", + 1024: "1024 ", + 10240: "10.2 k", + 102400: "102 k", + 1024000: "1024 k", + 10240000: "10.2 M", + 102400000: "102 M", + 2147483647: "2147 M", + 2147483648: "2147 M", + 1024000000: "1024 M", + 10240000000: "10.2 G", + 9: "9 ", + 99: "99 ", + 999: "999 ", + 9999: "9999 ", + 99999: "100.0 k", + 999999: "1000 k", + 9999999: "10000 k", + 99999999: "100.0 M", + 999999999: "1000 M", + 9999999999: "10000 M", + 99999999999: "100.0 G", + 999999999999: "1000 G", + 9999999999999: "10000 G", + 99999999999999: "100.0 T", + 999999999999999: "1000 T", + 9999999999999999: "10.0 P", + 99999999999999999: "100 P", + 999999999999999999: "1000 P", + 9999999999999999999: "10.0 E", + 99999999999999999999: "100 E", + 999999999999999999999: "1000 E", + 9999999999999999999999: "10.0 Z", + 999999999999999999999999: "1000 Z", + } def test_from_data(self): for k, v in self.DATA.items(): @@ -96,7 +94,7 @@ class SizeToStrTestCase(TestCase): def test_raise_on_unsupported(self): for v in ["hello", None, {}, [], ()]: with self.assertRaises(TypeError): - apt_pkg.size_to_str(v) + apt_pkg.size_to_str(v) class RegressionTestCase(unittest.TestCase): diff --git a/tests/test_tagfile.py b/tests/test_tagfile.py index f26f851b..6ff6a32a 100644 --- a/tests/test_tagfile.py +++ b/tests/test_tagfile.py @@ -27,6 +27,7 @@ if libdir: import apt_pkg + class TestTagFile(unittest.TestCase): """ test the apt_pkg.TagFile """ diff --git a/tests/test_utils.py b/tests/test_utils.py index 35c0a466..12d5a554 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -13,12 +13,13 @@ import unittest from apt.utils import ( get_maintenance_end_date, get_release_date_from_release_file, - ) +) + class TestUtils(unittest.TestCase): def test_get_release_date_from_release_file(self): - path = os.path.join(os.path.dirname(__file__), + path = os.path.join(os.path.dirname(__file__), "data", "misc", "foo_Release") t = get_release_date_from_release_file(path) self.assertEqual(str(datetime.datetime.utcfromtimestamp(t)), @@ -28,33 +29,38 @@ class TestUtils(unittest.TestCase): months_of_support = 18 # test historic releases, jaunty release_date = datetime.datetime(2009, 4, 23) - (end_year, end_month) = get_maintenance_end_date(release_date, months_of_support) + (end_year, end_month) = get_maintenance_end_date( + release_date, months_of_support) self.assertEqual(end_year, 2010) self.assertEqual(end_month, 10) # test historic releases, karmic release_date = datetime.datetime(2009, 10, 29) - (end_year, end_month) = get_maintenance_end_date(release_date, months_of_support) + (end_year, end_month) = get_maintenance_end_date( + release_date, months_of_support) self.assertEqual(end_year, 2011) self.assertEqual(end_month, 4) # test maverick release_date = datetime.datetime(2010, 10, 10) - (end_year, end_month) = get_maintenance_end_date(release_date, months_of_support) + (end_year, end_month) = get_maintenance_end_date( + release_date, months_of_support) self.assertEqual(end_year, 2012) self.assertEqual(end_month, 4) # test with modulo zero release_date = datetime.datetime(2010, 6, 10) - (end_year, end_month) = get_maintenance_end_date(release_date, months_of_support) + (end_year, end_month) = get_maintenance_end_date( + release_date, months_of_support) self.assertEqual(end_year, 2011) self.assertEqual(end_month, 12) # test dapper months_of_support = 60 release_date = datetime.datetime(2008, 4, 24) - (end_year, end_month) = get_maintenance_end_date(release_date, months_of_support) + (end_year, end_month) = get_maintenance_end_date( + release_date, months_of_support) self.assertEqual(end_year, 2013) self.assertEqual(end_month, 4) - + # what datetime says #d = datetime.timedelta(18*30) #print "end date: ", release_date + d diff --git a/utils/doclint.py b/utils/doclint.py index a387b05f..f010ec53 100644 --- a/utils/doclint.py +++ b/utils/doclint.py @@ -35,19 +35,22 @@ def handle(filename): continue for member in objects.get(modname + '.' + modmember): if not member in dir(module.__dict__[modmember]): - print 'W: Unknown', modname + '.' + modmember + '.' + member - - assert(types[objects[modname+"."+modmember][member][1]] in ('method', 'attribute')) + print ('W: Unknown', modname + '.' + modmember + + '.' + member) + t = types[objects[modname + "." + modmember][member][1]] + assert(t in ('method', 'attribute')) all = getattr(module, '__all__', []) for modmember in dir(module): - if getattr(module.__dict__[modmember], "__module__", modname) != modname: + if (getattr(module.__dict__[modmember], "__module__", modname) != + modname): continue if isinstance(module.__dict__[modmember], type(module)): continue if modmember.startswith("_"): continue - if not modmember in objects[modname] and (not all or modmember in all): + if (not modmember in objects[modname] and + (not all or modmember in all)): print 'E: Missing', modname + '.' + modmember elif not modmember in objects[modname]: print 'W: Missing', modname + '.' + modmember @@ -64,14 +67,16 @@ def handle(filename): continue except: pass - if not member in objects.get(modname + '.' + modmember, ""): - print 'E: Missing', modname + '.' + modmember + '.' + member + if not member in objects.get( + modname + '.' + modmember, ""): + print('E: Missing', modname + '.' + modmember + '.' + + member) if __name__ == '__main__': scriptdir = os.path.dirname(__file__) parentdir = os.path.join(scriptdir, "..") - directory = os.path.join(parentdir, "doc", "build", "pickle") + directory = os.path.join(parentdir, "doc", "build", "pickle") directory = os.path.normpath(directory) sys.path.insert(0, os.path.abspath(parentdir)) handle(os.path.join(directory, "searchindex.pickle")) diff --git a/utils/get_ubuntu_mirrors.py b/utils/get_ubuntu_mirrors.py index cf509088..01344852 100755 --- a/utils/get_ubuntu_mirrors.py +++ b/utils/get_ubuntu_mirrors.py @@ -37,7 +37,7 @@ req = urllib2.Request("https://wiki.ubuntu.com/Archive?action=raw") try: print "Downloading mirrors list from the Ubuntu wiki..." - uri=urllib2.urlopen(req) + 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: -- cgit v1.2.3 From d95a8f27774842beb43bda54c4c61b67fe76a032 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 6 Jan 2014 12:17:44 +0100 Subject: Style fix: Do not use "is True" / "is False" This is uncommon style. It's better to use "pred" instead of "pred is True" and "not pred" instead of "pred is False". --- aptsources/distro.py | 26 +++++++++++++------------- doc/examples/acquire.py | 2 +- tests/test_aptsources.py | 4 ++-- 3 files changed, 16 insertions(+), 16 deletions(-) (limited to 'aptsources') diff --git a/aptsources/distro.py b/aptsources/distro.py index a71d5af2..9b48a10f 100644 --- a/aptsources/distro.py +++ b/aptsources/distro.py @@ -95,40 +95,40 @@ class Distribution(object): enabled_comps = [] #source_code = [] for source in self.sourceslist.list: - if (source.invalid is False and + if (not source.invalid and self.is_codename(source.dist) and source.template and - source.template.official is True and + source.template.official 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 is False): + not source.disabled): self.cdrom_sources.append(source) cdrom_comps.extend(source.comps) elif (source.uri.startswith("cdrom:") and - source.disabled is True): + source.disabled): self.cdrom_sources.append(source) elif (source.type == self.binary_type and - source.disabled is False): + not source.disabled): self.main_sources.append(source) comps.extend(source.comps) media.append(source.uri) elif (source.type == self.binary_type and - source.disabled is True): + source.disabled): self.disabled_sources.append(source) elif (source.type == self.source_type - and source.disabled is False): + and not source.disabled): self.source_code_sources.append(source) elif (source.type == self.source_type and - source.disabled is True): + source.disabled): self.disabled_sources.append(source) - if (source.invalid is False and + if (not source.invalid and source.template in self.source_template.children): - if (source.disabled is False + if (not source.disabled and source.type == self.binary_type): self.child_sources.append(source) - elif (source.disabled is False + elif (not source.disabled and source.type == self.source_type): self.source_code_sources.append(source) else: @@ -280,7 +280,7 @@ class Distribution(object): 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 is True and type == self.binary_type: + if self.get_source_code and type == self.binary_type: self.sourceslist.add( self.source_type, uri, dist, comps, comment, file=new_source.file, @@ -355,7 +355,7 @@ class Distribution(object): add_component_only_once(source, comps_per_sdist) # check if there is a main source code source at all - if self.get_source_code is True: + if self.get_source_code: if len(self.source_code_sources) < 1: # create a new main source self.add_source(type=self.source_type, comps=["%s" % comp]) diff --git a/doc/examples/acquire.py b/doc/examples/acquire.py index 1971ba2f..942d0686 100644 --- a/doc/examples/acquire.py +++ b/doc/examples/acquire.py @@ -66,7 +66,7 @@ for item in fetcher.items: print item if item.status == item.STAT_ERROR: print "Some error ocured: '%s'" % item.error_text - if item.complete is False: + if not item.complete: print "No error, still nothing downloaded (%s)" % item.error_text print diff --git a/tests/test_aptsources.py b/tests/test_aptsources.py index 4539b2d1..e6d0bd82 100644 --- a/tests/test_aptsources.py +++ b/tests/test_aptsources.py @@ -149,14 +149,14 @@ class TestAptSources(unittest.TestCase): apt_pkg.config.set("Dir::Etc::sourcelist", "data/aptsources/" "sources.list") sources = aptsources.sourceslist.SourcesList(True, self.templates) - assert sources.list[8].invalid is False + assert not sources.list[8].invalid assert sources.list[8].type == "deb" assert sources.list[8].architectures == ["amd64", "i386"] assert sources.list[8].uri == "http://de.archive.ubuntu.com/ubuntu/" assert sources.list[8].dist == "natty" assert sources.list[8].comps == ["main"] assert sources.list[8].line.strip() == str(sources.list[8]) - assert sources.list[8].trusted is None + assert not sources.list[8].trusted def testMultipleOptions(self): """aptsources: Test multi-arch parsing""" -- cgit v1.2.3 From 8b8a55f10ca47fe297fbb9b16a8e100658c60df3 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 6 Jan 2014 13:24:51 +0100 Subject: Use print_function everywhere This brings the code closer to Python 3. Automatically converted using 2to3 -f print. --- apt/__init__.py | 2 ++ apt/auth.py | 2 ++ apt/cache.py | 28 ++++++++++--------- apt/cdrom.py | 2 ++ apt/debfile.py | 28 ++++++++++--------- apt/package.py | 70 ++++++++++++++++++++++++----------------------- apt/progress/__init__.py | 2 ++ apt/progress/base.py | 4 ++- apt/progress/gtk2.py | 4 ++- apt/progress/text.py | 2 ++ apt/utils.py | 1 + aptsources/__init__.py | 2 ++ aptsources/sourceslist.py | 2 +- 13 files changed, 86 insertions(+), 63 deletions(-) (limited to 'aptsources') diff --git a/apt/__init__.py b/apt/__init__.py index c4e78ba0..b8d291e3 100644 --- a/apt/__init__.py +++ b/apt/__init__.py @@ -18,6 +18,8 @@ # USA # import the core of apt_pkg """High-Level Interface for working with apt.""" +from __future__ import print_function + import apt_pkg # import some fancy classes diff --git a/apt/auth.py b/apt/auth.py index acc612a9..814cf1dc 100644 --- a/apt/auth.py +++ b/apt/auth.py @@ -24,6 +24,8 @@ # USA """Handle GnuPG keys used to trust signed repositories.""" +from __future__ import print_function + import os import os.path import shutil diff --git a/apt/cache.py b/apt/cache.py index 6b1e2bda..593e70a7 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -19,6 +19,8 @@ # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA +from __future__ import print_function + import fnmatch import os import weakref @@ -721,31 +723,31 @@ class FilteredCache(object): def cache_pre_changed(): - print "cache pre changed" + print("cache pre changed") def cache_post_changed(): - print "cache post changed" + print("cache post changed") def _test(): """Internal test code.""" - print "Cache self test" + print("Cache self test") apt_pkg.init() cache = Cache(apt.progress.text.OpProgress()) cache.connect("cache_pre_change", cache_pre_changed) cache.connect("cache_post_change", cache_post_changed) - print ("aptitude" in cache) + print(("aptitude" in cache)) pkg = cache["aptitude"] - print pkg.name - print len(cache) + print(pkg.name) + print(len(cache)) for pkgname in cache.keys(): assert cache[pkgname].name == pkgname cache.upgrade() changes = cache.get_changes() - print len(changes) + print(len(changes)) for pkg in changes: assert pkg.name @@ -759,28 +761,28 @@ def _test(): cache._fetch_archives(fetcher, pm) #sys.exit(1) - print "Testing filtered cache (argument is old cache)" + print("Testing filtered cache (argument is old cache)") filtered = FilteredCache(cache) filtered.cache.connect("cache_pre_change", cache_pre_changed) filtered.cache.connect("cache_post_change", cache_post_changed) filtered.cache.upgrade() filtered.set_filter(MarkedChangesFilter()) - print len(filtered) + print(len(filtered)) for pkgname in filtered.keys(): assert pkgname == filtered[pkg].name - print len(filtered) + print(len(filtered)) - print "Testing filtered cache (no argument)" + print("Testing filtered cache (no argument)") filtered = FilteredCache(progress=apt.progress.base.OpProgress()) filtered.cache.connect("cache_pre_change", cache_pre_changed) filtered.cache.connect("cache_post_change", cache_post_changed) filtered.cache.upgrade() filtered.set_filter(MarkedChangesFilter()) - print len(filtered) + print(len(filtered)) for pkgname in filtered.keys(): assert pkgname == filtered[pkgname].name - print len(filtered) + print(len(filtered)) if __name__ == '__main__': _test() diff --git a/apt/cdrom.py b/apt/cdrom.py index 3c48fd07..35a0b180 100644 --- a/apt/cdrom.py +++ b/apt/cdrom.py @@ -20,6 +20,8 @@ # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA """Classes related to cdrom handling.""" +from __future__ import print_function + import glob import apt_pkg diff --git a/apt/debfile.py b/apt/debfile.py index 679c8468..1dd1a372 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -17,6 +17,8 @@ # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA """Classes for working with locally available Debian packages.""" +from __future__ import print_function + import apt import apt_inst import apt_pkg @@ -659,7 +661,7 @@ class DebPackage(object): def _dbg(self, level, msg): """Write debugging output to sys.stderr.""" if level <= self.debug: - print >> sys.stderr, msg + print(msg, file=sys.stderr) def install(self, install_progress=None): """Install the package.""" @@ -756,25 +758,25 @@ def _test(): cache = Cache() vp = "www-browser" - print "%s virtual: %s" % (vp, cache.is_virtual_package(vp)) + print("%s virtual: %s" % (vp, cache.is_virtual_package(vp))) providers = cache.get_providing_packages(vp) - print "Providers for %s :" % vp + print("Providers for %s :" % vp) for pkg in providers: - print " %s" % pkg.name + print(" %s" % pkg.name) d = DebPackage(sys.argv[1], cache) - print "Deb: %s" % d.pkgname + print("Deb: %s" % d.pkgname) if not d.check(): - print "can't be satified" - print d._failure_string - print "missing deps: %s" % d.missing_deps - print d.required_changes + print("can't be satified") + print(d._failure_string) + print("missing deps: %s" % d.missing_deps) + print(d.required_changes) - print d.filelist + print(d.filelist) - print "Installing ..." + print("Installing ...") ret = d.install(InstallProgress()) - print ret + print(ret) #s = DscSrcPackage(cache, "../tests/3ddesktop_0.2.9-6.dsc") #s.check_dep() @@ -783,7 +785,7 @@ def _test(): s = DscSrcPackage(cache=cache) d = "libc6 (>= 2.3.2), libaio (>= 0.3.96) | libaio1 (>= 0.3.96)" - print s._satisfy_depends(apt_pkg.parse_depends(d, False)) + print(s._satisfy_depends(apt_pkg.parse_depends(d, False))) if __name__ == "__main__": _test() diff --git a/apt/package.py b/apt/package.py index d4217195..f7f07680 100644 --- a/apt/package.py +++ b/apt/package.py @@ -19,6 +19,8 @@ # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA """Functionality related to packages.""" +from __future__ import print_function + import httplib import os import sys @@ -534,7 +536,7 @@ class Version(object): base = os.path.basename(self._records.filename) destfile = os.path.join(destdir, base) if _file_is_same(destfile, self.size, self._records.md5_hash): - print('Ignoring already existing file: %s' % destfile) + print(('Ignoring already existing file: %s' % destfile)) return os.path.abspath(destfile) acq = apt_pkg.Acquire(progress or apt.progress.text.AcquireProgress()) acqfile = apt_pkg.AcquireFile(acq, self.uri, self._records.md5_hash, @@ -583,7 +585,7 @@ class Version(object): if type_ == 'dsc': dsc = destfile if _file_is_same(destfile, size, md5): - print('Ignoring already existing file: %s' % destfile) + print(('Ignoring already existing file: %s' % destfile)) continue files.append(apt_pkg.AcquireFile(acq, src.index.archive_uri(path), md5, size, base, destfile=destfile)) @@ -1134,59 +1136,59 @@ class Package(object): def _test(): """Self-test.""" - print "Self-test for the Package modul" + print("Self-test for the Package modul") import random apt_pkg.init() progress = apt.progress.text.OpProgress() cache = apt.Cache(progress) pkg = cache["apt-utils"] - print "Name: %s " % pkg.name - print "ID: %s " % pkg.id - print "Priority (Candidate): %s " % pkg.candidate.priority - print "Priority (Installed): %s " % pkg.installed.priority - print "Installed: %s " % pkg.installed.version - print "Candidate: %s " % pkg.candidate.version - print "CandidateDownloadable: %s" % pkg.candidate.downloadable - print "CandidateOrigins: %s" % pkg.candidate.origins - print "SourcePkg: %s " % pkg.candidate.source_name - print "Section: %s " % pkg.section - print "Summary: %s" % pkg.candidate.summary - print "Description (formatted) :\n%s" % pkg.candidate.description - print "Description (unformatted):\n%s" % pkg.candidate.raw_description - print "InstalledSize: %s " % pkg.candidate.installed_size - print "PackageSize: %s " % pkg.candidate.size - print "Dependencies: %s" % pkg.installed.dependencies - print "Recommends: %s" % pkg.installed.recommends + print("Name: %s " % pkg.name) + print("ID: %s " % pkg.id) + print("Priority (Candidate): %s " % pkg.candidate.priority) + print("Priority (Installed): %s " % pkg.installed.priority) + print("Installed: %s " % pkg.installed.version) + print("Candidate: %s " % pkg.candidate.version) + print("CandidateDownloadable: %s" % pkg.candidate.downloadable) + print("CandidateOrigins: %s" % pkg.candidate.origins) + print("SourcePkg: %s " % pkg.candidate.source_name) + print("Section: %s " % pkg.section) + print("Summary: %s" % pkg.candidate.summary) + print("Description (formatted) :\n%s" % pkg.candidate.description) + print("Description (unformatted):\n%s" % pkg.candidate.raw_description) + print("InstalledSize: %s " % pkg.candidate.installed_size) + print("PackageSize: %s " % pkg.candidate.size) + print("Dependencies: %s" % pkg.installed.dependencies) + print("Recommends: %s" % pkg.installed.recommends) for dep in pkg.candidate.dependencies: - print ",".join("%s (%s) (%s) (%s)" % (o.name, o.version, o.relation, - o.pre_depend) for o in dep.or_dependencies) - print "arch: %s" % pkg.candidate.architecture - print "homepage: %s" % pkg.candidate.homepage - print "rec: ", pkg.candidate.record + print(",".join("%s (%s) (%s) (%s)" % (o.name, o.version, o.relation, + o.pre_depend) for o in dep.or_dependencies)) + print("arch: %s" % pkg.candidate.architecture) + print("homepage: %s" % pkg.candidate.homepage) + print("rec: ", pkg.candidate.record) - print cache["2vcard"].get_changelog() + print(cache["2vcard"].get_changelog()) for i in True, False: - print "Running install on random upgradable pkgs with AutoFix: %s " % i + print("Running install on random upgradable pkgs with AutoFix: ", i) for pkg in cache: if pkg.is_upgradable: if random.randint(0, 1) == 1: pkg.mark_install(i) - print "Broken: %s " % cache._depcache.broken_count - print "InstCount: %s " % cache._depcache.inst_count + print("Broken: %s " % cache._depcache.broken_count) + print("InstCount: %s " % cache._depcache.inst_count) - print + print() # get a new cache for i in True, False: - print "Randomly remove some packages with AutoFix: %s" % i + print("Randomly remove some packages with AutoFix: %s" % i) cache = apt.Cache(progress) for name in cache.keys(): if random.randint(0, 1) == 1: try: cache[name].mark_delete(i) except SystemError: - print "Error trying to remove: %s " % name - print "Broken: %s " % cache._depcache.broken_count - print "DelCount: %s " % cache._depcache.del_count + print("Error trying to remove: %s " % name) + print("Broken: %s " % cache._depcache.broken_count) + print("DelCount: %s " % cache._depcache.del_count) # self-test if __name__ == "__main__": diff --git a/apt/progress/__init__.py b/apt/progress/__init__.py index 776a7034..c689de5c 100644 --- a/apt/progress/__init__.py +++ b/apt/progress/__init__.py @@ -23,5 +23,7 @@ This package provides progress reporting for the python-apt package. The module GTK+ applications, and the module 'text' provides classes for terminals, etc. """ +from __future__ import print_function + __all__ = [] diff --git a/apt/progress/base.py b/apt/progress/base.py index 2c80ae29..66d56173 100644 --- a/apt/progress/base.py +++ b/apt/progress/base.py @@ -22,6 +22,8 @@ Custom progress classes should inherit from these classes. They can also be used as dummy progress classes which simply do nothing. """ +from __future__ import print_function + import errno import fcntl import os @@ -217,7 +219,7 @@ class InstallProgress(object): except IOError as err: # resource temporarly unavailable is ignored if err.errno != errno.EAGAIN and err.errno != errno.EWOULDBLOCK: - print err.strerror + print(err.strerror) return pkgname = status = status_str = percent = base = "" diff --git a/apt/progress/gtk2.py b/apt/progress/gtk2.py index b978c34f..7d142399 100644 --- a/apt/progress/gtk2.py +++ b/apt/progress/gtk2.py @@ -22,6 +22,8 @@ # USA """GObject-powered progress classes and a GTK+ status widget.""" +from __future__ import print_function + import pygtk pygtk.require('2.0') import gtk @@ -422,7 +424,7 @@ def _test(): try: cache.commit(apt_progress.acquire, apt_progress.install) except Exception as exc: - print >> sys.stderr, "Exception happened:", exc + print("Exception happened:", exc, file=sys.stderr) if len(sys.argv) > 1: deb = DebPackage(sys.argv[1], cache) deb.install(apt_progress.dpkg_install) diff --git a/apt/progress/text.py b/apt/progress/text.py index 76a4309e..880a112c 100644 --- a/apt/progress/text.py +++ b/apt/progress/text.py @@ -15,6 +15,8 @@ # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA """Progress reporting for text interfaces.""" +from __future__ import print_function + import os import sys diff --git a/apt/utils.py b/apt/utils.py index 9451f4bc..5a914fc2 100644 --- a/apt/utils.py +++ b/apt/utils.py @@ -16,6 +16,7 @@ # 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., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +from __future__ import print_function import os.path diff --git a/aptsources/__init__.py b/aptsources/__init__.py index 0929e12b..d711b4f3 100644 --- a/aptsources/__init__.py +++ b/aptsources/__init__.py @@ -1,3 +1,5 @@ +from __future__ import print_function + import apt_pkg diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index 1b68d52e..91ce8eff 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -23,7 +23,7 @@ # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA -from __future__ import absolute_import +from __future__ import absolute_import, print_function import glob import logging -- cgit v1.2.3 From a05fa8f6bacea135ba2954e9702aa95b54203322 Mon Sep 17 00:00:00 2001 From: Steve Langasek Date: Sat, 15 Mar 2014 18:51:40 +0100 Subject: aptsources/sourceslist.py: ensure that our sources are opened with UTF-8 ensure that our sources are opened with UTF-8 encoding, regardless of the current locale, and handle the sources lines as Unicode internally for consistency between python2 and python3. LP: #1069019. [jak: Squashed a PEP8 fixup change by Brian Murray] --- aptsources/sourceslist.py | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) (limited to 'aptsources') diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index 91ce8eff..6065fee4 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -31,6 +31,7 @@ import os.path import re import shutil import time +import io import apt_pkg from .distinfo import DistInfo @@ -234,25 +235,26 @@ class SourceEntry(object): """ return the current line as string """ if self.invalid: return self.line - line = "" + line = u"" if self.disabled: - line = "# " + line = u"# " line += self.type if self.architectures and self.trusted is not None: - line += " [arch=%s trusted=%s]" % ( - ",".join(self.architectures), "yes" if self.trusted else "no") + line += u" [arch=%s trusted=%s]" % ( + u",".join(self.architectures), + u"yes" if self.trusted else u"no") elif self.trusted is not None: - line += " [trusted=%s]" % ("yes" if self.trusted else "no") + line += u" [trusted=%s]" % (u"yes" if self.trusted else u"no") elif self.architectures: - line += " [arch=%s]" % ",".join(self.architectures) - line += " %s %s" % (self.uri, self.dist) + line += u" [arch=%s]" % u",".join(self.architectures) + line += u" %s %s" % (self.uri, self.dist) if len(self.comps) > 0: - line += " " + " ".join(self.comps) + line += u" " + u" ".join(self.comps) if self.comment != "": - line += " #" + self.comment - line += "\n" + line += u" #" + self.comment + line += u"\n" return line @@ -343,13 +345,13 @@ class SourcesList(object): # there isn't any matching source, so create a new line and parse it line = type if architectures: - line += " [arch=%s]" % ",".join(architectures) - line += " %s %s" % (uri, dist) + line += u" [arch=%s]" % u",".join(architectures) + line += u" %s %s" % (uri, dist) for c in comps: - line = line + " " + c + line = line + u" " + c if comment != "": - line = "%s #%s\n" % (line, comment) - line = line + "\n" + line = u"%s #%s\n" % (line, comment) + line = line + u"\n" new_entry = SourceEntry(line) if file is not None: new_entry.file = file @@ -387,7 +389,7 @@ class SourcesList(object): def load(self, file): """ (re)load the current sources """ try: - with open(file, "r") as f: + with io.open(file, "r", encoding="utf-8") as f: for line in f: source = SourceEntry(line, file) self.list.append(source) @@ -405,14 +407,15 @@ class SourcesList(object): "# Remember that you can only use http, ftp or file URIs\n" "# CDROMs are managed through the apt-cdrom tool.\n") - with open(path, "w") as f: + with io.open(path, "w", encoding="utf-8") as f: f.write(header) return try: for source in self.list: if source.file not in files: - files[source.file] = open(source.file, "w") + files[source.file] = io.open(source.file, "w", + encoding="utf-8") files[source.file].write(source.str()) finally: for f in files: -- cgit v1.2.3 From 50a8a9d573d97f0678721a84bcf9fdc697e96cb0 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 18 Mar 2014 19:26:52 +0100 Subject: Revert "aptsources/sourceslist.py: ensure that our sources are opened with UTF-8" This reverts commit a05fa8f6bacea135ba2954e9702aa95b54203322. --- aptsources/sourceslist.py | 39 ++++++++++++++++++--------------------- 1 file changed, 18 insertions(+), 21 deletions(-) (limited to 'aptsources') diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index 6065fee4..91ce8eff 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -31,7 +31,6 @@ import os.path import re import shutil import time -import io import apt_pkg from .distinfo import DistInfo @@ -235,26 +234,25 @@ class SourceEntry(object): """ return the current line as string """ if self.invalid: return self.line - line = u"" + line = "" if self.disabled: - line = u"# " + line = "# " line += self.type if self.architectures and self.trusted is not None: - line += u" [arch=%s trusted=%s]" % ( - u",".join(self.architectures), - u"yes" if self.trusted else u"no") + line += " [arch=%s trusted=%s]" % ( + ",".join(self.architectures), "yes" if self.trusted else "no") elif self.trusted is not None: - line += u" [trusted=%s]" % (u"yes" if self.trusted else u"no") + line += " [trusted=%s]" % ("yes" if self.trusted else "no") elif self.architectures: - line += u" [arch=%s]" % u",".join(self.architectures) - line += u" %s %s" % (self.uri, self.dist) + line += " [arch=%s]" % ",".join(self.architectures) + line += " %s %s" % (self.uri, self.dist) if len(self.comps) > 0: - line += u" " + u" ".join(self.comps) + line += " " + " ".join(self.comps) if self.comment != "": - line += u" #" + self.comment - line += u"\n" + line += " #" + self.comment + line += "\n" return line @@ -345,13 +343,13 @@ class SourcesList(object): # there isn't any matching source, so create a new line and parse it line = type if architectures: - line += u" [arch=%s]" % u",".join(architectures) - line += u" %s %s" % (uri, dist) + line += " [arch=%s]" % ",".join(architectures) + line += " %s %s" % (uri, dist) for c in comps: - line = line + u" " + c + line = line + " " + c if comment != "": - line = u"%s #%s\n" % (line, comment) - line = line + u"\n" + line = "%s #%s\n" % (line, comment) + line = line + "\n" new_entry = SourceEntry(line) if file is not None: new_entry.file = file @@ -389,7 +387,7 @@ class SourcesList(object): def load(self, file): """ (re)load the current sources """ try: - with io.open(file, "r", encoding="utf-8") as f: + with open(file, "r") as f: for line in f: source = SourceEntry(line, file) self.list.append(source) @@ -407,15 +405,14 @@ class SourcesList(object): "# Remember that you can only use http, ftp or file URIs\n" "# CDROMs are managed through the apt-cdrom tool.\n") - with io.open(path, "w", encoding="utf-8") as f: + with open(path, "w") as f: f.write(header) return try: for source in self.list: if source.file not in files: - files[source.file] = io.open(source.file, "w", - encoding="utf-8") + files[source.file] = open(source.file, "w") files[source.file].write(source.str()) finally: for f in files: -- cgit v1.2.3 From 9db885ce4fb06f8e154b97cd6cf4e0f09a241f54 Mon Sep 17 00:00:00 2001 From: Michael Vogt Date: Mon, 30 Jun 2014 11:21:36 +0200 Subject: make pep8 happy (again) --- apt/cache.py | 2 +- apt/debfile.py | 20 +++++++++--------- apt/utils.py | 10 ++++----- aptsources/distinfo.py | 4 ++-- aptsources/distro.py | 42 ++++++++++++++++++------------------- aptsources/sourceslist.py | 41 ++++++++++++++++++------------------ doc/examples/all_deps.py | 4 ++-- doc/source/examples/missing-deps.py | 2 +- tests/test_aptsources.py | 38 ++++++++++++++++----------------- tests/test_debfile_multiarch.py | 2 +- tests/test_pep8.py | 3 ++- utils/get_debian_mirrors.py | 2 +- utils/get_ubuntu_mirrors_from_lp.py | 2 +- 13 files changed, 86 insertions(+), 86 deletions(-) (limited to 'aptsources') diff --git a/apt/cache.py b/apt/cache.py index 36a9fa6b..69ee3693 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -530,7 +530,7 @@ class Cache(object): def connect(self, name, callback): """ connect to a signal, currently only used for cache_{post,pre}_{changed,open} """ - if not name in self._callbacks: + if name not in self._callbacks: self._callbacks[name] = [] self._callbacks[name].append(callback) diff --git a/apt/debfile.py b/apt/debfile.py index ca38fdc0..2c95bdf1 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -119,7 +119,7 @@ class DebPackage(object): # now do the real multiarch checking multiarch_pkgname = "%s:%s" % (pkgname, self._multiarch) # the upper layers will handle this - if not multiarch_pkgname in self._cache: + if multiarch_pkgname not in self._cache: return multiarch_pkgname # now check the multiarch state cand = self._cache[multiarch_pkgname].candidate._cand @@ -131,7 +131,7 @@ class DebPackage(object): # for conflicts we need a special case here, any not multiarch enabled # package has a implicit conflict if (in_conflict_checking and - not (cand.multi_arch & cand.MULTI_ARCH_SAME)): + not (cand.multi_arch & cand.MULTI_ARCH_SAME)): return pkgname return multiarch_pkgname @@ -152,7 +152,7 @@ class DebPackage(object): depname = self._maybe_append_multiarch_suffix(depname) # check for virtual pkgs - if not depname in self._cache: + if depname not in self._cache: if self._cache.is_virtual_package(depname): self._dbg( 3, "_is_or_group_satisfied(): %s is virtual dep" % @@ -190,7 +190,7 @@ class DebPackage(object): depname = self._maybe_append_multiarch_suffix(depname) # if we don't have it in the cache, it may be virtual - if not depname in self._cache: + if depname not in self._cache: if not self._cache.is_virtual_package(depname): continue providers = self._cache.get_providing_packages(depname) @@ -245,7 +245,7 @@ class DebPackage(object): #print "pkgver: %s " % pkgver #print "oper: %s " % oper if (apt_pkg.check_dep(pkgver, oper, ver) and not - self.replaces_real_pkg(pkgname, oper, ver)): + self.replaces_real_pkg(pkgname, oper, ver)): self._failure_string += _("Conflicts with the installed package " "'%s'") % pkg.name self._dbg(3, "conflicts with installed pkg '%s'" % pkg.name) @@ -266,7 +266,7 @@ class DebPackage(object): depname, in_conflict_checking=True) # check conflicts with virtual pkgs - if not depname in self._cache: + if depname not in self._cache: # FIXME: we have to check for virtual replaces here as # well (to pass tests/gdebi-test8.deb) if self._cache.is_virtual_package(depname): @@ -430,7 +430,7 @@ class DebPackage(object): self._cache.op_progress.done() return False if (c_or.target_pkg.name in provides and - self.pkgname != pkg.name): + self.pkgname != pkg.name): self._dbg( 2, "would break (conflicts) %s" % provides) self._failure_string += _( @@ -483,7 +483,7 @@ class DebPackage(object): self._check_was_run = True # check arch - if not "Architecture" in self._sections: + if "Architecture" not in self._sections: self._dbg(1, "ERROR: no architecture field") self._failure_string = _("No Architecture field in the package") return False @@ -713,11 +713,11 @@ class DscSrcPackage(DebPackage): try: for sec in tagfile: for tag in depends_tags: - if not tag in sec: + if tag not in sec: continue self._depends.extend(apt_pkg.parse_src_depends(sec[tag])) for tag in conflicts_tags: - if not tag in sec: + if tag not in sec: continue self._conflicts.extend(apt_pkg.parse_src_depends(sec[tag])) if 'Source' in sec: diff --git a/apt/utils.py b/apt/utils.py index 5a914fc2..948aac92 100644 --- a/apt/utils.py +++ b/apt/utils.py @@ -50,7 +50,7 @@ def get_release_date_from_release_file(path): return None tag = apt_pkg.TagFile(open(path)) section = next(tag) - if not "Date" in section: + if "Date" not in section: return None date = section["Date"] return apt_pkg.str_to_time(date) @@ -70,8 +70,8 @@ def get_release_filename_for_pkg(cache, pkgname, label, release): for ver_file, _index in aver.file_list: #print verFile if (ver_file.origin == label and - ver_file.label == label and - ver_file.archive == release): + ver_file.label == label and + ver_file.archive == release): ver = aver if not ver: return None @@ -79,8 +79,8 @@ def get_release_filename_for_pkg(cache, pkgname, label, release): for metaindex in cache._list.list: for m in metaindex.index_files: if (indexfile and - indexfile.describe == m.describe and - indexfile.is_trusted): + indexfile.describe == m.describe and + indexfile.is_trusted): dirname = apt_pkg.config.find_dir("Dir::State::lists") name = (apt_pkg.uri_to_filename(metaindex.uri) + "dists_%s_Release" % metaindex.dist) diff --git a/aptsources/distinfo.py b/aptsources/distinfo.py index b03e68f8..8fcbac96 100644 --- a/aptsources/distinfo.py +++ b/aptsources/distinfo.py @@ -254,8 +254,8 @@ class DistInfo(object): template.description = _(value) elif field == 'Component': if (component and not - template.has_component(component.name)): - template.components.append(component) + template.has_component(component.name)): + template.components.append(component) component = Component(value) elif field == 'CompDescription': component.set_description(_(value)) diff --git a/aptsources/distro.py b/aptsources/distro.py index 9b48a10f..f75aa06b 100644 --- a/aptsources/distro.py +++ b/aptsources/distro.py @@ -77,7 +77,7 @@ class Distribution(object): # find the distro template for template in self.sourceslist.matcher.templates: if (self.is_codename(template.name) and - template.distribution == self.id): + template.distribution == self.id): #print "yeah! found a template for %s" % self.description #print template.description, template.base_uri, \ # template.components @@ -96,40 +96,40 @@ class Distribution(object): #source_code = [] for source in self.sourceslist.list: if (not source.invalid and - self.is_codename(source.dist) and - source.template and - source.template.official and - self.is_codename(source.template.name)): + self.is_codename(source.dist) and + source.template and + source.template.official 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 - not source.disabled): - self.cdrom_sources.append(source) - cdrom_comps.extend(source.comps) + not source.disabled): + self.cdrom_sources.append(source) + cdrom_comps.extend(source.comps) elif (source.uri.startswith("cdrom:") and - source.disabled): + source.disabled): self.cdrom_sources.append(source) elif (source.type == self.binary_type and - not source.disabled): + not source.disabled): self.main_sources.append(source) comps.extend(source.comps) media.append(source.uri) elif (source.type == self.binary_type and - source.disabled): + source.disabled): self.disabled_sources.append(source) - elif (source.type == self.source_type - and not source.disabled): + elif (source.type == self.source_type and + not source.disabled): self.source_code_sources.append(source) elif (source.type == self.source_type and - source.disabled): + source.disabled): self.disabled_sources.append(source) if (not source.invalid and - source.template in self.source_template.children): + source.template in self.source_template.children): if (not source.disabled - and source.type == self.binary_type): - self.child_sources.append(source) + and source.type == self.binary_type): + self.child_sources.append(source) elif (not source.disabled - and source.type == self.source_type): + and source.type == self.source_type): self.source_code_sources.append(source) else: self.disabled_sources.append(source) @@ -256,9 +256,9 @@ class Distribution(object): 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)): + compare_mirrors(server, self.main_server)): continue - elif not mirror_entry in mirrors: + elif mirror_entry not in mirrors: mirrors.append(mirror_entry) return mirrors @@ -405,7 +405,7 @@ class Distribution(object): for source in self.child_sources: # Do not change the forces server of a child source if (source.template.base_uri is None or - source.template.base_uri != source.uri): + 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) diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index 91ce8eff..842b1451 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -87,23 +87,22 @@ class SourceEntry(object): """ 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.architectures = [] # architectures - self.trusted = None # Trusted - 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 + self.invalid = False # is the source entry valid + self.disabled = False # is it disabled ('#' in front) + self.type = "" # what type (deb, deb-src) + self.architectures = [] # architectures + self.trusted = None # Trusted + 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 is None: file = apt_pkg.config.find_dir( "Dir::Etc") + apt_pkg.config.find("Dir::Etc::sourcelist") - self.file = file # the file that the entry is located in + self.file = file # the file that the entry is located in self.parse(line) - self.template = None # type DistInfo.Suite + self.template = None # type DistInfo.Suite self.children = [] def __eq__(self, other): @@ -301,7 +300,7 @@ class SourcesList(object): def __find(self, *predicates, **attrs): for source in self.list: if (all(getattr(source, key) == attrs[key] for key in attrs) and - all(predicate(source) for predicate in predicates)): + all(predicate(source) for predicate in predicates)): yield source def add(self, type, uri, dist, orig_comps, comment="", pos=-1, file=None, @@ -379,8 +378,8 @@ class SourcesList(object): 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 \ - and os.path.exists(source.file): + if (source.file not in already_backuped + and os.path.exists(source.file)): shutil.copy(source.file, "%s%s" % (source.file, backup_ext)) return backup_ext @@ -467,15 +466,15 @@ class SourceEntryMatcher(object): found = False for template in self.templates: if (re.search(template.match_uri, source.uri) and - re.match(template.match_name, source.dist) and - # deb is a valid fallback for deb-src (if that is not - # definied, see #760035 - (source.type == template.type or template.type == "deb")): + re.match(template.match_name, source.dist) and + # deb is a valid fallback for deb-src (if that is not + # definied, see #760035 + (source.type == template.type or template.type == "deb")): found = True source.template = template break elif (template.is_mirror(source.uri) and - re.match(template.match_name, source.dist)): + re.match(template.match_name, source.dist)): found = True source.template = template break diff --git a/doc/examples/all_deps.py b/doc/examples/all_deps.py index 179501f4..6ce264bb 100644 --- a/doc/examples/all_deps.py +++ b/doc/examples/all_deps.py @@ -14,8 +14,8 @@ def dependencies(cache, pkg, deps, key="Depends"): for depVerList in dependslist[key]: for dep in depVerList: if dep.target_pkg.name in cache: - if pkg.name != dep.target_pkg.name and \ - not dep.target_pkg.name in deps: + if (pkg.name != dep.target_pkg.name and + dep.target_pkg.name not in deps): deps.add(dep.target_pkg.name) dependencies( cache, cache[dep.target_pkg.name], deps, key) diff --git a/doc/source/examples/missing-deps.py b/doc/source/examples/missing-deps.py index 7af18128..b9ccdc19 100644 --- a/doc/source/examples/missing-deps.py +++ b/doc/source/examples/missing-deps.py @@ -43,7 +43,7 @@ def main(): # Check every version for pfile, _ in version.file_list: if (pfile.origin == "Debian" and pfile.component == "main" and - pfile.archive == "unstable"): + pfile.archive == "unstable"): # We only want packages from Debian unstable main. check_version(version) break diff --git a/tests/test_aptsources.py b/tests/test_aptsources.py index f955205f..f174bd41 100644 --- a/tests/test_aptsources.py +++ b/tests/test_aptsources.py @@ -77,9 +77,9 @@ class TestAptSources(unittest.TestCase): found = False for entry in sources: if (entry.type == "deb" and - entry.uri == "http://de.archive.ubuntu.com/ubuntu/" and - entry.dist == "edgy" and - "multiverse" in entry.comps): + entry.uri == "http://de.archive.ubuntu.com/ubuntu/" and + entry.dist == "edgy" and + "multiverse" in entry.comps): found = True self.assertTrue(found) @@ -90,10 +90,10 @@ class TestAptSources(unittest.TestCase): found = False for entry in sources: if (entry.type == "deb" and - entry.uri == "http://de.archive.ubuntu.com/ubuntu/" and - entry.dist == "natty" and - entry.architectures == [] and - "multiverse" in entry.comps): + entry.uri == "http://de.archive.ubuntu.com/ubuntu/" and + entry.dist == "natty" and + entry.architectures == [] and + "multiverse" in entry.comps): found = True self.assertTrue(found) @@ -104,10 +104,10 @@ class TestAptSources(unittest.TestCase): found = False for entry in sources: if (entry.type == "deb" and - entry.uri == "http://de.archive.ubuntu.com/ubuntu/" and - entry.dist == "natty" and - set(entry.architectures) == set(["amd64", "i386"]) and - set(entry.comps) == set(["main", "universe"])): + entry.uri == "http://de.archive.ubuntu.com/ubuntu/" and + entry.dist == "natty" and + set(entry.architectures) == set(["amd64", "i386"]) and + set(entry.comps) == set(["main", "universe"])): found = True self.assertTrue(found) # test to add something new: multiverse *and* @@ -120,8 +120,8 @@ class TestAptSources(unittest.TestCase): found_something = 0 for entry in sources: if (entry.type == "deb" and - entry.uri == "http://de.archive.ubuntu.com/ubuntu/" and - entry.dist == "edgy"): + entry.uri == "http://de.archive.ubuntu.com/ubuntu/" and + entry.dist == "edgy"): for c in entry.comps: if c == "universe": found_universe += 1 @@ -219,11 +219,11 @@ class TestAptSources(unittest.TestCase): found = {} for entry in sources: if (entry.type == "deb" and - entry.uri == "http://de.archive.ubuntu.com/ubuntu/" and - "edgy" in entry.dist): + entry.uri == "http://de.archive.ubuntu.com/ubuntu/" and + "edgy" in entry.dist): for c in entry.comps: if c == comp: - if not entry.dist in found: + if entry.dist not in found: found[entry.dist] = 0 found[entry.dist] += 1 #print "".join([s.str() for s in sources]) @@ -236,11 +236,11 @@ class TestAptSources(unittest.TestCase): found = {} for entry in sources: if (entry.type == "deb" and - entry.template and - entry.template.name == "edgy"): + entry.template and + entry.template.name == "edgy"): for c in entry.comps: if c == comp: - if not entry.dist in found.has_key: + if entry.dist not in found.has_key: found[entry.dist] = 0 found[entry.dist] += 1 #print "".join([s.str() for s in sources]) diff --git a/tests/test_debfile_multiarch.py b/tests/test_debfile_multiarch.py index 045daf72..f8847838 100644 --- a/tests/test_debfile_multiarch.py +++ b/tests/test_debfile_multiarch.py @@ -39,7 +39,7 @@ class TestDebfileMultiarch(unittest.TestCase): # WARNING: this assumes that lib3ds-1-3 is a non-multiarch lib # use "lib3ds-1-3" as a test to see if non-multiach lib conflicts work canary = "lib3ds-1-3" - if not canary in cache: + if canary not in cache: # TODO: use unittest.skip #logging.warning("skipping test because %s is missing" % canary) return diff --git a/tests/test_pep8.py b/tests/test_pep8.py index 2e1f43fc..b3ec2dba 100755 --- a/tests/test_pep8.py +++ b/tests/test_pep8.py @@ -16,7 +16,8 @@ class PackagePep8TestCase(unittest.TestCase): # E126 continuation line over-indented for hanging indent # E127 continuation line over-indented for visual indent # E128 continuation line under-indented for visual indent - "--ignore=E125,E126,E127,E128", + # E265 block comment should start with '# ' + "--ignore=E125,E126,E127,E128,E265", "--exclude", "build,tests/old", "--repeat", py_dir]) if res != 0: diff --git a/utils/get_debian_mirrors.py b/utils/get_debian_mirrors.py index 5f4d7ff0..de4ebb95 100755 --- a/utils/get_debian_mirrors.py +++ b/utils/get_debian_mirrors.py @@ -29,7 +29,7 @@ masterlist = urllib2.urlopen("http://anonscm.debian.org/viewvc/" "mirror/Mirrors.masterlist?revision=HEAD") for mirror in deb822.Deb822.iter_paragraphs(masterlist): - if not "Country" in mirror: + if "Country" not in mirror: continue country = mirror["Country"].split(None, 1)[0] site = mirror["Site"] diff --git a/utils/get_ubuntu_mirrors_from_lp.py b/utils/get_ubuntu_mirrors_from_lp.py index dd02b63d..41d37be9 100755 --- a/utils/get_ubuntu_mirrors_from_lp.py +++ b/utils/get_ubuntu_mirrors_from_lp.py @@ -34,7 +34,7 @@ countries = {} for entry in d.entries: countrycode = entry.mirror_countrycode - if not countrycode in countries: + if countrycode not in countries: countries[countrycode] = set() for link in entry.links: countries[countrycode].add(link.href) -- cgit v1.2.3 From d53b66524df74f7637fb34f0db4c66535ba64cd0 Mon Sep 17 00:00:00 2001 From: Michael Vogt Date: Fri, 24 Oct 2014 10:10:05 -0400 Subject: Merged UbuntuRTMDistribution detection from ubuntu * Add template for the "Ubuntu-RTM" derived distribution. * Detect whether a system is running Ubuntu-RTM by way of "system-image-cli -i". Not perfect but close enough. --- aptsources/distro.py | 34 ++++++++++++++++++++++++++++++++++ debian/changelog | 9 +++++++++ 2 files changed, 43 insertions(+) (limited to 'aptsources') diff --git a/aptsources/distro.py b/aptsources/distro.py index f75aa06b..e11f113c 100644 --- a/aptsources/distro.py +++ b/aptsources/distro.py @@ -457,6 +457,13 @@ class UbuntuDistribution(Distribution): self, mirror_template="http://%s.archive.ubuntu.com/ubuntu/") +class UbuntuRTMDistribution(UbuntuDistribution): + ''' Class to support specific Ubuntu RTM features ''' + + def get_mirrors(self): + self.main_server = self.source_template.base_uri + + def _lsb_release(): """Call lsb_release --idrc and return a mapping.""" from subprocess import Popen, PIPE @@ -475,6 +482,24 @@ def _lsb_release(): return result +def _system_image_channel(): + """Get the current channel from system-image-cli -i if possible.""" + from subprocess import Popen, PIPE + import errno + try: + out = Popen( + ['system-image-cli', '-i'], stdout=PIPE, + universal_newlines=True).communicate()[0] + for l in out.splitlines(): + if l.startswith('channel: '): + return l.split(': ', 1)[1] + except OSError as exc: + if exc.errno != errno.ENOENT: + logging.warning( + 'system-image-cli failed, using defaults: %s' % exc) + return None + + def get_distro(id=None, codename=None, description=None, release=None): """ Check the currently used distribution and return the corresponding @@ -490,8 +515,17 @@ def get_distro(id=None, codename=None, description=None, release=None): codename = result['Codename'] description = result['Description'] release = result['Release'] + if id == "Ubuntu": + channel = _system_image_channel() + if channel is not None and "ubuntu-rtm/" in channel: + id = "Ubuntu-RTM" + codename = channel.rsplit("/", 1)[1].split("-", 1)[0] + description = codename + release = codename if id == "Ubuntu": return UbuntuDistribution(id, codename, description, release) + if id == "Ubuntu-RTM": + return UbuntuRTMDistribution(id, codename, description, release) elif id == "Debian": return DebianDistribution(id, codename, description, release) else: diff --git a/debian/changelog b/debian/changelog index 95852649..672ab6e0 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,12 @@ +python-apt (0.9.3.11) UNRELEASED; urgency=low + + [ Colin Watson ] + * Add template for the "Ubuntu-RTM" derived distribution. + * Detect whether a system is running Ubuntu-RTM by way of + "system-image-cli -i". Not perfect but close enough. + + -- Michael Vogt Wed, 24 Sep 2014 11:36:00 +0200 + python-apt (0.9.3.10) unstable; urgency=medium * python/tag.cc: ensure that the final \n is there when -- cgit v1.2.3 From 8f31026d3a1d5b097f60fdd14247d483945985d3 Mon Sep 17 00:00:00 2001 From: von Date: Sun, 10 May 2015 16:38:02 +0200 Subject: Fix indentation and docstring problems Closes: #784910 --- apt/cache.py | 12 ++++++------ apt/package.py | 1 + aptsources/sourceslist.py | 8 ++++---- 3 files changed, 11 insertions(+), 10 deletions(-) (limited to 'aptsources') diff --git a/apt/cache.py b/apt/cache.py index 69ee3693..f94f2146 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -59,11 +59,11 @@ class Cache(object): objects (although only getting items is supported). Keyword arguments: - progress -- a OpProgress object - rootdir -- a alternative root directory. if that is given - the system sources.list and system lists/ files are - not read, only files relative to the given rootdir - memonly -- build the cache in memory only + progress -- a OpProgress object, + rootdir -- an alternative root directory. if that is given the system + sources.list and system lists/files are not read, only file relative + to the given rootdir, + memonly -- build the cache in memory only. """ def __init__(self, progress=None, rootdir=None, memonly=False): @@ -409,7 +409,7 @@ class Cache(object): apt.progress.FetchProgress, the default is apt.progress.FetchProgress() . sources_list -- Update a alternative sources.list than the default. - Note that the sources.list.d directory is ignored in this case + Note that the sources.list.d directory is ignored in this case """ lockfile = apt_pkg.config.find_dir("Dir::State::Lists") + "lock" lock = apt_pkg.get_lock(lockfile) diff --git a/apt/package.py b/apt/package.py index 810d9dcc..8561d3c4 100644 --- a/apt/package.py +++ b/apt/package.py @@ -785,6 +785,7 @@ class Package(object): as :attr:`shortname` .. versionchanged:: 0.7.100.3 + As part of multi-arch, this field now may include architecture information. """ diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index 842b1451..f4903523 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -44,10 +44,10 @@ __all__ = ['is_mirror', 'SourceEntry', 'NullMatcher', 'SourcesList', 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 + """ 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("/ ") -- cgit v1.2.3