From c90351220c2c3393c25963513806e258d62715af Mon Sep 17 00:00:00 2001 From: Safa Ariman Date: Thu, 6 Jun 2019 01:31:19 +0300 Subject: [PATCH] Add python3 support --- pisi-cli | 11 +- pisi/__init__.py | 12 +- pisi/actionsapi/autotools.py | 2 +- pisi/actionsapi/cmaketools.py | 2 +- pisi/actionsapi/coreutils.py | 16 +- pisi/actionsapi/get.py | 2 +- pisi/actionsapi/javamodules.py | 4 +- pisi/actionsapi/kde.py | 2 +- pisi/actionsapi/kerneltools.py | 2 +- pisi/actionsapi/libtools.py | 2 +- pisi/actionsapi/perlmodules.py | 14 +- pisi/actionsapi/pisitools.py | 10 +- pisi/actionsapi/pisitoolsfunctions.py | 4 +- pisi/actionsapi/pkgconfig.py | 14 +- pisi/actionsapi/pythonmodules.py | 10 +- pisi/actionsapi/qt4.py | 2 +- pisi/actionsapi/rubymodules.py | 8 +- pisi/actionsapi/scons.py | 2 +- pisi/actionsapi/shelltools.py | 30 +++- pisi/actionsapi/texlivemodules.py | 18 +- pisi/actionsapi/variables.py | 5 +- pisi/api.py | 24 +-- pisi/archive.py | 15 +- pisi/atomicoperations.py | 16 +- pisi/cli/__init__.py | 30 ++-- pisi/cli/addrepo.py | 5 +- pisi/cli/blame.py | 8 +- pisi/cli/build.py | 5 +- pisi/cli/check.py | 5 +- pisi/cli/clean.py | 6 +- pisi/cli/command.py | 12 +- pisi/cli/configurepending.py | 6 +- pisi/cli/deletecache.py | 6 +- pisi/cli/delta.py | 5 +- pisi/cli/disablerepo.py | 5 +- pisi/cli/emerge.py | 5 +- pisi/cli/enablerepo.py | 5 +- pisi/cli/fetch.py | 5 +- pisi/cli/graph.py | 6 +- pisi/cli/help.py | 6 +- pisi/cli/history.py | 22 ++- pisi/cli/index.py | 5 +- pisi/cli/info.py | 25 ++- pisi/cli/install.py | 5 +- pisi/cli/listavailable.py | 11 +- pisi/cli/listcomponents.py | 9 +- pisi/cli/listinstalled.py | 14 +- pisi/cli/listnewest.py | 9 +- pisi/cli/listpending.py | 7 +- pisi/cli/listrepo.py | 7 +- pisi/cli/listsources.py | 9 +- pisi/cli/listupgrades.py | 11 +- pisi/cli/pisicli.py | 4 +- pisi/cli/rebuilddb.py | 5 +- pisi/cli/remove.py | 5 +- pisi/cli/removerepo.py | 5 +- pisi/cli/search.py | 7 +- pisi/cli/searchfile.py | 5 +- pisi/cli/updaterepo.py | 5 +- pisi/cli/upgrade.py | 5 +- pisi/comariface.py | 24 +-- pisi/component.py | 24 +-- pisi/config.py | 10 +- pisi/configfile.py | 32 ++-- pisi/conflict.py | 10 +- pisi/constants.py | 18 +- pisi/db/componentdb.py | 16 +- pisi/db/filesdb.py | 10 +- pisi/db/groupdb.py | 4 +- pisi/db/historydb.py | 9 +- pisi/db/installdb.py | 24 +-- pisi/db/itembyrepo.py | 28 ++- pisi/db/lazydb.py | 18 +- pisi/db/packagedb.py | 18 +- pisi/db/repodb.py | 18 +- pisi/db/sourcedb.py | 6 +- pisi/dependency.py | 4 +- pisi/fetcher.py | 12 +- pisi/file.py | 30 ++-- pisi/files.py | 8 +- pisi/graph.py | 2 +- pisi/group.py | 17 +- pisi/history.py | 19 +- pisi/index.py | 16 +- pisi/metadata.py | 16 +- pisi/mirrors.py | 6 +- pisi/oo.py | 8 +- pisi/operations/build.py | 54 +++--- pisi/operations/check.py | 6 +- pisi/operations/delta.py | 4 +- pisi/operations/emerge.py | 2 +- pisi/operations/helper.py | 4 +- pisi/operations/history.py | 4 +- pisi/operations/install.py | 10 +- pisi/operations/remove.py | 4 +- pisi/operations/upgrade.py | 16 +- pisi/package.py | 8 +- pisi/pgraph.py | 2 +- pisi/pxml/autoxml.py | 111 ++++++------ pisi/pxml/xmlext.py | 4 +- pisi/pxml/xmlfile.py | 10 +- pisi/relation.py | 4 +- pisi/replace.py | 2 +- pisi/scenarioapi/constants.py | 10 +- pisi/scenarioapi/package.py | 2 +- pisi/scenarioapi/pspec.py | 8 +- pisi/scenarioapi/repoops.py | 8 +- pisi/scenarioapi/withops.py | 28 +-- pisi/signalhandler.py | 6 +- pisi/sourcearchive.py | 4 +- pisi/specfile.py | 50 +++--- pisi/ui.py | 2 +- pisi/uri.py | 8 +- pisi/util.py | 48 +++--- pisi/version.py | 24 +-- scenarios/run.py | 10 +- scripts/check-newconfigs.py | 8 +- scripts/cleanArchives.py | 6 +- scripts/cleanCache.py | 12 +- scripts/createdelta.py | 8 +- scripts/fix_old_metadata_files.py | 4 +- scripts/lspisi | 10 +- scripts/make-changelog.py | 4 +- scripts/newpisipackage | 14 +- scripts/package-signing/pisi-key.py | 240 +------------------------- scripts/package-signing/pisign.py | 34 ++-- scripts/pisi-sandbox | 14 +- scripts/pisisdr | 8 +- scripts/svndist-v0.2.py | 6 +- scripts/svndist.py | 6 +- scripts/unpisi | 12 +- setup.py | 26 +-- tests/constanttest.py | 2 +- tests/database/componentdbtest.py | 2 +- tests/database/filesdbtest.py | 2 +- tests/database/installdbtest.py | 4 +- tests/database/itembyrepotest.py | 2 +- tests/database/lazydbtest.py | 4 +- tests/database/packagedbtest.py | 2 +- tests/database/repodbtest.py | 2 +- tests/database/sourcedbtest.py | 2 +- tests/filetest.py | 16 +- tests/replacetest.py | 2 +- tests/srcarchivetest.py | 4 +- tests/utiltest.py | 6 +- tests/versiontest.py | 44 ++--- 146 files changed, 806 insertions(+), 1082 deletions(-) diff --git a/pisi-cli b/pisi-cli index 4b5d4436..2bc09ec4 100755 --- a/pisi-cli +++ b/pisi-cli @@ -13,7 +13,6 @@ import sys import errno import traceback -import exceptions import signal import pisi @@ -24,21 +23,24 @@ import gettext gettext.bindtextdomain('pisi', "/usr/share/locale") gettext.textdomain('pisi') __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext + def sig_handler(sig, frame): if sig == signal.SIGTERM: exit() + def exit(): sys.exit(1) + def handle_exception(exception, value, tb): signal.signal(signal.SIGINT, signal.SIG_IGN) # disable further interrupts - ui = pisi.cli.CLI() # make a temporary UI + ui = pisi.cli.CLI() # make a temporary UI show_traceback = False - if exception == exceptions.KeyboardInterrupt: + if exception == KeyboardInterrupt: ui.error(_("Keyboard Interrupt: Exiting...")) exit() elif isinstance(value, pisi.Error): @@ -73,6 +75,7 @@ def handle_exception(exception, value, tb): exit() + if __name__ == "__main__": sys.excepthook = handle_exception diff --git a/pisi/__init__.py b/pisi/__init__.py index d24aad17..f7d990ba 100644 --- a/pisi/__init__.py +++ b/pisi/__init__.py @@ -17,8 +17,9 @@ import sys import atexit import logging import logging.handlers +from importlib import reload -__version__ = "2.4" +__version__ = "3.0a1" __all__ = [ 'api', 'configfile', 'db'] @@ -26,11 +27,11 @@ __all__ = [ 'api', 'configfile', 'db'] class Exception(Exception): """Class of exceptions that must be caught and handled within PiSi""" def __str__(self): - s = u'' + s = '' for x in self.args: if s != '': s += '\n' - s += unicode(x) + s += str(x) return s class Error(Exception): @@ -43,7 +44,7 @@ import pisi.context as ctx def init_logging(): log_dir = os.path.join(ctx.config.dest_dir(), ctx.config.log_dir()) - if os.access(log_dir, os.W_OK) and not sys.modules.has_key("distutils.core"): + if os.access(log_dir, os.W_OK) and "distutils.core" not in sys.modules: handler = logging.handlers.RotatingFileHandler('%s/pisi.log' % log_dir) formatter = logging.Formatter('%(asctime)-12s: %(levelname)-8s %(message)s') handler.setFormatter(formatter) @@ -71,8 +72,9 @@ def _cleanup(): # Hack for pisi to work with non-patched Python. pisi needs # lots of work for not doing this. + + reload(sys) -sys.setdefaultencoding('utf-8') atexit.register(_cleanup) diff --git a/pisi/actionsapi/autotools.py b/pisi/actionsapi/autotools.py index f7b11d88..1bb94fc6 100644 --- a/pisi/actionsapi/autotools.py +++ b/pisi/actionsapi/autotools.py @@ -14,7 +14,7 @@ import os import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # Pisi Modules import pisi.context as ctx diff --git a/pisi/actionsapi/cmaketools.py b/pisi/actionsapi/cmaketools.py index 94560c28..23506106 100644 --- a/pisi/actionsapi/cmaketools.py +++ b/pisi/actionsapi/cmaketools.py @@ -14,7 +14,7 @@ import os import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # Pisi Modules import pisi.context as ctx diff --git a/pisi/actionsapi/coreutils.py b/pisi/actionsapi/coreutils.py index 0d470e5b..e1dc4480 100644 --- a/pisi/actionsapi/coreutils.py +++ b/pisi/actionsapi/coreutils.py @@ -12,31 +12,31 @@ # Standard Python Modules import re import sys -from itertools import izip -from itertools import imap + + from itertools import count -from itertools import ifilter -from itertools import ifilterfalse + +from itertools import filterfalse # ActionsAPI import pisi.actionsapi def cat(filename): - return file(filename).xreadlines() + return open(filename) class grep: '''keep only lines that match the regexp''' def __init__(self, pat, flags = 0): self.fun = re.compile(pat, flags).match def __ror__(self, input): - return ifilter(self.fun, input) + return filter(self.fun, input) class tr: '''apply arbitrary transform to each sequence element''' def __init__(self, transform): self.tr = transform def __ror__(self, input): - return imap(self.tr, input) + return map(self.tr, input) class printto: '''print sequence elements one per line''' @@ -44,7 +44,7 @@ class printto: self.out = out def __ror__(self,input): for line in input: - print >> self.out, line + print(line, file=self.out) printlines = printto(sys.stdout) diff --git a/pisi/actionsapi/get.py b/pisi/actionsapi/get.py index 1f09bcef..e39762e5 100644 --- a/pisi/actionsapi/get.py +++ b/pisi/actionsapi/get.py @@ -15,7 +15,7 @@ import sys import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # PiSi Modules import pisi.actionsapi diff --git a/pisi/actionsapi/javamodules.py b/pisi/actionsapi/javamodules.py index 0e8486c8..e1cac039 100644 --- a/pisi/actionsapi/javamodules.py +++ b/pisi/actionsapi/javamodules.py @@ -16,7 +16,7 @@ from shutil import copy, copytree import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # Pisi Modules import pisi.util as util @@ -126,7 +126,7 @@ def _generate_exec_file(dest_dir, exe, java_args, exe_args): # Using low level I/O to set permission without calling os.chmod exec_file = os.open(util.join_path(exec_dir, get.srcNAME()), os.O_CREAT | os.O_WRONLY, - 0755) + 0o755) os.write(exec_file, EXEC_TEMPLATE % (util.join_path('/', dest_dir), java_args, exe, diff --git a/pisi/actionsapi/kde.py b/pisi/actionsapi/kde.py index 21dc2293..522cd42b 100644 --- a/pisi/actionsapi/kde.py +++ b/pisi/actionsapi/kde.py @@ -14,7 +14,7 @@ import os import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # Pisi Modules import pisi.context as ctx diff --git a/pisi/actionsapi/kerneltools.py b/pisi/actionsapi/kerneltools.py index 9abb7014..6d4d95d1 100644 --- a/pisi/actionsapi/kerneltools.py +++ b/pisi/actionsapi/kerneltools.py @@ -16,7 +16,7 @@ import shutil import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # Pisi Modules import pisi.context as ctx diff --git a/pisi/actionsapi/libtools.py b/pisi/actionsapi/libtools.py index f8385cbf..df5d5ea1 100644 --- a/pisi/actionsapi/libtools.py +++ b/pisi/actionsapi/libtools.py @@ -14,7 +14,7 @@ import os import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # Pisi-Core Modules import pisi.context as ctx diff --git a/pisi/actionsapi/perlmodules.py b/pisi/actionsapi/perlmodules.py index 2ddf52a8..1d40c8c7 100644 --- a/pisi/actionsapi/perlmodules.py +++ b/pisi/actionsapi/perlmodules.py @@ -15,7 +15,7 @@ import glob import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # Pisi Modules import pisi.context as ctx @@ -51,28 +51,28 @@ def configure(parameters = ''): export('PERL_MM_USE_DEFAULT', '1') if can_access_file('Build.PL'): if system('perl Build.PL installdirs=vendor destdir=%s' % get.installDIR()): - raise ConfigureError, _('Configure failed.') + raise ConfigureError(_('Configure failed.')) else: if system('perl Makefile.PL %s PREFIX=/usr INSTALLDIRS=vendor DESTDIR=%s' % (parameters, get.installDIR())): - raise ConfigureError, _('Configure failed.') + raise ConfigureError(_('Configure failed.')) def make(parameters = ''): '''make source with given parameters.''' if can_access_file('Makefile'): if system('make %s' % parameters): - raise MakeError, _('Make failed.') + raise MakeError(_('Make failed.')) else: if system('perl Build %s' % parameters): - raise MakeError, _('perl build failed.') + raise MakeError(_('perl build failed.')) def install(parameters = 'install'): '''install source with given parameters.''' if can_access_file('Makefile'): if system('make %s' % parameters): - raise InstallError, _('Make failed.') + raise InstallError(_('Make failed.')) else: if system('perl Build install'): - raise MakeError, _('perl install failed.') + raise MakeError(_('perl install failed.')) removePacklist() diff --git a/pisi/actionsapi/pisitools.py b/pisi/actionsapi/pisitools.py index f396130f..0b8e05db 100644 --- a/pisi/actionsapi/pisitools.py +++ b/pisi/actionsapi/pisitools.py @@ -22,7 +22,7 @@ import filecmp import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # Pisi Modules import pisi.context as ctx @@ -98,7 +98,7 @@ def dolib(sourceFile, destinationDirectory = '/usr/lib'): sourceFile = join_path(os.getcwd(), sourceFile) destinationDirectory = join_path(get.installDIR(), destinationDirectory) - lib_insinto(sourceFile, destinationDirectory, 0755) + lib_insinto(sourceFile, destinationDirectory, 0o755) def dolib_a(sourceFile, destinationDirectory = '/usr/lib'): '''insert the static library into /usr/lib with permission 0644''' @@ -107,7 +107,7 @@ def dolib_a(sourceFile, destinationDirectory = '/usr/lib'): sourceFile = join_path(os.getcwd(), sourceFile) destinationDirectory = join_path(get.installDIR(), destinationDirectory) - lib_insinto(sourceFile, destinationDirectory, 0644) + lib_insinto(sourceFile, destinationDirectory, 0o644) def dolib_so(sourceFile, destinationDirectory = '/usr/lib'): '''insert the dynamic library into /usr/lib with permission 0755''' @@ -116,7 +116,7 @@ def dolib_so(sourceFile, destinationDirectory = '/usr/lib'): sourceFile = join_path(os.getcwd(), sourceFile) destinationDirectory = join_path(get.installDIR(), destinationDirectory) - lib_insinto(sourceFile, destinationDirectory, 0755) + lib_insinto(sourceFile, destinationDirectory, 0o755) def doman(*sourceFiles): '''inserts the man pages in the list of files into /usr/share/man/''' @@ -184,7 +184,7 @@ def rename(sourceFile, destinationFile): try: os.rename(join_path(get.installDIR(), sourceFile), join_path(get.installDIR(), baseDir, destinationFile)) - except OSError, e: + except OSError as e: error(_('ActionsAPI [rename]: %s: %s') % (e, sourceFile)) def dosed(sourceFiles, findPattern, replacePattern = ''): diff --git a/pisi/actionsapi/pisitoolsfunctions.py b/pisi/actionsapi/pisitoolsfunctions.py index a372a501..41a91794 100644 --- a/pisi/actionsapi/pisitoolsfunctions.py +++ b/pisi/actionsapi/pisitoolsfunctions.py @@ -17,7 +17,7 @@ import glob import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # Pisi Modules import pisi.context as ctx @@ -73,7 +73,7 @@ def readable_insinto(destinationDirectory, *sourceFiles): for source in sourceFileGlob: system('install -m0644 "%s" %s' % (source, destinationDirectory)) -def lib_insinto(sourceFile, destinationDirectory, permission = 0644): +def lib_insinto(sourceFile, destinationDirectory, permission = 0o644): '''inserts a library fileinto destinationDirectory with given permission''' if not sourceFile or not destinationDirectory: diff --git a/pisi/actionsapi/pkgconfig.py b/pisi/actionsapi/pkgconfig.py index 60483823..eb04086a 100644 --- a/pisi/actionsapi/pkgconfig.py +++ b/pisi/actionsapi/pkgconfig.py @@ -14,7 +14,7 @@ import subprocess import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # PiSi Modules import pisi.context as ctx @@ -35,7 +35,7 @@ def getVariableForLibrary(library, variable): stdout=subprocess.PIPE, stderr=subprocess.PIPE) return_code = proc.wait() - except OSError, exception: + except OSError as exception: if exception.errno == 2: raise PkgconfigError(_("pkg-config is not installed on your system.")) else: @@ -54,7 +54,7 @@ def getLibraryVersion(library): stdout=subprocess.PIPE, stderr=subprocess.PIPE) return_code = proc.wait() - except OSError, exception: + except OSError as exception: if exception.errno == 2: raise PkgconfigError(_("pkg-config is not installed on your system.")) else: @@ -74,7 +74,7 @@ def getLibraryCFLAGS(library): stdout=subprocess.PIPE, stderr=subprocess.PIPE) return_code = proc.wait() - except OSError, exception: + except OSError as exception: if exception.errno == 2: raise PkgconfigError(_("pkg-config is not installed on your system.")) else: @@ -94,7 +94,7 @@ def getLibraryLIBADD(library): stdout=subprocess.PIPE, stderr=subprocess.PIPE) return_code = proc.wait() - except OSError, exception: + except OSError as exception: if exception.errno == 2: raise PkgconfigError(_("pkg-config is not installed on your system.")) else: @@ -113,7 +113,7 @@ def runManualCommand(*args): stdout=subprocess.PIPE, stderr=subprocess.PIPE) return_code = proc.wait() - except OSError, exception: + except OSError as exception: if exception.errno == 2: raise PkgconfigError(_("pkg-config is not installed on your system.")) else: @@ -131,7 +131,7 @@ def libraryExists(library): result = subprocess.call(["pkg-config", "--exists", "%s" % library]) - except OSError, exception: + except OSError as exception: if exception.errno == 2: raise PkgconfigError(_("pkg-config is not installed on your system.")) else: diff --git a/pisi/actionsapi/pythonmodules.py b/pisi/actionsapi/pythonmodules.py index 095ee228..350f5e29 100644 --- a/pisi/actionsapi/pythonmodules.py +++ b/pisi/actionsapi/pythonmodules.py @@ -15,7 +15,7 @@ import glob import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # Pisi Modules import pisi.context as ctx @@ -53,18 +53,18 @@ class RunTimeError(pisi.actionsapi.Error): def configure(parameters = ''): '''does python setup.py configure''' if system('python setup.py configure %s' % (parameters)): - raise ConfigureError, _('Configuration failed.') + raise ConfigureError(_('Configuration failed.')) def compile(parameters = ''): '''compile source with given parameters.''' if system('python setup.py build %s' % (parameters)): - raise CompileError, _('Make failed.') + raise CompileError(_('Make failed.')) def install(parameters = ''): '''does python setup.py install''' if system('python setup.py install --root=%s --no-compile -O0 %s' % (get.installDIR(), parameters)): - raise InstallError, _('Install failed.') + raise InstallError(_('Install failed.')) docFiles = ('AUTHORS', 'CHANGELOG', 'CONTRIBUTORS', 'COPYING*', 'COPYRIGHT', 'Change*', 'KNOWN_BUGS', 'LICENSE', 'MAINTAINERS', 'NEWS', @@ -78,7 +78,7 @@ def install(parameters = ''): def run(parameters = ''): '''executes parameters with python''' if system('python %s' % (parameters)): - raise RunTimeError, _('Running %s failed.') % parameters + raise RunTimeError(_('Running %s failed.') % parameters) def fixCompiledPy(lookInto = '/usr/lib/%s/' % get.curPYTHON()): ''' cleans *.py[co] from packages ''' diff --git a/pisi/actionsapi/qt4.py b/pisi/actionsapi/qt4.py index 25beb465..1ab0bee9 100644 --- a/pisi/actionsapi/qt4.py +++ b/pisi/actionsapi/qt4.py @@ -12,7 +12,7 @@ import glob import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # Pisi Modules import pisi.context as ctx diff --git a/pisi/actionsapi/rubymodules.py b/pisi/actionsapi/rubymodules.py index 02a3f255..0cf8bc53 100644 --- a/pisi/actionsapi/rubymodules.py +++ b/pisi/actionsapi/rubymodules.py @@ -15,7 +15,7 @@ from glob import glob from gettext import translation __trans = translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # Pisi Modules import pisi.context as ctx @@ -89,14 +89,14 @@ def auto_dodoc(): def install(parameters=''): '''does ruby setup.rb install''' if system('ruby -w setup.rb --prefix=/%s --destdir=%s %s' % (get.defaultprefixDIR(), get.installDIR(), parameters)): - raise InstallError, _('Install failed.') + raise InstallError(_('Install failed.')) auto_dodoc() def rake_install(parameters=''): '''execute rake script for installation''' if system('rake -t -l %s %s' % (os.path.join('/', get.defaultprefixDIR(), 'lib'), parameters)): - raise InstallError, _('Install failed.') + raise InstallError(_('Install failed.')) auto_dodoc() @@ -105,4 +105,4 @@ def run(parameters=''): export('DESTDIR', get.installDIR()) if system('ruby %s' % parameters): - raise RuntimeError, _("Running 'ruby %s' failed.") % parameters + raise RuntimeError(_("Running 'ruby %s' failed.") % parameters) diff --git a/pisi/actionsapi/scons.py b/pisi/actionsapi/scons.py index 6b2a146e..fdc6b8ad 100644 --- a/pisi/actionsapi/scons.py +++ b/pisi/actionsapi/scons.py @@ -15,7 +15,7 @@ import pisi.context as ctx import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # ActionsAPI Modules import pisi.actionsapi diff --git a/pisi/actionsapi/shelltools.py b/pisi/actionsapi/shelltools.py index 3b9f11e2..8d54487b 100644 --- a/pisi/actionsapi/shelltools.py +++ b/pisi/actionsapi/shelltools.py @@ -19,7 +19,7 @@ import grp import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # Pisi Modules import pisi.context as ctx @@ -32,14 +32,17 @@ from pisi.actionsapi import error from pisi.util import run_logged from pisi.util import join_path + def can_access_file(filePath): '''test the existence of file''' return os.access(filePath, os.F_OK) + def can_access_directory(destinationDirectory): '''test readability, writability and executablility of directory''' return os.access(destinationDirectory, os.R_OK | os.W_OK | os.X_OK) + def makedirs(destinationDirectory): '''recursive directory creation function''' try: @@ -48,6 +51,7 @@ def makedirs(destinationDirectory): except OSError: error(_('Cannot create directory %s') % destinationDirectory) + def echo(destionationFile, content): try: f = open(destionationFile, 'a') @@ -56,7 +60,8 @@ def echo(destionationFile, content): except IOError: error(_('ActionsAPI [echo]: Can\'t append to file %s.') % (destionationFile)) -def chmod(filePath, mode = 0755): + +def chmod(filePath, mode=0o755): '''change the mode of filePath to the mode''' filePathGlob = glob.glob(filePath) if len(filePathGlob) == 0: @@ -72,6 +77,7 @@ def chmod(filePath, mode = 0755): else: ctx.ui.error(_('ActionsAPI [chmod]: File %s doesn\'t exists.') % (fileName)) + def chown(filePath, uid = 'root', gid = 'root'): '''change the owner and group id of filePath to uid and gid''' if can_access_file(filePath): @@ -83,6 +89,7 @@ def chown(filePath, uid = 'root', gid = 'root'): else: ctx.ui.error(_('ActionsAPI [chown]: File %s doesn\'t exists.') % filePath) + def sym(source, destination): '''creates symbolic link''' try: @@ -90,6 +97,7 @@ def sym(source, destination): except OSError: ctx.ui.error(_('ActionsAPI [sym]: Permission denied: %s to %s') % (source, destination)) + def unlink(pattern): '''remove the file path''' filePathGlob = glob.glob(pattern) @@ -108,6 +116,7 @@ def unlink(pattern): else: ctx.ui.error(_('ActionsAPI [unlink]: File %s doesn\'t exists.') % (filePath)) + def unlinkDir(sourceDirectory): '''delete an entire directory tree''' if isDirectory(sourceDirectory) or isLink(sourceDirectory): @@ -120,6 +129,7 @@ def unlinkDir(sourceDirectory): else: error(_('ActionsAPI [unlinkDir]: Directory %s doesn\'t exists.') % (sourceDirectory)) + def move(source, destination): '''recursively move a "source" file or directory to "destination"''' sourceGlob = glob.glob(source) @@ -135,6 +145,7 @@ def move(source, destination): else: error(_('ActionsAPI [move]: File %s doesn\'t exists.') % (filePath)) + # FIXME: instead of passing a sym parameter, split copy and copytree into 4 different function def copy(source, destination, sym = True): '''recursively copy a "source" file or directory to "destination"''' @@ -165,6 +176,7 @@ def copy(source, destination, sym = True): else: error(_('ActionsAPI [copy]: File %s does not exist.') % filePath) + def copytree(source, destination, sym = True): '''recursively copy an entire directory tree rooted at source''' if isDirectory(source): @@ -177,11 +189,12 @@ def copytree(source, destination, sym = True): return try: shutil.copytree(source, destination, sym) - except OSError, e: + except OSError as e: error(_('ActionsAPI [copytree] %s to %s: %s') % (source, destination, e)) else: error(_('ActionsAPI [copytree]: Directory %s doesn\'t exists.') % (source)) + def touch(filePath): '''changes the access time of the 'filePath', or creates it if it does not exist''' filePathGlob = glob.glob(filePath) @@ -199,6 +212,7 @@ def touch(filePath): except IOError: error(_('ActionsAPI [touch]: Permission denied: %s') % (filePath)) + def cd(directoryName = ''): '''change directory''' current = os.getcwd() @@ -207,6 +221,7 @@ def cd(directoryName = ''): else: os.chdir(os.path.dirname(current)) + def ls(source): '''listdir''' if os.path.isdir(source): @@ -214,38 +229,47 @@ def ls(source): else: return glob.glob(source) + def export(key, value): '''export environ variable''' os.environ[key] = value + def isLink(filePath): '''return True if filePath refers to a symbolic link''' return os.path.islink(filePath) + def isFile(filePath): '''return True if filePath is an existing regular file''' return os.path.isfile(filePath) + def isDirectory(filePath): '''Return True if filePath is an existing directory''' return os.path.isdir(filePath) + def isEmpty(filePath): '''Return True if filePath is an empty file''' return os.path.getsize(filePath) == 0 + def realPath(filePath): '''return the canonical path of the specified filename, eliminating any symbolic links encountered in the path''' return os.path.realpath(filePath) + def baseName(filePath): '''return the base name of pathname filePath''' return os.path.basename(filePath) + def dirName(filePath): '''return the directory name of pathname path''' return os.path.dirname(filePath) + def system(command): command = string.join(string.split(command)) retValue = run_logged(command) diff --git a/pisi/actionsapi/texlivemodules.py b/pisi/actionsapi/texlivemodules.py index a081c504..5a6c4ea1 100644 --- a/pisi/actionsapi/texlivemodules.py +++ b/pisi/actionsapi/texlivemodules.py @@ -16,7 +16,7 @@ import shutil import shlex import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # Pisi Modules import pisi.context as ctx @@ -53,36 +53,36 @@ def compile(parameters = ''): # Move sources according to tplobj files if moveSources(): - raise CompileError, _('Moving source files failed') + raise CompileError(_('Moving source files failed')) # Generate config files if generateConfigFiles(): - raise CompileError, _('Generate config files failed') + raise CompileError(_('Generate config files failed')) # Build format files if buildFormatFiles(): - raise CompileError, _('Building format files failed') + raise CompileError(_('Building format files failed')) def install(parameters = ''): '''Installing texlive packages''' # Create symlinks from format to engines if createSymlinksFormat2Engines(): - raise InstallError, _('Creating symlinks from format to engines failed') + raise InstallError(_('Creating symlinks from format to engines failed')) # Installing docs if installDocFiles(): - raise InstallError, _('Installing docs failed') + raise InstallError(_('Installing docs failed')) # Installing texmf, texmf-dist, tlpkg, texmf-var if installTexmfFiles(): - raise InstallError, _('Installing texmf files failed') + raise InstallError(_('Installing texmf files failed')) # Installing config files if installConfigFiles(): - raise InstallError, _('Installing config files failed') + raise InstallError(_('Installing config files failed')) # Handle config files if handleConfigFiles(): - raise Installing, _('Handle config files failed') + raise Installing(_('Handle config files failed')) def createSymlinksFormat2Engines(): '''Create symlinks from format to engines''' diff --git a/pisi/actionsapi/variables.py b/pisi/actionsapi/variables.py index 33a8e262..7c4f9dca 100644 --- a/pisi/actionsapi/variables.py +++ b/pisi/actionsapi/variables.py @@ -28,7 +28,7 @@ def exportFlags(): # Build systems depend on these environment variables. That is why # we export them instead of using as (instance) variables. values = ctx.config.values - os.environ['HOST'] = values.build.host + os.environ['HOST'] = values.build.host os.environ['CFLAGS'] = values.build.cflags os.environ['CXXFLAGS'] = values.build.cxxflags os.environ['LDFLAGS'] = values.build.ldflags @@ -40,6 +40,7 @@ def exportFlags(): os.environ['CXX'] = values.build.cxx os.environ['LD'] = values.build.ld + class Env(object): '''General environment variables used in actions API''' def __init__(self): @@ -65,7 +66,7 @@ class Env(object): # Using environment variables is somewhat tricky. Each time # you need them you need to check for their value. - if self.__vars.has_key(attr): + if attr in self.__vars: return os.getenv(self.__vars[attr]) else: return None diff --git a/pisi/api.py b/pisi/api.py index 5c0dd27c..c26eac41 100644 --- a/pisi/api.py +++ b/pisi/api.py @@ -12,11 +12,11 @@ import os import fcntl import re -import fetcher +from . import fetcher import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.context as ctx @@ -53,7 +53,7 @@ def locked(func): """ def wrapper(*__args,**__kw): try: - lock = file(pisi.util.join_path(pisi.context.config.lock_dir(), 'pisi'), 'w') + lock = open(pisi.util.join_path(pisi.context.config.lock_dir(), 'pisi'), 'w') except IOError: raise pisi.errors.PrivilegeError(_("You have to be root for this operation.")) @@ -254,7 +254,7 @@ def list_upgradable(): installdb = pisi.db.installdb.InstallDB() is_upgradable = pisi.operations.upgrade.is_upgradable - upgradable = filter(is_upgradable, installdb.list_installed()) + upgradable = list(filter(is_upgradable, installdb.list_installed())) # replaced packages can not pass is_upgradable test, so we add them manually upgradable.extend(list_replaces()) @@ -535,7 +535,7 @@ def delete_cache(): pisi.util.clean_dir(ctx.config.archives_dir()) ctx.ui.info(_("Cleaning temporary directory %s...") % ctx.config.tmp_dir()) pisi.util.clean_dir(ctx.config.tmp_dir()) - for cache in filter(lambda x: x.endswith(".cache"), os.listdir(ctx.config.cache_root_dir())): + for cache in [x for x in os.listdir(ctx.config.cache_root_dir()) if x.endswith(".cache")]: cache_file = pisi.util.join_path(ctx.config.cache_root_dir(), cache) ctx.ui.info(_("Removing cache file %s...") % cache_file) os.unlink(cache_file) @@ -766,7 +766,7 @@ def info_name(package_name, useinstalldb=False): if useinstalldb and installdb.has_package(package.name): try: files = installdb.get_files(package.name) - except pisi.Error, e: + except pisi.Error as e: ctx.ui.warning(e) files = None else: @@ -844,7 +844,7 @@ def __update_repo(repo, force=False): repouri = repodb.get_repo(repo).indexuri.get_uri() try: index.read_uri_of_repo(repouri, repo) - except pisi.file.AlreadyHaveException, e: + except pisi.file.AlreadyHaveException as e: ctx.ui.info(_('%s repository information is up-to-date.') % repo) if force: ctx.ui.info(_('Updating database at any rate as requested')) @@ -857,7 +857,7 @@ def __update_repo(repo, force=False): try: index.check_signature(repouri, repo) - except pisi.file.NoSignatureFound, e: + except pisi.file.NoSignatureFound as e: ctx.ui.warning(e) ctx.ui.info(_('Package database updated.')) @@ -962,7 +962,7 @@ def clearCache(all=False): # sort dictionary by value from PEP-265 from operator import itemgetter - return sorted(sizes.iteritems(), key=itemgetter(1), reverse=False) + return sorted(iter(sizes.items()), key=itemgetter(1), reverse=False) def removeOrderByLimit(cacheDir, order, limit): totalSize = 0 @@ -971,7 +971,7 @@ def clearCache(all=False): if totalSize >= limit: try: os.remove(os.path.join(cacheDir, pkg) + ctx.const.package_suffix) - except exceptions.OSError: + except OSError: pass def removeAll(cacheDir): @@ -979,12 +979,12 @@ def clearCache(all=False): for pkg in cached: try: os.remove(pkg) - except exceptions.OSError: + except OSError: pass cacheDir = ctx.config.cached_packages_dir() - pkgList = map(lambda x: os.path.basename(x).split(ctx.const.package_suffix)[0], glob.glob("%s/*.pisi" % cacheDir)) + pkgList = [os.path.basename(x).split(ctx.const.package_suffix)[0] for x in glob.glob("%s/*.pisi" % cacheDir)] if not all: # Cache limits from pisi.conf config = pisi.configfile.ConfigurationFile("/etc/pisi/pisi.conf") diff --git a/pisi/archive.py b/pisi/archive.py index a8f9cff0..125b009b 100644 --- a/pisi/archive.py +++ b/pisi/archive.py @@ -19,10 +19,11 @@ import errno import shutil import tarfile import zipfile +import lzma import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # PiSi modules import pisi @@ -73,7 +74,7 @@ class _LZMAProxy(object): break b.append(data) x += len(data) - self.buf = "".join(b) + self.buf = b"".join([b_item if type(b_item) == bytes else b_item.encode() for b_item in b]) buf = self.buf[:size] self.buf = self.buf[size:] @@ -106,7 +107,7 @@ class TarFile(tarfile.TarFile): name=None, mode="r", fileobj=None, - compressformat="xz", + compressformat=lzma.FORMAT_XZ, compresslevel=9, **kwargs): """Open lzma/xz compressed tar archive name for reading or writing. @@ -126,12 +127,12 @@ class TarFile(tarfile.TarFile): else: options = {"format": compressformat, "level": compresslevel} - fileobj = lzma.LZMAFile(name, mode, options=options) + fileobj = lzma.LZMAFile(name, mode, format=1, preset=compresslevel) try: t = cls.taropen(name, mode, fileobj, **kwargs) except IOError: - raise ReadError("not a lzma file") + raise tarfile.ReadError("not a lzma file") t._extfileobj = False return t @@ -339,7 +340,7 @@ class ArchiveTar(ArchiveBase): try: self.tar.extract(tarinfo) - except OSError, e: + except OSError as e: # Handle the case where an upper directory cannot # be created because of a conflict with an existing # regular file or symlink. In this case, remove @@ -545,7 +546,7 @@ class ArchiveZip(ArchiveBase): arc_name = arc_name or "" self.zip_obj.writestr(arc_name + '/', '') attr_obj = self.zip_obj.getinfo(arc_name + '/') - attr_obj.external_attr = stat.S_IMODE(os.stat(file_name)[0]) << 16L + attr_obj.external_attr = stat.S_IMODE(os.stat(file_name)[0]) << 16 for f in os.listdir(file_name): self.add_to_archive(os.path.join(file_name, f), os.path.join(arc_name, f)) diff --git a/pisi/atomicoperations.py b/pisi/atomicoperations.py index 835e28a9..e6121cab 100644 --- a/pisi/atomicoperations.py +++ b/pisi/atomicoperations.py @@ -13,7 +13,7 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import os import shutil @@ -54,7 +54,7 @@ class AtomicOperation(object): pass # possible paths of install operation -(INSTALL, REINSTALL, UPGRADE, DOWNGRADE, REMOVE) = range(5) +(INSTALL, REINSTALL, UPGRADE, DOWNGRADE, REMOVE) = list(range(5)) opttostr = {INSTALL:"install", REMOVE:"remove", REINSTALL:"reinstall", UPGRADE:"upgrade", DOWNGRADE:"downgrade"} class Install(AtomicOperation): @@ -206,7 +206,7 @@ class Install(AtomicOperation): if not self.pkginfo.conflicts: return True - return not pkg in map(lambda x:x.package, self.pkginfo.conflicts) + return not pkg in [x.package for x in self.pkginfo.conflicts] # check file conflicts file_conflicts = [] @@ -450,8 +450,8 @@ class Install(AtomicOperation): if self.reinstall(): # get 'config' typed file objects - new = filter(lambda x: x.type == 'config', self.files.list) - old = filter(lambda x: x.type == 'config', self.old_files.list) + new = [x for x in self.files.list if x.type == 'config'] + old = [x for x in self.old_files.list if x.type == 'config'] # get config path lists newconfig = set(str(x.path) for x in new) @@ -459,7 +459,7 @@ class Install(AtomicOperation): config_overlaps = newconfig & oldconfig if config_overlaps: - files = filter(lambda x: x.path in config_overlaps, old) + files = [x for x in old if x.path in config_overlaps] for f in files: check_config_changed(f) else: @@ -562,9 +562,9 @@ class Remove(AtomicOperation): self.package = self.installdb.get_package(self.package_name) try: self.files = self.installdb.get_files(self.package_name) - except pisi.Error, e: + except pisi.Error as e: # for some reason file was deleted, we still allow removes! - ctx.ui.error(unicode(e)) + ctx.ui.error(str(e)) ctx.ui.warning(_('File list could not be read for package %s, continuing removal.') % package_name) self.files = pisi.files.Files() diff --git a/pisi/cli/__init__.py b/pisi/cli/__init__.py index d2b60789..df965ee0 100644 --- a/pisi/cli/__init__.py +++ b/pisi/cli/__init__.py @@ -15,7 +15,7 @@ import locale import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.context as ctx @@ -31,13 +31,12 @@ class Exception(pisi.Exception): def printu(obj, err = False): - if not isinstance(obj, unicode): - obj = unicode(obj) + obj = str(obj) if err: out = sys.stderr else: out = sys.stdout - out.write(obj.encode('utf-8')) + out.write(obj) out.flush() class CLI(pisi.ui.UI): @@ -53,8 +52,7 @@ class CLI(pisi.ui.UI): def output(self, msg, err = False, verbose = False): if (verbose and self.show_verbose) or (not verbose): - if type(msg)==type(unicode()): - msg = msg.encode('utf-8') + msg = str(msg) if err: out = sys.stderr else: @@ -99,17 +97,17 @@ class CLI(pisi.ui.UI): if not noln: new_msg = "%s\n" % new_msg msg = new_msg - self.output(unicode(msg), verbose=verbose) + self.output(str(msg), verbose=verbose) def info(self, msg, verbose = False, noln = False): # TODO: need to look at more kinds of info messages # let's cheat from KDE :) if not noln: msg = '%s\n' % msg - self.output(unicode(msg), verbose=verbose) + self.output(str(msg), verbose=verbose) def warning(self, msg, verbose = False): - msg = unicode(msg) + msg = str(msg) self.warnings += 1 if ctx.log: ctx.log.warning(msg) @@ -119,7 +117,7 @@ class CLI(pisi.ui.UI): self.output(pisi.util.colorize(msg + '\n', 'brightyellow'), err=True, verbose=verbose) def error(self, msg): - msg = unicode(msg) + msg = str(msg) self.errors += 1 if ctx.log: ctx.log.error(msg) @@ -130,22 +128,22 @@ class CLI(pisi.ui.UI): def action(self, msg, verbose = False): #TODO: this seems quite redundant? - msg = unicode(msg) + msg = str(msg) if ctx.log: ctx.log.info(msg) self.output(pisi.util.colorize(msg + '\n', 'green')) def choose(self, msg, opts): - msg = unicode(msg) + msg = str(msg) prompt = msg + pisi.util.colorize(' (%s)' % "/".join(opts), 'red') while True: - s = raw_input(prompt.encode('utf-8')) + s = input(prompt.encode('utf-8')) for opt in opts: if opt.startswith(s): return opt def confirm(self, msg): - msg = unicode(msg) + msg = str(msg) if ctx.config.options and ctx.config.options.yes_all: return True @@ -164,7 +162,7 @@ class CLI(pisi.ui.UI): while True: tty.tcflush(sys.stdin.fileno(), 0) prompt = msg + pisi.util.colorize(_(' (yes/no)'), 'red') - s = raw_input(prompt.encode('utf-8')) + s = input(prompt) if yes_expr.search(s): return True @@ -191,7 +189,7 @@ class CLI(pisi.ui.UI): def status(self, msg = None): if msg: - msg = unicode(msg) + msg = str(msg) self.output(pisi.util.colorize(msg + '\n', 'brightgreen')) pisi.util.xterm_title(msg) diff --git a/pisi/cli/addrepo.py b/pisi/cli/addrepo.py index d88bd8c0..c29030d6 100644 --- a/pisi/cli/addrepo.py +++ b/pisi/cli/addrepo.py @@ -14,13 +14,13 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.api import pisi.cli.command as command import pisi.context as ctx -class AddRepo(command.Command): +class AddRepo(command.Command, metaclass=command.autocommand): __doc__ = _("""Add a repository Usage: add-repo @@ -30,7 +30,6 @@ Usage: add-repo NB: We support only local files (e.g., /a/b/c) and http:// URIs at the moment """) - __metaclass__ = command.autocommand def __init__(self, args): super(AddRepo, self).__init__(args) diff --git a/pisi/cli/blame.py b/pisi/cli/blame.py index 6572b350..f4774159 100644 --- a/pisi/cli/blame.py +++ b/pisi/cli/blame.py @@ -14,21 +14,19 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx import pisi.db -class Blame(command.Command): +class Blame(command.Command, metaclass=command.autocommand): __doc__ = _("""Information about the package owner and release Usage: blame ... """) - __metaclass__ = command.autocommand - def __init__(self, args=None): super(Blame, self).__init__(args) self.installdb = pisi.db.installdb.InstallDB() @@ -67,7 +65,7 @@ Usage: blame ... def print_package_info(self, package, hno=0): s = _('Name: %s, version: %s, release: %s\n') % ( package.name, package.history[hno].version, package.history[hno].release) - s += _('Package Maintainer: %s <%s>\n') % (unicode(package.source.packager.name), package.source.packager.email) + s += _('Package Maintainer: %s <%s>\n') % (str(package.source.packager.name), package.source.packager.email) s += _('Release Updater: %s <%s>\n') % (package.history[hno].name, package.history[hno].email) s += _('Update Date: %s\n') % package.history[hno].date s += '\n%s\n' % package.history[hno].comment diff --git a/pisi/cli/build.py b/pisi/cli/build.py index 2484becc..793ca87b 100644 --- a/pisi/cli/build.py +++ b/pisi/cli/build.py @@ -14,7 +14,7 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.api @@ -34,10 +34,9 @@ to be downloaded from a repository containing sources. """) -class Build(command.Command): +class Build(command.Command, metaclass=command.autocommand): __doc__ = usage - __metaclass__ = command.autocommand def __init__(self, args): super(Build, self).__init__(args) diff --git a/pisi/cli/check.py b/pisi/cli/check.py index 48d3bcff..87bc4829 100644 --- a/pisi/cli/check.py +++ b/pisi/cli/check.py @@ -14,7 +14,7 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.api import pisi.cli.command as command @@ -38,10 +38,9 @@ If no packages are given, checks all installed packages. """) -class Check(command.Command): +class Check(command.Command, metaclass=command.autocommand): __doc__ = usage - __metaclass__ = command.autocommand def __init__(self, args): super(Check, self).__init__(args) diff --git a/pisi/cli/clean.py b/pisi/cli/clean.py index af75f86b..8cba9e59 100644 --- a/pisi/cli/clean.py +++ b/pisi/cli/clean.py @@ -12,11 +12,11 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command -class Clean(command.Command): +class Clean(command.Command, metaclass=command.autocommand): __doc__ = _("""Clean stale locks Usage: clean @@ -24,8 +24,6 @@ Usage: clean PiSi uses filesystem locks for managing database access. This command deletes unused locks from the database directory.""") - __metaclass__ = command.autocommand - def __init__(self, args=None): super(Clean, self).__init__(args) diff --git a/pisi/cli/command.py b/pisi/cli/command.py index 5065ee16..8878a56d 100644 --- a/pisi/cli/command.py +++ b/pisi/cli/command.py @@ -16,7 +16,7 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.api import pisi.context as ctx @@ -30,7 +30,7 @@ class autocommand(type): raise pisi.cli.Error(_('Command lacks name')) longname, shortname = name def add_cmd(cmd): - if Command.cmd_dict.has_key(cmd): + if cmd in Command.cmd_dict: raise pisi.cli.Error(_('Duplicate command %s') % cmd) else: Command.cmd_dict[cmd] = cls @@ -54,7 +54,7 @@ class Command(object): for name in l: commandcls = Command.cmd_dict[name] trans = gettext.translation('pisi', fallback=True) - summary = trans.ugettext(commandcls.__doc__).split('\n')[0] + summary = trans.gettext(commandcls.__doc__).split('\n')[0] name = commandcls.name[0] if commandcls.name[1]: name += ' (%s)' % commandcls.name[1] @@ -64,7 +64,7 @@ class Command(object): @staticmethod def get_command(cmd, fail=False, args=None): - if Command.cmd_dict.has_key(cmd): + if cmd in Command.cmd_dict: return Command.cmd_dict[cmd](args) if fail: @@ -182,8 +182,8 @@ class Command(object): def help(self): """print help for the command""" trans = gettext.translation('pisi', fallback=True) - print "%s: %s\n" % (self.format_name(), trans.ugettext(self.__doc__)) - print self.parser.format_option_help() + print("%s: %s\n" % (self.format_name(), trans.gettext(self.__doc__))) + print(self.parser.format_option_help()) def die(self): """exit program""" diff --git a/pisi/cli/configurepending.py b/pisi/cli/configurepending.py index abfd2270..f9621143 100644 --- a/pisi/cli/configurepending.py +++ b/pisi/cli/configurepending.py @@ -14,12 +14,12 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.api import pisi.cli.command as command -class ConfigurePending(command.PackageOp): +class ConfigurePending(command.PackageOp, metaclass=command.autocommand): __doc__ = _("""Configure pending packages If COMAR configuration of some packages were not @@ -28,8 +28,6 @@ of packages waiting to be configured. This command configures those packages. """) - __metaclass__ = command.autocommand - def __init__(self, args): super(ConfigurePending, self).__init__(args) diff --git a/pisi/cli/deletecache.py b/pisi/cli/deletecache.py index 2d3edfa3..7a5c9cfc 100644 --- a/pisi/cli/deletecache.py +++ b/pisi/cli/deletecache.py @@ -12,13 +12,13 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.api import pisi.cli.command as command -class DeleteCache(command.Command): +class DeleteCache(command.Command, metaclass=command.autocommand): __doc__ = _("""Delete cache files Usage: delete-cache @@ -27,8 +27,6 @@ Sources, packages and temporary files are stored under /var directory. Since these accumulate they can consume a lot of disk space.""") - __metaclass__ = command.autocommand - def __init__(self, args=None): super(DeleteCache, self).__init__(args) diff --git a/pisi/cli/delta.py b/pisi/cli/delta.py index 5c7ae5d5..60c8d2e4 100644 --- a/pisi/cli/delta.py +++ b/pisi/cli/delta.py @@ -14,7 +14,7 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.cli.command as command @@ -32,10 +32,9 @@ a delta package with the changed files. """) -class Delta(command.Command): +class Delta(command.Command, metaclass=command.autocommand): __doc__ = usage - __metaclass__ = command.autocommand def __init__(self, args): super(Delta, self).__init__(args) diff --git a/pisi/cli/disablerepo.py b/pisi/cli/disablerepo.py index 6460597d..4e2071b7 100644 --- a/pisi/cli/disablerepo.py +++ b/pisi/cli/disablerepo.py @@ -12,12 +12,12 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.api -class DisableRepo(command.Command): +class DisableRepo(command.Command, metaclass=command.autocommand): __doc__ = _("""Disable repository Usage: disable-repo [ ... ] @@ -26,7 +26,6 @@ Usage: disable-repo [ ... ] Disabled repositories are not taken into account in operations """) - __metaclass__ = command.autocommand def __init__(self,args): super(DisableRepo, self).__init__(args) diff --git a/pisi/cli/emerge.py b/pisi/cli/emerge.py index 0a7b7145..9fe583cb 100644 --- a/pisi/cli/emerge.py +++ b/pisi/cli/emerge.py @@ -14,14 +14,14 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.cli.build as build import pisi.context as ctx import pisi.api -class Emerge(build.Build): +class Emerge(build.Build, metaclass=command.autocommand): __doc__ = _("""Build and install PiSi source packages from repository Usage: emerge ... @@ -31,7 +31,6 @@ downloaded from a repository containing sources. You can also give the name of a component. """) - __metaclass__ = command.autocommand def __init__(self, args): super(Emerge, self).__init__(args) diff --git a/pisi/cli/enablerepo.py b/pisi/cli/enablerepo.py index 191ef74a..39f4b398 100644 --- a/pisi/cli/enablerepo.py +++ b/pisi/cli/enablerepo.py @@ -12,12 +12,12 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.api -class EnableRepo(command.Command): +class EnableRepo(command.Command, metaclass=command.autocommand): __doc__ = _("""Enable repository Usage: enable-repo [ ... ] @@ -26,7 +26,6 @@ Usage: enable-repo [ ... ] Disabled repositories are not taken into account in operations """) - __metaclass__ = command.autocommand def __init__(self,args): super(EnableRepo, self).__init__(args) diff --git a/pisi/cli/fetch.py b/pisi/cli/fetch.py index 571085c1..f140af03 100644 --- a/pisi/cli/fetch.py +++ b/pisi/cli/fetch.py @@ -15,13 +15,13 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx import pisi.api -class Fetch(command.Command): +class Fetch(command.Command, metaclass=command.autocommand): __doc__ = _("""Fetch a package Usage: fetch [ ... ] @@ -30,7 +30,6 @@ Usage: fetch [ ... ] Downloads the given pisi packages to working directory """) - __metaclass__ = command.autocommand def __init__(self,args): super(Fetch, self).__init__(args) diff --git a/pisi/cli/graph.py b/pisi/cli/graph.py index 64557f1c..0815643e 100644 --- a/pisi/cli/graph.py +++ b/pisi/cli/graph.py @@ -14,7 +14,7 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.api @@ -22,7 +22,7 @@ import pisi.cli.command as command import pisi.context as ctx import pisi.db -class Graph(command.Command): +class Graph(command.Command, metaclass=command.autocommand): __doc__ = _("""Graph package relations Usage: graph [ ...] @@ -33,8 +33,6 @@ shows the package relations among repository packages, and writes the package in graphviz format to 'pgraph.dot'. """) - __metaclass__ = command.autocommand - def __init__(self, args=None): super(Graph, self).__init__(args) diff --git a/pisi/cli/help.py b/pisi/cli/help.py index 41ce912d..9c074d9a 100644 --- a/pisi/cli/help.py +++ b/pisi/cli/help.py @@ -12,21 +12,19 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli import pisi.cli.command as command import pisi.context as ctx -class Help(command.Command): +class Help(command.Command, metaclass=command.autocommand): __doc__ = _("""Prints help for given commands Usage: help [ ... ] If run without parameters, it prints the general help.""") - __metaclass__ = command.autocommand - def __init__(self, args = None): super(Help, self).__init__(args) diff --git a/pisi/cli/history.py b/pisi/cli/history.py index f0ad1c25..bb92cd39 100644 --- a/pisi/cli/history.py +++ b/pisi/cli/history.py @@ -16,7 +16,7 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.api @@ -27,15 +27,13 @@ import pisi.cli.command as command # Operation names for translation opttrans = {"upgrade":_("upgrade"),"remove":_("remove"),"emerge":_("emerge"), "install":_("install"), "snapshot":_("snapshot"), "takeback":_("takeback"), "repoupdate":_("repository update")} -class History(command.PackageOp): +class History(command.PackageOp, metaclass=command.autocommand): __doc__ = _("""History of pisi operations Usage: history Lists previous operations.""") - __metaclass__ = command.autocommand - def __init__(self, args=None): super(History, self).__init__(args) self.historydb = pisi.db.historydb.HistoryDB() @@ -64,19 +62,19 @@ Lists previous operations.""") def print_history(self): for operation in self.historydb.get_last(ctx.get_option('last')): - print _("Operation #%d: %s") % (operation.no, opttrans[operation.type]) - print _("Date: %s %s") % (operation.date, operation.time) - print + print(_("Operation #%d: %s") % (operation.no, opttrans[operation.type])) + print(_("Date: %s %s") % (operation.date, operation.time)) + print() if operation.type == "snapshot": - print _(" * There are %d packages in this snapshot.") % len(operation.packages) + print(_(" * There are %d packages in this snapshot.") % len(operation.packages)) elif operation.type == "repoupdate": for repo in operation.repos: - print " *", repo + print(" *", repo) else: for pkg in operation.packages: - print " *", pkg - print + print(" *", pkg) + print() def redirect_output(self, func): if os.isatty(sys.stdout.fileno()): @@ -98,7 +96,7 @@ Lists previous operations.""") def write(self, s): try: - self.less.stdin.write(s) + self.less.stdin.write(s.encode()) except IOError: raise LessException diff --git a/pisi/cli/index.py b/pisi/cli/index.py index 6c73d874..90e7d826 100644 --- a/pisi/cli/index.py +++ b/pisi/cli/index.py @@ -14,7 +14,7 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx @@ -34,10 +34,9 @@ everything in a single index file. """) -class Index(command.Command): +class Index(command.Command, metaclass=command.autocommand): __doc__ = usage - __metaclass__ = command.autocommand def __init__(self, args): super(Index, self).__init__(args) diff --git a/pisi/cli/info.py b/pisi/cli/info.py index f0f8b306..4044d619 100644 --- a/pisi/cli/info.py +++ b/pisi/cli/info.py @@ -14,7 +14,7 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx @@ -22,14 +22,13 @@ import pisi.util as util import pisi.api import pisi.db -class Info(command.Command): +class Info(command.Command, metaclass=command.autocommand): __doc__ = _("""Display package information Usage: info ... is either a package name or a .pisi file, """) - __metaclass__ = command.autocommand def __init__(self, args): super(Info, self).__init__(args) @@ -81,7 +80,7 @@ Usage: info ... index.add_component(component) else: if not self.options.short: - ctx.ui.info(unicode(component)) + ctx.ui.info(str(component)) else: ctx.ui.info("%s - %s" % (component.name, component.summary)) @@ -114,31 +113,31 @@ Usage: info ... files.list.sort(key = lambda x:x.path) for fileinfo in files.list: if self.options.files: - print fileinfo + print(fileinfo) else: - print "/" + fileinfo.path + print("/" + fileinfo.path) def print_metadata(self, metadata, packagedb=None): if ctx.get_option('short'): pkg = metadata.package - ctx.ui.formatted_output(" - ".join((pkg.name, unicode(pkg.summary)))) + ctx.ui.formatted_output(" - ".join((pkg.name, str(pkg.summary)))) else: - ctx.ui.formatted_output(unicode(metadata.package)) + ctx.ui.formatted_output(str(metadata.package)) if packagedb: revdeps = [name for name, dep in packagedb.get_rev_deps(metadata.package.name)] ctx.ui.formatted_output(" ".join((_("Reverse Dependencies:"), util.strlist(revdeps)))) - print + print() def print_specdata(self, spec, sourcedb=None): src = spec.source if ctx.get_option('short'): - ctx.ui.formatted_output(" - ".join((src.name, unicode(src.summary)))) + ctx.ui.formatted_output(" - ".join((src.name, str(src.summary)))) else: - ctx.ui.formatted_output(unicode(spec)) + ctx.ui.formatted_output(str(spec)) if sourcedb: revdeps = [name for name, dep in sourcedb.get_rev_deps(spec.source.name)] - print _('Reverse Build Dependencies:'), util.strlist(revdeps) - print + print(_('Reverse Build Dependencies:'), util.strlist(revdeps)) + print() def pisifile_info(self, package): metadata, files = pisi.api.info_file(package) diff --git a/pisi/cli/install.py b/pisi/cli/install.py index 7b755ec2..d92751b5 100644 --- a/pisi/cli/install.py +++ b/pisi/cli/install.py @@ -14,14 +14,14 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx import pisi.api import pisi.db -class Install(command.PackageOp): +class Install(command.PackageOp, metaclass=command.autocommand): __doc__ = _("""Install PiSi packages Usage: install ... @@ -32,7 +32,6 @@ specified a package name, it should exist in a specified repository. You can also specify components instead of package names, which will be expanded to package names. """) - __metaclass__ = command.autocommand def __init__(self, args): super(Install, self).__init__(args) diff --git a/pisi/cli/listavailable.py b/pisi/cli/listavailable.py index 9da50e21..a793aa07 100644 --- a/pisi/cli/listavailable.py +++ b/pisi/cli/listavailable.py @@ -14,7 +14,7 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx @@ -22,7 +22,7 @@ import pisi.util as util import pisi.api import pisi.db -class ListAvailable(command.Command): +class ListAvailable(command.Command, metaclass=command.autocommand): __doc__ = _("""List available packages in the repositories Usage: list-available [ ... repon ] @@ -31,7 +31,6 @@ Gives a brief list of PiSi packages published in the specified repositories. If no repository is specified, we list packages in all repositories. """) - __metaclass__ = command.autocommand def __init__(self, args): super(ListAvailable, self).__init__(args) @@ -73,7 +72,7 @@ all repositories. if component: try: l = self.componentdb.get_packages(component, repo=repo, walk=True) - except Exception, e: + except Exception as e: return else: l = pisi.api.list_available(repo) @@ -97,7 +96,7 @@ all repositories. package.name = util.colorize(package.name, 'brightwhite') if self.options.long: - ctx.ui.info(unicode(package)+'\n') + ctx.ui.info(str(package)+'\n') else: package.name += ' ' * max(0, maxlen - len(p)) - ctx.ui.info('%s - %s ' % (package.name, unicode(package.summary))) + ctx.ui.info('%s - %s ' % (package.name, str(package.summary))) diff --git a/pisi/cli/listcomponents.py b/pisi/cli/listcomponents.py index c1811de3..22824e41 100644 --- a/pisi/cli/listcomponents.py +++ b/pisi/cli/listcomponents.py @@ -14,13 +14,13 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx import pisi.db -class ListComponents(command.Command): +class ListComponents(command.Command, metaclass=command.autocommand): __doc__ = _("""List available components Usage: list-components @@ -28,7 +28,6 @@ Usage: list-components Gives a brief list of PiSi components published in the repositories. """) - __metaclass__ = command.autocommand def __init__(self, args): super(ListComponents, self).__init__(args) @@ -53,10 +52,10 @@ repositories. for p in l: component = self.componentdb.get_component(p) if self.options.long: - ctx.ui.info(unicode(component)) + ctx.ui.info(str(component)) else: lenp = len(p) #if p in installed_list: # p = util.colorize(p, 'cyan') p = p + ' ' * max(0, 15 - lenp) - ctx.ui.info('%s - %s ' % (component.name, unicode(component.summary))) + ctx.ui.info('%s - %s ' % (component.name, str(component.summary))) diff --git a/pisi/cli/listinstalled.py b/pisi/cli/listinstalled.py index 05403804..a2139464 100644 --- a/pisi/cli/listinstalled.py +++ b/pisi/cli/listinstalled.py @@ -14,20 +14,18 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx import pisi.db -class ListInstalled(command.Command): +class ListInstalled(command.Command, metaclass=command.autocommand): __doc__ = _("""Print the list of all installed packages Usage: list-installed """) - __metaclass__ = command.autocommand - def __init__(self, args): super(ListInstalled, self).__init__(args) self.installdb = pisi.db.installdb.InstallDB() @@ -76,15 +74,15 @@ Usage: list-installed if self.options.install_info: ctx.ui.info(_('Package Name |St| Version| Rel.| Distro| Date')) - print '===========================================================================' + print('===========================================================================') for pkg in installed: package = self.installdb.get_package(pkg) inst_info = self.installdb.get_info(pkg) if self.options.long: - ctx.ui.info(unicode(package)) - ctx.ui.info(unicode(inst_info)) + ctx.ui.info(str(package)) + ctx.ui.info(str(inst_info)) elif self.options.install_info: ctx.ui.info('%-20s |%s' % (package.name, inst_info.one_liner())) else: package.name = package.name + ' ' * (maxlen - len(package.name)) - ctx.ui.info('%s - %s' % (package.name, unicode(package.summary))) + ctx.ui.info('%s - %s' % (package.name, str(package.summary))) diff --git a/pisi/cli/listnewest.py b/pisi/cli/listnewest.py index 5f4b43e3..dbfa52ee 100644 --- a/pisi/cli/listnewest.py +++ b/pisi/cli/listnewest.py @@ -14,14 +14,14 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx import pisi.api import pisi.db -class ListNewest(command.Command): +class ListNewest(command.Command, metaclass=command.autocommand): __doc__ = _("""List newest packages in the repositories Usage: list-newest [ ... repon ] @@ -30,7 +30,6 @@ Gives a list of PiSi newly published packages in the specified repositories. If no repository is specified, we list the new packages from all repositories. """) - __metaclass__ = command.autocommand def __init__(self, args): super(ListNewest, self).__init__(args) @@ -85,7 +84,7 @@ packages from all repositories. package = self.packagedb.get_package(p, repo) lenp = len(p) p = p + ' ' * max(0, maxlen - lenp) - ctx.ui.info('%s - %s ' % (p, unicode(package.summary))) + ctx.ui.info('%s - %s ' % (p, str(package.summary))) - print + print() diff --git a/pisi/cli/listpending.py b/pisi/cli/listpending.py index 652ca13d..1d66a072 100644 --- a/pisi/cli/listpending.py +++ b/pisi/cli/listpending.py @@ -12,18 +12,17 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx import pisi.api -class ListPending(command.Command): +class ListPending(command.Command, metaclass=command.autocommand): __doc__ = _("""List pending packages Lists packages waiting to be configured. """) - __metaclass__ = command.autocommand def __init__(self, args): super(ListPending, self).__init__(args) @@ -36,6 +35,6 @@ Lists packages waiting to be configured. A = pisi.api.list_pending() if len(A): for p in pisi.api.generate_pending_order(A): - print p + print(p) else: ctx.ui.info(_('There are no packages waiting to be configured')) diff --git a/pisi/cli/listrepo.py b/pisi/cli/listrepo.py index 73b28317..fa60062b 100644 --- a/pisi/cli/listrepo.py +++ b/pisi/cli/listrepo.py @@ -12,21 +12,20 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx import pisi.util as util import pisi.db -class ListRepo(command.Command): +class ListRepo(command.Command, metaclass=command.autocommand): __doc__ = _("""List repositories Usage: list-repo Lists currently tracked repositories. """) - __metaclass__ = command.autocommand def __init__(self, args): super(ListRepo, self).__init__(args) @@ -43,5 +42,5 @@ Lists currently tracked repositories. ctx.ui.info(util.colorize(_("%s [%s]") % (repo, active), 'green')) else: ctx.ui.info(util.colorize(_("%s [%s]") % (repo, active), 'red')) - print ' ', self.repodb.get_repo_url(repo) + print(' ', self.repodb.get_repo_url(repo)) diff --git a/pisi/cli/listsources.py b/pisi/cli/listsources.py index ebbc0fe0..2c830dac 100644 --- a/pisi/cli/listsources.py +++ b/pisi/cli/listsources.py @@ -14,20 +14,19 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx import pisi.db -class ListSources(command.Command): +class ListSources(command.Command, metaclass=command.autocommand): __doc__ = _("""List available sources Usage: list-sources Gives a brief list of sources published in the repositories. """) - __metaclass__ = command.autocommand def __init__(self, args): super(ListSources, self).__init__(args) @@ -51,10 +50,10 @@ Gives a brief list of sources published in the repositories. sf, repo = self.sourcedb.get_spec_repo(p) if self.options.long: ctx.ui.info('[Repository: ' + repo + ']') - ctx.ui.info(unicode(sf.source)) + ctx.ui.info(str(sf.source)) else: lenp = len(p) #if p in installed_list: # p = util.colorize(p, 'cyan') p = p + ' ' * max(0, 15 - lenp) - ctx.ui.info('%s - %s' % (sf.source.name, unicode(sf.source.summary))) + ctx.ui.info('%s - %s' % (sf.source.name, str(sf.source.summary))) diff --git a/pisi/cli/listupgrades.py b/pisi/cli/listupgrades.py index ccb2721c..9cfd9269 100644 --- a/pisi/cli/listupgrades.py +++ b/pisi/cli/listupgrades.py @@ -14,7 +14,7 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.blacklist @@ -22,14 +22,13 @@ import pisi.context as ctx import pisi.api import pisi.db -class ListUpgrades(command.Command): +class ListUpgrades(command.Command, metaclass=command.autocommand): __doc__ = _("""List packages to be upgraded Usage: list-upgrades Lists the packages that will be upgraded. """) - __metaclass__ = command.autocommand def __init__(self, args): super(ListUpgrades, self).__init__(args) @@ -71,15 +70,15 @@ Lists the packages that will be upgraded. if self.options.install_info: ctx.ui.info(_('Package Name |St| Version| Rel.| Distro| Date')) - print '===========================================================================' + print('===========================================================================') for pkg in upgradable_pkgs: package = self.installdb.get_package(pkg) inst_info = self.installdb.get_info(pkg) if self.options.long: ctx.ui.info(package) - print inst_info + print(inst_info) elif self.options.install_info: ctx.ui.info('%-20s |%s ' % (package.name, inst_info.one_liner())) else: package.name = package.name + ' ' * (maxlen - len(package.name)) - ctx.ui.info('%s - %s' % (package.name, unicode(package.summary))) + ctx.ui.info('%s - %s' % (package.name, str(package.summary))) diff --git a/pisi/cli/pisicli.py b/pisi/cli/pisicli.py index 53260169..983e5395 100644 --- a/pisi/cli/pisicli.py +++ b/pisi/cli/pisicli.py @@ -15,7 +15,7 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.cli @@ -66,7 +66,7 @@ class PreParser(optparse.OptionParser): optparse.OptionParser.__init__(self, usage=pisi.cli.help.usage_text, version=version) def error(self, msg): - raise ParserError, msg + raise ParserError(msg) def parse_args(self, args=None): self.opts = [] diff --git a/pisi/cli/rebuilddb.py b/pisi/cli/rebuilddb.py index 13822b68..72fb143e 100644 --- a/pisi/cli/rebuilddb.py +++ b/pisi/cli/rebuilddb.py @@ -14,13 +14,13 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx import pisi.api -class RebuildDb(command.Command): +class RebuildDb(command.Command, metaclass=command.autocommand): __doc__ = _("""Rebuild Databases Usage: rebuilddb [ ... ] @@ -30,7 +30,6 @@ Rebuilds the PiSi databases If package specs are given, they should be the names of package dirs under /var/lib/pisi """) - __metaclass__ = command.autocommand def __init__(self, args): super(RebuildDb, self).__init__(args) diff --git a/pisi/cli/remove.py b/pisi/cli/remove.py index d7a91e08..f19793c5 100644 --- a/pisi/cli/remove.py +++ b/pisi/cli/remove.py @@ -14,14 +14,14 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx import pisi.api import pisi.db -class Remove(command.PackageOp): +class Remove(command.PackageOp, metaclass=command.autocommand): __doc__ = _("""Remove PiSi packages Usage: remove ... @@ -31,7 +31,6 @@ Remove package(s) from your system. Just give the package names to remove. You can also specify components instead of package names, which will be expanded to package names. """) - __metaclass__ = command.autocommand def __init__(self, args): super(Remove, self).__init__(args) diff --git a/pisi/cli/removerepo.py b/pisi/cli/removerepo.py index aedecf5b..61c11ec8 100644 --- a/pisi/cli/removerepo.py +++ b/pisi/cli/removerepo.py @@ -12,19 +12,18 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.api -class RemoveRepo(command.Command): +class RemoveRepo(command.Command, metaclass=command.autocommand): __doc__ = _("""Remove repositories Usage: remove-repo ... Remove all repository information from the system. """) - __metaclass__ = command.autocommand def __init__(self,args): super(RemoveRepo, self).__init__(args) diff --git a/pisi/cli/search.py b/pisi/cli/search.py index 15c4abd0..9d900912 100644 --- a/pisi/cli/search.py +++ b/pisi/cli/search.py @@ -15,13 +15,13 @@ import re import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx import pisi.db -class Search(command.Command): +class Search(command.Command, metaclass=command.autocommand): __doc__ = _("""Search packages Usage: search ... @@ -32,7 +32,6 @@ Default search is done in package database. Use options to search in install database or source database. """) - __metaclass__ = command.autocommand def __init__(self, args): super(Search, self).__init__(args) @@ -101,7 +100,7 @@ database. lenp = len(name) name = replace.sub(pisi.util.colorize(r"\1", "brightred"), name) - if lang and summary.has_key(lang): + if lang and lang in summary: summary = replace.sub(pisi.util.colorize(r"\1", "brightred"), str(summary[lang])) else: summary = replace.sub(pisi.util.colorize(r"\1", "brightred"), str(summary)) diff --git a/pisi/cli/searchfile.py b/pisi/cli/searchfile.py index 1df402a6..2fb9fa27 100644 --- a/pisi/cli/searchfile.py +++ b/pisi/cli/searchfile.py @@ -14,20 +14,19 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.context as ctx import pisi.cli.command as command -class SearchFile(command.Command): +class SearchFile(command.Command, metaclass=command.autocommand): __doc__ = _("""Search for a file Usage: search-file ... Finds the installed package which contains the specified file. """) - __metaclass__ = command.autocommand def __init__(self, args): super(SearchFile, self).__init__(args) diff --git a/pisi/cli/updaterepo.py b/pisi/cli/updaterepo.py index 18071691..32da8f7a 100644 --- a/pisi/cli/updaterepo.py +++ b/pisi/cli/updaterepo.py @@ -14,13 +14,13 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx import pisi.api -class UpdateRepo(command.Command): +class UpdateRepo(command.Command, metaclass=command.autocommand): __doc__ = _("""Update repository databases Usage: update-repo [ ... ] @@ -30,7 +30,6 @@ Usage: update-repo [ ... ] Synchronizes the PiSi databases with the current repository. If no repository is given, all repositories are updated. """) - __metaclass__ = command.autocommand def __init__(self,args): super(UpdateRepo, self).__init__(args) diff --git a/pisi/cli/upgrade.py b/pisi/cli/upgrade.py index e88b0a74..a18611e2 100644 --- a/pisi/cli/upgrade.py +++ b/pisi/cli/upgrade.py @@ -14,14 +14,14 @@ import optparse import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.cli.command as command import pisi.context as ctx import pisi.api import pisi.db -class Upgrade(command.PackageOp): +class Upgrade(command.PackageOp, metaclass=command.autocommand): __doc__ = _("""Upgrade PiSi packages Usage: Upgrade [ ... ] @@ -39,7 +39,6 @@ reinstall a package from a PiSi file, use the install command. You can also specify components instead of package names, which will be expanded to package names. """) - __metaclass__ = command.autocommand def __init__(self, args): super(Upgrade, self).__init__(args) diff --git a/pisi/comariface.py b/pisi/comariface.py index fe1c5236..66615b49 100644 --- a/pisi/comariface.py +++ b/pisi/comariface.py @@ -16,7 +16,7 @@ import string import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.context as ctx @@ -79,9 +79,9 @@ def get_link(): link = comar.Link(socket=sockname, alternate=alternate) link.setLocale() return link - except dbus.DBusException, e: + except dbus.DBusException as e: exceptions.append(str(e)) - except Exception, e: + except Exception as e: exceptions.append(str(e)) time.sleep(0.2) timeout -= 0.2 @@ -115,12 +115,12 @@ def post_install(package_name, provided_scripts, try: link.register(script_name, script.om, os.path.join(scriptpath, script.script)) - except dbus.DBusException, exception: + except dbus.DBusException as exception: raise Error(_("Script error: %s") % exception) if script.om == "System.Service": try: link.System.Service[script_name].registerState() - except dbus.DBusException, exception: + except dbus.DBusException as exception: raise Error(_("Script error: %s") % exception) ctx.ui.debug(_("Calling post install handlers")) @@ -130,7 +130,7 @@ def post_install(package_name, provided_scripts, metapath, filepath, timeout=ctx.dbus_timeout) - except dbus.DBusException, exception: + except dbus.DBusException as exception: # Do nothing if setupPackage method is not defined # in package script if not is_method_missing(exception): @@ -147,7 +147,7 @@ def post_install(package_name, provided_scripts, link.System.Package[package_name].postInstall( fromVersion, fromRelease, toVersion, toRelease, timeout=ctx.dbus_timeout) - except dbus.DBusException, exception: + except dbus.DBusException as exception: # Do nothing if postInstall method is not defined in package script if not is_method_missing(exception): raise Error(_("Script error: %s") % exception) @@ -166,7 +166,7 @@ def pre_remove(package_name, metapath, filepath): try: link.System.Package[package_name].preRemove( timeout=ctx.dbus_timeout) - except dbus.DBusException, exception: + except dbus.DBusException as exception: # Do nothing if preRemove method is not defined in package script if not is_method_missing(exception): raise Error(_("Script error: %s") % exception) @@ -176,7 +176,7 @@ def pre_remove(package_name, metapath, filepath): try: link.System.PackageHandler[handler].cleanupPackage( metapath, filepath, timeout=ctx.dbus_timeout) - except dbus.DBusException, exception: + except dbus.DBusException as exception: # Do nothing if cleanupPackage method is not defined # in package script if not is_method_missing(exception): @@ -199,7 +199,7 @@ def post_remove(package_name, metapath, filepath, provided_scripts=[]): try: link.System.Package[package_name].postRemove( timeout=ctx.dbus_timeout) - except dbus.DBusException, exception: + except dbus.DBusException as exception: # Do nothing if postRemove method is not defined in package script if not is_method_missing(exception): raise Error(_("Script error: %s") % exception) @@ -209,7 +209,7 @@ def post_remove(package_name, metapath, filepath, provided_scripts=[]): try: link.System.PackageHandler[handler].postCleanupPackage( metapath, filepath, timeout=ctx.dbus_timeout) - except dbus.DBusException, exception: + except dbus.DBusException as exception: # Do nothing if postCleanupPackage method is not defined # in package script if not is_method_missing(exception): @@ -219,5 +219,5 @@ def post_remove(package_name, metapath, filepath, provided_scripts=[]): for scr in scripts: try: link.remove(scr, timeout=ctx.dbus_timeout) - except dbus.DBusException, exception: + except dbus.DBusException as exception: raise Error(_("Script error: %s") % exception) diff --git a/pisi/component.py b/pisi/component.py index fe1227ef..7e540169 100644 --- a/pisi/component.py +++ b/pisi/component.py @@ -13,22 +13,18 @@ import pisi.pxml.xmlfile as xmlfile import pisi.pxml.autoxml as autoxml -class Error(object): +class Error(object, metaclass=autoxml.autoxml): - __metaclass__ = autoxml.autoxml + pass -class Obsolete: - - __metaclass__ = autoxml.autoxml +class Obsolete(metaclass=autoxml.autoxml): s_Package = [autoxml.String, autoxml.mandatory] def __str__(self): return self.package -class Distribution(xmlfile.XmlFile): - - __metaclass__ = autoxml.autoxml +class Distribution(xmlfile.XmlFile, metaclass=autoxml.autoxml): tag = "PISI" @@ -43,11 +39,9 @@ class Distribution(xmlfile.XmlFile): t_Obsoletes = [ [Obsolete], autoxml.optional, "Obsoletes/Package"] -class Maintainer(xmlfile.XmlFile): +class Maintainer(xmlfile.XmlFile, metaclass=autoxml.autoxml): "representation for component responsibles" - __metaclass__ = autoxml.autoxml - t_Name = [autoxml.Text, autoxml.mandatory] t_Email = [autoxml.String, autoxml.mandatory] @@ -55,11 +49,9 @@ class Maintainer(xmlfile.XmlFile): s = "%s <%s>" % (self.name, self.email) return s -class Component(xmlfile.XmlFile): +class Component(xmlfile.XmlFile, metaclass=autoxml.autoxml): "representation for component declarations" - __metaclass__ = autoxml.autoxml - t_Name = [autoxml.String, autoxml.mandatory] # fully qualified name # component name in other languages, for instance in Turkish @@ -82,11 +74,9 @@ class Component(xmlfile.XmlFile): t_Sources = [ [autoxml.String], autoxml.optional, "Parts/Source"] -class Components(xmlfile.XmlFile): +class Components(xmlfile.XmlFile, metaclass=autoxml.autoxml): "representation for component declarations" - __metaclass__ = autoxml.autoxml - tag = "PISI" t_Components = [ [Component], autoxml.optional, "Components/Component" ] diff --git a/pisi/config.py b/pisi/config.py index 97502fc2..0c36b851 100644 --- a/pisi/config.py +++ b/pisi/config.py @@ -20,7 +20,7 @@ import copy import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.context as ctx @@ -32,7 +32,7 @@ class Error(pisi.Error): class Options(object): def __getattr__(self, name): - if not self.__dict__.has_key(name): + if name not in self.__dict__: return None else: return self.__dict__[name] @@ -40,11 +40,9 @@ class Options(object): def __setattr__(self, name, value): self.__dict__[name] = value -class Config(object): +class Config(object, metaclass=pisi.util.Singleton): """Config Singleton""" - __metaclass__ = pisi.util.Singleton - def __init__(self, options = Options()): self.set_options(options) self.values = pisi.configfile.ConfigurationFile("/etc/pisi/pisi.conf") @@ -137,7 +135,7 @@ class Config(object): def tmp_dir(self): sysdir = self.subdir(self.values.dirs.tmp_dir) - if os.environ.has_key('USER'): + if 'USER' in os.environ: userdir = self.subdir('/tmp/pisi-' + os.environ['USER']) else: userdir = self.subdir('/tmp/pisi-root') diff --git a/pisi/configfile.py b/pisi/configfile.py index 37ea46c1..be9bd894 100644 --- a/pisi/configfile.py +++ b/pisi/configfile.py @@ -60,12 +60,12 @@ import os import re -import StringIO -import ConfigParser +import io +import configparser import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi @@ -150,7 +150,7 @@ class ConfigurationSection(object): self.defaults = DirectoriesDefaults else: e = _("No section by name '%s'") % section - raise Error, e + raise Error(e) self.section = section @@ -182,26 +182,26 @@ class ConfigurationSection(object): class ConfigurationFile(object): """Parse and get configuration values from the configuration file""" def __init__(self, filePath): - self.parser = ConfigParser.ConfigParser() + self.parser = configparser.ConfigParser() self.filePath = filePath self.parser.read(self.filePath) try: generalitems = self.parser.items("general") - except ConfigParser.NoSectionError: + except configparser.NoSectionError: generalitems = [] self.general = ConfigurationSection("general", generalitems) try: builditems = self.parser.items("build") - except ConfigParser.NoSectionError: + except configparser.NoSectionError: builditems = [] self.build = ConfigurationSection("build", builditems) try: dirsitems = self.parser.items("directories") - except ConfigParser.NoSectionError: + except configparser.NoSectionError: dirsitems = [] self.dirs = ConfigurationSection("directories", dirsitems) @@ -213,7 +213,7 @@ class ConfigurationFile(object): def get(self, section, option): try: return self.parser.get(section, option) - except ConfigParser.NoOptionError: + except configparser.NoOptionError: return None def set(self, section, option, value): @@ -221,7 +221,7 @@ class ConfigurationFile(object): def write_config(self, add_missing=True): sections = {} - current = StringIO.StringIO() + current = io.StringIO() replacement = [current] sect = None opt = None @@ -269,10 +269,10 @@ class ConfigurationFile(object): if sect: sections[sect] = current sect = mo.group('header') - current = StringIO.StringIO() + current = io.StringIO() replacement.append(current) sects = self.parser.sections() - sects.append(ConfigParser.DEFAULTSECT) + sects.append(configparser.DEFAULTSECT) if sect in sects: current.write(line) # So sections can't start with a continuation line: @@ -307,14 +307,14 @@ class ConfigurationFile(object): # Add any new sections. sects = self.parser.sections() if len(self.parser._defaults) > 0: - sects.append(ConfigParser.DEFAULTSECT) + sects.append(configparser.DEFAULTSECT) sects.sort() for sect in sects: - if sect == ConfigParser.DEFAULTSECT: - opts = self.parser._defaults.keys() + if sect == configparser.DEFAULTSECT: + opts = list(self.parser._defaults.keys()) else: # Must use _section here to avoid defaults. - opts = self.parser._sections[sect].keys() + opts = list(self.parser._sections[sect].keys()) opts.sort() if sect in sections: output = sections[sect] or current diff --git a/pisi/conflict.py b/pisi/conflict.py index 08884885..b1c6b918 100644 --- a/pisi/conflict.py +++ b/pisi/conflict.py @@ -14,7 +14,7 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.relation @@ -70,13 +70,13 @@ def calculate_conflicts(order, packagedb): # check if any package has conflicts with the installed packages conflicts = check_installed(pkg, order) if conflicts: - conflicting_pairs[x] = map(lambda c:str(c), conflicts) - conflicting_pkgs = conflicting_pkgs.union(map(lambda c:c.package, conflicts)) + conflicting_pairs[x] = [str(c) for c in conflicts] + conflicting_pkgs = conflicting_pkgs.union([c.package for c in conflicts]) # now check if any package has conflicts with each other - B_i = B_0.intersection(set(map(lambda c:c.package, pkg.conflicts))) + B_i = B_0.intersection(set([c.package for c in pkg.conflicts])) conflicts_inorder_i = set() - for p in map(lambda x:packagedb.get_package(x), B_i): + for p in [packagedb.get_package(x) for x in B_i]: conflicted = package_conflicts(p, pkg.conflicts) if conflicted: conflicts_inorder_i.add(str(conflicted)) diff --git a/pisi/constants.py b/pisi/constants.py index 6a0aded4..eacc325a 100644 --- a/pisi/constants.py +++ b/pisi/constants.py @@ -16,7 +16,7 @@ defined.""" import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext from pisi.util import Singleton @@ -26,22 +26,20 @@ class _constant: pass def __setattr__(self, name, value): - if self.__dict__.has_key(name): - raise self.ConstError, _("Can't rebind constant: %s") % name + if name in self.__dict__: + raise self.ConstError(_("Can't rebind constant: %s") % name) # Binding an attribute once to a const is available self.__dict__[name] = value def __delattr__(self, name): - if self.__dict__.has_key(name): - raise self.ConstError, _("Can't unbind constant: %s") % name + if name in self.__dict__: + raise self.ConstError(_("Can't unbind constant: %s") % name) # we don't have an attribute by this name - raise NameError, name + raise NameError(name) -class Constants: +class Constants(metaclass=Singleton): "Pisi Constants Singleton" - __metaclass__ = Singleton - __c = _constant() def __init__(self): @@ -99,7 +97,7 @@ class Constants: self.__c.repos = "repos" #file/directory permissions - self.__c.umask = 0022 + self.__c.umask = 0o022 # functions in actions_file self.__c.setup_func = "setup" diff --git a/pisi/db/componentdb.py b/pisi/db/componentdb.py index 581892bb..df2c966f 100644 --- a/pisi/db/componentdb.py +++ b/pisi/db/componentdb.py @@ -13,7 +13,7 @@ import re import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.db.repodb @@ -57,7 +57,7 @@ class ComponentDB(lazydb.LazyDB): return components def __generate_components(self, doc): - return dict(map(lambda x: (x.getTagData("Name"), x.toString()), doc.tags("Component"))) + return dict([(x.getTagData("Name"), x.toString()) for x in doc.tags("Component")]) def has_component(self, name, repo = None): return self.cdb.has_item(name, repo) @@ -74,9 +74,9 @@ class ComponentDB(lazydb.LazyDB): lang = pisi.pxml.autoxml.LocalText.get_lang() found = [] for name, xml in self.cdb.get_items_iter(repo): - if name not in found and terms == filter(lambda term: re.compile(rename % (lang, term), re.I).search(xml) or \ + if name not in found and terms == [term for term in terms if re.compile(rename % (lang, term), re.I).search(xml) or \ re.compile(resum % (lang, term), re.I).search(xml) or \ - re.compile(redesc % (lang, term), re.I).search(xml), terms): + re.compile(redesc % (lang, term), re.I).search(xml)]: found.append(name) return found @@ -132,7 +132,7 @@ class ComponentDB(lazydb.LazyDB): packages = [] packages.extend(component.packages) - sub_components = filter(lambda x:x.startswith(component_name+"."), self.list_components(repo)) + sub_components = [x for x in self.list_components(repo) if x.startswith(component_name+".")] for sub in sub_components: try: packages.extend(self.get_component(sub, repo).packages) @@ -152,7 +152,7 @@ class ComponentDB(lazydb.LazyDB): packages = [] packages.extend(component.packages) - sub_components = filter(lambda x:x.startswith(component_name+"."), self.list_components()) + sub_components = [x for x in self.list_components() if x.startswith(component_name+".")] for sub in sub_components: try: packages.extend(self.get_union_component(sub).packages) @@ -173,7 +173,7 @@ class ComponentDB(lazydb.LazyDB): sources = [] sources.extend(component.sources) - sub_components = filter(lambda x:x.startswith(component_name+"."), self.list_components(repo)) + sub_components = [x for x in self.list_components(repo) if x.startswith(component_name+".")] for sub in sub_components: try: sources.extend(self.get_component(sub, repo).sources) @@ -193,7 +193,7 @@ class ComponentDB(lazydb.LazyDB): sources = [] sources.extend(component.sources) - sub_components = filter(lambda x:x.startswith(component_name+"."), self.list_components()) + sub_components = [x for x in self.list_components() if x.startswith(component_name+".")] for sub in sub_components: try: sources.extend(self.get_union_component(sub).sources) diff --git a/pisi/db/filesdb.py b/pisi/db/filesdb.py index b48f7cc2..9048651b 100644 --- a/pisi/db/filesdb.py +++ b/pisi/db/filesdb.py @@ -32,10 +32,10 @@ class FilesDB(lazydb.LazyDB): self.__check_filesdb() def has_file(self, path): - return self.filesdb.has_key(hashlib.md5(path).digest()) + return hashlib.md5(path.encode()).hexdigest() in self.filesdb def get_file(self, path): - return self.filesdb[hashlib.md5(path).digest()], path + return self.filesdb[hashlib.md5(path.encode()).hexdigest()], path def search_file(self, term): if self.has_file(term): @@ -56,12 +56,12 @@ class FilesDB(lazydb.LazyDB): self.__check_filesdb() for f in files.list: - self.filesdb[hashlib.md5(f.path).digest()] = pkg + self.filesdb[hashlib.md5(f.path.encode()).hexdigest()] = pkg def remove_files(self, files): for f in files: - if self.filesdb.has_key(hashlib.md5(f.path).digest()): - del self.filesdb[hashlib.md5(f.path).digest()] + if hashlib.md5(f.path.encode()).hexdigest() in self.filesdb: + del self.filesdb[hashlib.md5(f.path.encode()).hexdigest()] def destroy(self): files_db = os.path.join(ctx.config.info_dir(), ctx.const.files_db) diff --git a/pisi/db/groupdb.py b/pisi/db/groupdb.py index 503c51c4..dce47c5c 100644 --- a/pisi/db/groupdb.py +++ b/pisi/db/groupdb.py @@ -12,7 +12,7 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.db.repodb @@ -52,7 +52,7 @@ class GroupDB(lazydb.LazyDB): return groups def __generate_groups(self, doc): - return dict(map(lambda x: (x.getTagData("Name"), x.toString()), doc.tags("Group"))) + return dict([(x.getTagData("Name"), x.toString()) for x in doc.tags("Group")]) def has_group(self, name, repo = None): return self.gdb.has_item(name, repo) diff --git a/pisi/db/historydb.py b/pisi/db/historydb.py index 1bf7e6a7..18f4e5e6 100644 --- a/pisi/db/historydb.py +++ b/pisi/db/historydb.py @@ -23,9 +23,8 @@ class HistoryDB(lazydb.LazyDB): self.history = pisi.history.History() def __generate_history(self): - logs = filter(lambda x:x.endswith(".xml"), os.listdir(ctx.config.history_dir())) - logs.sort(lambda x,y:int(x.split("_")[0]) - int(y.split("_")[0])) - logs.reverse() + logs = list(filter(lambda x:x.endswith(".xml"), os.listdir(ctx.config.history_dir()))) + logs.sort(key=lambda x: int(x.split("_")[0]), reverse=True) return logs def create_history(self, operation): @@ -93,7 +92,7 @@ class HistoryDB(lazydb.LazyDB): return allconfigs def get_till_operation(self, operation): - if not filter(lambda x:x.startswith("%03d_" % operation), self.__logs): + if not [x for x in self.__logs if x.startswith("%03d_" % operation)]: return for log in self.__logs: @@ -112,7 +111,7 @@ class HistoryDB(lazydb.LazyDB): yield hist.operation def get_last_repo_update(self, last=1): - repoupdates = filter(lambda l:l.endswith("repoupdate.xml"), self.__logs) + repoupdates = [l for l in self.__logs if l.endswith("repoupdate.xml")] repoupdates.reverse() if not len(repoupdates) >= 2: return None diff --git a/pisi/db/installdb.py b/pisi/db/installdb.py index 7f4cc3f5..04aee990 100644 --- a/pisi/db/installdb.py +++ b/pisi/db/installdb.py @@ -17,7 +17,7 @@ import os import re import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import piksemel @@ -73,7 +73,7 @@ class InstallDB(lazydb.LazyDB): name, version, release = dirname.rsplit("-", 2) return name, version + "-" + release - return dict(map(split_name, os.listdir(ctx.config.packages_dir()))) + return dict(list(map(split_name, os.listdir(ctx.config.packages_dir())))) def __get_marked_packages(self, _type): info_path = os.path.join(ctx.config.info_dir(), _type) @@ -113,10 +113,10 @@ class InstallDB(lazydb.LazyDB): return revdeps def list_installed(self): - return self.installed_db.keys() + return list(self.installed_db.keys()) def has_package(self, package): - return self.installed_db.has_key(package) + return package in self.installed_db def list_installed_with_build_host(self, build_host): build_host_re = re.compile("(.*?)") @@ -166,7 +166,7 @@ class InstallDB(lazydb.LazyDB): def get_config_files(self, package): files = self.get_files(package) - return filter(lambda x: x.type == 'config', files.list) + return [x for x in files.list if x.type == 'config'] def search_package(self, terms, lang=None, fields=None): """ @@ -187,12 +187,12 @@ class InstallDB(lazydb.LazyDB): found = [] for name in self.list_installed(): xml = open(os.path.join(self.package_path(name), ctx.const.metadata_xml)).read() - if terms == filter(lambda term: (fields['name'] and \ + if terms == [term for term in terms if (fields['name'] and \ re.compile(term, re.I).search(name)) or \ (fields['summary'] and \ re.compile(resum % (lang, term), re.I).search(xml)) or \ (fields['desc'] and \ - re.compile(redesc % (lang, term), re.I).search(xml)), terms): + re.compile(redesc % (lang, term), re.I).search(xml))]: found.append(name) return found @@ -243,7 +243,7 @@ class InstallDB(lazydb.LazyDB): package_revdeps = self.rev_deps_db.get(name) if package_revdeps: - for pkg, dep in package_revdeps.items(): + for pkg, dep in list(package_revdeps.items()): dependency = self.__create_dependency(dep) rev_deps.append((pkg, dependency)) @@ -275,7 +275,7 @@ class InstallDB(lazydb.LazyDB): def add_package(self, pkginfo): # Cleanup old revdep info - for revdep_info in self.rev_deps_db.values(): + for revdep_info in list(self.rev_deps_db.values()): if pkginfo.name in revdep_info: del revdep_info[pkginfo.name] @@ -283,11 +283,11 @@ class InstallDB(lazydb.LazyDB): self.__add_to_revdeps(pkginfo.name, self.rev_deps_db) def remove_package(self, package_name): - if self.installed_db.has_key(package_name): + if package_name in self.installed_db: del self.installed_db[package_name] # Cleanup revdep info - for revdep_info in self.rev_deps_db.values(): + for revdep_info in list(self.rev_deps_db.values()): if package_name in revdep_info: del revdep_info[package_name] @@ -329,7 +329,7 @@ class InstallDB(lazydb.LazyDB): def package_path(self, package): - if self.installed_db.has_key(package): + if package in self.installed_db: return os.path.join(ctx.config.packages_dir(), "%s-%s" % (package, self.installed_db[package])) raise Exception(_('Package %s is not installed') % package) diff --git a/pisi/db/itembyrepo.py b/pisi/db/itembyrepo.py index b35fc18c..7a15a939 100644 --- a/pisi/db/itembyrepo.py +++ b/pisi/db/itembyrepo.py @@ -12,8 +12,10 @@ import gzip import gettext +import zlib + __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.db @@ -23,27 +25,27 @@ class ItemByRepo: self.compressed = compressed def has_repo(self, repo): - return self.dbobj.has_key(repo) + return repo in self.dbobj def has_item(self, item, repo=None): for r in self.item_repos(repo): - if self.dbobj.has_key(r) and self.dbobj[r].has_key(item): + if r in self.dbobj and item in self.dbobj[r]: return True return False def which_repo(self, item): for r in pisi.db.repodb.RepoDB().list_repos(): - if self.dbobj.has_key(r) and self.dbobj[r].has_key(item): + if r in self.dbobj and item in self.dbobj[r]: return r raise Exception(_("%s not found in any repository.") % str(item)) def get_item_repo(self, item, repo=None): for r in self.item_repos(repo): - if self.dbobj.has_key(r) and self.dbobj[r].has_key(item): + if r in self.dbobj and item in self.dbobj[r]: if self.compressed: - return gzip.zlib.decompress(self.dbobj[r][item]), r + return zlib.decompress(self.dbobj[r][item]), r else: return self.dbobj[r][item], r @@ -59,8 +61,8 @@ class ItemByRepo: if not self.has_repo(r): raise Exception(_('Repository %s does not exist.') % repo) - if self.dbobj.has_key(r): - items.extend(self.dbobj[r].keys()) + if r in self.dbobj: + items.extend(list(self.dbobj[r].keys())) return list(set(items)) @@ -70,7 +72,7 @@ class ItemByRepo: if not self.has_repo(r): raise Exception(_('Repository %s does not exist.') % repo) - if self.dbobj.has_key(r): + if r in self.dbobj: items.extend(self.dbobj[r]) return list(set(items)) @@ -80,12 +82,8 @@ class ItemByRepo: if not self.has_repo(r): raise Exception(_('Repository %s does not exist.') % repo) - if self.compressed: - for item in self.dbobj[r].keys(): - yield item, gzip.zlib.decompress(self.dbobj[r][item]) - else: - for item in self.dbobj[r].keys(): - yield item, self.dbobj[r][item] + for item, data in self.dbobj[r].items(): + yield item, zlib.decompress(data) if self.compressed else data def item_repos(self, repo=None): repos = pisi.db.repodb.RepoDB().list_repos() diff --git a/pisi/db/lazydb.py b/pisi/db/lazydb.py index 99c1e7a8..dd0c4104 100644 --- a/pisi/db/lazydb.py +++ b/pisi/db/lazydb.py @@ -11,14 +11,14 @@ # import os -import cPickle +import pickle import time import pisi.context as ctx import pisi.util as util import string # lower borks for international locales. What we want is ascii lower. -lower_map = string.maketrans(string.ascii_uppercase, string.ascii_lowercase) +lower_map = str.maketrans(string.ascii_uppercase, string.ascii_lowercase) class Singleton(object): _the_instances = {} @@ -39,7 +39,7 @@ class LazyDB(Singleton): cache_version = "2.4" def __init__(self, cacheable=False, cachedir=None): - if not self.__dict__.has_key("initialized"): + if "initialized" not in self.__dict__: self.initialized = False self.cacheable = cacheable self.cachedir = cachedir @@ -65,8 +65,8 @@ class LazyDB(Singleton): f.write(LazyDB.cache_version) f.flush() os.fsync(f.fileno()) - cPickle.dump(self._instance().__dict__, - file(self.__cache_file(), 'wb'), 1) + pickle.dump(self._instance().__dict__, + open(self.__cache_file(), 'wb'), 1) def cache_valid(self): if not self.cachedir: @@ -83,9 +83,9 @@ class LazyDB(Singleton): def cache_load(self): if os.path.exists(self.__cache_file()) and self.cache_valid(): try: - self._instance().__dict__ = cPickle.load(file(self.__cache_file(), 'rb')) + self._instance().__dict__ = pickle.load(open(self.__cache_file(), 'rb'), encoding='utf8', errors='ignore') return True - except (cPickle.UnpicklingError, EOFError): + except (pickle.UnpicklingError, EOFError): if os.access(ctx.config.cache_root_dir(), os.W_OK): os.unlink(self.__cache_file()) return False @@ -116,7 +116,7 @@ class LazyDB(Singleton): ctx.ui.debug("%s initialized in %s." % (self.__class__.__name__, end - start)) self.initialized = True - if not self.__dict__.has_key(attr): - raise AttributeError, attr + if attr not in self.__dict__: + raise AttributeError(attr) return self.__dict__[attr] diff --git a/pisi/db/packagedb.py b/pisi/db/packagedb.py index 1fb7b90b..79338610 100644 --- a/pisi/db/packagedb.py +++ b/pisi/db/packagedb.py @@ -16,7 +16,7 @@ import gzip import gettext import datetime __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import piksemel @@ -62,10 +62,10 @@ class PackageDB(lazydb.LazyDB): if not obsoletes or src_repo: return [] - return map(lambda x: x.firstChild().data(), obsoletes.tags("Package")) + return [x.firstChild().data() for x in obsoletes.tags("Package")] def __generate_packages(self, doc): - return dict(map(lambda x: (x.getTagData("Name"), gzip.zlib.compress(x.toString())), doc.tags("Package"))) + return dict([(x.getTagData("Name"), gzip.zlib.compress(x.toString().encode())) for x in doc.tags("Package")]) def __generate_revdeps(self, doc): revdeps = {} @@ -92,9 +92,9 @@ class PackageDB(lazydb.LazyDB): found = [] for name in packages: xml = self.pdb.get_item(name) - if terms == filter(lambda term: re.compile(term, re.I).search(name) or \ + if terms == [term for term in terms if re.compile(term, re.I).search(name) or \ re.compile(resum % (lang, term), re.I).search(xml) or \ - re.compile(redesc % (lang, term), re.I).search(xml), terms): + re.compile(redesc % (lang, term), re.I).search(xml)]: found.append(name) return found @@ -116,12 +116,12 @@ class PackageDB(lazydb.LazyDB): fields = {'name': True, 'summary': True, 'desc': True} found = [] for name, xml in self.pdb.get_items_iter(repo): - if terms == filter(lambda term: (fields['name'] and \ + if terms == [term for term in terms if (fields['name'] and \ re.compile(term, re.I).search(name)) or \ (fields['summary'] and \ - re.compile(resum % (lang, term), re.I).search(xml)) or \ + re.compile(resum % (lang, term), re.I).search(xml.decode())) or \ (fields['desc'] and \ - re.compile(redesc % (lang, term), re.I).search(xml)), terms): + re.compile(redesc % (lang, term), re.I).search(xml.decode()))]: found.append(name) return found @@ -201,7 +201,7 @@ class PackageDB(lazydb.LazyDB): for pkg_name in self.rpdb.get_list_item(): xml = self.pdb.get_item(pkg_name, repo) - package = piksemel.parseString(xml) + package = piksemel.parseString(xml.decode()) replaces_tag = package.getTag("Replaces") if replaces_tag: for node in replaces_tag.tags("Package"): diff --git a/pisi/db/repodb.py b/pisi/db/repodb.py index bba631c8..16c62982 100644 --- a/pisi/db/repodb.py +++ b/pisi/db/repodb.py @@ -12,7 +12,7 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import os @@ -35,7 +35,7 @@ class Repo: def __init__(self, indexuri): self.indexuri = indexuri -medias = (cd, usb, remote, local) = range(4) +medias = (cd, usb, remote, local) = list(range(4)) class RepoOrder: @@ -106,14 +106,16 @@ class RepoOrder: #FIXME: get media order from pisi.conf for m in ["cd", "usb", "remote", "local"]: - if self.repos.has_key(m): + if m in self.repos: order.extend(self.repos[m]) return order def _update(self, doc): - repos_file = os.path.join(ctx.config.info_dir(), ctx.const.repos) - open(repos_file, "w").write("%s\n" % doc.toPrettyString()) + repos_file_path = os.path.join(ctx.config.info_dir(), ctx.const.repos) + repo_file = open(repos_file_path, "w") + repo_file.write("%s\n" % doc.toPrettyString()) + repo_file.close() self._doc = None self.repos = self._get_repos() @@ -173,7 +175,7 @@ class RepoDB(lazydb.LazyDB): try: return piksemel.parse(index_path) - except Exception, e: + except Exception as e: raise RepoError(_("Error parsing repository index information. Index file does not exist or is malformed.")) def get_repo(self, repo): @@ -185,7 +187,9 @@ class RepoDB(lazydb.LazyDB): raise RepoError(_("Repository %s does not exist.") % repo) urifile_path = pisi.util.join_path(ctx.config.index_dir(), repo, "uri") - uri = open(urifile_path, "r").read() + urifile = open(urifile_path, "r") + uri = urifile.read() + urifile.close() return uri.rstrip() def add_repo(self, name, repo_info, at = None): diff --git a/pisi/db/sourcedb.py b/pisi/db/sourcedb.py index dd89e212..fffcab91 100644 --- a/pisi/db/sourcedb.py +++ b/pisi/db/sourcedb.py @@ -46,7 +46,7 @@ class SourceDB(lazydb.LazyDB): for spec in doc.tags("SpecFile"): src_name = spec.getTag("Source").getTagData("Name") - sources[src_name] = gzip.zlib.compress(spec.toString()) + sources[src_name] = gzip.zlib.compress(spec.toString().encode()) for package in spec.tags("Package"): pkgstosrc[package.getTagData("Name")] = src_name @@ -97,12 +97,12 @@ class SourceDB(lazydb.LazyDB): lang = pisi.pxml.autoxml.LocalText.get_lang() found = [] for name, xml in self.sdb.get_items_iter(repo): - if terms == filter(lambda term: (fields['name'] and \ + if terms == [term for term in terms if (fields['name'] and \ re.compile(term, re.I).search(name)) or \ (fields['summary'] and \ re.compile(resum % (lang, term), re.I).search(xml)) or \ (fields['desc'] and \ - re.compile(redesc % (lang, term), re.I).search(xml)), terms): + re.compile(redesc % (lang, term), re.I).search(xml))]: found.append(name) return found diff --git a/pisi/dependency.py b/pisi/dependency.py index 95956984..993f9395 100644 --- a/pisi/dependency.py +++ b/pisi/dependency.py @@ -14,7 +14,7 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.relation import pisi.db @@ -40,7 +40,7 @@ class Dependency(pisi.relation.Relation): return self.package def satisfied_by_dict_repo(self, dict_repo): - if not dict_repo.has_key(self.package): + if self.package not in dict_repo: return False else: pkg = dict_repo[self.package] diff --git a/pisi/fetcher.py b/pisi/fetcher.py index 82c23d1f..3e3c65f8 100644 --- a/pisi/fetcher.py +++ b/pisi/fetcher.py @@ -23,7 +23,7 @@ import shutil import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # pisi modules import pisi @@ -166,7 +166,7 @@ class Fetcher: reget = self._test_range_support(), copy_local = 1, user_agent = 'PiSi Fetcher/' + pisi.__version__) - except urlgrabber.grabber.URLGrabError, e: + except urlgrabber.grabber.URLGrabError as e: raise FetchError(_('Could not fetch destination file "%s": %s') % (self.url.get_uri(), e)) if os.stat(self.partial_file).st_size == 0: @@ -220,17 +220,17 @@ class Fetcher: if not os.path.exists(self.partial_file): return None - import urllib2 + import urllib.request, urllib.error, urllib.parse try: - file_obj = urllib2.urlopen(urllib2.Request(self.url.get_uri())) - except urllib2.URLError: + file_obj = urllib.request.urlopen(urllib.request.Request(self.url.get_uri())) + except urllib.error.URLError: ctx.ui.debug(_("Remote file can not be reached. Previously downloaded part of the file will be removed.")) os.remove(self.partial_file) return None headers = file_obj.info() file_obj.close() - if headers.has_key('Content-Length'): + if 'Content-Length' in headers: return 'simple' else: ctx.ui.debug(_("Server doesn't support partial downloads. Previously downloaded part of the file will be over-written.")) diff --git a/pisi/file.py b/pisi/file.py index b07ed03a..d61bfd21 100644 --- a/pisi/file.py +++ b/pisi/file.py @@ -22,7 +22,7 @@ import shutil import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.uri @@ -57,8 +57,8 @@ class File: COMPRESSION_TYPE_BZ2 = 1 COMPRESSION_TYPE_XZ = 2 - (read, write) = range(2) # modes - (detached, whatelse) = range(2) + (read, write) = list(range(2)) # modes + (detached, whatelse) = list(range(2)) __compressed_file_extensions = {".xz": COMPRESSION_TYPE_XZ, ".bz2": COMPRESSION_TYPE_BZ2} @@ -66,7 +66,7 @@ class File: @staticmethod def make_uri(uri): "handle URI arg" - if isinstance(uri, basestring): + if isinstance(uri, str): uri = pisi.uri.URI(uri) elif not isinstance(uri, pisi.uri.URI): raise Error(_("uri must have type either URI or string")) @@ -75,7 +75,7 @@ class File: @staticmethod def choose_method(filename, compress): if compress == File.COMPRESSION_TYPE_AUTO: - for ext, method in File.__compressed_file_extensions.items(): + for ext, method in list(File.__compressed_file_extensions.items()): if filename.endswith(ext): return method @@ -92,7 +92,7 @@ class File: compress = File.choose_method(localfile, compress) if compress == File.COMPRESSION_TYPE_XZ: import lzma - open(localfile[:-3], "w").write(lzma.LZMAFile(localfile).read()) + open(localfile[:-3], "wb").write(lzma.LZMAFile(localfile).read()) localfile = localfile[:-3] elif compress == File.COMPRESSION_TYPE_BZ2: import bz2 @@ -115,7 +115,7 @@ class File: if sha1sum: sha1filename = File.download(pisi.uri.URI(uri.get_uri() + '.sha1sum'), transfer_dir) - sha1f = file(sha1filename) + sha1f = open(sha1filename) newsha1 = sha1f.read().split("\n")[0] if uri.is_remote_file() or copylocal: @@ -125,7 +125,7 @@ class File: # TODO: code to use old .sha1sum file, is this a necessary optimization? #oldsha1fn = localfile + '.sha1sum' #if os.exists(oldsha1fn): - #oldsha1 = file(oldsha1fn).readlines()[0] + #oldsha1 = open(oldsha1fn).readlines()[0] if sha1sum and os.path.exists(origfile): oldsha1 = pisi.util.sha1_file(origfile) if (newsha1 == oldsha1): @@ -202,7 +202,7 @@ class File: access = 'r' else: access = 'w' - self.__file__ = file(localfile, access) + self.__file__ = open(localfile, access) self.localfile = localfile def local_file(self): @@ -233,12 +233,12 @@ class File: if self.sha1sum: sha1 = pisi.util.sha1_file(self.localfile) - cs = file(self.localfile + '.sha1sum', 'w') + cs = open(self.localfile + '.sha1sum', 'w') cs.write(sha1) cs.close() for compressed_file in compressed_files: sha1 = pisi.util.sha1_file(compressed_file) - cs = file(compressed_file + '.sha1sum', 'w') + cs = open(compressed_file + '.sha1sum', 'w') cs.write(sha1) cs.close() @@ -256,7 +256,7 @@ class File: sigfilename = File.download(pisi.uri.URI(uri + '.sig'), transfer_dir) except KeyboardInterrupt: raise - except Exception, e: #FIXME: what exception could we catch here, replace with that. + except Exception as e: #FIXME: what exception could we catch here, replace with that. raise NoSignatureFound(uri) if os.system('gpg --verify ' + sigfilename) != 0: raise InvalidSignature(uri) @@ -271,8 +271,8 @@ class File: def isatty(self): return self.__file__.isatty() - def next(self): - return self.__file__.next() + def __next__(self): + return next(self.__file__) def read(self, size = None): if size: @@ -293,7 +293,7 @@ class File: return self.__file__.readlines() def xreadlines(self): - return self.__file__.xreadlines() + return self.__file__ def seek(self, offset, whence=0): self.__file__.seek(offset, whence) diff --git a/pisi/files.py b/pisi/files.py index 67560e3a..5f0601df 100644 --- a/pisi/files.py +++ b/pisi/files.py @@ -16,11 +16,9 @@ during the build process of a package and used in installation.''' import pisi.pxml.autoxml as autoxml -class FileInfo: +class FileInfo(metaclass=autoxml.autoxml): """File holds the information for a File node/tag in files.xml""" - __metaclass__ = autoxml.autoxml - t_Path = [ autoxml.String, autoxml.mandatory ] t_Type = [ autoxml.String, autoxml.mandatory ] t_Size = [ autoxml.Long, autoxml.optional ] @@ -36,9 +34,7 @@ class FileInfo: return s -class Files(autoxml.xmlfile.XmlFile): - - __metaclass__ = autoxml.autoxml +class Files(autoxml.xmlfile.XmlFile, metaclass=autoxml.autoxml): tag = "Files" diff --git a/pisi/graph.py b/pisi/graph.py index 1e01f8e6..6e16ad8e 100644 --- a/pisi/graph.py +++ b/pisi/graph.py @@ -16,7 +16,7 @@ import pisi import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext class CycleException(pisi.Exception): def __init__(self, cycle): diff --git a/pisi/group.py b/pisi/group.py index f99a28f9..655466c1 100644 --- a/pisi/group.py +++ b/pisi/group.py @@ -14,25 +14,22 @@ import pisi import pisi.pxml.xmlfile as xmlfile import pisi.pxml.autoxml as autoxml + class Error(pisi.Error): pass -__metaclass__ = autoxml.autoxml -class Group(xmlfile.XmlFile): - "representation for group declarations" - - __metaclass__ = autoxml.autoxml +class Group(xmlfile.XmlFile, metaclass=autoxml.autoxml): + """Representation for group declarations""" t_Name = [autoxml.String, autoxml.mandatory] t_LocalName = [autoxml.LocalText, autoxml.mandatory] - t_Icon = [ autoxml.String, autoxml.optional] + t_Icon = [autoxml.String, autoxml.optional] -class Groups(xmlfile.XmlFile): - "representation for component declarations" - __metaclass__ = autoxml.autoxml +class Groups(xmlfile.XmlFile, metaclass=autoxml.autoxml): + """Representation for component declarations""" tag = "PISI" - t_Groups = [ [Group], autoxml.optional, "Groups/Group" ] + t_Groups = [[Group], autoxml.optional, "Groups/Group"] diff --git a/pisi/history.py b/pisi/history.py index 8a76f964..8820b312 100644 --- a/pisi/history.py +++ b/pisi/history.py @@ -14,15 +14,14 @@ import os import time import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.pxml.autoxml as autoxml import pisi.pxml.xmlfile as xmlfile import pisi.context as ctx -__metaclass__ = autoxml.autoxml -class PackageInfo: +class PackageInfo(metaclass=autoxml.autoxml): a_version = [autoxml.String, autoxml.mandatory] a_release = [autoxml.String, autoxml.mandatory] @@ -34,7 +33,7 @@ class PackageInfo: return "-".join((self.version, self.release, distro_id, arch)) -class Repo: +class Repo(metaclass=autoxml.autoxml): a_operation = [autoxml.String, autoxml.mandatory] t_Name = [autoxml.String, autoxml.mandatory] @@ -50,7 +49,7 @@ class Repo: elif self.operation == "remove": pass # TBD -class Package: +class Package(metaclass=autoxml.autoxml): a_operation = [autoxml.String, autoxml.mandatory] a_type = [autoxml.String, autoxml.optional] @@ -78,7 +77,8 @@ class Package: else: return "" -class Operation: + +class Operation(metaclass=autoxml.autoxml): a_type = [autoxml.String, autoxml.mandatory] a_date = [autoxml.String, autoxml.mandatory] @@ -90,9 +90,8 @@ class Operation: def __str__(self): return self.type -class History(xmlfile.XmlFile): - __metaclass__ = autoxml.autoxml +class History(xmlfile.XmlFile, metaclass=autoxml.autoxml): tag = "PISI" @@ -148,10 +147,10 @@ class History(xmlfile.XmlFile): def _get_latest(self): - files = filter(lambda h:h.endswith(".xml"), os.listdir(ctx.config.history_dir())) + files = [h for h in os.listdir(ctx.config.history_dir()) if h.endswith(".xml")] if not files: return "001" - files.sort(lambda x,y:int(x.split("_")[0]) - int(y.split("_")[0])) + files.sort(key=lambda x: int(x.split("_")[0])) no, opxml = files[-1].split("_") return "%03d" % (int(no) + 1) diff --git a/pisi/index.py b/pisi/index.py index 488fb5bb..c39d0049 100644 --- a/pisi/index.py +++ b/pisi/index.py @@ -18,7 +18,7 @@ import multiprocessing import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.context as ctx @@ -37,9 +37,7 @@ import pisi.operations.build class Error(pisi.Error): pass -class Index(xmlfile.XmlFile): - __metaclass__ = autoxml.autoxml - +class Index(xmlfile.XmlFile, metaclass=autoxml.autoxml): tag = "PISI" t_Distribution = [ component.Distribution, autoxml.optional ] @@ -67,7 +65,7 @@ class Index(xmlfile.XmlFile): pisi.util.ensure_dirs(tmpdir) # write uri - urlfile = file(pisi.util.join_path(tmpdir, 'uri'), 'w') + urlfile = open(pisi.util.join_path(tmpdir, 'uri'), 'w') urlfile.write(uri) # uri urlfile.close() @@ -136,7 +134,7 @@ class Index(xmlfile.XmlFile): raise try: - obsoletes_list = map(str, self.distribution.obsoletes) + obsoletes_list = list(map(str, self.distribution.obsoletes)) except AttributeError: obsoletes_list = [] @@ -178,7 +176,7 @@ def add_package(params): package = pisi.package.Package(path, 'r') md = package.get_metadata() - md.package.packageSize = long(os.path.getsize(path)) + md.package.packageSize = int(os.path.getsize(path)) md.package.packageHash = util.sha1_file(path) if ctx.config.options and ctx.config.options.absolute_urls: md.package.packageURI = os.path.realpath(path) @@ -190,7 +188,7 @@ def add_package(params): if md.errors(): ctx.ui.info("") ctx.ui.error(_('Package %s: metadata corrupt, skipping...') % md.package.name) - ctx.ui.error(unicode(Error(*errs))) + ctx.ui.error(str(Error(*errs))) else: # No need to carry these with index (#3965) md.package.files = None @@ -211,7 +209,7 @@ def add_package(params): delta = metadata.Delta() delta.packageURI = util.removepathprefix(repo_uri, delta_path) - delta.packageSize = long(os.path.getsize(delta_path)) + delta.packageSize = int(os.path.getsize(delta_path)) delta.packageHash = util.sha1_file(delta_path) delta.releaseFrom = src_release diff --git a/pisi/metadata.py b/pisi/metadata.py index 5c72ca4a..48f5071e 100644 --- a/pisi/metadata.py +++ b/pisi/metadata.py @@ -19,32 +19,29 @@ a package index. import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.specfile as specfile import pisi.pxml.xmlfile as xmlfile import pisi.pxml.autoxml as autoxml import pisi.util as util -class Delta: - __metaclass__ = autoxml.autoxml +class Delta(metaclass=autoxml.autoxml): t_PackageURI = [ autoxml.String, autoxml.optional] t_PackageSize = [ autoxml.Long, autoxml.optional] t_PackageHash = [ autoxml.String, autoxml.optional, "SHA1Sum" ] a_buildFrom = [autoxml.String, autoxml.optional] a_releaseFrom = [autoxml.String, autoxml.optional] -class Source: - __metaclass__ = autoxml.autoxml +class Source(metaclass=autoxml.autoxml): t_Name = [autoxml.String, autoxml.mandatory] t_Homepage = [autoxml.String, autoxml.optional] t_Packager = [specfile.Packager, autoxml.mandatory] -class Package(specfile.Package, xmlfile.XmlFile): - __metaclass__ = autoxml.autoxml +class Package(specfile.Package, xmlfile.XmlFile, metaclass=autoxml.autoxml): t_Build = [ autoxml.Integer, autoxml.optional] t_BuildHost = [autoxml.String, autoxml.optional] t_Distribution = [ autoxml.String, autoxml.mandatory] @@ -87,12 +84,11 @@ class Package(specfile.Package, xmlfile.XmlFile): return s -class MetaData(xmlfile.XmlFile): + +class MetaData(xmlfile.XmlFile, metaclass=autoxml.autoxml): """Package metadata. Metadata is composed of Specfile and various other information. A metadata has two parts, Source and Package.""" - __metaclass__ = autoxml.autoxml - tag = "PISI" t_Source = [ Source, autoxml.mandatory] diff --git a/pisi/mirrors.py b/pisi/mirrors.py index b17e1b42..44517347 100644 --- a/pisi/mirrors.py +++ b/pisi/mirrors.py @@ -15,7 +15,7 @@ import pisi.context as ctx import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext class Mirrors: def __init__(self, config=ctx.const.mirrors_conf): @@ -23,13 +23,13 @@ class Mirrors: self._parse(config) def get_mirrors(self, name): - if self.mirrors.has_key(name): + if name in self.mirrors: return list(self.mirrors[name]) return None def _add_mirror(self, name, url): - if self.mirrors.has_key(name): + if name in self.mirrors: self.mirrors[name].append(url) else: self.mirrors[name] = [url] diff --git a/pisi/oo.py b/pisi/oo.py index 5b893f24..f95903fa 100644 --- a/pisi/oo.py +++ b/pisi/oo.py @@ -8,10 +8,10 @@ class autoprop(type): def __init__(cls, name, bases, dict): super(autoprop, cls).__init__(name, bases, dict) props = {} - for name in dict.keys(): + for name in list(dict.keys()): if name.startswith("_get_") or name.startswith("_set_"): props[name[5:]] = 1 - for name in props.keys(): + for name in list(props.keys()): fget = getattr(cls, "_get_%s" % name, None) fset = getattr(cls, "_set_%s" % name, None) setattr(cls, name, property(fget, fset)) @@ -32,8 +32,6 @@ class autoeq(type): return self.__dict__ == other.__dict__ cls.__eq__ = equal -class Struct: - __metaclass__ = autoeq - +class Struct(metaclass=autoeq): def __init__(self, **entries): self.__dict__.update(entries) diff --git a/pisi/operations/build.py b/pisi/operations/build.py index 0c2d360a..b7491f27 100644 --- a/pisi/operations/build.py +++ b/pisi/operations/build.py @@ -22,7 +22,7 @@ import fnmatch import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.specfile @@ -129,14 +129,14 @@ def exclude_special_files(filepath, fileinfo, ag): # patches, PiSi removes wrong paths... if re.match(patterns["libtool"], fileinfo) and \ not os.path.islink(filepath): - ladata = file(filepath).read() + ladata = open(filepath).read() new_ladata = re.sub("-L%s/\S*" % ctx.config.tmp_dir(), "", ladata) new_ladata = re.sub("%s/\S*/install/" % ctx.config.tmp_dir(), "/", new_ladata) if new_ladata != ladata: - file(filepath, "w").write(new_ladata) + open(filepath, "w").write(new_ladata) - for name, pattern in patterns.items(): + for name, pattern in list(patterns.items()): if name in keeplist: continue @@ -592,7 +592,7 @@ class Builder: abandoned_files.append(fpath) len_install_dir = len(install_dir) - return map(lambda x: x[len_install_dir:], abandoned_files) + return [x[len_install_dir:] for x in abandoned_files] def copy_additional_source_files(self): # store additional files @@ -611,10 +611,10 @@ class Builder: try: buf = open(fname).read() return compile(buf, fname, "exec") - except IOError, e: + except IOError as e: raise Error(_("Unable to read Actions Script (%s): %s") % (fname, e)) - except SyntaxError, e: + except SyntaxError as e: raise Error(_("SyntaxError in Actions Script (%s): %s") % (fname, e)) @@ -625,8 +625,8 @@ class Builder: try: localSymbols = globalSymbols = {} - exec compiled_script in localSymbols, globalSymbols - except Exception, e: + exec(compiled_script, localSymbols, globalSymbols) + except Exception as e: import traceback traceback.print_exc(e) raise ActionScriptException @@ -644,10 +644,10 @@ class Builder: try: buf = open(fname).read() compile(buf, "error", "exec") - except IOError, e: + except IOError as e: raise Error(_("Unable to read COMAR script (%s): %s") % (fname, e)) - except SyntaxError, e: + except SyntaxError as e: raise Error(_("SyntaxError in COMAR file (%s): %s") % (fname, e)) @@ -711,7 +711,7 @@ class Builder: valid_paths = [self.pkg_dir()] conf_file = ctx.const.sandbox_conf if os.path.exists(conf_file): - for line in file(conf_file): + for line in open(conf_file): line = line.strip() if len(line) > 0 and not line.startswith("#"): if line.startswith("~"): @@ -728,7 +728,7 @@ class Builder: logger=self.log_sandbox_violation) # Retcode can be 0 while there is a sanbox violation, so only # look for violations to correctly handle it - if ret.violations != []: + if ret.violations: ctx.ui.error(_("Sandbox violation result:")) for result in ret.violations: ctx.ui.error("%s (%s -> %s)" % (result[0], @@ -785,7 +785,7 @@ class Builder: build_deps_names = set([x.package for x in build_deps]) devel_deps_names = set(self.componentdb.get_component('system.devel').packages) extra_names = devel_deps_names - build_deps_names - extra_names = filter(lambda x: not self.installdb.has_package(x), extra_names) + extra_names = [x for x in extra_names if not self.installdb.has_package(x)] if extra_names: ctx.ui.warning(_('Safety switch: following extra packages in system.devel will be installed: ') + util.strlist(extra_names)) @@ -867,8 +867,8 @@ class Builder: static_package_obj = pisi.specfile.Package() static_package_obj.name = self.spec.source.name + ctx.const.static_name_suffix # FIXME: find a better way to deal with the summary and description constants. - static_package_obj.summary['en'] = u'Ar files for %s' % (self.spec.source.name) - static_package_obj.description['en'] = u'Ar files for %s' % (self.spec.source.name) + static_package_obj.summary['en'] = 'Ar files for %s' % (self.spec.source.name) + static_package_obj.description['en'] = 'Ar files for %s' % (self.spec.source.name) static_package_obj.partOf = self.spec.source.partOf for f in ar_files: static_package_obj.files.append(pisi.specfile.Path(path=f[len(self.pkg_install_dir()):], fileType="library")) @@ -885,8 +885,8 @@ class Builder: debug_package_obj.debug_package = True debug_package_obj.name = package.name + ctx.const.debug_name_suffix # FIXME: find a better way to deal with the summary and description constants. - debug_package_obj.summary['en'] = u'Debug files for %s' % (package.name) - debug_package_obj.description['en'] = u'Debug files for %s' % (package.name) + debug_package_obj.summary['en'] = 'Debug files for %s' % (package.name) + debug_package_obj.description['en'] = 'Debug files for %s' % (package.name) debug_package_obj.partOf = package.partOf dependency = pisi.dependency.Dependency() @@ -920,7 +920,7 @@ class Builder: for fileinfo in self.files.list: size += fileinfo.size - metadata.package.installedSize = long(size) + metadata.package.installedSize = int(size) self.metadata = metadata @@ -957,7 +957,7 @@ class Builder: continue frpath = util.removepathprefix(install_dir, fpath) # relative path ftype, permanent = get_file_type(frpath, package.files) - fsize = long(util.dir_size(fpath)) + fsize = int(util.dir_size(fpath)) if not os.path.islink(fpath): st = os.stat(fpath) else: @@ -976,7 +976,7 @@ class Builder: add_path(path) files = pisi.files.Files() - for fileinfo in d.itervalues(): + for fileinfo in d.values(): files.append(fileinfo) files_xml_path = util.join_path(self.pkg_dir(), ctx.const.files_xml) @@ -987,17 +987,15 @@ class Builder: install_dir = self.pkg_install_dir() import magic - ms = magic.open(magic.MAGIC_NONE) - ms.load() + ms = magic.Magic() for root, dirs, files in os.walk(install_dir): for fn in files: filepath = util.join_path(root, fn) - fileinfo = ms.file(filepath) + fileinfo = ms.from_file(filepath) strip_debug_action(filepath, fileinfo, install_dir, self.actionGlobals) exclude_special_files(filepath, fileinfo, self.actionGlobals) - ms.close() def build_packages(self): """Build each package defined in PSPEC file. After this process there @@ -1190,7 +1188,7 @@ class Builder: old_packages = {} - for old_release, search_paths in self.delta_search_paths.items(): + for old_release, search_paths in list(self.delta_search_paths.items()): if old_release in old_packages: continue @@ -1228,7 +1226,7 @@ class Builder: old_packages.update(found_old_packages) from pisi.operations.delta import create_delta_packages_from_obj - return create_delta_packages_from_obj(old_packages.values(), + return create_delta_packages_from_obj(list(old_packages.values()), package, self.specdir) @@ -1242,7 +1240,7 @@ def build(pspec): pb = Builder.from_name(pspec) try: pb.build() - except ActionScriptException, e: + except ActionScriptException as e: ctx.ui.error(_("Action script error caught.")) raise e finally: diff --git a/pisi/operations/check.py b/pisi/operations/check.py index f9fec7e9..e7693cb8 100644 --- a/pisi/operations/check.py +++ b/pisi/operations/check.py @@ -15,7 +15,7 @@ import pisi.context as ctx import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext def file_corrupted(pfile): path = os.path.join(ctx.config.dest_dir(), pfile.path) @@ -26,7 +26,7 @@ def file_corrupted(pfile): try: if pisi.util.sha1_file(path) != pfile.hash: return True - except pisi.util.FilePermissionDeniedError, e: + except pisi.util.FilePermissionDeniedError as e: raise e return False @@ -51,7 +51,7 @@ def check_files(files, check_config=False): try: is_file_corrupted = file_corrupted(f) - except pisi.util.FilePermissionDeniedError, e: + except pisi.util.FilePermissionDeniedError as e: # Can't read file, probably because of permissions, skip results['denied'].append(f.path) diff --git a/pisi/operations/delta.py b/pisi/operations/delta.py index 82dad436..354d48ea 100644 --- a/pisi/operations/delta.py +++ b/pisi/operations/delta.py @@ -13,7 +13,7 @@ import os import gettext __trans = gettext.translation("pisi", fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.context as ctx import pisi.package @@ -181,7 +181,7 @@ def find_relocations(oldfiles, newfiles): files_old.setdefault(f.hash, []).append(f) relocations = [] - for h in files_new.keys(): + for h in list(files_new.keys()): if h and h in files_old: old_paths = [x.path for x in files_old[h]] for i in range(len(files_new[h])): diff --git a/pisi/operations/emerge.py b/pisi/operations/emerge.py index 3701dd47..4972b561 100644 --- a/pisi/operations/emerge.py +++ b/pisi/operations/emerge.py @@ -14,7 +14,7 @@ import sys import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.operations diff --git a/pisi/operations/helper.py b/pisi/operations/helper.py index 799da7f4..f05b25cc 100644 --- a/pisi/operations/helper.py +++ b/pisi/operations/helper.py @@ -14,7 +14,7 @@ import os import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.context as ctx @@ -53,7 +53,7 @@ def check_conflicts(order, packagedb): if pkg_conflicts: conflicts = "" - for pkg in pkg_conflicts.keys(): + for pkg in list(pkg_conflicts.keys()): conflicts += _("[%s conflicts with: %s]\n") % (pkg, util.strlist(pkg_conflicts[pkg])) ctx.ui.info(_("The following packages have conflicts:\n%s") % diff --git a/pisi/operations/history.py b/pisi/operations/history.py index fcbc5ff9..411344ee 100644 --- a/pisi/operations/history.py +++ b/pisi/operations/history.py @@ -12,7 +12,7 @@ import os import gettext __trans = gettext.translation("pisi", fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.context as ctx @@ -87,7 +87,7 @@ def fetch_remote_file(package, errors): if not os.path.exists(filepath): try: pisi.fetcher.fetch_url(uri, dest, ctx.ui.Progress) - except pisi.fetcher.FetchError, e: + except pisi.fetcher.FetchError as e: errors.append(package) ctx.ui.info(pisi.util.colorize(_("%s could not be found") % (package), "red")) return False diff --git a/pisi/operations/install.py b/pisi/operations/install.py index 141f6e1d..55400f91 100644 --- a/pisi/operations/install.py +++ b/pisi/operations/install.py @@ -16,7 +16,7 @@ import zipfile import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.context as ctx @@ -41,7 +41,7 @@ def install_pkg_names(A, reinstall = False): # filter packages that are already installed if not reinstall: - Ap = set(filter(lambda x: not installdb.has_package(x), A)) + Ap = set([x for x in A if not installdb.has_package(x)]) d = A - Ap if len(d) > 0: ctx.ui.warning(_("The following package(s) are already installed " @@ -159,7 +159,7 @@ def install_pkg_files(package_URIs, reinstall = False): # check packages' DistributionReleases and Architecture if not ctx.get_option('ignore_check'): - for x in d_t.keys(): + for x in list(d_t.keys()): pkg = d_t[x] if pkg.distributionRelease != ctx.config.values.general.distribution_release: raise pisi.Error(_('Package %s is not compatible with your distribution release %s %s.') \ @@ -178,7 +178,7 @@ def install_pkg_files(package_URIs, reinstall = False): # that aren't already satisfied and try to install them # from the repository dep_unsatis = [] - for name in d_t.keys(): + for name in list(d_t.keys()): pkg = d_t[name] deps = pkg.runtimeDependencies() for dep in deps: @@ -207,7 +207,7 @@ def install_pkg_files(package_URIs, reinstall = False): packagedb = PackageDB() - A = d_t.keys() + A = list(d_t.keys()) if len(A)==0: ctx.ui.info(_('No packages to install.')) diff --git a/pisi/operations/remove.py b/pisi/operations/remove.py index 0307cd81..11692d11 100644 --- a/pisi/operations/remove.py +++ b/pisi/operations/remove.py @@ -14,7 +14,7 @@ import sys import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.context as ctx @@ -122,7 +122,7 @@ def remove_conflicting_packages(conflicts): def remove_obsoleted_packages(): installdb = pisi.db.installdb.InstallDB() packagedb = pisi.db.packagedb.PackageDB() - obsoletes = filter(installdb.has_package, packagedb.get_obsoletes()) + obsoletes = list(filter(installdb.has_package, packagedb.get_obsoletes())) if obsoletes: if remove(obsoletes, ignore_dep=True, ignore_safety=True): raise Exception(_("Obsoleted packages remaining")) diff --git a/pisi/operations/upgrade.py b/pisi/operations/upgrade.py index 628c43fc..5a672951 100644 --- a/pisi/operations/upgrade.py +++ b/pisi/operations/upgrade.py @@ -14,7 +14,7 @@ import sys import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.ui as ui @@ -40,7 +40,7 @@ def check_update_actions(packages): version, release, build = installdb.get_version(package) pkg_actions = pkg.get_update_actions(release) - for action_name, action_targets in pkg_actions.items(): + for action_name, action_targets in list(pkg_actions.items()): item = actions.setdefault(action_name, []) for action_target in action_targets: item.append((package, action_target)) @@ -72,7 +72,7 @@ def find_upgrades(packages, replaces): Ap = [] for i_pkg in packages: - if i_pkg in replaces.keys(): + if i_pkg in list(replaces.keys()): # Replaced packages will be forced for upgrade, cause replaced packages are marked as obsoleted also. So we # pass them. continue @@ -128,7 +128,7 @@ def upgrade(A=[], repo=None): # Force upgrading of installed but replaced packages or else they will be removed (they are obsoleted also). # This is not wanted for a replaced driver package (eg. nvidia-X). - A |= set(pisi.util.flatten_list(replaces.values())) + A |= set(pisi.util.flatten_list(list(replaces.values()))) A |= upgrade_base(A) @@ -170,7 +170,7 @@ def upgrade(A=[], repo=None): needs_confirm = check_update_actions(order) # NOTE: replaces.values() was already flattened above, it can be reused - if set(order) - A_0 - set(pisi.util.flatten_list(replaces.values())): + if set(order) - A_0 - set(pisi.util.flatten_list(list(replaces.values()))): ctx.ui.warning(_("There are extra packages due to dependencies.")) needs_confirm = True @@ -226,7 +226,7 @@ def plan_upgrade(A, force_replaced=True, replaces=None): if force_replaced: if replaces is None: replaces = packagedb.get_replaces() - A |= set(pisi.util.flatten_list(replaces.values())) + A |= set(pisi.util.flatten_list(list(replaces.values()))) # find the "install closure" graph of G_f by package # set A using packagedb @@ -343,14 +343,14 @@ def upgrade_base(A = set()): if not ctx.config.values.general.ignore_safety and not ctx.get_option('ignore_safety'): if componentdb.has_component('system.base'): systembase = set(componentdb.get_union_component('system.base').packages) - extra_installs = filter(lambda x: not installdb.has_package(x), systembase - set(A)) + extra_installs = [x for x in systembase - set(A) if not installdb.has_package(x)] extra_installs = pisi.blacklist.exclude_from(extra_installs, ctx.const.blacklist) if extra_installs: ctx.ui.warning(_("Safety switch forces the installation of " "following packages:")) ctx.ui.info(util.format_by_columns(sorted(extra_installs))) G_f, install_order = operations.install.plan_install_pkg_names(extra_installs) - extra_upgrades = filter(lambda x: is_upgradable(x), systembase - set(install_order)) + extra_upgrades = [x for x in systembase - set(install_order) if is_upgradable(x)] upgrade_order = [] extra_upgrades = pisi.blacklist.exclude_from(extra_upgrades, ctx.const.blacklist) diff --git a/pisi/package.py b/pisi/package.py index eb4673ca..ae15d41a 100644 --- a/pisi/package.py +++ b/pisi/package.py @@ -16,7 +16,7 @@ import os.path import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import pisi.context as ctx @@ -26,7 +26,7 @@ import pisi.metadata import pisi.file import pisi.files import pisi.util as util -import fetcher +from . import fetcher class Error(pisi.Error): @@ -64,7 +64,7 @@ class Package: try: self.impl = archive.ArchiveZip(self.filepath, 'zip', mode) - except IOError, e: + except IOError as e: raise Error(_("Cannot open package file: %s") % e) self.install_archive = None @@ -217,7 +217,7 @@ class Package: if os.path.isfile(tarinfo.name) or os.path.islink(tarinfo.name): try: os.unlink(tarinfo.name) - except OSError, e: + except OSError as e: ctx.ui.warning(e) else: diff --git a/pisi/pgraph.py b/pisi/pgraph.py index 28db5f86..bd5885fe 100644 --- a/pisi/pgraph.py +++ b/pisi/pgraph.py @@ -12,7 +12,7 @@ """PiSi package relation graph that represents the state of packagedb""" -import graph +from . import graph # Cache the results from packagedb queries in a graph diff --git a/pisi/pxml/autoxml.py b/pisi/pxml/autoxml.py index 2738baa6..68f06a10 100644 --- a/pisi/pxml/autoxml.py +++ b/pisi/pxml/autoxml.py @@ -24,13 +24,13 @@ import locale import types import formatter import sys -import StringIO +import io import inspect import re import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # PiSi import pisi @@ -45,15 +45,15 @@ class Error(pisi.Error): # requirement specs -mandatory, optional = range(2) # poor man's enum +mandatory, optional = list(range(2)) # poor man's enum # basic types -String = types.StringType -Text = types.UnicodeType -Integer = types.IntType -Long = types.LongType -Float = types.FloatType +String = str +Text = str +Integer = int +Long = int +Float = float #class datatype(type): # def __init__(cls, name, bases, dict): @@ -91,7 +91,7 @@ class LocalText(dict): def encode(self, node, errs): assert self.tag != '' - for key in self.iterkeys(): + for key in self.keys(): newnode = xmlext.addNode(node, self.tag) xmlext.setNodeAttribute(newnode, 'xml:lang', key) xmlext.addText(newnode, '', self[key]) @@ -109,25 +109,25 @@ class LocalText(dict): return lang[0:2] except KeyboardInterrupt: raise - except Exception, e: #FIXME: what exception could we catch here, replace with that. + except Exception as e: #FIXME: what exception could we catch here, replace with that. raise Error(_('LocalText: unable to get either current or default locale')) - def errors(self, where = unicode()): + def errors(self, where = str()): errs = [] langs = [ LocalText.get_lang(), 'en', 'tr', ] - if self.keys() and not util.any(lambda x : self.has_key(x), langs): + if list(self.keys()) and not util.any(lambda x : x in self, langs): errs.append( where + ': ' + _("Tag should have at least the current locale, or failing that an English or Turkish version")) #FIXME: check if all entries are unicode return errs def format(self, f, errs): L = LocalText.get_lang() - if self.has_key(L): + if L in self: f.add_flowing_data(self[L]) - elif self.has_key('en'): + elif 'en' in self: # fallback to English, blah f.add_flowing_data(self['en']) - elif self.has_key('tr'): + elif 'tr' in self: # fallback to Turkish f.add_flowing_data(self['tr']) else: @@ -145,16 +145,16 @@ class LocalText(dict): def __str__(self): L = LocalText.get_lang() - if self.has_key(L): - return unicode(self[L]) - elif self.has_key('en'): + if L in self: + return str(self[L]) + elif 'en' in self: # fallback to English, blah - return unicode(self['en']) - elif self.has_key('tr'): + return str(self['en']) + elif 'tr' in self: # fallback to Turkish - return unicode(self['tr']) + return str(self['tr']) else: - return unicode() + return str() class Writer(formatter.DumbWriter): """adds unicode support""" @@ -163,7 +163,7 @@ class Writer(formatter.DumbWriter): formatter.DumbWriter.__init__(self, file, maxcol) def send_literal_data(self, data): - self.file.write(data.encode("utf-8")) + self.file.write(data) i = data.rfind('\n') if i >= 0: self.col = 0 @@ -252,13 +252,13 @@ class autoxml(oo.autosuper, oo.autoprop): xmlfile_support = xmlfile.XmlFile in bases - cls.autoxml_bases = filter(lambda base: isinstance(base, autoxml), bases) + cls.autoxml_bases = [base for base in bases if isinstance(base, autoxml)] #TODO: initialize class attribute __xml_tags #setattr(cls, 'xml_variables', []) # default class tag is class name - if not dict.has_key('tag'): + if 'tag' not in dict: cls.tag = name # generate helper routines, for each XML component @@ -278,18 +278,18 @@ class autoxml(oo.autosuper, oo.autoprop): fn = re.compile('\s*([tas]_[a-zA-Z]+).*').findall inspect.linecache.clearcache() - lines = filter(fn, inspect.getsourcelines(cls)[0]) - decl_order = map(lambda x:x.split()[0], lines) + lines = list(filter(fn, inspect.getsourcelines(cls)[0])) + decl_order = [x.split()[0] for x in lines] except IOError: - decl_order = dict.keys() + decl_order = list(dict.keys()) # there should be at most one str member, and it should be # the first to process - order = filter(lambda x: not x.startswith('s_'), decl_order) + order = [x for x in decl_order if not x.startswith('s_')] # find string member - str_members = filter(lambda x:x.startswith('s_'), decl_order) + str_members = [x for x in decl_order if x.startswith('s_')] if len(str_members)>1: raise Error('Only one str member can be defined') elif len(str_members)==1: @@ -317,7 +317,7 @@ class autoxml(oo.autosuper, oo.autoprop): def initialize(self, uri = None, keepDoc = False, tmpDir = '/tmp', **args): if xmlfile_support: - if args.has_key('tag'): + if 'tag' in args: xmlfile.XmlFile.__init__(self, tag = args['tag']) else: xmlfile.XmlFile.__init__(self, tag = cls.tag) @@ -325,7 +325,7 @@ class autoxml(oo.autosuper, oo.autoprop): base.__init__(self) for init in inits: init(self) - for x in args.iterkeys(): + for x in args.keys(): setattr(self, x, args[x]) # init hook if hasattr(self, 'init'): @@ -336,7 +336,7 @@ class autoxml(oo.autosuper, oo.autoprop): cls.__init__ = initialize cls.decoders = decoders - def decode(self, node, errs, where = unicode(cls.tag)): + def decode(self, node, errs, where=cls.tag): for base in cls.autoxml_bases: base.decode(self, node, errs, where) for decode_member in decoders:#self.__class__.decoders: @@ -356,7 +356,7 @@ class autoxml(oo.autosuper, oo.autoprop): cls.encode = encode cls.errorss = errorss - def errors(self, where = unicode(name)): + def errors(self, where=name): errs = [] for base in cls.autoxml_bases: errs.extend(base.errors(self, where)) @@ -389,16 +389,16 @@ class autoxml(oo.autosuper, oo.autoprop): for x in errs: ctx.ui.warning(x) cls.print_text = print_text - if not dict.has_key('__str__'): + if '__str__' not in dict: def str(self): - strfile = StringIO.StringIO() + strfile = io.StringIO() self.print_text(strfile) str = strfile.getvalue() strfile.close() return str cls.__str__ = str - if not dict.has_key('__eq__'): + if '__eq__' not in dict: def equal(self, other): # handle None if other ==None: @@ -409,7 +409,7 @@ class autoxml(oo.autosuper, oo.autoprop): return False except KeyboardInterrupt: raise - except Exception, e: #FIXME: what exception could we catch here, replace with that. + except Exception as e: #FIXME: what exception could we catch here, replace with that. return False return True def notequal(self, other): @@ -508,8 +508,8 @@ class autoxml(oo.autosuper, oo.autoprop): def gen_tag(cls, tag, spec): """generate readers and writers for the tag""" tag_type = spec[0] - if type(tag_type) is types.TypeType and \ - autoxml.basic_cons_map.has_key(tag_type): + if type(tag_type) is type and \ + tag_type in autoxml.basic_cons_map: def readtext(node, tagpath): #print 'read tag', node, tagpath return xmlext.getNodeText(node, tagpath) @@ -517,11 +517,11 @@ class autoxml(oo.autosuper, oo.autoprop): #print 'write tag', node, tagpath, text xmlext.addText(node, tagpath, text) return cls.gen_anon_basic(tag, spec, readtext, writetext) - elif type(tag_type) is types.ListType: + elif type(tag_type) is list: return cls.gen_list_tag(tag, spec) elif tag_type is LocalText: return cls.gen_insetclass_tag(tag, spec) - elif type(tag_type) is autoxml or type(tag_type) is types.TypeType: + elif type(tag_type) is autoxml or type(tag_type) is type: return cls.gen_class_tag(tag, spec) else: raise Error(_('gen_tag: unrecognized tag type %s in spec') % @@ -554,7 +554,7 @@ class autoxml(oo.autosuper, oo.autoprop): def decode(self, node, errs, where): """decode component from DOM node""" - setattr(self, name, decode_a(node, errs, where + '.' + unicode(name))) + setattr(self, name, decode_a(node, errs, where + '.' + str(name))) def encode(self, node, errs): """encode self inside, possibly new, DOM node using xml""" @@ -602,7 +602,7 @@ class autoxml(oo.autosuper, oo.autoprop): "returns split of the tag path into last tag and the rest" try: lastsep = tagpath.rindex('/') - except ValueError, e: + except ValueError as e: return ('', tagpath) return (tagpath[:lastsep], tagpath[lastsep+1:]) @@ -651,7 +651,7 @@ class autoxml(oo.autosuper, oo.autoprop): value = autoxml.basic_cons_map[token_type](text) except KeyboardInterrupt: raise - except Exception, e: #FIXME: what exception could we catch here, replace with that. + except Exception as e: #FIXME: what exception could we catch here, replace with that. value = None errs.append(where + ': ' + _('Type mismatch: read text cannot be decoded')) return value @@ -663,7 +663,7 @@ class autoxml(oo.autosuper, oo.autoprop): def encode(node, value, errs): """encode given value inside DOM node""" if value is not None: - writetext(node, token, unicode(value)) + writetext(node, token, str(value)) else: if req == mandatory: errs.append(_('Mandatory token %s not available') % token) @@ -677,7 +677,7 @@ class autoxml(oo.autosuper, oo.autoprop): def format(value, f, errs): """format value for pretty printing""" - f.add_literal_data(unicode(value)) + f.add_literal_data(str(value)) return initialize, decode, encode, errors, format @@ -687,7 +687,7 @@ class autoxml(oo.autosuper, oo.autoprop): def make_object(): obj = tag_type.__new__(tag_type) - obj.__init__(tag=tag, req=req) + obj.__init__() return obj def init(): @@ -765,7 +765,7 @@ class autoxml(oo.autosuper, oo.autoprop): for node in nodes: dummy = xmlext.newNode(node, "Dummy") xmlext.addNode(dummy, '', node) - l.append(decode_item(dummy, errs, where + unicode("[%s]" % ix))) + l.append(decode_item(dummy, errs, where + str("[%s]" % ix))) #l.append(decode_item(node, errs, where + unicode("[%s]" % ix))) ix += 1 return l @@ -855,12 +855,11 @@ class autoxml(oo.autosuper, oo.autoprop): if req == mandatory: errs.append(_('Mandatory argument not available')) - return (init, decode, encode, errors, format) + return init, decode, encode, errors, format basic_cons_map = { - types.StringType : str, - types.UnicodeType : unicode, - types.IntType : int, - types.FloatType : float, - types.LongType : long - } + bytes: str, + str: str, + int: int, + float: float, + } diff --git a/pisi/pxml/xmlext.py b/pisi/pxml/xmlext.py index 0f6ae0d9..08b62ba7 100644 --- a/pisi/pxml/xmlext.py +++ b/pisi/pxml/xmlext.py @@ -24,7 +24,7 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi import piksemel as iks @@ -39,7 +39,7 @@ def getAllNodes(node, tagPath): return [] nodeList = [node] # basis case for tag in tags: - results = map(lambda x: getTagByName(x, tag), nodeList) + results = [getTagByName(x, tag) for x in nodeList] nodeList = [] for x in results: nodeList.extend(x) diff --git a/pisi/pxml/xmlfile.py b/pisi/pxml/xmlfile.py index 3331a795..b2ee96f6 100644 --- a/pisi/pxml/xmlfile.py +++ b/pisi/pxml/xmlfile.py @@ -23,7 +23,7 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import piksemel as iks @@ -54,9 +54,9 @@ class XmlFile(object): def parsexml(self, xml): """parses xml string and returns DOM""" try: - self.doc = iks.parseString(xml) + self.doc = iks.parseString(xml.decode() if type(xml) == bytes else xml) return self.doc - except Exception, e: + except Exception as e: raise Error(_("String '%s' has invalid XML") % (xml)) def readxml(self, uri, tmpDir='/tmp', sha1sum=False, @@ -79,9 +79,9 @@ class XmlFile(object): try: self.doc = iks.parse(localpath) return self.doc - except OSError, e: + except OSError as e: raise Error(_("Unable to read file (%s): %s") %(localpath,e)) - except Exception, e: + except Exception as e: raise Error(_("File '%s' has invalid XML") % (localpath) ) def writexml(self, uri, tmpDir = '/tmp', sha1sum=False, compress=None, sign=None): diff --git a/pisi/relation.py b/pisi/relation.py index 62c920ac..b18bbea4 100644 --- a/pisi/relation.py +++ b/pisi/relation.py @@ -15,9 +15,7 @@ import pisi.version import pisi.db import pisi.pxml.autoxml as autoxml -class Relation: - - __metaclass__ = autoxml.autoxml +class Relation(metaclass=autoxml.autoxml): s_Package = [autoxml.String, autoxml.mandatory] a_version = [autoxml.String, autoxml.optional] diff --git a/pisi/replace.py b/pisi/replace.py index 373d294c..bbed40ca 100644 --- a/pisi/replace.py +++ b/pisi/replace.py @@ -12,7 +12,7 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi.relation diff --git a/pisi/scenarioapi/constants.py b/pisi/scenarioapi/constants.py index 87739b14..5f08d1f0 100644 --- a/pisi/scenarioapi/constants.py +++ b/pisi/scenarioapi/constants.py @@ -15,16 +15,16 @@ class _constant: pass def __setattr__(self, name, value): - if self.__dict__.has_key(name): - raise self.ConstError, "Can't rebind constant: %s" % name + if name in self.__dict__: + raise self.ConstError("Can't rebind constant: %s" % name) # Binding an attribute once to a const is available self.__dict__[name] = value def __delattr__(self, name): - if self.__dict__.has_key(name): - raise self.ConstError, "Can't unbind constant: %s" % name + if name in self.__dict__: + raise self.ConstError("Can't unbind constant: %s" % name) # we don't have an attribute by this name - raise NameError, name + raise NameError(name) class Constants: diff --git a/pisi/scenarioapi/package.py b/pisi/scenarioapi/package.py index 310d0173..170cee25 100644 --- a/pisi/scenarioapi/package.py +++ b/pisi/scenarioapi/package.py @@ -21,7 +21,7 @@ from pisi.scenarioapi.withops import * import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext class Package: def __init__(self, name, deps = [], cons = [], date = "2006-18-18", ver = "1.0", partOf="None"): diff --git a/pisi/scenarioapi/pspec.py b/pisi/scenarioapi/pspec.py index 281b44c3..1862f41e 100644 --- a/pisi/scenarioapi/pspec.py +++ b/pisi/scenarioapi/pspec.py @@ -56,7 +56,7 @@ class Pspec: if type(dependencies[0]) == dict: dep = Dependency() (kw, dep.package) = dependencies - dep.__dict__[kw.keys()[0]] = kw.values()[0] + dep.__dict__[list(kw.keys())[0]] = list(kw.values())[0] self.package.packageDependencies.append(dep) return @@ -78,7 +78,7 @@ class Pspec: if type(conflicts[0]) == dict: conf = Conflict() (kw, conf.package) = conflicts - conf.__dict__[kw.keys()[0]] = kw.values()[0] + conf.__dict__[list(kw.keys())[0]] = list(kw.values())[0] self.package.conflicts.append(conf) return @@ -119,9 +119,9 @@ class Pspec: self.pspec.source.description["en"] = description def set_packager(self, name, email): - self.pspec.source.packager.name = unicode(name) + self.pspec.source.packager.name = str(name) self.pspec.source.packager.email = email - self.update.name = unicode(name) + self.update.name = str(name) self.update.email = email def add_archive(self, sha1sum, type, uri): diff --git a/pisi/scenarioapi/repoops.py b/pisi/scenarioapi/repoops.py index 14ea481e..3303fde9 100644 --- a/pisi/scenarioapi/repoops.py +++ b/pisi/scenarioapi/repoops.py @@ -19,12 +19,12 @@ from pisi.scenarioapi.constants import * import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext repodb = {} def repo_added_package(package, *args): - if repodb.has_key(package): + if package in repodb: raise Exception(_("Repo already has package named %s.") % package) version = "1.0" @@ -48,14 +48,14 @@ def repo_added_package(package, *args): repodb[package] = Package(package, dependencies, conflicts, ver=version, partOf=partOf) def repo_removed_package(package): - if not repodb.has_key(package): + if package not in repodb: raise Exception(_("Repo does not have package named %s.") % package) os.unlink(os.path.join(consts.repo_path, repodb[package].get_file_name())) del repodb[package] def repo_version_bumped(package, *args): - if not repodb.has_key(package): + if package not in repodb: raise Exception(_("Repo does not have package named %s.") % package) old_file = repodb[package].get_file_name() diff --git a/pisi/scenarioapi/withops.py b/pisi/scenarioapi/withops.py index 4bb7baad..5eb5b59a 100644 --- a/pisi/scenarioapi/withops.py +++ b/pisi/scenarioapi/withops.py @@ -11,8 +11,8 @@ # Please read the COPYING file. # -ADDED, REMOVED, INIT = range(3) -PARTOF, VERSION, CONFLICT, DEPENDENCY, REQUIRES = range(5) +ADDED, REMOVED, INIT = list(range(3)) +PARTOF, VERSION, CONFLICT, DEPENDENCY, REQUIRES = list(range(5)) class With: def __init__(self): @@ -58,12 +58,12 @@ def with_added_conflict(package, **kw): if not len(kw): return with_action(CONFLICT, ADDED, [package]) - if (kw.has_key("versionFrom") or - kw.has_key("versionTo") or - kw.has_key("version") or - kw.has_key("releaseFrom") or - kw.has_key("releaseTo") or - kw.has_key("release")): + if ("versionFrom" in kw or + "versionTo" in kw or + "version" in kw or + "releaseFrom" in kw or + "releaseTo" in kw or + "release" in kw): return with_action(CONFLICT, ADDED, [kw, package]) # pass other keywords. @@ -75,12 +75,12 @@ def with_added_dependency(package, **kw): if not len(kw): return with_action(DEPENDENCY, ADDED, [package]) - if (kw.has_key("versionFrom") or - kw.has_key("versionTo") or - kw.has_key("version") or - kw.has_key("releaseFrom") or - kw.has_key("releaseTo") or - kw.has_key("release")): + if ("versionFrom" in kw or + "versionTo" in kw or + "version" in kw or + "releaseFrom" in kw or + "releaseTo" in kw or + "release" in kw): return with_action(DEPENDENCY, ADDED, [kw, package]) # pass other keywords. diff --git a/pisi/signalhandler.py b/pisi/signalhandler.py index e876fc45..1522cfc2 100644 --- a/pisi/signalhandler.py +++ b/pisi/signalhandler.py @@ -32,12 +32,12 @@ class SignalHandler: self.signals[sig].pending = True def disable_signal(self, sig): - if sig not in self.signals.keys(): + if sig not in list(self.signals.keys()): self.signals[sig] = Signal(sig) signal.signal(sig, self.signal_handler) def enable_signal(self, sig): - if sig in self.signals.keys(): + if sig in list(self.signals.keys()): if self.signals[sig].oldhandler: oldhandler = self.signals[sig].oldhandler else: @@ -49,7 +49,7 @@ class SignalHandler: raise exception[sig] def signal_disabled(self, sig): - return sig in self.signals.keys() + return sig in list(self.signals.keys()) def signal_pending(self, sig): return self.signal_disabled(sig) and self.signals[sig].pending diff --git a/pisi/sourcearchive.py b/pisi/sourcearchive.py index ab39c0e0..e6fb0173 100644 --- a/pisi/sourcearchive.py +++ b/pisi/sourcearchive.py @@ -14,7 +14,7 @@ import os import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # pisi modules import pisi @@ -115,7 +115,7 @@ class SourceArchive: # check archive file's integrity if not util.check_file_hash(self.archiveFile, self.archive.sha1sum): - raise Error, _("unpack: check_file_hash failed") + raise Error(_("unpack: check_file_hash failed")) try: archive = pisi.archive.Archive(self.archiveFile, self.archive.type) diff --git a/pisi/specfile.py b/pisi/specfile.py index 9d1846ff..2a78d6d4 100644 --- a/pisi/specfile.py +++ b/pisi/specfile.py @@ -18,7 +18,7 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext # standard python modules import os.path @@ -39,9 +39,8 @@ import pisi.db class Error(pisi.Error): pass -__metaclass__ = autoxml.autoxml -class Packager: +class Packager(metaclass=autoxml.autoxml): t_Name = [autoxml.Text, autoxml.mandatory] t_Email = [autoxml.String, autoxml.mandatory] @@ -51,7 +50,7 @@ class Packager: return s -class AdditionalFile: +class AdditionalFile(metaclass=autoxml.autoxml): s_Filename = [autoxml.String, autoxml.mandatory] a_target = [autoxml.String, autoxml.mandatory] @@ -65,12 +64,12 @@ class AdditionalFile: s += '(%s)' % self.permission return s -class Type: +class Type(metaclass=autoxml.autoxml): s_type = [autoxml.String, autoxml.mandatory] a_package = [autoxml.String, autoxml.optional] -class Action: +class Action(metaclass=autoxml.autoxml): # Valid actions: # @@ -85,7 +84,7 @@ class Action: def __str__(self): return self.action -class Patch: +class Patch(metaclass=autoxml.autoxml): s_Filename = [autoxml.String, autoxml.mandatory] a_compressionType = [autoxml.String, autoxml.optional] @@ -105,7 +104,7 @@ class Patch: s += ' level:' + self.level return s -class Update: +class Update(metaclass=autoxml.autoxml): a_release = [autoxml.String, autoxml.mandatory] # 'type' attribute is here to keep backward compatibility @@ -126,7 +125,7 @@ class Update: s += ", type=" + self.type return s -class Path: +class Path(metaclass=autoxml.autoxml): s_Path = [autoxml.String, autoxml.mandatory] a_fileType = [autoxml.String, autoxml.optional] @@ -138,7 +137,7 @@ class Path: return s -class ComarProvide: +class ComarProvide(metaclass=autoxml.autoxml): s_om = [autoxml.String, autoxml.mandatory] a_script = [autoxml.String, autoxml.mandatory] @@ -150,7 +149,7 @@ class ComarProvide: s += ' (' + self.om + '%s' % (' for %s' % self.name if self.name else '') + ')' return s -class Archive: +class Archive(metaclass=autoxml.autoxml): s_uri = [ autoxml.String, autoxml.mandatory ] a_type = [ autoxml.String, autoxml.optional ] @@ -164,7 +163,7 @@ class Archive: s = _('URI: %s, type: %s, sha1sum: %s') % (self.uri, self.type, self.sha1sum) return s -class Source: +class Source(metaclass=autoxml.autoxml): t_Name = [autoxml.String, autoxml.mandatory] t_Homepage = [autoxml.String, autoxml.optional] @@ -187,7 +186,7 @@ class Source: def buildtimeDependencies(self): return self.buildDependencies -class AnyDependency: +class AnyDependency(metaclass=autoxml.autoxml): t_Dependencies = [[pisi.dependency.Dependency], autoxml.optional, "Dependency"] def __str__(self): @@ -223,7 +222,7 @@ class AnyDependency: return True return False -class Package: +class Package(metaclass=autoxml.autoxml): t_Name = [ autoxml.String, autoxml.mandatory ] t_Summary = [ autoxml.LocalText, autoxml.optional ] @@ -369,10 +368,10 @@ class Package: def __str__(self): s = _('Name: %s, version: %s, release: %s\n') \ % (self.name, self.version, self.release) - s += _('Summary: %s\n') % unicode(self.summary) - s += _('Description: %s\n') % unicode(self.description) - s += _('Licenses: %s\n') % u", ".join(self.license) - s += _('Component: %s\n') % unicode(self.partOf) + s += _('Summary: %s\n') % str(self.summary) + s += _('Description: %s\n') % str(self.description) + s += _('Licenses: %s\n') % ", ".join(self.license) + s += _('Component: %s\n') % str(self.partOf) s += _('Provides: ') for x in self.providesComar: s += x.om + ' ' @@ -387,8 +386,7 @@ class Package: return s + '\n' -class SpecFile(xmlfile.XmlFile): - __metaclass__ = autoxml.autoxml #needed when we specify a superclass +class SpecFile(xmlfile.XmlFile, metaclass=autoxml.autoxml): tag = "PISI" @@ -407,7 +405,7 @@ class SpecFile(xmlfile.XmlFile): deps += sum([x.dependencies for x in package.packageAnyDependencies], []) for dep in deps: - for attr_name, attr_value in dep.__dict__.items(): + for attr_name, attr_value in list(dep.__dict__.items()): if attr_value != "current": continue @@ -439,7 +437,7 @@ class SpecFile(xmlfile.XmlFile): return try: doc = piksemel.parse(path) - except Exception, e: + except Exception as e: raise Error(_("File '%s' has invalid XML") % (path) ) if doc.getTag("Source").getTagData("Name") == self.source.name: @@ -455,10 +453,10 @@ class SpecFile(xmlfile.XmlFile): def __str__(self): s = _('Name: %s, version: %s, release: %s\n') % ( self.source.name, self.history[0].version, self.history[0].release) - s += _('Summary: %s\n') % unicode(self.source.summary) - s += _('Description: %s\n') % unicode(self.source.description) - s += _('Licenses: %s\n') % u", ".join(self.source.license) - s += _('Component: %s\n') % unicode(self.source.partOf) + s += _('Summary: %s\n') % str(self.source.summary) + s += _('Description: %s\n') % str(self.source.description) + s += _('Licenses: %s\n') % ", ".join(self.source.license) + s += _('Component: %s\n') % str(self.source.partOf) s += _('Build Dependencies: ') for x in self.source.buildDependencies: s += x.package + ' ' diff --git a/pisi/ui.py b/pisi/ui.py index 31a77ba4..9645b01b 100644 --- a/pisi/ui.py +++ b/pisi/ui.py @@ -13,7 +13,7 @@ # (installed, upgraded, removed, installing, removing, configuring, configured, extracting, - downloading, packagestogo, updatingrepo, cached, desktopfile) = range(13) + downloading, packagestogo, updatingrepo, cached, desktopfile) = list(range(13)) class UI(object): "Abstract class for UI operations, derive from this." diff --git a/pisi/uri.py b/pisi/uri.py index df1e583e..3a3a1f8f 100644 --- a/pisi/uri.py +++ b/pisi/uri.py @@ -13,12 +13,12 @@ """Simplifies working with URLs, purl module provides common URL parsing and processing""" -import urlparse +import urllib.parse import os.path import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext class URI(object): """URI class provides a URL parser and simplifies working with @@ -47,7 +47,7 @@ class URI(object): def set_uri(self, uri): # (scheme, location, path, params, query, fragment) uri = str(uri) - u = urlparse.urlparse(uri, "file") + u = urllib.parse.urlparse(uri, "file") self.__scheme = u[0] self.__location = u[1] self.__path = u[2] @@ -75,7 +75,7 @@ class URI(object): def set_auth_info(self, authTuple): if not isinstance(authTuple, tuple): - raise Exception, _("setAuthInfo needs a tuple (user, pass)") + raise Exception(_("setAuthInfo needs a tuple (user, pass)")) self.__authinfo = authTuple def auth_info(self): diff --git a/pisi/util.py b/pisi/util.py index 185b5936..6768064c 100644 --- a/pisi/util.py +++ b/pisi/util.py @@ -22,15 +22,16 @@ import string import struct import fnmatch import hashlib -import statvfs import termios import operator import subprocess import unicodedata import gettext +from functools import reduce __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext + class Singleton(type): def __init__(cls, name, bases, dict): @@ -47,6 +48,7 @@ class Singleton(type): import pisi import pisi.context as ctx + class Error(pisi.Error): pass @@ -62,7 +64,7 @@ class FilePermissionDeniedError(Error): ######################### def any(pred, seq): - return reduce(operator.or_, map(pred, seq), False) + return reduce(operator.or_, list(map(pred, seq)), False) def flatten_list(l): """Flatten a list of lists.""" @@ -72,7 +74,7 @@ def flatten_list(l): def strlist(l): """Concatenate string reps of l's elements.""" - return "".join(map(lambda x: str(x) + ' ', l)) + return "".join([str(x) + ' ' for x in l]) def prefix(a, b): """Check if sequence a is a prefix of sequence b.""" @@ -171,6 +173,7 @@ def format_by_columns(strings, sep_width=2): return "\n".join(lines) + ############################## # Process Releated Functions # ############################## @@ -183,6 +186,7 @@ def search_executable(executable): return full_path return None + def run_batch(cmd): """Run command and report return value and output.""" ctx.ui.info(_('Running ') + cmd, verbose=True) @@ -190,7 +194,8 @@ def run_batch(cmd): stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() ctx.ui.debug(_('return value for "%s" is %s') % (cmd, p.returncode)) - return (p.returncode, out, err) + return p.returncode, out, err + # TODO: it might be worthwhile to try to remove the # use of ctx.stdout, and use run_batch()'s return @@ -219,6 +224,7 @@ def run_logged(cmd): return p.returncode + ###################### # Terminal functions # ###################### @@ -233,9 +239,10 @@ def get_terminal_size(): return struct.unpack("hh", ret) + def xterm_title(message): """Set message as console window title.""" - if os.environ.has_key("TERM") and sys.stderr.isatty(): + if "TERM" in os.environ and sys.stderr.isatty(): terminalType = os.environ["TERM"] for term in ["xterm", "Eterm", "aterm", "rxvt", "screen", "kterm", "rxvt-unicode"]: if terminalType.startswith(term): @@ -243,9 +250,10 @@ def xterm_title(message): sys.stderr.flush() break + def xterm_title_reset(): """Reset console window title.""" - if os.environ.has_key("TERM"): + if "TERM" in os.environ: xterm_title("") ############################# @@ -341,7 +349,7 @@ def dir_size(_dir): return os.path.getsize(_dir) if os.path.islink(_dir): - return long(len(read_link(_dir))) + return int(len(read_link(_dir))) def sizes(): for root, dirs, files in os.walk(_dir): @@ -368,13 +376,13 @@ def read_link(link): return os.path.normpath(os.readlink(link)) def is_ar_file(file_path): - return open(file_path).read(8) == '!\n' + return open(file_path, encoding='utf8', errors='ignore').read(8) == '!\n' def clean_ar_timestamps(ar_file): """Zero all timestamps in the ar files.""" if not is_ar_file(ar_file): return - content = open(ar_file).readlines() + content = open(ar_file, encoding='utf8', errors='ignore').readlines() fp = open(ar_file, 'w') for line in content: pos = line.rfind(chr(32) + chr(96)) @@ -416,7 +424,7 @@ def get_file_hashes(top, excludePrefix=None, removePrefix=None): if excludePrefix: temp = remove_prefix(removePrefix, path) while temp != "/": - if len(filter(lambda x: fnmatch.fnmatch(temp, x), excludePrefix)) > 0: + if len([x for x in excludePrefix if fnmatch.fnmatch(temp, x)]) > 0: return False temp = os.path.dirname(temp) return True @@ -474,7 +482,7 @@ def sha1_file(filename): # we wont have two allocated blocks with same size del block return m.hexdigest() - except IOError, e: + except IOError as e: if e.errno == 13: # Permission denied, the file doesn't have read permissions, skip raise FilePermissionDeniedError(_("You don't have necessary read permissions")) @@ -484,7 +492,7 @@ def sha1_file(filename): def sha1_data(data): """Calculate sha1 hash of given data.""" m = hashlib.sha1() - m.update(data) + m.update(data.encode()) return m.hexdigest() def uncompress(patchFile, compressType="gz", targetDir=""): @@ -496,7 +504,7 @@ def uncompress(patchFile, compressType="gz", targetDir=""): archive = pisi.archive.Archive(patchFile, compressType) try: archive.unpack(targetDir) - except Exception, msg: + except Exception as msg: raise Error(_("Error while decompressing %s: %s") % (patchFile, msg)) # FIXME: Get file path from Archive instance @@ -604,7 +612,7 @@ def strip_file(filepath, fileinfo, outpath): def partition_freespace(directory): """Return free space of given directory's partition.""" st = os.statvfs(directory) - return st[statvfs.F_BSIZE] * st[statvfs.F_BFREE] + return st.f_bsize * st.f_bfree ######################################## # Package/Repository Related Functions # @@ -780,7 +788,7 @@ def filter_latest_packages(package_paths): name, version = parse_package_name(os.path.basename(path[:-len(ctx.const.package_suffix)])) - if latest.has_key(name): + if name in latest: l_version, l_release, l_build = split_version(latest[name][1]) r_version, r_release, r_build = split_version(version) @@ -811,11 +819,11 @@ def filter_latest_packages(package_paths): if version: latest[name] = (path, version) - return map(lambda x: x[0], latest.values()) + return [x[0] for x in list(latest.values())] def colorize(msg, color): """Colorize the given message for console output""" - if ctx.const.colors.has_key(color) and not ctx.get_option('no_color'): + if color in ctx.const.colors and not ctx.get_option('no_color'): return ctx.const.colors[color] + msg + ctx.const.colors['default'] else: return msg @@ -844,8 +852,8 @@ def rmdirs(dirpath): def letters(): start = end = None result = [] - for index in xrange(sys.maxunicode + 1): - c = unichr(index) + for index in range(sys.maxunicode + 1): + c = chr(index) if unicodedata.category(c)[0] == 'L': if start is None: start = end = c diff --git a/pisi/version.py b/pisi/version.py index 1cfddae3..2a50663d 100644 --- a/pisi/version.py +++ b/pisi/version.py @@ -14,7 +14,7 @@ import gettext __trans = gettext.translation('pisi', fallback=True) -_ = __trans.ugettext +_ = __trans.gettext import pisi @@ -48,17 +48,17 @@ def make_version(version): if "a" <= suffix <= "s": for keyword, value in __keywords: if suffix.startswith(keyword): - return map(__make_version_item, ver.split(".")), value, \ - map(__make_version_item, suffix[len(keyword):].split(".")) + return list(map(__make_version_item, ver.split("."))), value, \ + list(map(__make_version_item, suffix[len(keyword):].split("."))) else: # Probably an invalid version string. Reset ver string # to raise an exception in __make_version_item function. ver = "" else: - return map(__make_version_item, ver.split(".")), 0, \ - map(__make_version_item, suffix.split(".")) + return list(map(__make_version_item, ver.split("."))), 0, \ + list(map(__make_version_item, suffix.split("."))) - return map(__make_version_item, ver.split(".")), 0, [(0, None)] + return list(map(__make_version_item, ver.split("."))), 0, [(0, None)] except ValueError: raise InvalidVersionError(_("Invalid version string: '%s'") % version) @@ -83,37 +83,37 @@ class Version(object): return self.__version_string def compare(self, ver): - if isinstance(ver, basestring): + if isinstance(ver, str): return cmp(self.__version, make_version(ver)) return cmp(self.__version, ver.__version) def __lt__(self, rhs): - if isinstance(rhs, basestring): + if isinstance(rhs, str): return self.__version < make_version(rhs) return self.__version < rhs.__version def __le__(self, rhs): - if isinstance(rhs, basestring): + if isinstance(rhs, str): return self.__version <= make_version(rhs) return self.__version <= rhs.__version def __gt__(self, rhs): - if isinstance(rhs, basestring): + if isinstance(rhs, str): return self.__version > make_version(rhs) return self.__version > rhs.__version def __ge__(self, rhs): - if isinstance(rhs, basestring): + if isinstance(rhs, str): return self.__version >= make_version(rhs) return self.__version >= rhs.__version def __eq__(self, rhs): - if isinstance(rhs, basestring): + if isinstance(rhs, str): return self.__version_string == rhs return self.__version_string == rhs.__version_string diff --git a/scenarios/run.py b/scenarios/run.py index cc624856..a739e157 100755 --- a/scenarios/run.py +++ b/scenarios/run.py @@ -30,14 +30,14 @@ def run_scen(scenario): scenario() def run_all(): - print '** Running all scenarios' + print('** Running all scenarios') for root, dirs, files in os.walk("."): - scensources = filter(lambda x:x.endswith('scen.py'), files) + scensources = [x for x in files if x.endswith('scen.py')] for scensource in scensources: clean_out() running = "\n* Running scenario in %s\n" % scensource - print running - print len(running) * "=" + "\n" + print(running) + print(len(running) * "=" + "\n") module = __import__(scensource[:len(scensource)-3]) run_scen(module.run) @@ -50,7 +50,7 @@ if __name__ == "__main__": for scen in scens: clean_out() scen += 'scen.py' - print "\n* Running scenario in %s\n" % scen + print("\n* Running scenario in %s\n" % scen) module = __import__(scen[:len(scen)-3]) run_scen(module.run) else: diff --git a/scripts/check-newconfigs.py b/scripts/check-newconfigs.py index 0392204b..bf367e15 100755 --- a/scripts/check-newconfigs.py +++ b/scripts/check-newconfigs.py @@ -20,7 +20,7 @@ installdb = pisi.db.installdb.InstallDB() def ask_action(msg, actions, default): while True: - s = raw_input(msg) + s = eval(input(msg)) if len(s) == 0: return default else: @@ -35,8 +35,8 @@ def get_installed_packages(): def check_changed_config_files(package): all_files = installdb.get_files(package) - config_files = filter(lambda x: x.type == 'config', all_files.list) - config_paths = map(lambda x: "/" + str(x.path), config_files) + config_files = [x for x in all_files.list if x.type == 'config'] + config_paths = ["/" + str(x.path) for x in config_files] newconfig = [] for path in config_paths: @@ -75,7 +75,7 @@ def check_changes(): if __name__ == "__main__": if len(sys.argv) == 1: - print "Checking all packages" + print("Checking all packages") check_changes() if len(sys.argv) == 2: check_package(sys.argv[1]) diff --git a/scripts/cleanArchives.py b/scripts/cleanArchives.py index 62261b5d..1c736e3d 100755 --- a/scripts/cleanArchives.py +++ b/scripts/cleanArchives.py @@ -35,7 +35,7 @@ if __name__ == "__main__": try: packages = scanPSPEC(sys.argv[1]) except: - print "Usage: cleanArchives.py path2repo" + print("Usage: cleanArchives.py path2repo") sys.exit(1) if "--dry-run" in sys.argv: @@ -54,10 +54,10 @@ if __name__ == "__main__": files.append(URI.filename()) archiveFiles = os.listdir("/var/cache/pisi/archives/") - unneededFiles = filter(lambda x:x not in files, archiveFiles) + unneededFiles = [x for x in archiveFiles if x not in files] for i in unneededFiles: if not clean: - print("/var/cache/pisi/archives/%s" % i) + print(("/var/cache/pisi/archives/%s" % i)) else: cleanArchives("/var/cache/pisi/archives/%s" % i) diff --git a/scripts/cleanCache.py b/scripts/cleanCache.py index 647676e7..54268a1c 100755 --- a/scripts/cleanCache.py +++ b/scripts/cleanCache.py @@ -23,7 +23,7 @@ def findUnneededFiles(listdir): for f in listdir: try: name, version = util.parse_package_name(f) - if dict.has_key(name): + if name in dict: if Version(dict[name]) < Version(version): dict[name] = version else: @@ -42,20 +42,20 @@ def doit(root, listdir, clean, suffix = ""): for f in listdir: target = os.path.join(root, "%s%s" % (f, suffix)) if os.path.exists(target): - print "%s%s" % (f, suffix) + print(("%s%s" % (f, suffix))) if clean == True: try: if os.path.isdir(target): shutil.rmtree(target) else: os.remove(target) - except OSError,e : + except OSError as e : usage("Permission denied: %s" % e) def cleanPisis(clean, root = '/var/cache/pisi/packages'): # pisi packages - list = map(lambda x: os.path.basename(x).split(".pisi")[0], glob.glob("%s/*.pisi" % root)) + list = [os.path.basename(x).split(".pisi")[0] for x in glob.glob("%s/*.pisi" % root)] list.sort() l = findUnneededFiles(list) doit(root, l, clean, ".pisi") @@ -71,13 +71,13 @@ def cleanBuilds(clean, root = '/var/pisi'): doit(root, l, clean) def usage(msg): - print """ + print((""" Error: %s Usage: cleanCache --dry-run (Shows unneeded files) cleanCache --clean (Removes unneeded files) - """ % msg + """ % msg)) sys.exit(1) diff --git a/scripts/createdelta.py b/scripts/createdelta.py index 7b629217..836362ee 100644 --- a/scripts/createdelta.py +++ b/scripts/createdelta.py @@ -19,7 +19,7 @@ from pisi.delta import create_delta_package def minsandmaxes(): - packages = map(lambda x: os.path.basename(x).split(".pisi")[0], set(glob.glob("*.pisi")) - set(glob.glob("*.delta.pisi"))) + packages = [os.path.basename(x).split(".pisi")[0] for x in set(glob.glob("*.pisi")) - set(glob.glob("*.delta.pisi"))] versions = {} for file in packages: @@ -28,7 +28,7 @@ def minsandmaxes(): mins = {} maxs = {} - for pkg in versions.keys(): + for pkg in list(versions.keys()): mins[pkg] = min(versions[pkg]) maxs[pkg] = max(versions[pkg]) @@ -37,7 +37,7 @@ def minsandmaxes(): if __name__ == "__main__": mi, ma = minsandmaxes() - for pkg in mi.keys(): + for pkg in list(mi.keys()): old_pkg = "%s-%s.pisi" % (pkg, str(mi[pkg])) new_pkg = "%s-%s.pisi" % (pkg, str(ma[pkg])) name, version = util.parse_package_name(pkg) @@ -46,5 +46,5 @@ if __name__ == "__main__": # skip if same if not os.path.exists("%s-%s-%s.delta.pisi" % (name, str(mi[pkg].build), str(ma[pkg].build))): # skip if delta exists - print "%s --> Min: %s Max: %s \n %s-%s-%s.delta.pisi" % (pkg, old_pkg, new_pkg, name, str(mi[pkg].build), str(ma[pkg].build)) + print(("%s --> Min: %s Max: %s \n %s-%s-%s.delta.pisi" % (pkg, old_pkg, new_pkg, name, str(mi[pkg].build), str(ma[pkg].build)))) create_delta_package(old_pkg, new_pkg) diff --git a/scripts/fix_old_metadata_files.py b/scripts/fix_old_metadata_files.py index ed1305d1..558d1803 100755 --- a/scripts/fix_old_metadata_files.py +++ b/scripts/fix_old_metadata_files.py @@ -56,6 +56,6 @@ def findMetadata(): for file in findMetadata(): if saveMetadata(fixMetadata(file), file): - print "Güncellendi : ", file + print(("Güncellendi : ", file)) else: - print "Hiç bir şey yapılmadı: ", file + print(("Hiç bir şey yapılmadı: ", file)) diff --git a/scripts/lspisi b/scripts/lspisi index 3a7b042c..7e143b31 100755 --- a/scripts/lspisi +++ b/scripts/lspisi @@ -26,13 +26,13 @@ def uniq(alist): return [set.setdefault(e, e) for e in alist if e not in set] def usage(errmsg): - print """ + print(""" Error: %s Usage: lspisi PiSi_package.PiSi (lists the content of package) lspisi dirs PiSi_package.PiSi (lists directories in the package for the package developer) - """ % (errmsg) + """ % (errmsg)) sys.exit(1) @@ -47,14 +47,14 @@ def main(): dirlist.append(os.path.dirname(file)) for dir in uniq(dirlist): - print "/%s" % dir + print("/%s" % dir) elif not os.path.exists(sys.argv[1]): - print "File %s not found" % sys.argv[1] + print("File %s not found" % sys.argv[1]) else: for file in show_info(sys.argv[1]): - print "/%s" % file + print("/%s" % file) if __name__ == "__main__": sys.exit(main()) diff --git a/scripts/make-changelog.py b/scripts/make-changelog.py index f022e058..11fd8f70 100755 --- a/scripts/make-changelog.py +++ b/scripts/make-changelog.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- import os -import urllib2 +import urllib.request, urllib.error, urllib.parse import piksemel @@ -12,7 +12,7 @@ authors = {} def get_author_name_mail(author): if not authors: - accounts = urllib2.urlopen(accounts_url) + accounts = urllib.request.urlopen(accounts_url) for line in accounts: if line.startswith("#"): continue diff --git a/scripts/newpisipackage b/scripts/newpisipackage index c139214b..05427067 100755 --- a/scripts/newpisipackage +++ b/scripts/newpisipackage @@ -175,11 +175,11 @@ temp_translation = ''' def write(filename, data): try: - f = file("%s/%s" % (target, filename), "w") + f = open("%s/%s" % (target, filename), "w") f.write(data) f.close() except: - print "Could not write file %s/%s" % (target, filename) + print("Could not write file %s/%s" % (target, filename)) def create_dirs(): @@ -187,7 +187,7 @@ def create_dirs(): os.makedirs("%s/files" % target) os.makedirs("%s/comar" % target) except: - print "Could not make directory %s" % target + print("Could not make directory %s" % target) sys.exit(1) def readConfig(): @@ -196,7 +196,7 @@ def readConfig(): d = {"name": "", "email": ""} if home != "" and os.path.exists(cfg): - for line in file(cfg): + for line in open(cfg): if line != "" and not line.startswith("#") and "=" in line: l, m = line.split("=", 1) k = l.strip() @@ -210,7 +210,7 @@ def readConfig(): # some checks if len(sys.argv) < 2: - print "Usage : %s NewPackageDir" % sys.argv[0] + print("Usage : %s NewPackageDir" % sys.argv[0]) sys.exit(0) else: target = sys.argv[1] @@ -218,10 +218,10 @@ else: data["package_cap"] = string.capitalize(data["package"]) if os.path.exists(target): - print "%s already exists, please remove it first" % target + print("%s already exists, please remove it first" % target) sys.exit(1) elif " " in data["package"]: - print "You should not use empty space in package name" + print("You should not use empty space in package name") sys.exit(1) # here we go diff --git a/scripts/package-signing/pisi-key.py b/scripts/package-signing/pisi-key.py index f4fbd448..581a012f 100644 --- a/scripts/package-signing/pisi-key.py +++ b/scripts/package-signing/pisi-key.py @@ -1,239 +1 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# -# pisi-key script adopted from apt-key -# -# Author : Serdar Dalgic - serdar AT pardus DOT org DOT tr -# Any comments are welcomed -# -# TODO: -# * a python wrapper for GPG can be used instead of using python's subprocess module -# * Fill in rest of the functions -# WARNING!! Still a prototype -# - -import sys -import os -import subprocess - -# We don't use a secret keyring, of course, but gpg panics and -# implodes if there isn't one available -GPG_CMD = 'gpg --ignore-time-conflict --no-options --no-default-keyring \ - --secret-keyring /etc/pisi/secring.gpg --trustdb-name /etc/pisi/trustdb.gpg' - -GPG = GPG_CMD - -MASTER_KEYRING = '' -ARCHIVE_KEYRING_URI = '' -# MASTER_KEYRING = '/usr/share/keyrings/pardus-master-keyring.gpg' -# ARCHIVE_KEYRING_URI = 'http://ftp.pardus.org.tr/pardus/pardus-archive-keyring.gpg' - -ARCHIVE_KEYRING='/usr/share/keyrings/pardus-archive-keyring.gpg' -REMOVED_KEYS='/usr/share/keyrings/pardus-archive-removed-keys.gpg' - -def addKey(GPG, keyfile): - """ add the key """ - - cmd = GPG + ' --quiet --batch --import %s' % keyfile - print "cmd: " + cmd - pass - pipe = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) - return pipe.wait() == 0 - -def removeKey(GPG, keyfile): - """ remove the key """ - - cmd = GPG + ' --quiet --batch --delete-key --yes %s' % keyfile - print "cmd: " + cmd - pass - pipe = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) - return pipe.wait() == 0 - -def update(GPG): - """ update keys using the keyring package: - - we do not use add_keys_with_verify_against_master_keyring here, - because "update" is run on regular package updates. An - attacker might as well replace the master-archive-keyring file - in the package and add his own keys. so this check wouldn't - add any security. we *need* this check on net-update though """ - - if not os.access(ARCHIVE_KEYRING, os.F_OK): - print "ERROR: Can't find the archive-keyring" - print "Is the pisi-archive-keyring package installed?" - sys.exit(1) - - cmd = GPG_CMD + ' --quiet --batch --keyring %s --export | %s --import' % (ARCHIVE_KEYRING, GPG) - print "cmd: " + cmd - pass - pipe = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) - if not pipe.wait() == 0: - print "An error occured, inform the maintainer about this issue" - sys.exit(1) - - if os.access(REMOVED_KEYS, os.R_OK): - # remove no-longer supported/used keys - cmd = '%s --keyring %s --with-colons --list-keys | grep ^pub | cut -d: -f5' % (GPG_CMD, REMOVED_KEYS) - pipe = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) - keys = pipe.stdout.read() - for key in keys: - cmd = '%s --list-keys --with-colons | grep ^pub | cut -d: -f5 | grep -q %s' % (GPG, key) - pipe = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) - if pipe.stdout.read(): - cmd = '%s --quiet --batch --delete-key --yes %s' % (GPG, key) - else: - print "Warning: removed keys keyring %s missing or not readable" % REMOVED_KEYS - sys.exit(1) - - -def net_update(): - """ update the current archive signing keyring from a network URI: - the archive-keyring keys needs to be signed with the master key - (otherwise it does not make sense from a security POV) """ - if len(ARCHIVE_KEYRING_URI) == 0: - print "Error: no location for the archive-keyring given" - sys.exit(1) - - #TODO: Network connection should be checked!! - if not os.path.isdir("/var/lib/pisi/keyrings"): - os.mkdir("/var/lib/pisi/keyrings") - - keyring = "/var/lib/pisi/keyrings/%s" ARCHIVE_KEYRING.split("/")[-1] - if os.path.exists(keyring): - old_mtime = os.stat(keyring).st_mtime - else: - old_mtime = 0 - - pass - -def list_keys(GPG): - """ list keys """ - cmd = GPG + ' --batch --list_keys' - print "cmd: " + cmd - pass - pipe = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) - return pipe.wait() == 0 - -def list_fingerprints(GPG): - """ list fingerprints """ - cmd = GPG + ' --batch --fingerprint' - print "cmd: " + cmd - pass - pipe = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) - return pipe.wait() == 0 - -def export(GPG, keyid): - """ output the key with the """ - cmd = GPG + ' --armor --export %s' keyid - print "cmd: " + cmd - pass - pipe = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) - return pipe.wait() == 0 - -def exportAll(GPG): - """ output all trusted keys """ - cmd = GPG + ' --armor --export' - print "cmd: " + cmd - pipe = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) - return pipe.wait() == 0 - -def printUsage(): - """ - Prints usage information of application and exits. - """ - - print "Usage: pisi-key [--keyring file] [command] [arguments]" - print - print "Manage pisi's list of trusted keys" - print - print " pisi-key add - add the key contained in ('-' for stdin)" - print " pisi-key del - remove the key " - print " pisi-key export - output the key " - print " pisi-key exportall - output all trusted keys" - print " pisi-key update - update keys using the keyring package" - print " pisi-key net-update - update keys using the network" - print " pisi-key list - list keys" - print " pisi-key finger - list fingerprints" - print " pisi-key adv - pass advanced options to gpg (download key)" - print - print "If no specific keyring file is given the command applies to all keyring files." - sys.exit(1) - -if __name__ == '__main__': - - if len(sys.argv) < 2: - printUsage() - sys.exit(1) - - argc=1 - #FIXME:: check whether gnupg is installed on the system or not!! - - # Determine on which keyring we want to work - # if sys.argv[1] == '--keyring': - if sys.argv[argc] == '--keyring': - # keyring is the TRUSTEDFILE - argc += 1 # becomes 2 - keyring = sys.argv[argc] - if not os.access(keyring, F_OK): - print "Error: The specified keyring %s is missing or not readable" % keyring - sys.exit(1) - - argc += 1 # becomes 3 - operation = sys.argv[argc] - GPG += ' --keyring %s --primary-keyring %s' % (keyring, keyring) - argc += 1 # becomes 4 - - else: - # otherwise use the default - keyring = '/etc/pisi/trusted.gpg' - if os.access(keyring, os.F_OK): - GPG += ' --keyring %s' % keyring - GPG += ' --primary-keyring %s' % keyring - #NOTICE:: TRUSTEDPARTS is not implemented. - operation = sys.argv[argc] - argc += 1 # becomes 2 - - # print 'COMMAND: %s' % GPG - - if operation == 'help': - printUsage() - sys.exit(0) - - elif operation == 'add': - keyfile = sys.argv[argc] - # TODO: check whether key_path is alive ('-' can be used for stdin) e.g. gpg --keyring pisi-keyring.gpg --armour --export 102030AB | pisi-key add - - addKey(GPG, keyfile) - print "Key in %s is succesfully added." % keyfile - - elif operation == 'del': - keyfile = sys.argv[argc] - removeKey(GPG, keyfile) - print "Key in %s is succesfully deleted." % keyfile - - elif operation == 'update': - update(GPG) - - elif operation == 'net-update': - net_update() - - elif operation == 'list': - list_keys(GPG) - - elif operation == 'finger': - list_fingerprints(GPG) - - elif operation == 'export': - keyid = sys.argv[argc] - export(GPG, keyid) - - elif operation == 'exportall': - exportAll(GPG) - - elif operation == 'adv': - adv_command = GPG + ' ' + sys.args[3:] - print 'Executing: ' + adv_command - # TODO: execute - pass - else: - printUsage() - +Non \ No newline at end of file diff --git a/scripts/package-signing/pisign.py b/scripts/package-signing/pisign.py index f33b5e44..c48ac826 100755 --- a/scripts/package-signing/pisign.py +++ b/scripts/package-signing/pisign.py @@ -24,13 +24,13 @@ EXT_SIGN = 'sig' EXT_CERT = 'crt' # Signature validity -SIGN_OK, SIGN_NO, SIGN_SELF, SIGN_UNTRUSTED, SIGN_CORRUPTED = range(5) +SIGN_OK, SIGN_NO, SIGN_SELF, SIGN_UNTRUSTED, SIGN_CORRUPTED = list(range(5)) # Certificate validity -CERT_OK, CERT_SELF, CERT_CORRUPTED = range(3) +CERT_OK, CERT_SELF, CERT_CORRUPTED = list(range(3)) # Certificate trustworthiness -CERT_TRUSTED, CERT_UNTRUSTED = range(2) +CERT_TRUSTED, CERT_UNTRUSTED = list(range(2)) def sign_data(data, key_file, password_fd): """ @@ -333,15 +333,15 @@ def sign_file(filename, key_file, cert_file, password_fd): cert_file: Certificate password_fd: File that contains passphrase """ - data = file(filename).read() + data = open(filename).read() signed_binary = sign_data(data, key_file, password_fd) - cert_data = file(cert_file).read() + cert_data = open(cert_file).read() # Save certificate - file('%s.%s' % (filename, EXT_CERT), 'w').write(cert_data) + open('%s.%s' % (filename, EXT_CERT), 'w').write(cert_data) # Save signed data - file('%s.%s' % (filename, EXT_SIGN), 'w').write(signed_binary) + open('%s.%s' % (filename, EXT_SIGN), 'w').write(signed_binary) def sign_zipfile(filename, key_file, cert_file, password_fd): """ @@ -361,7 +361,7 @@ def sign_zipfile(filename, key_file, cert_file, password_fd): signed_ascii = base64.b64encode(signed_binary) # Encode certificate - cert_data = file(cert_file).read() + cert_data = open(cert_file).read() cert_ascii = base64.b64encode(cert_data) # Add signed data as ZIP comment @@ -376,9 +376,9 @@ def print_usage(): Prints usage information of application and exits. """ - print "Usage:" - print " %s sign " % sys.argv[0] - print " %s verify " % sys.argv[0] + print("Usage:") + print((" %s sign " % sys.argv[0])) + print((" %s verify " % sys.argv[0])) sys.exit(1) def main(): @@ -410,7 +410,7 @@ def main(): sign_zipfile(filename, key_file, cert_file, password_fd) else: sign_file(filename, key_file, cert_file, password_fd) - print "Signed %s with %s" % (filename, key_file) + print(("Signed %s with %s" % (filename, key_file))) # Destroy temporary file password_fd.close() @@ -430,15 +430,15 @@ def main(): else: result = verify_file(filename, trust_dir) if result == SIGN_OK: - print "%s is signed by a trusted source." % filename + print(("%s is signed by a trusted source." % filename)) elif result == SIGN_NO: - print "%s is unsigned." % filename + print(("%s is unsigned." % filename)) elif result == SIGN_SELF: - print "%s is self-signed by a trusted source." % filename + print(("%s is self-signed by a trusted source." % filename)) elif result == SIGN_UNTRUSTED: - print "%s is signed by an untrusted source." % filename + print(("%s is signed by an untrusted source." % filename)) else: - print "%s is corrupted." % filename + print(("%s is corrupted." % filename)) else: print_usage() diff --git a/scripts/pisi-sandbox b/scripts/pisi-sandbox index c0d3d7ca..92b5b146 100755 --- a/scripts/pisi-sandbox +++ b/scripts/pisi-sandbox @@ -21,7 +21,7 @@ import getopt def chroot_comar(image_dir): if os.fork() == 0: try: - os.makedirs(os.path.join(image_dir, "var/db"), 0700) + os.makedirs(os.path.join(image_dir, "var/db"), 0o700) except OSError: pass os.chroot(image_dir) @@ -45,10 +45,10 @@ def chroot_comar(image_dir): # run command and terminate if something goes wrong def run(cmd, ignore_error=False): - print cmd + print(cmd) ret = os.system(cmd) if ret and not ignore_error: - print "%s returned %s" % (cmd, ret) + print("%s returned %s" % (cmd, ret)) sys.exit(1) def create_sandbox(output_dir, repository): @@ -66,11 +66,11 @@ def create_sandbox(output_dir, repository): run('cp -p "%s" "%s"' % (os.path.join(path, name), os.path.join(path2, name))) # Create character device - os.mknod("%s/dev/null" % output_dir, 0666 | stat.S_IFCHR, os.makedev(1, 3)) - os.mknod("%s/dev/console" % output_dir, 0666 | stat.S_IFCHR, os.makedev(5, 1)) + os.mknod("%s/dev/null" % output_dir, 0o666 | stat.S_IFCHR, os.makedev(1, 3)) + os.mknod("%s/dev/console" % output_dir, 0o666 | stat.S_IFCHR, os.makedev(5, 1)) # Create urandom character device - os.mknod("%s/dev/urandom" % output_dir, 0666 | stat.S_IFCHR, os.makedev(1, 9)) + os.mknod("%s/dev/urandom" % output_dir, 0o666 | stat.S_IFCHR, os.makedev(1, 9)) # run command in chroot def chrun(cmd): @@ -85,7 +85,7 @@ def create_sandbox(output_dir, repository): chrun("/usr/bin/hav call baselayout User.Manager setUser 0 'Root' '/root' '/bin/bash' 'pardus' '' ") # Now it is 2011 release - file(os.path.join(output_dir, "etc/pardus-release"), "w").write("Pardus 2011\n") + open(os.path.join(output_dir, "etc/pardus-release"), "w").write("Pardus 2011\n") except KeyboardInterrupt: run('umount %s/proc' % output_dir, ignore_error=True) diff --git a/scripts/pisisdr b/scripts/pisisdr index 50302769..59864128 100755 --- a/scripts/pisisdr +++ b/scripts/pisisdr @@ -19,10 +19,10 @@ import pisi import pisi.context as ctx def usage(): - print """ + print(""" Usage: pisisdr reponame - """ + """) sys.exit(1) def main(): @@ -33,8 +33,8 @@ def main(): try: ctx.repodb.set_default_repo(repo) - except pisi.lockeddbshelve.Error, e: - print e + except pisi.lockeddbshelve.Error as e: + print(e) if __name__ == "__main__": sys.exit(main()) diff --git a/scripts/svndist-v0.2.py b/scripts/svndist-v0.2.py index 1029f46f..d029b592 100755 --- a/scripts/svndist-v0.2.py +++ b/scripts/svndist-v0.2.py @@ -17,7 +17,7 @@ import pisi from optparse import OptionParser def run(cmd): - print 'running', cmd + print(('running', cmd)) os.system(cmd) if __name__ == "__main__": @@ -48,7 +48,7 @@ if __name__ == "__main__": (opts, args) = parser.parse_args() - print 'Exporting svn directory' + print('Exporting svn directory') if not os.path.exists(opts.svndist): os.makedirs(opts.svndist) @@ -78,5 +78,5 @@ if __name__ == "__main__": time = datetime.datetime.now() os.rename('pisi-r%s.tar.bz2' % opts.rev , 'pisi-r%s-%s.%s.%s.tar.bz2' % (opts.rev, time.year, time.month, time.day)) - print 'Have a look at %s directory' % opts.svndist + print(('Have a look at %s directory' % opts.svndist)) diff --git a/scripts/svndist.py b/scripts/svndist.py index dfc3896c..8db9a1a3 100755 --- a/scripts/svndist.py +++ b/scripts/svndist.py @@ -9,7 +9,7 @@ import os import shutil def run(cmd): - print 'running', cmd + print(('running', cmd)) os.system(cmd) sys.path.insert(0, '.') @@ -22,10 +22,10 @@ ver = pisi.__version__ if os.path.exists('svndist/pisi-%s' % ver): shutil.rmtree('svndist/pisi-%s' % ver) -print 'Exporting svn directory' +print('Exporting svn directory') run('svn export http://svn.uludag.org.tr/uludag/trunk/pisi svndist/pisi-%s' % ver) os.chdir('svndist') run('tar cjvf pisi-%s.tar.bz2 pisi-%s' % (ver, ver)) -print 'Have a look at svndist directory' +print('Have a look at svndist directory') diff --git a/scripts/unpisi b/scripts/unpisi index 8a69691f..8e3aed29 100755 --- a/scripts/unpisi +++ b/scripts/unpisi @@ -16,13 +16,14 @@ from zipfile import BadZipfile from pisi.package import Package + def usage(errmsg): - print """ + print(""" Error: %s Usage: unpisi PiSi_package.pisi [target_dir] - """ % (errmsg) + """ % (errmsg)) sys.exit(1) @@ -36,8 +37,8 @@ def main(): try: package = Package(sys.argv[1]) - except BadZipfile, e: - print e + except BadZipfile as e: + print(e) sys.exit(1) if not os.path.exists("install"): @@ -53,10 +54,11 @@ def main(): package.extract_install(os.path.join(target, 'install')) # FIXME: There is a Pisi bug, it already creates an install directory even its empty. - if os.listdir('install') == []: + if not os.listdir('install'): os.rmdir('install') return 0 + if __name__ == "__main__": sys.exit(main()) diff --git a/setup.py b/setup.py index 0d5b2c92..bfecf49d 100755 --- a/setup.py +++ b/setup.py @@ -77,7 +77,7 @@ class BuildPo(build): # Update PO files for item in glob.glob1("po", "*.po"): - print "Updating .. ", item + print("Updating .. ", item) os.system("msgmerge --update --no-wrap --sort-by-file po/%s po/%s.pot" % (item, PROJECT)) # Cleanup @@ -103,7 +103,7 @@ class Install(install): if not name.endswith('.po'): continue lang = name[:-3] - print "Installing '%s' translations..." % lang + print("Installing '%s' translations..." % lang) os.popen("msgfmt po/%s.po -o po/%s.mo" % (lang, lang)) if not self.root: self.root = "/" @@ -118,7 +118,7 @@ class Install(install): os.makedirs(destpath) os.chdir('doc') for pdf in glob.glob('*.pdf'): - print 'Installing', pdf + print('Installing', pdf) shutil.copy(pdf, os.path.join(destpath, pdf)) os.chdir('..') @@ -153,22 +153,20 @@ class Install(install): pisiconf.write('\n') - -setup(name="pisi", - version= pisi.__version__, +setup( + name="pisi", + version=pisi.__version__, description="PiSi (Packages Installed Successfully as Intended)", long_description="PiSi is the package management system of Pardus Linux.", license="GNU GPL2", author="Pardus Developers", author_email="pisi@pardus.org.tr", url="http://www.pardus.org.tr/eng/pisi/", - package_dir = {'': ''}, - packages = ['pisi', 'pisi.cli', 'pisi.operations', 'pisi.actionsapi', 'pisi.pxml', 'pisi.scenarioapi', 'pisi.db'], - scripts = ['pisi-cli', 'scripts/lspisi', 'scripts/unpisi', 'scripts/check-newconfigs.py', 'scripts/revdep-rebuild'], - cmdclass = {'build' : Build, - 'build_po' : BuildPo, - 'install' : Install} - ) + package_dir={'': ''}, + packages=['pisi', 'pisi.cli', 'pisi.operations', 'pisi.actionsapi', 'pisi.pxml', 'pisi.scenarioapi', 'pisi.db'], + scripts=['pisi-cli', 'scripts/lspisi', 'scripts/unpisi', 'scripts/check-newconfigs.py', 'scripts/revdep-rebuild'], + cmdclass={'build': Build, 'build_po': BuildPo, 'install': Install} +) # the below stuff is really nice but we already have a version # we can use this stuff for svn snapshots in a separate @@ -176,6 +174,7 @@ setup(name="pisi", PISI_VERSION = pisi.__version__ + def getRevision(): import os try: @@ -190,6 +189,7 @@ def getRevision(): # doesn't working in a Subversion directory return None + def getVersion(): rev = getRevision() if rev: diff --git a/tests/constanttest.py b/tests/constanttest.py index 1a1ed695..1ab38748 100644 --- a/tests/constanttest.py +++ b/tests/constanttest.py @@ -8,7 +8,7 @@ class ConstantTestCase(unittest.TestCase): constants = ctx.const constDict = {"actions": "actions.py", "setup":"setup","metadata":"metadata.xml"} - for i in constDict.keys(): + for i in list(constDict.keys()): if hasattr(constants,i): value = getattr(constants,i) self.assertEqual(value, constDict[i]) diff --git a/tests/database/componentdbtest.py b/tests/database/componentdbtest.py index 3a9d384f..43c67766 100644 --- a/tests/database/componentdbtest.py +++ b/tests/database/componentdbtest.py @@ -10,7 +10,7 @@ # Please read the COPYING file. # -import testcase +from . import testcase import pisi class ComponentDBTestCase(testcase.TestCase): diff --git a/tests/database/filesdbtest.py b/tests/database/filesdbtest.py index 2aaf87aa..6dfb4d14 100644 --- a/tests/database/filesdbtest.py +++ b/tests/database/filesdbtest.py @@ -10,7 +10,7 @@ # Please read the COPYING file. # -import testcase +from . import testcase import pisi class FilesDBTestCase(testcase.TestCase): diff --git a/tests/database/installdbtest.py b/tests/database/installdbtest.py index 3c8de5d6..9a9f50f3 100644 --- a/tests/database/installdbtest.py +++ b/tests/database/installdbtest.py @@ -10,7 +10,7 @@ # Please read the COPYING file. # -import testcase +from . import testcase import pisi class InstallDBTestCase(testcase.TestCase): @@ -69,7 +69,7 @@ class InstallDBTestCase(testcase.TestCase): pisi.api.install(["ctorrent"]) self.installdb = pisi.db.installdb.InstallDB() revdeps = self.installdb.get_rev_deps("openssl") - assert set(["ctorrent", "curl"]) == set(map(lambda x:x[0], revdeps)) + assert set(["ctorrent", "curl"]) == set([x[0] for x in revdeps]) def testAddRemovePackage(self): pisi.api.install(["ctorrent"]) diff --git a/tests/database/itembyrepotest.py b/tests/database/itembyrepotest.py index f6c8c720..3b45baa4 100644 --- a/tests/database/itembyrepotest.py +++ b/tests/database/itembyrepotest.py @@ -10,7 +10,7 @@ # Please read the COPYING file. # -import testcase +from . import testcase import pisi.db.itembyrepo class TestDB: diff --git a/tests/database/lazydbtest.py b/tests/database/lazydbtest.py index 7f4fdc7b..2020f4f3 100644 --- a/tests/database/lazydbtest.py +++ b/tests/database/lazydbtest.py @@ -26,12 +26,12 @@ class LazyDBTestCase(unittest.TestCase): def testDatabaseMethodForcingInit(self): db = TestDB() assert db.getTestField() - assert db.__dict__.has_key("testfield") + assert "testfield" in db.__dict__ db._delete() def testDatabaseWithoutInit(self): db = TestDB() - assert not db.__dict__.has_key("testfield") + assert "testfield" not in db.__dict__ db._delete() def testSingletonBehaviour(self): diff --git a/tests/database/packagedbtest.py b/tests/database/packagedbtest.py index a5e850d6..f3dd69a0 100644 --- a/tests/database/packagedbtest.py +++ b/tests/database/packagedbtest.py @@ -10,7 +10,7 @@ # Please read the COPYING file. # -import testcase +from . import testcase import pisi class PackageDBTestCase(testcase.TestCase): diff --git a/tests/database/repodbtest.py b/tests/database/repodbtest.py index 7ed2c0dc..d82b9a42 100644 --- a/tests/database/repodbtest.py +++ b/tests/database/repodbtest.py @@ -10,7 +10,7 @@ # Please read the COPYING file. # -import testcase +from . import testcase import pisi class RepoDBTestCase(testcase.TestCase): diff --git a/tests/database/sourcedbtest.py b/tests/database/sourcedbtest.py index cd5dd945..0246f0af 100644 --- a/tests/database/sourcedbtest.py +++ b/tests/database/sourcedbtest.py @@ -10,7 +10,7 @@ # Please read the COPYING file. # -import testcase +from . import testcase import pisi class SourceDBTestCase(testcase.TestCase): diff --git a/tests/filetest.py b/tests/filetest.py index f81b3566..8bb7b0a3 100644 --- a/tests/filetest.py +++ b/tests/filetest.py @@ -11,23 +11,23 @@ class FileTestCase(unittest.TestCase): def testMakeUri(self): spec = SpecFile("repos/pardus-2007/system/base/curl/pspec.xml") url = uri.URI(spec.source.archive[0].uri) - self.assert_(File.make_uri(url)) + self.assertTrue(File.make_uri(url)) def testChooseMethod(self): - compress = File('repos/contrib-2007/pisi-index.xml', File.read) - self.assert_(File.choose_method('pisi.conf', compress)) + compress = open('repos/contrib-2007/pisi-index.xml', File.read) + self.assertTrue(File.choose_method('pisi.conf', compress)) def testDecompress(self): - localfile = File('repos/pardus-2007/system/base/curl/pspec.xml', File.read) - compress = File('repos/contrib-2007/pisi-index.xml', File.read) - self.assert_(File.decompress(localfile,compress)) + localfile = open('repos/pardus-2007/system/base/curl/pspec.xml', File.read) + compress = open('repos/contrib-2007/pisi-index.xml', File.read) + self.assertTrue(File.decompress(localfile,compress)) def testLocalFile(self): - f = File('repos/pardus-2007/system/base/curl/pspec.xml', File.read) + f = open('repos/pardus-2007/system/base/curl/pspec.xml', File.read) r = f.readlines() assert (len(r) > 0) def testRemoteRead(self): - f = File('http://www.gnu.org/licenses/gpl2.txt', File.read) + f = open('http://www.gnu.org/licenses/gpl2.txt', File.read) r = f.readlines() assert (len(r) > 0) diff --git a/tests/replacetest.py b/tests/replacetest.py index c4ca7b2c..c762fa37 100644 --- a/tests/replacetest.py +++ b/tests/replacetest.py @@ -13,7 +13,7 @@ class ReplaceTestCase(unittest.TestCase): replace = pisi.replace.Replace(relation) replace.package = "zlib" # Check if the replaced package is installed - self.assert_(pisi.replace.installed_package_replaced(replace)) + self.assertTrue(pisi.replace.installed_package_replaced(replace)) repinfo = pisi.replace.Replace(relation) repinfo.package = "ctorrent" assert not pisi.replace.installed_package_replaced(repinfo) diff --git a/tests/srcarchivetest.py b/tests/srcarchivetest.py index 2e585437..c52c44ee 100644 --- a/tests/srcarchivetest.py +++ b/tests/srcarchivetest.py @@ -7,7 +7,7 @@ class SourceArchiveTestCase(unittest.TestCase): def testFetch(self): spec = SpecFile('repos/pardus-2007/system/base/curl/pspec.xml') srcarch = pisi.sourcearchive.SourceArchive(spec.source.archive[0]) - self.assert_(not srcarch.fetch()) + self.assertTrue(not srcarch.fetch()) def testIscached(self): spec = SpecFile('repos/pardus-2007/system/base/curl/pspec.xml') @@ -18,7 +18,7 @@ class SourceArchiveTestCase(unittest.TestCase): spec = SpecFile('repos/pardus-2007/system/base/curl/pspec.xml') targetDir = '/tmp/tests' srcarch = pisi.sourcearchive.SourceArchive(spec.source.archive[0]) - self.assert_(not srcarch.unpack(targetDir)) + self.assertTrue(not srcarch.unpack(targetDir)) def testUnpack(self): spec = SpecFile('repos/pardus-2007/system/base/curl/pspec.xml') diff --git a/tests/utiltest.py b/tests/utiltest.py index 9a99bbea..7a89dd7e 100644 --- a/tests/utiltest.py +++ b/tests/utiltest.py @@ -27,9 +27,9 @@ class UtilTestCase(unittest.TestCase): assert ['usr', 'lib', 'pardus'] == splitpath('usr/lib/pardus') def testSubPath(self): - self.assert_(subpath('usr','usr')) - self.assert_(subpath('usr','usr/local/src')) - self.assert_(not subpath('usr/local','usr')) + self.assertTrue(subpath('usr','usr')) + self.assertTrue(subpath('usr','usr/local/src')) + self.assertTrue(not subpath('usr/local','usr')) def testRemovePathPrefix(self): pathname = removepathprefix('usr/local', 'usr/local/src') diff --git a/tests/versiontest.py b/tests/versiontest.py index 1266eafe..e574a89b 100644 --- a/tests/versiontest.py +++ b/tests/versiontest.py @@ -19,7 +19,7 @@ class VersionTestCase(unittest.TestCase): def testSingle(self): v1 = Version("103") v2 = Version("90") - self.assert_(v1 > v2) + self.assertTrue(v1 > v2) def testOpsNumerical(self): v1 = Version("0.3.1") @@ -27,11 +27,11 @@ class VersionTestCase(unittest.TestCase): v3 = Version("1.5.2") v4 = Version("0.3.1") v5 = Version("2.07") - self.assert_(v1 < v2) - self.assert_(v3 > v2) - self.assert_(v1 <= v3) - self.assert_(v4 >= v4) - self.assert_(v5 > v3) + self.assertTrue(v1 < v2) + self.assertTrue(v3 > v2) + self.assertTrue(v1 <= v3) + self.assertTrue(v4 >= v4) + self.assertTrue(v5 > v3) def testOpsKeywords(self): # with keywords @@ -43,33 +43,33 @@ class VersionTestCase(unittest.TestCase): v6 = Version("2.23_m1") v7 = Version("2.23_rc1") v8 = Version("2.23_rc2") - self.assert_(v1 < v2) - self.assert_(v1 > v3) - self.assert_(v1 < v4) - self.assert_(v1 > v5) - self.assert_(v2 < v4) - self.assert_(v2 > v5) - self.assert_(v6 < v4) - self.assert_(v6 > v5) - self.assert_(v7 > v5) - self.assert_(v8 > v7) + self.assertTrue(v1 < v2) + self.assertTrue(v1 > v3) + self.assertTrue(v1 < v4) + self.assertTrue(v1 > v5) + self.assertTrue(v2 < v4) + self.assertTrue(v2 > v5) + self.assertTrue(v6 < v4) + self.assertTrue(v6 > v5) + self.assertTrue(v7 > v5) + self.assertTrue(v8 > v7) v1 = Version("1.0_alpha1") v2 = Version("1.0_alpha2") - self.assert_(v2 > v1) + self.assertTrue(v2 > v1) def testOpsCharacters(self): # with character v1 = Version("2.10a") v2 = Version("2.10") v3 = Version("2.10d") - self.assert_(v1 > v2) - self.assert_(v1 < v3) - self.assert_(v2 < v3) + self.assertTrue(v1 > v2) + self.assertTrue(v1 < v3) + self.assertTrue(v2 < v3) def testGeBug(self): # bug 603 v1 = Version('1.8.0') v2 = Version('1.9.1') - self.assert_( not v1 > v2 ) - self.assert_( not v1 >= v2 ) + self.assertTrue( not v1 > v2 ) + self.assertTrue( not v1 >= v2 )