Add python3 support

This commit is contained in:
Safa Ariman
2019-06-06 01:31:19 +03:00
parent 68344a2d87
commit c90351220c
146 changed files with 806 additions and 1082 deletions
+7 -4
View File
@@ -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
+7 -5
View File
@@ -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)
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+8 -8
View File
@@ -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)
+1 -1
View File
@@ -15,7 +15,7 @@ import sys
import gettext
__trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext
_ = __trans.gettext
# PiSi Modules
import pisi.actionsapi
+2 -2
View File
@@ -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,
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+7 -7
View File
@@ -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()
+5 -5
View File
@@ -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 = ''):
+2 -2
View File
@@ -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:
+7 -7
View File
@@ -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:
+5 -5
View File
@@ -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 '''
+1 -1
View File
@@ -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
+4 -4
View File
@@ -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)
+1 -1
View File
@@ -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
+27 -3
View File
@@ -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)
+9 -9
View File
@@ -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'''
+3 -2
View File
@@ -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
+12 -12
View File
@@ -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")
+8 -7
View File
@@ -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))
+8 -8
View File
@@ -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()
+14 -16
View File
@@ -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)
+2 -3
View File
@@ -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 <repo> <indexuri>
@@ -30,7 +30,6 @@ Usage: add-repo <repo> <indexuri>
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)
+3 -5
View File
@@ -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 <package> ... <package>
""")
__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 <package> ... <package>
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
+2 -3
View File
@@ -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)
+2 -3
View File
@@ -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)
+2 -4
View File
@@ -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)
+6 -6
View File
@@ -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"""
+2 -4
View File
@@ -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)
+2 -4
View File
@@ -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)
+2 -3
View File
@@ -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)
+2 -3
View File
@@ -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 [<repo1> <repo2> ... <repon>]
@@ -26,7 +26,6 @@ Usage: disable-repo [<repo1> <repo2> ... <repon>]
Disabled repositories are not taken into account in operations
""")
__metaclass__ = command.autocommand
def __init__(self,args):
super(DisableRepo, self).__init__(args)
+2 -3
View File
@@ -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 <sourcename> ...
@@ -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)
+2 -3
View File
@@ -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 [<repo1> <repo2> ... <repon>]
@@ -26,7 +26,6 @@ Usage: enable-repo [<repo1> <repo2> ... <repon>]
Disabled repositories are not taken into account in operations
""")
__metaclass__ = command.autocommand
def __init__(self,args):
super(EnableRepo, self).__init__(args)
+2 -3
View File
@@ -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 [<package1> <package2> ... <packagen>]
@@ -30,7 +30,6 @@ Usage: fetch [<package1> <package2> ... <packagen>]
Downloads the given pisi packages to working directory
""")
__metaclass__ = command.autocommand
def __init__(self,args):
super(Fetch, self).__init__(args)
+2 -4
View File
@@ -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 [<package1> <package2> ...]
@@ -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)
+2 -4
View File
@@ -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 [ <command1> <command2> ... <commandn> ]
If run without parameters, it prints the general help.""")
__metaclass__ = command.autocommand
def __init__(self, args = None):
super(Help, self).__init__(args)
+10 -12
View File
@@ -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
+2 -3
View File
@@ -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)
+12 -13
View File
@@ -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 <package1> <package2> ... <packagen>
<packagei> 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 <package1> <package2> ... <packagen>
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 <package1> <package2> ... <packagen>
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)
+2 -3
View File
@@ -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 <package1> <package2> ... <packagen>
@@ -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)
+5 -6
View File
@@ -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 [ <repo1> <repo2> ... 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)))
+4 -5
View File
@@ -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)))
+6 -8
View File
@@ -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)))
+4 -5
View File
@@ -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 [ <repo1> <repo2> ... 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()
+3 -4
View File
@@ -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'))
+3 -4
View File
@@ -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))
+4 -5
View File
@@ -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)))
+5 -6
View File
@@ -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)))
+2 -2
View File
@@ -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 = []
+2 -3
View File
@@ -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 [ <package1> <package2> ... <packagen> ]
@@ -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)
+2 -3
View File
@@ -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 <package1> <package2> ... <packagen>
@@ -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)
+2 -3
View File
@@ -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 <repo1> <repo2> ... <repon>
Remove all repository information from the system.
""")
__metaclass__ = command.autocommand
def __init__(self,args):
super(RemoveRepo, self).__init__(args)
+3 -4
View File
@@ -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 <term1> <term2> ... <termn>
@@ -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))
+2 -3
View File
@@ -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 <path1> <path2> ... <pathn>
Finds the installed package which contains the specified file.
""")
__metaclass__ = command.autocommand
def __init__(self, args):
super(SearchFile, self).__init__(args)
+2 -3
View File
@@ -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 [<repo1> <repo2> ... <repon>]
@@ -30,7 +30,6 @@ Usage: update-repo [<repo1> <repo2> ... <repon>]
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)
+2 -3
View File
@@ -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 [<package1> <package2> ... <packagen>]
@@ -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)
+12 -12
View File
@@ -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)
+7 -17
View File
@@ -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" ]
+4 -6
View File
@@ -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')
+16 -16
View File
@@ -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
+5 -5
View File
@@ -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))
+8 -10
View File
@@ -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"
+8 -8
View File
@@ -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)
+5 -5
View File
@@ -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)
+2 -2
View File
@@ -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)
+4 -5
View File
@@ -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
+12 -12
View File
@@ -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("<BuildHost>(.*?)</BuildHost>")
@@ -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)
+13 -15
View File
@@ -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()
+9 -9
View File
@@ -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]
+9 -9
View File
@@ -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"):
+11 -7
View File
@@ -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):
+3 -3
View File
@@ -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
+2 -2
View File
@@ -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]
+6 -6
View File
@@ -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."))
+15 -15
View File
@@ -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)
+2 -6
View File
@@ -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"
+1 -1
View File
@@ -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):
+7 -10
View File
@@ -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"]
+9 -10
View File
@@ -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)
+7 -9
View File
@@ -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
+6 -10
View File
@@ -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]
+3 -3
View File
@@ -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]
+3 -5
View File
@@ -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)
+26 -28
View File
@@ -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:
+3 -3
View File
@@ -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)
+2 -2
View File
@@ -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])):
+1 -1
View File
@@ -14,7 +14,7 @@ import sys
import gettext
__trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext
_ = __trans.gettext
import pisi
import pisi.operations
+2 -2
View File
@@ -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") %
+2 -2
View File
@@ -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
+5 -5
View File
@@ -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.'))
+2 -2
View File
@@ -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"))
+8 -8
View File
@@ -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)
+4 -4
View File
@@ -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:
+1 -1
View File
@@ -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
+55 -56
View File
@@ -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,
}
+2 -2
View File
@@ -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)

Some files were not shown because too many files have changed in this diff Show More