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 sys
import errno import errno
import traceback import traceback
import exceptions
import signal import signal
import pisi import pisi
@@ -24,21 +23,24 @@ import gettext
gettext.bindtextdomain('pisi', "/usr/share/locale") gettext.bindtextdomain('pisi', "/usr/share/locale")
gettext.textdomain('pisi') gettext.textdomain('pisi')
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
def sig_handler(sig, frame): def sig_handler(sig, frame):
if sig == signal.SIGTERM: if sig == signal.SIGTERM:
exit() exit()
def exit(): def exit():
sys.exit(1) sys.exit(1)
def handle_exception(exception, value, tb): def handle_exception(exception, value, tb):
signal.signal(signal.SIGINT, signal.SIG_IGN) # disable further interrupts 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 show_traceback = False
if exception == exceptions.KeyboardInterrupt: if exception == KeyboardInterrupt:
ui.error(_("Keyboard Interrupt: Exiting...")) ui.error(_("Keyboard Interrupt: Exiting..."))
exit() exit()
elif isinstance(value, pisi.Error): elif isinstance(value, pisi.Error):
@@ -73,6 +75,7 @@ def handle_exception(exception, value, tb):
exit() exit()
if __name__ == "__main__": if __name__ == "__main__":
sys.excepthook = handle_exception sys.excepthook = handle_exception
+7 -5
View File
@@ -17,8 +17,9 @@ import sys
import atexit import atexit
import logging import logging
import logging.handlers import logging.handlers
from importlib import reload
__version__ = "2.4" __version__ = "3.0a1"
__all__ = [ 'api', 'configfile', 'db'] __all__ = [ 'api', 'configfile', 'db']
@@ -26,11 +27,11 @@ __all__ = [ 'api', 'configfile', 'db']
class Exception(Exception): class Exception(Exception):
"""Class of exceptions that must be caught and handled within PiSi""" """Class of exceptions that must be caught and handled within PiSi"""
def __str__(self): def __str__(self):
s = u'' s = ''
for x in self.args: for x in self.args:
if s != '': if s != '':
s += '\n' s += '\n'
s += unicode(x) s += str(x)
return s return s
class Error(Exception): class Error(Exception):
@@ -43,7 +44,7 @@ import pisi.context as ctx
def init_logging(): def init_logging():
log_dir = os.path.join(ctx.config.dest_dir(), ctx.config.log_dir()) 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) handler = logging.handlers.RotatingFileHandler('%s/pisi.log' % log_dir)
formatter = logging.Formatter('%(asctime)-12s: %(levelname)-8s %(message)s') formatter = logging.Formatter('%(asctime)-12s: %(levelname)-8s %(message)s')
handler.setFormatter(formatter) handler.setFormatter(formatter)
@@ -71,8 +72,9 @@ def _cleanup():
# Hack for pisi to work with non-patched Python. pisi needs # Hack for pisi to work with non-patched Python. pisi needs
# lots of work for not doing this. # lots of work for not doing this.
reload(sys) reload(sys)
sys.setdefaultencoding('utf-8')
atexit.register(_cleanup) atexit.register(_cleanup)
+1 -1
View File
@@ -14,7 +14,7 @@ import os
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# Pisi Modules # Pisi Modules
import pisi.context as ctx import pisi.context as ctx
+1 -1
View File
@@ -14,7 +14,7 @@ import os
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# Pisi Modules # Pisi Modules
import pisi.context as ctx import pisi.context as ctx
+8 -8
View File
@@ -12,31 +12,31 @@
# Standard Python Modules # Standard Python Modules
import re import re
import sys import sys
from itertools import izip
from itertools import imap
from itertools import count from itertools import count
from itertools import ifilter
from itertools import ifilterfalse from itertools import filterfalse
# ActionsAPI # ActionsAPI
import pisi.actionsapi import pisi.actionsapi
def cat(filename): def cat(filename):
return file(filename).xreadlines() return open(filename)
class grep: class grep:
'''keep only lines that match the regexp''' '''keep only lines that match the regexp'''
def __init__(self, pat, flags = 0): def __init__(self, pat, flags = 0):
self.fun = re.compile(pat, flags).match self.fun = re.compile(pat, flags).match
def __ror__(self, input): def __ror__(self, input):
return ifilter(self.fun, input) return filter(self.fun, input)
class tr: class tr:
'''apply arbitrary transform to each sequence element''' '''apply arbitrary transform to each sequence element'''
def __init__(self, transform): def __init__(self, transform):
self.tr = transform self.tr = transform
def __ror__(self, input): def __ror__(self, input):
return imap(self.tr, input) return map(self.tr, input)
class printto: class printto:
'''print sequence elements one per line''' '''print sequence elements one per line'''
@@ -44,7 +44,7 @@ class printto:
self.out = out self.out = out
def __ror__(self,input): def __ror__(self,input):
for line in input: for line in input:
print >> self.out, line print(line, file=self.out)
printlines = printto(sys.stdout) printlines = printto(sys.stdout)
+1 -1
View File
@@ -15,7 +15,7 @@ import sys
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# PiSi Modules # PiSi Modules
import pisi.actionsapi import pisi.actionsapi
+2 -2
View File
@@ -16,7 +16,7 @@ from shutil import copy, copytree
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# Pisi Modules # Pisi Modules
import pisi.util as util 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 # Using low level I/O to set permission without calling os.chmod
exec_file = os.open(util.join_path(exec_dir, get.srcNAME()), exec_file = os.open(util.join_path(exec_dir, get.srcNAME()),
os.O_CREAT | os.O_WRONLY, os.O_CREAT | os.O_WRONLY,
0755) 0o755)
os.write(exec_file, EXEC_TEMPLATE % (util.join_path('/', dest_dir), os.write(exec_file, EXEC_TEMPLATE % (util.join_path('/', dest_dir),
java_args, java_args,
exe, exe,
+1 -1
View File
@@ -14,7 +14,7 @@ import os
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# Pisi Modules # Pisi Modules
import pisi.context as ctx import pisi.context as ctx
+1 -1
View File
@@ -16,7 +16,7 @@ import shutil
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# Pisi Modules # Pisi Modules
import pisi.context as ctx import pisi.context as ctx
+1 -1
View File
@@ -14,7 +14,7 @@ import os
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# Pisi-Core Modules # Pisi-Core Modules
import pisi.context as ctx import pisi.context as ctx
+7 -7
View File
@@ -15,7 +15,7 @@ import glob
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# Pisi Modules # Pisi Modules
import pisi.context as ctx import pisi.context as ctx
@@ -51,28 +51,28 @@ def configure(parameters = ''):
export('PERL_MM_USE_DEFAULT', '1') export('PERL_MM_USE_DEFAULT', '1')
if can_access_file('Build.PL'): if can_access_file('Build.PL'):
if system('perl Build.PL installdirs=vendor destdir=%s' % get.installDIR()): if system('perl Build.PL installdirs=vendor destdir=%s' % get.installDIR()):
raise ConfigureError, _('Configure failed.') raise ConfigureError(_('Configure failed.'))
else: else:
if system('perl Makefile.PL %s PREFIX=/usr INSTALLDIRS=vendor DESTDIR=%s' % (parameters, get.installDIR())): 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 = ''): def make(parameters = ''):
'''make source with given parameters.''' '''make source with given parameters.'''
if can_access_file('Makefile'): if can_access_file('Makefile'):
if system('make %s' % parameters): if system('make %s' % parameters):
raise MakeError, _('Make failed.') raise MakeError(_('Make failed.'))
else: else:
if system('perl Build %s' % parameters): if system('perl Build %s' % parameters):
raise MakeError, _('perl build failed.') raise MakeError(_('perl build failed.'))
def install(parameters = 'install'): def install(parameters = 'install'):
'''install source with given parameters.''' '''install source with given parameters.'''
if can_access_file('Makefile'): if can_access_file('Makefile'):
if system('make %s' % parameters): if system('make %s' % parameters):
raise InstallError, _('Make failed.') raise InstallError(_('Make failed.'))
else: else:
if system('perl Build install'): if system('perl Build install'):
raise MakeError, _('perl install failed.') raise MakeError(_('perl install failed.'))
removePacklist() removePacklist()
+5 -5
View File
@@ -22,7 +22,7 @@ import filecmp
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# Pisi Modules # Pisi Modules
import pisi.context as ctx import pisi.context as ctx
@@ -98,7 +98,7 @@ def dolib(sourceFile, destinationDirectory = '/usr/lib'):
sourceFile = join_path(os.getcwd(), sourceFile) sourceFile = join_path(os.getcwd(), sourceFile)
destinationDirectory = join_path(get.installDIR(), destinationDirectory) destinationDirectory = join_path(get.installDIR(), destinationDirectory)
lib_insinto(sourceFile, destinationDirectory, 0755) lib_insinto(sourceFile, destinationDirectory, 0o755)
def dolib_a(sourceFile, destinationDirectory = '/usr/lib'): def dolib_a(sourceFile, destinationDirectory = '/usr/lib'):
'''insert the static library into /usr/lib with permission 0644''' '''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) sourceFile = join_path(os.getcwd(), sourceFile)
destinationDirectory = join_path(get.installDIR(), destinationDirectory) destinationDirectory = join_path(get.installDIR(), destinationDirectory)
lib_insinto(sourceFile, destinationDirectory, 0644) lib_insinto(sourceFile, destinationDirectory, 0o644)
def dolib_so(sourceFile, destinationDirectory = '/usr/lib'): def dolib_so(sourceFile, destinationDirectory = '/usr/lib'):
'''insert the dynamic library into /usr/lib with permission 0755''' '''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) sourceFile = join_path(os.getcwd(), sourceFile)
destinationDirectory = join_path(get.installDIR(), destinationDirectory) destinationDirectory = join_path(get.installDIR(), destinationDirectory)
lib_insinto(sourceFile, destinationDirectory, 0755) lib_insinto(sourceFile, destinationDirectory, 0o755)
def doman(*sourceFiles): def doman(*sourceFiles):
'''inserts the man pages in the list of files into /usr/share/man/''' '''inserts the man pages in the list of files into /usr/share/man/'''
@@ -184,7 +184,7 @@ def rename(sourceFile, destinationFile):
try: try:
os.rename(join_path(get.installDIR(), sourceFile), join_path(get.installDIR(), baseDir, destinationFile)) 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)) error(_('ActionsAPI [rename]: %s: %s') % (e, sourceFile))
def dosed(sourceFiles, findPattern, replacePattern = ''): def dosed(sourceFiles, findPattern, replacePattern = ''):
+2 -2
View File
@@ -17,7 +17,7 @@ import glob
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# Pisi Modules # Pisi Modules
import pisi.context as ctx import pisi.context as ctx
@@ -73,7 +73,7 @@ def readable_insinto(destinationDirectory, *sourceFiles):
for source in sourceFileGlob: for source in sourceFileGlob:
system('install -m0644 "%s" %s' % (source, destinationDirectory)) 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''' '''inserts a library fileinto destinationDirectory with given permission'''
if not sourceFile or not destinationDirectory: if not sourceFile or not destinationDirectory:
+7 -7
View File
@@ -14,7 +14,7 @@ import subprocess
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# PiSi Modules # PiSi Modules
import pisi.context as ctx import pisi.context as ctx
@@ -35,7 +35,7 @@ def getVariableForLibrary(library, variable):
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE) stderr=subprocess.PIPE)
return_code = proc.wait() return_code = proc.wait()
except OSError, exception: except OSError as exception:
if exception.errno == 2: if exception.errno == 2:
raise PkgconfigError(_("pkg-config is not installed on your system.")) raise PkgconfigError(_("pkg-config is not installed on your system."))
else: else:
@@ -54,7 +54,7 @@ def getLibraryVersion(library):
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE) stderr=subprocess.PIPE)
return_code = proc.wait() return_code = proc.wait()
except OSError, exception: except OSError as exception:
if exception.errno == 2: if exception.errno == 2:
raise PkgconfigError(_("pkg-config is not installed on your system.")) raise PkgconfigError(_("pkg-config is not installed on your system."))
else: else:
@@ -74,7 +74,7 @@ def getLibraryCFLAGS(library):
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE) stderr=subprocess.PIPE)
return_code = proc.wait() return_code = proc.wait()
except OSError, exception: except OSError as exception:
if exception.errno == 2: if exception.errno == 2:
raise PkgconfigError(_("pkg-config is not installed on your system.")) raise PkgconfigError(_("pkg-config is not installed on your system."))
else: else:
@@ -94,7 +94,7 @@ def getLibraryLIBADD(library):
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE) stderr=subprocess.PIPE)
return_code = proc.wait() return_code = proc.wait()
except OSError, exception: except OSError as exception:
if exception.errno == 2: if exception.errno == 2:
raise PkgconfigError(_("pkg-config is not installed on your system.")) raise PkgconfigError(_("pkg-config is not installed on your system."))
else: else:
@@ -113,7 +113,7 @@ def runManualCommand(*args):
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE) stderr=subprocess.PIPE)
return_code = proc.wait() return_code = proc.wait()
except OSError, exception: except OSError as exception:
if exception.errno == 2: if exception.errno == 2:
raise PkgconfigError(_("pkg-config is not installed on your system.")) raise PkgconfigError(_("pkg-config is not installed on your system."))
else: else:
@@ -131,7 +131,7 @@ def libraryExists(library):
result = subprocess.call(["pkg-config", result = subprocess.call(["pkg-config",
"--exists", "--exists",
"%s" % library]) "%s" % library])
except OSError, exception: except OSError as exception:
if exception.errno == 2: if exception.errno == 2:
raise PkgconfigError(_("pkg-config is not installed on your system.")) raise PkgconfigError(_("pkg-config is not installed on your system."))
else: else:
+5 -5
View File
@@ -15,7 +15,7 @@ import glob
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# Pisi Modules # Pisi Modules
import pisi.context as ctx import pisi.context as ctx
@@ -53,18 +53,18 @@ class RunTimeError(pisi.actionsapi.Error):
def configure(parameters = ''): def configure(parameters = ''):
'''does python setup.py configure''' '''does python setup.py configure'''
if system('python setup.py configure %s' % (parameters)): if system('python setup.py configure %s' % (parameters)):
raise ConfigureError, _('Configuration failed.') raise ConfigureError(_('Configuration failed.'))
def compile(parameters = ''): def compile(parameters = ''):
'''compile source with given parameters.''' '''compile source with given parameters.'''
if system('python setup.py build %s' % (parameters)): if system('python setup.py build %s' % (parameters)):
raise CompileError, _('Make failed.') raise CompileError(_('Make failed.'))
def install(parameters = ''): def install(parameters = ''):
'''does python setup.py install''' '''does python setup.py install'''
if system('python setup.py install --root=%s --no-compile -O0 %s' % (get.installDIR(), parameters)): 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', docFiles = ('AUTHORS', 'CHANGELOG', 'CONTRIBUTORS', 'COPYING*', 'COPYRIGHT',
'Change*', 'KNOWN_BUGS', 'LICENSE', 'MAINTAINERS', 'NEWS', 'Change*', 'KNOWN_BUGS', 'LICENSE', 'MAINTAINERS', 'NEWS',
@@ -78,7 +78,7 @@ def install(parameters = ''):
def run(parameters = ''): def run(parameters = ''):
'''executes parameters with python''' '''executes parameters with python'''
if system('python %s' % (parameters)): 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()): def fixCompiledPy(lookInto = '/usr/lib/%s/' % get.curPYTHON()):
''' cleans *.py[co] from packages ''' ''' cleans *.py[co] from packages '''
+1 -1
View File
@@ -12,7 +12,7 @@
import glob import glob
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# Pisi Modules # Pisi Modules
import pisi.context as ctx import pisi.context as ctx
+4 -4
View File
@@ -15,7 +15,7 @@ from glob import glob
from gettext import translation from gettext import translation
__trans = translation('pisi', fallback=True) __trans = translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# Pisi Modules # Pisi Modules
import pisi.context as ctx import pisi.context as ctx
@@ -89,14 +89,14 @@ def auto_dodoc():
def install(parameters=''): def install(parameters=''):
'''does ruby setup.rb install''' '''does ruby setup.rb install'''
if system('ruby -w setup.rb --prefix=/%s --destdir=%s %s' % (get.defaultprefixDIR(), get.installDIR(), parameters)): 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() auto_dodoc()
def rake_install(parameters=''): def rake_install(parameters=''):
'''execute rake script for installation''' '''execute rake script for installation'''
if system('rake -t -l %s %s' % (os.path.join('/', get.defaultprefixDIR(), 'lib'), parameters)): if system('rake -t -l %s %s' % (os.path.join('/', get.defaultprefixDIR(), 'lib'), parameters)):
raise InstallError, _('Install failed.') raise InstallError(_('Install failed.'))
auto_dodoc() auto_dodoc()
@@ -105,4 +105,4 @@ def run(parameters=''):
export('DESTDIR', get.installDIR()) export('DESTDIR', get.installDIR())
if system('ruby %s' % parameters): 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 import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# ActionsAPI Modules # ActionsAPI Modules
import pisi.actionsapi import pisi.actionsapi
+27 -3
View File
@@ -19,7 +19,7 @@ import grp
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# Pisi Modules # Pisi Modules
import pisi.context as ctx import pisi.context as ctx
@@ -32,14 +32,17 @@ from pisi.actionsapi import error
from pisi.util import run_logged from pisi.util import run_logged
from pisi.util import join_path from pisi.util import join_path
def can_access_file(filePath): def can_access_file(filePath):
'''test the existence of file''' '''test the existence of file'''
return os.access(filePath, os.F_OK) return os.access(filePath, os.F_OK)
def can_access_directory(destinationDirectory): def can_access_directory(destinationDirectory):
'''test readability, writability and executablility of directory''' '''test readability, writability and executablility of directory'''
return os.access(destinationDirectory, os.R_OK | os.W_OK | os.X_OK) return os.access(destinationDirectory, os.R_OK | os.W_OK | os.X_OK)
def makedirs(destinationDirectory): def makedirs(destinationDirectory):
'''recursive directory creation function''' '''recursive directory creation function'''
try: try:
@@ -48,6 +51,7 @@ def makedirs(destinationDirectory):
except OSError: except OSError:
error(_('Cannot create directory %s') % destinationDirectory) error(_('Cannot create directory %s') % destinationDirectory)
def echo(destionationFile, content): def echo(destionationFile, content):
try: try:
f = open(destionationFile, 'a') f = open(destionationFile, 'a')
@@ -56,7 +60,8 @@ def echo(destionationFile, content):
except IOError: except IOError:
error(_('ActionsAPI [echo]: Can\'t append to file %s.') % (destionationFile)) 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''' '''change the mode of filePath to the mode'''
filePathGlob = glob.glob(filePath) filePathGlob = glob.glob(filePath)
if len(filePathGlob) == 0: if len(filePathGlob) == 0:
@@ -72,6 +77,7 @@ def chmod(filePath, mode = 0755):
else: else:
ctx.ui.error(_('ActionsAPI [chmod]: File %s doesn\'t exists.') % (fileName)) ctx.ui.error(_('ActionsAPI [chmod]: File %s doesn\'t exists.') % (fileName))
def chown(filePath, uid = 'root', gid = 'root'): def chown(filePath, uid = 'root', gid = 'root'):
'''change the owner and group id of filePath to uid and gid''' '''change the owner and group id of filePath to uid and gid'''
if can_access_file(filePath): if can_access_file(filePath):
@@ -83,6 +89,7 @@ def chown(filePath, uid = 'root', gid = 'root'):
else: else:
ctx.ui.error(_('ActionsAPI [chown]: File %s doesn\'t exists.') % filePath) ctx.ui.error(_('ActionsAPI [chown]: File %s doesn\'t exists.') % filePath)
def sym(source, destination): def sym(source, destination):
'''creates symbolic link''' '''creates symbolic link'''
try: try:
@@ -90,6 +97,7 @@ def sym(source, destination):
except OSError: except OSError:
ctx.ui.error(_('ActionsAPI [sym]: Permission denied: %s to %s') % (source, destination)) ctx.ui.error(_('ActionsAPI [sym]: Permission denied: %s to %s') % (source, destination))
def unlink(pattern): def unlink(pattern):
'''remove the file path''' '''remove the file path'''
filePathGlob = glob.glob(pattern) filePathGlob = glob.glob(pattern)
@@ -108,6 +116,7 @@ def unlink(pattern):
else: else:
ctx.ui.error(_('ActionsAPI [unlink]: File %s doesn\'t exists.') % (filePath)) ctx.ui.error(_('ActionsAPI [unlink]: File %s doesn\'t exists.') % (filePath))
def unlinkDir(sourceDirectory): def unlinkDir(sourceDirectory):
'''delete an entire directory tree''' '''delete an entire directory tree'''
if isDirectory(sourceDirectory) or isLink(sourceDirectory): if isDirectory(sourceDirectory) or isLink(sourceDirectory):
@@ -120,6 +129,7 @@ def unlinkDir(sourceDirectory):
else: else:
error(_('ActionsAPI [unlinkDir]: Directory %s doesn\'t exists.') % (sourceDirectory)) error(_('ActionsAPI [unlinkDir]: Directory %s doesn\'t exists.') % (sourceDirectory))
def move(source, destination): def move(source, destination):
'''recursively move a "source" file or directory to "destination"''' '''recursively move a "source" file or directory to "destination"'''
sourceGlob = glob.glob(source) sourceGlob = glob.glob(source)
@@ -135,6 +145,7 @@ def move(source, destination):
else: else:
error(_('ActionsAPI [move]: File %s doesn\'t exists.') % (filePath)) error(_('ActionsAPI [move]: File %s doesn\'t exists.') % (filePath))
# FIXME: instead of passing a sym parameter, split copy and copytree into 4 different function # FIXME: instead of passing a sym parameter, split copy and copytree into 4 different function
def copy(source, destination, sym = True): def copy(source, destination, sym = True):
'''recursively copy a "source" file or directory to "destination"''' '''recursively copy a "source" file or directory to "destination"'''
@@ -165,6 +176,7 @@ def copy(source, destination, sym = True):
else: else:
error(_('ActionsAPI [copy]: File %s does not exist.') % filePath) error(_('ActionsAPI [copy]: File %s does not exist.') % filePath)
def copytree(source, destination, sym = True): def copytree(source, destination, sym = True):
'''recursively copy an entire directory tree rooted at source''' '''recursively copy an entire directory tree rooted at source'''
if isDirectory(source): if isDirectory(source):
@@ -177,11 +189,12 @@ def copytree(source, destination, sym = True):
return return
try: try:
shutil.copytree(source, destination, sym) shutil.copytree(source, destination, sym)
except OSError, e: except OSError as e:
error(_('ActionsAPI [copytree] %s to %s: %s') % (source, destination, e)) error(_('ActionsAPI [copytree] %s to %s: %s') % (source, destination, e))
else: else:
error(_('ActionsAPI [copytree]: Directory %s doesn\'t exists.') % (source)) error(_('ActionsAPI [copytree]: Directory %s doesn\'t exists.') % (source))
def touch(filePath): def touch(filePath):
'''changes the access time of the 'filePath', or creates it if it does not exist''' '''changes the access time of the 'filePath', or creates it if it does not exist'''
filePathGlob = glob.glob(filePath) filePathGlob = glob.glob(filePath)
@@ -199,6 +212,7 @@ def touch(filePath):
except IOError: except IOError:
error(_('ActionsAPI [touch]: Permission denied: %s') % (filePath)) error(_('ActionsAPI [touch]: Permission denied: %s') % (filePath))
def cd(directoryName = ''): def cd(directoryName = ''):
'''change directory''' '''change directory'''
current = os.getcwd() current = os.getcwd()
@@ -207,6 +221,7 @@ def cd(directoryName = ''):
else: else:
os.chdir(os.path.dirname(current)) os.chdir(os.path.dirname(current))
def ls(source): def ls(source):
'''listdir''' '''listdir'''
if os.path.isdir(source): if os.path.isdir(source):
@@ -214,38 +229,47 @@ def ls(source):
else: else:
return glob.glob(source) return glob.glob(source)
def export(key, value): def export(key, value):
'''export environ variable''' '''export environ variable'''
os.environ[key] = value os.environ[key] = value
def isLink(filePath): def isLink(filePath):
'''return True if filePath refers to a symbolic link''' '''return True if filePath refers to a symbolic link'''
return os.path.islink(filePath) return os.path.islink(filePath)
def isFile(filePath): def isFile(filePath):
'''return True if filePath is an existing regular file''' '''return True if filePath is an existing regular file'''
return os.path.isfile(filePath) return os.path.isfile(filePath)
def isDirectory(filePath): def isDirectory(filePath):
'''Return True if filePath is an existing directory''' '''Return True if filePath is an existing directory'''
return os.path.isdir(filePath) return os.path.isdir(filePath)
def isEmpty(filePath): def isEmpty(filePath):
'''Return True if filePath is an empty file''' '''Return True if filePath is an empty file'''
return os.path.getsize(filePath) == 0 return os.path.getsize(filePath) == 0
def realPath(filePath): def realPath(filePath):
'''return the canonical path of the specified filename, eliminating any symbolic links encountered in the path''' '''return the canonical path of the specified filename, eliminating any symbolic links encountered in the path'''
return os.path.realpath(filePath) return os.path.realpath(filePath)
def baseName(filePath): def baseName(filePath):
'''return the base name of pathname filePath''' '''return the base name of pathname filePath'''
return os.path.basename(filePath) return os.path.basename(filePath)
def dirName(filePath): def dirName(filePath):
'''return the directory name of pathname path''' '''return the directory name of pathname path'''
return os.path.dirname(filePath) return os.path.dirname(filePath)
def system(command): def system(command):
command = string.join(string.split(command)) command = string.join(string.split(command))
retValue = run_logged(command) retValue = run_logged(command)
+9 -9
View File
@@ -16,7 +16,7 @@ import shutil
import shlex import shlex
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# Pisi Modules # Pisi Modules
import pisi.context as ctx import pisi.context as ctx
@@ -53,36 +53,36 @@ def compile(parameters = ''):
# Move sources according to tplobj files # Move sources according to tplobj files
if moveSources(): if moveSources():
raise CompileError, _('Moving source files failed') raise CompileError(_('Moving source files failed'))
# Generate config files # Generate config files
if generateConfigFiles(): if generateConfigFiles():
raise CompileError, _('Generate config files failed') raise CompileError(_('Generate config files failed'))
# Build format files # Build format files
if buildFormatFiles(): if buildFormatFiles():
raise CompileError, _('Building format files failed') raise CompileError(_('Building format files failed'))
def install(parameters = ''): def install(parameters = ''):
'''Installing texlive packages''' '''Installing texlive packages'''
# Create symlinks from format to engines # Create symlinks from format to engines
if createSymlinksFormat2Engines(): if createSymlinksFormat2Engines():
raise InstallError, _('Creating symlinks from format to engines failed') raise InstallError(_('Creating symlinks from format to engines failed'))
# Installing docs # Installing docs
if installDocFiles(): if installDocFiles():
raise InstallError, _('Installing docs failed') raise InstallError(_('Installing docs failed'))
# Installing texmf, texmf-dist, tlpkg, texmf-var # Installing texmf, texmf-dist, tlpkg, texmf-var
if installTexmfFiles(): if installTexmfFiles():
raise InstallError, _('Installing texmf files failed') raise InstallError(_('Installing texmf files failed'))
# Installing config files # Installing config files
if installConfigFiles(): if installConfigFiles():
raise InstallError, _('Installing config files failed') raise InstallError(_('Installing config files failed'))
# Handle config files # Handle config files
if handleConfigFiles(): if handleConfigFiles():
raise Installing, _('Handle config files failed') raise Installing(_('Handle config files failed'))
def createSymlinksFormat2Engines(): def createSymlinksFormat2Engines():
'''Create symlinks from format to engines''' '''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 # Build systems depend on these environment variables. That is why
# we export them instead of using as (instance) variables. # we export them instead of using as (instance) variables.
values = ctx.config.values values = ctx.config.values
os.environ['HOST'] = values.build.host os.environ['HOST'] = values.build.host
os.environ['CFLAGS'] = values.build.cflags os.environ['CFLAGS'] = values.build.cflags
os.environ['CXXFLAGS'] = values.build.cxxflags os.environ['CXXFLAGS'] = values.build.cxxflags
os.environ['LDFLAGS'] = values.build.ldflags os.environ['LDFLAGS'] = values.build.ldflags
@@ -40,6 +40,7 @@ def exportFlags():
os.environ['CXX'] = values.build.cxx os.environ['CXX'] = values.build.cxx
os.environ['LD'] = values.build.ld os.environ['LD'] = values.build.ld
class Env(object): class Env(object):
'''General environment variables used in actions API''' '''General environment variables used in actions API'''
def __init__(self): def __init__(self):
@@ -65,7 +66,7 @@ class Env(object):
# Using environment variables is somewhat tricky. Each time # Using environment variables is somewhat tricky. Each time
# you need them you need to check for their value. # 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]) return os.getenv(self.__vars[attr])
else: else:
return None return None
+12 -12
View File
@@ -12,11 +12,11 @@
import os import os
import fcntl import fcntl
import re import re
import fetcher from . import fetcher
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.context as ctx import pisi.context as ctx
@@ -53,7 +53,7 @@ def locked(func):
""" """
def wrapper(*__args,**__kw): def wrapper(*__args,**__kw):
try: 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: except IOError:
raise pisi.errors.PrivilegeError(_("You have to be root for this operation.")) raise pisi.errors.PrivilegeError(_("You have to be root for this operation."))
@@ -254,7 +254,7 @@ def list_upgradable():
installdb = pisi.db.installdb.InstallDB() installdb = pisi.db.installdb.InstallDB()
is_upgradable = pisi.operations.upgrade.is_upgradable 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 # replaced packages can not pass is_upgradable test, so we add them manually
upgradable.extend(list_replaces()) upgradable.extend(list_replaces())
@@ -535,7 +535,7 @@ def delete_cache():
pisi.util.clean_dir(ctx.config.archives_dir()) pisi.util.clean_dir(ctx.config.archives_dir())
ctx.ui.info(_("Cleaning temporary directory %s...") % ctx.config.tmp_dir()) ctx.ui.info(_("Cleaning temporary directory %s...") % ctx.config.tmp_dir())
pisi.util.clean_dir(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) cache_file = pisi.util.join_path(ctx.config.cache_root_dir(), cache)
ctx.ui.info(_("Removing cache file %s...") % cache_file) ctx.ui.info(_("Removing cache file %s...") % cache_file)
os.unlink(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): if useinstalldb and installdb.has_package(package.name):
try: try:
files = installdb.get_files(package.name) files = installdb.get_files(package.name)
except pisi.Error, e: except pisi.Error as e:
ctx.ui.warning(e) ctx.ui.warning(e)
files = None files = None
else: else:
@@ -844,7 +844,7 @@ def __update_repo(repo, force=False):
repouri = repodb.get_repo(repo).indexuri.get_uri() repouri = repodb.get_repo(repo).indexuri.get_uri()
try: try:
index.read_uri_of_repo(repouri, repo) 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) ctx.ui.info(_('%s repository information is up-to-date.') % repo)
if force: if force:
ctx.ui.info(_('Updating database at any rate as requested')) ctx.ui.info(_('Updating database at any rate as requested'))
@@ -857,7 +857,7 @@ def __update_repo(repo, force=False):
try: try:
index.check_signature(repouri, repo) index.check_signature(repouri, repo)
except pisi.file.NoSignatureFound, e: except pisi.file.NoSignatureFound as e:
ctx.ui.warning(e) ctx.ui.warning(e)
ctx.ui.info(_('Package database updated.')) ctx.ui.info(_('Package database updated.'))
@@ -962,7 +962,7 @@ def clearCache(all=False):
# sort dictionary by value from PEP-265 # sort dictionary by value from PEP-265
from operator import itemgetter 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): def removeOrderByLimit(cacheDir, order, limit):
totalSize = 0 totalSize = 0
@@ -971,7 +971,7 @@ def clearCache(all=False):
if totalSize >= limit: if totalSize >= limit:
try: try:
os.remove(os.path.join(cacheDir, pkg) + ctx.const.package_suffix) os.remove(os.path.join(cacheDir, pkg) + ctx.const.package_suffix)
except exceptions.OSError: except OSError:
pass pass
def removeAll(cacheDir): def removeAll(cacheDir):
@@ -979,12 +979,12 @@ def clearCache(all=False):
for pkg in cached: for pkg in cached:
try: try:
os.remove(pkg) os.remove(pkg)
except exceptions.OSError: except OSError:
pass pass
cacheDir = ctx.config.cached_packages_dir() 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: if not all:
# Cache limits from pisi.conf # Cache limits from pisi.conf
config = pisi.configfile.ConfigurationFile("/etc/pisi/pisi.conf") config = pisi.configfile.ConfigurationFile("/etc/pisi/pisi.conf")
+8 -7
View File
@@ -19,10 +19,11 @@ import errno
import shutil import shutil
import tarfile import tarfile
import zipfile import zipfile
import lzma
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# PiSi modules # PiSi modules
import pisi import pisi
@@ -73,7 +74,7 @@ class _LZMAProxy(object):
break break
b.append(data) b.append(data)
x += len(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] buf = self.buf[:size]
self.buf = self.buf[size:] self.buf = self.buf[size:]
@@ -106,7 +107,7 @@ class TarFile(tarfile.TarFile):
name=None, name=None,
mode="r", mode="r",
fileobj=None, fileobj=None,
compressformat="xz", compressformat=lzma.FORMAT_XZ,
compresslevel=9, compresslevel=9,
**kwargs): **kwargs):
"""Open lzma/xz compressed tar archive name for reading or writing. """Open lzma/xz compressed tar archive name for reading or writing.
@@ -126,12 +127,12 @@ class TarFile(tarfile.TarFile):
else: else:
options = {"format": compressformat, options = {"format": compressformat,
"level": compresslevel} "level": compresslevel}
fileobj = lzma.LZMAFile(name, mode, options=options) fileobj = lzma.LZMAFile(name, mode, format=1, preset=compresslevel)
try: try:
t = cls.taropen(name, mode, fileobj, **kwargs) t = cls.taropen(name, mode, fileobj, **kwargs)
except IOError: except IOError:
raise ReadError("not a lzma file") raise tarfile.ReadError("not a lzma file")
t._extfileobj = False t._extfileobj = False
return t return t
@@ -339,7 +340,7 @@ class ArchiveTar(ArchiveBase):
try: try:
self.tar.extract(tarinfo) self.tar.extract(tarinfo)
except OSError, e: except OSError as e:
# Handle the case where an upper directory cannot # Handle the case where an upper directory cannot
# be created because of a conflict with an existing # be created because of a conflict with an existing
# regular file or symlink. In this case, remove # regular file or symlink. In this case, remove
@@ -545,7 +546,7 @@ class ArchiveZip(ArchiveBase):
arc_name = arc_name or "" arc_name = arc_name or ""
self.zip_obj.writestr(arc_name + '/', '') self.zip_obj.writestr(arc_name + '/', '')
attr_obj = self.zip_obj.getinfo(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): for f in os.listdir(file_name):
self.add_to_archive(os.path.join(file_name, f), self.add_to_archive(os.path.join(file_name, f),
os.path.join(arc_name, f)) os.path.join(arc_name, f))
+8 -8
View File
@@ -13,7 +13,7 @@
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import os import os
import shutil import shutil
@@ -54,7 +54,7 @@ class AtomicOperation(object):
pass pass
# possible paths of install operation # 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"} opttostr = {INSTALL:"install", REMOVE:"remove", REINSTALL:"reinstall", UPGRADE:"upgrade", DOWNGRADE:"downgrade"}
class Install(AtomicOperation): class Install(AtomicOperation):
@@ -206,7 +206,7 @@ class Install(AtomicOperation):
if not self.pkginfo.conflicts: if not self.pkginfo.conflicts:
return True 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 # check file conflicts
file_conflicts = [] file_conflicts = []
@@ -450,8 +450,8 @@ class Install(AtomicOperation):
if self.reinstall(): if self.reinstall():
# get 'config' typed file objects # get 'config' typed file objects
new = filter(lambda x: x.type == 'config', self.files.list) new = [x for x in self.files.list if x.type == 'config']
old = filter(lambda x: x.type == 'config', self.old_files.list) old = [x for x in self.old_files.list if x.type == 'config']
# get config path lists # get config path lists
newconfig = set(str(x.path) for x in new) newconfig = set(str(x.path) for x in new)
@@ -459,7 +459,7 @@ class Install(AtomicOperation):
config_overlaps = newconfig & oldconfig config_overlaps = newconfig & oldconfig
if config_overlaps: 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: for f in files:
check_config_changed(f) check_config_changed(f)
else: else:
@@ -562,9 +562,9 @@ class Remove(AtomicOperation):
self.package = self.installdb.get_package(self.package_name) self.package = self.installdb.get_package(self.package_name)
try: try:
self.files = self.installdb.get_files(self.package_name) 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! # 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) ctx.ui.warning(_('File list could not be read for package %s, continuing removal.') % package_name)
self.files = pisi.files.Files() self.files = pisi.files.Files()
+14 -16
View File
@@ -15,7 +15,7 @@ import locale
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.context as ctx import pisi.context as ctx
@@ -31,13 +31,12 @@ class Exception(pisi.Exception):
def printu(obj, err = False): def printu(obj, err = False):
if not isinstance(obj, unicode): obj = str(obj)
obj = unicode(obj)
if err: if err:
out = sys.stderr out = sys.stderr
else: else:
out = sys.stdout out = sys.stdout
out.write(obj.encode('utf-8')) out.write(obj)
out.flush() out.flush()
class CLI(pisi.ui.UI): class CLI(pisi.ui.UI):
@@ -53,8 +52,7 @@ class CLI(pisi.ui.UI):
def output(self, msg, err = False, verbose = False): def output(self, msg, err = False, verbose = False):
if (verbose and self.show_verbose) or (not verbose): if (verbose and self.show_verbose) or (not verbose):
if type(msg)==type(unicode()): msg = str(msg)
msg = msg.encode('utf-8')
if err: if err:
out = sys.stderr out = sys.stderr
else: else:
@@ -99,17 +97,17 @@ class CLI(pisi.ui.UI):
if not noln: if not noln:
new_msg = "%s\n" % new_msg new_msg = "%s\n" % new_msg
msg = 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): def info(self, msg, verbose = False, noln = False):
# TODO: need to look at more kinds of info messages # TODO: need to look at more kinds of info messages
# let's cheat from KDE :) # let's cheat from KDE :)
if not noln: if not noln:
msg = '%s\n' % msg msg = '%s\n' % msg
self.output(unicode(msg), verbose=verbose) self.output(str(msg), verbose=verbose)
def warning(self, msg, verbose = False): def warning(self, msg, verbose = False):
msg = unicode(msg) msg = str(msg)
self.warnings += 1 self.warnings += 1
if ctx.log: if ctx.log:
ctx.log.warning(msg) 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) self.output(pisi.util.colorize(msg + '\n', 'brightyellow'), err=True, verbose=verbose)
def error(self, msg): def error(self, msg):
msg = unicode(msg) msg = str(msg)
self.errors += 1 self.errors += 1
if ctx.log: if ctx.log:
ctx.log.error(msg) ctx.log.error(msg)
@@ -130,22 +128,22 @@ class CLI(pisi.ui.UI):
def action(self, msg, verbose = False): def action(self, msg, verbose = False):
#TODO: this seems quite redundant? #TODO: this seems quite redundant?
msg = unicode(msg) msg = str(msg)
if ctx.log: if ctx.log:
ctx.log.info(msg) ctx.log.info(msg)
self.output(pisi.util.colorize(msg + '\n', 'green')) self.output(pisi.util.colorize(msg + '\n', 'green'))
def choose(self, msg, opts): def choose(self, msg, opts):
msg = unicode(msg) msg = str(msg)
prompt = msg + pisi.util.colorize(' (%s)' % "/".join(opts), 'red') prompt = msg + pisi.util.colorize(' (%s)' % "/".join(opts), 'red')
while True: while True:
s = raw_input(prompt.encode('utf-8')) s = input(prompt.encode('utf-8'))
for opt in opts: for opt in opts:
if opt.startswith(s): if opt.startswith(s):
return opt return opt
def confirm(self, msg): def confirm(self, msg):
msg = unicode(msg) msg = str(msg)
if ctx.config.options and ctx.config.options.yes_all: if ctx.config.options and ctx.config.options.yes_all:
return True return True
@@ -164,7 +162,7 @@ class CLI(pisi.ui.UI):
while True: while True:
tty.tcflush(sys.stdin.fileno(), 0) tty.tcflush(sys.stdin.fileno(), 0)
prompt = msg + pisi.util.colorize(_(' (yes/no)'), 'red') prompt = msg + pisi.util.colorize(_(' (yes/no)'), 'red')
s = raw_input(prompt.encode('utf-8')) s = input(prompt)
if yes_expr.search(s): if yes_expr.search(s):
return True return True
@@ -191,7 +189,7 @@ class CLI(pisi.ui.UI):
def status(self, msg = None): def status(self, msg = None):
if msg: if msg:
msg = unicode(msg) msg = str(msg)
self.output(pisi.util.colorize(msg + '\n', 'brightgreen')) self.output(pisi.util.colorize(msg + '\n', 'brightgreen'))
pisi.util.xterm_title(msg) pisi.util.xterm_title(msg)
+2 -3
View File
@@ -14,13 +14,13 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.api import pisi.api
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
class AddRepo(command.Command): class AddRepo(command.Command, metaclass=command.autocommand):
__doc__ = _("""Add a repository __doc__ = _("""Add a repository
Usage: add-repo <repo> <indexuri> 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 NB: We support only local files (e.g., /a/b/c) and http:// URIs at the moment
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(AddRepo, self).__init__(args) super(AddRepo, self).__init__(args)
+3 -5
View File
@@ -14,21 +14,19 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
import pisi.db import pisi.db
class Blame(command.Command): class Blame(command.Command, metaclass=command.autocommand):
__doc__ = _("""Information about the package owner and release __doc__ = _("""Information about the package owner and release
Usage: blame <package> ... <package> Usage: blame <package> ... <package>
""") """)
__metaclass__ = command.autocommand
def __init__(self, args=None): def __init__(self, args=None):
super(Blame, self).__init__(args) super(Blame, self).__init__(args)
self.installdb = pisi.db.installdb.InstallDB() self.installdb = pisi.db.installdb.InstallDB()
@@ -67,7 +65,7 @@ Usage: blame <package> ... <package>
def print_package_info(self, package, hno=0): def print_package_info(self, package, hno=0):
s = _('Name: %s, version: %s, release: %s\n') % ( s = _('Name: %s, version: %s, release: %s\n') % (
package.name, package.history[hno].version, package.history[hno].release) 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 += _('Release Updater: %s <%s>\n') % (package.history[hno].name, package.history[hno].email)
s += _('Update Date: %s\n') % package.history[hno].date s += _('Update Date: %s\n') % package.history[hno].date
s += '\n%s\n' % package.history[hno].comment s += '\n%s\n' % package.history[hno].comment
+2 -3
View File
@@ -14,7 +14,7 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.api 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 __doc__ = usage
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(Build, self).__init__(args) super(Build, self).__init__(args)
+2 -3
View File
@@ -14,7 +14,7 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.api import pisi.api
import pisi.cli.command as command 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 __doc__ = usage
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(Check, self).__init__(args) super(Check, self).__init__(args)
+2 -4
View File
@@ -12,11 +12,11 @@
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
class Clean(command.Command): class Clean(command.Command, metaclass=command.autocommand):
__doc__ = _("""Clean stale locks __doc__ = _("""Clean stale locks
Usage: clean Usage: clean
@@ -24,8 +24,6 @@ Usage: clean
PiSi uses filesystem locks for managing database access. PiSi uses filesystem locks for managing database access.
This command deletes unused locks from the database directory.""") This command deletes unused locks from the database directory.""")
__metaclass__ = command.autocommand
def __init__(self, args=None): def __init__(self, args=None):
super(Clean, self).__init__(args) super(Clean, self).__init__(args)
+6 -6
View File
@@ -16,7 +16,7 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.api import pisi.api
import pisi.context as ctx import pisi.context as ctx
@@ -30,7 +30,7 @@ class autocommand(type):
raise pisi.cli.Error(_('Command lacks name')) raise pisi.cli.Error(_('Command lacks name'))
longname, shortname = name longname, shortname = name
def add_cmd(cmd): 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) raise pisi.cli.Error(_('Duplicate command %s') % cmd)
else: else:
Command.cmd_dict[cmd] = cls Command.cmd_dict[cmd] = cls
@@ -54,7 +54,7 @@ class Command(object):
for name in l: for name in l:
commandcls = Command.cmd_dict[name] commandcls = Command.cmd_dict[name]
trans = gettext.translation('pisi', fallback=True) 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] name = commandcls.name[0]
if commandcls.name[1]: if commandcls.name[1]:
name += ' (%s)' % commandcls.name[1] name += ' (%s)' % commandcls.name[1]
@@ -64,7 +64,7 @@ class Command(object):
@staticmethod @staticmethod
def get_command(cmd, fail=False, args=None): 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) return Command.cmd_dict[cmd](args)
if fail: if fail:
@@ -182,8 +182,8 @@ class Command(object):
def help(self): def help(self):
"""print help for the command""" """print help for the command"""
trans = gettext.translation('pisi', fallback=True) trans = gettext.translation('pisi', fallback=True)
print "%s: %s\n" % (self.format_name(), trans.ugettext(self.__doc__)) print("%s: %s\n" % (self.format_name(), trans.gettext(self.__doc__)))
print self.parser.format_option_help() print(self.parser.format_option_help())
def die(self): def die(self):
"""exit program""" """exit program"""
+2 -4
View File
@@ -14,12 +14,12 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.api import pisi.api
import pisi.cli.command as command import pisi.cli.command as command
class ConfigurePending(command.PackageOp): class ConfigurePending(command.PackageOp, metaclass=command.autocommand):
__doc__ = _("""Configure pending packages __doc__ = _("""Configure pending packages
If COMAR configuration of some packages were not If COMAR configuration of some packages were not
@@ -28,8 +28,6 @@ of packages waiting to be configured. This command
configures those packages. configures those packages.
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(ConfigurePending, self).__init__(args) super(ConfigurePending, self).__init__(args)
+2 -4
View File
@@ -12,13 +12,13 @@
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.api import pisi.api
import pisi.cli.command as command import pisi.cli.command as command
class DeleteCache(command.Command): class DeleteCache(command.Command, metaclass=command.autocommand):
__doc__ = _("""Delete cache files __doc__ = _("""Delete cache files
Usage: delete-cache Usage: delete-cache
@@ -27,8 +27,6 @@ Sources, packages and temporary files are stored
under /var directory. Since these accumulate they can under /var directory. Since these accumulate they can
consume a lot of disk space.""") consume a lot of disk space.""")
__metaclass__ = command.autocommand
def __init__(self, args=None): def __init__(self, args=None):
super(DeleteCache, self).__init__(args) super(DeleteCache, self).__init__(args)
+2 -3
View File
@@ -14,7 +14,7 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.cli.command as command 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 __doc__ = usage
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(Delta, self).__init__(args) super(Delta, self).__init__(args)
+2 -3
View File
@@ -12,12 +12,12 @@
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.api import pisi.api
class DisableRepo(command.Command): class DisableRepo(command.Command, metaclass=command.autocommand):
__doc__ = _("""Disable repository __doc__ = _("""Disable repository
Usage: disable-repo [<repo1> <repo2> ... <repon>] 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 Disabled repositories are not taken into account in operations
""") """)
__metaclass__ = command.autocommand
def __init__(self,args): def __init__(self,args):
super(DisableRepo, self).__init__(args) super(DisableRepo, self).__init__(args)
+2 -3
View File
@@ -14,14 +14,14 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.cli.build as build import pisi.cli.build as build
import pisi.context as ctx import pisi.context as ctx
import pisi.api import pisi.api
class Emerge(build.Build): class Emerge(build.Build, metaclass=command.autocommand):
__doc__ = _("""Build and install PiSi source packages from repository __doc__ = _("""Build and install PiSi source packages from repository
Usage: emerge <sourcename> ... Usage: emerge <sourcename> ...
@@ -31,7 +31,6 @@ downloaded from a repository containing sources.
You can also give the name of a component. You can also give the name of a component.
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(Emerge, self).__init__(args) super(Emerge, self).__init__(args)
+2 -3
View File
@@ -12,12 +12,12 @@
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.api import pisi.api
class EnableRepo(command.Command): class EnableRepo(command.Command, metaclass=command.autocommand):
__doc__ = _("""Enable repository __doc__ = _("""Enable repository
Usage: enable-repo [<repo1> <repo2> ... <repon>] 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 Disabled repositories are not taken into account in operations
""") """)
__metaclass__ = command.autocommand
def __init__(self,args): def __init__(self,args):
super(EnableRepo, self).__init__(args) super(EnableRepo, self).__init__(args)
+2 -3
View File
@@ -15,13 +15,13 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
import pisi.api import pisi.api
class Fetch(command.Command): class Fetch(command.Command, metaclass=command.autocommand):
__doc__ = _("""Fetch a package __doc__ = _("""Fetch a package
Usage: fetch [<package1> <package2> ... <packagen>] Usage: fetch [<package1> <package2> ... <packagen>]
@@ -30,7 +30,6 @@ Usage: fetch [<package1> <package2> ... <packagen>]
Downloads the given pisi packages to working directory Downloads the given pisi packages to working directory
""") """)
__metaclass__ = command.autocommand
def __init__(self,args): def __init__(self,args):
super(Fetch, self).__init__(args) super(Fetch, self).__init__(args)
+2 -4
View File
@@ -14,7 +14,7 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.api import pisi.api
@@ -22,7 +22,7 @@ import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
import pisi.db import pisi.db
class Graph(command.Command): class Graph(command.Command, metaclass=command.autocommand):
__doc__ = _("""Graph package relations __doc__ = _("""Graph package relations
Usage: graph [<package1> <package2> ...] 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'. the package in graphviz format to 'pgraph.dot'.
""") """)
__metaclass__ = command.autocommand
def __init__(self, args=None): def __init__(self, args=None):
super(Graph, self).__init__(args) super(Graph, self).__init__(args)
+2 -4
View File
@@ -12,21 +12,19 @@
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli import pisi.cli
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
class Help(command.Command): class Help(command.Command, metaclass=command.autocommand):
__doc__ = _("""Prints help for given commands __doc__ = _("""Prints help for given commands
Usage: help [ <command1> <command2> ... <commandn> ] Usage: help [ <command1> <command2> ... <commandn> ]
If run without parameters, it prints the general help.""") If run without parameters, it prints the general help.""")
__metaclass__ = command.autocommand
def __init__(self, args = None): def __init__(self, args = None):
super(Help, self).__init__(args) super(Help, self).__init__(args)
+10 -12
View File
@@ -16,7 +16,7 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.api import pisi.api
@@ -27,15 +27,13 @@ import pisi.cli.command as command
# Operation names for translation # Operation names for translation
opttrans = {"upgrade":_("upgrade"),"remove":_("remove"),"emerge":_("emerge"), "install":_("install"), "snapshot":_("snapshot"), "takeback":_("takeback"), "repoupdate":_("repository update")} 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 __doc__ = _("""History of pisi operations
Usage: history Usage: history
Lists previous operations.""") Lists previous operations.""")
__metaclass__ = command.autocommand
def __init__(self, args=None): def __init__(self, args=None):
super(History, self).__init__(args) super(History, self).__init__(args)
self.historydb = pisi.db.historydb.HistoryDB() self.historydb = pisi.db.historydb.HistoryDB()
@@ -64,19 +62,19 @@ Lists previous operations.""")
def print_history(self): def print_history(self):
for operation in self.historydb.get_last(ctx.get_option('last')): for operation in self.historydb.get_last(ctx.get_option('last')):
print _("Operation #%d: %s") % (operation.no, opttrans[operation.type]) print(_("Operation #%d: %s") % (operation.no, opttrans[operation.type]))
print _("Date: %s %s") % (operation.date, operation.time) print(_("Date: %s %s") % (operation.date, operation.time))
print print()
if operation.type == "snapshot": 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": elif operation.type == "repoupdate":
for repo in operation.repos: for repo in operation.repos:
print " *", repo print(" *", repo)
else: else:
for pkg in operation.packages: for pkg in operation.packages:
print " *", pkg print(" *", pkg)
print print()
def redirect_output(self, func): def redirect_output(self, func):
if os.isatty(sys.stdout.fileno()): if os.isatty(sys.stdout.fileno()):
@@ -98,7 +96,7 @@ Lists previous operations.""")
def write(self, s): def write(self, s):
try: try:
self.less.stdin.write(s) self.less.stdin.write(s.encode())
except IOError: except IOError:
raise LessException raise LessException
+2 -3
View File
@@ -14,7 +14,7 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx 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 __doc__ = usage
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(Index, self).__init__(args) super(Index, self).__init__(args)
+12 -13
View File
@@ -14,7 +14,7 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
@@ -22,14 +22,13 @@ import pisi.util as util
import pisi.api import pisi.api
import pisi.db import pisi.db
class Info(command.Command): class Info(command.Command, metaclass=command.autocommand):
__doc__ = _("""Display package information __doc__ = _("""Display package information
Usage: info <package1> <package2> ... <packagen> Usage: info <package1> <package2> ... <packagen>
<packagei> is either a package name or a .pisi file, <packagei> is either a package name or a .pisi file,
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(Info, self).__init__(args) super(Info, self).__init__(args)
@@ -81,7 +80,7 @@ Usage: info <package1> <package2> ... <packagen>
index.add_component(component) index.add_component(component)
else: else:
if not self.options.short: if not self.options.short:
ctx.ui.info(unicode(component)) ctx.ui.info(str(component))
else: else:
ctx.ui.info("%s - %s" % (component.name, component.summary)) 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) files.list.sort(key = lambda x:x.path)
for fileinfo in files.list: for fileinfo in files.list:
if self.options.files: if self.options.files:
print fileinfo print(fileinfo)
else: else:
print "/" + fileinfo.path print("/" + fileinfo.path)
def print_metadata(self, metadata, packagedb=None): def print_metadata(self, metadata, packagedb=None):
if ctx.get_option('short'): if ctx.get_option('short'):
pkg = metadata.package pkg = metadata.package
ctx.ui.formatted_output(" - ".join((pkg.name, unicode(pkg.summary)))) ctx.ui.formatted_output(" - ".join((pkg.name, str(pkg.summary))))
else: else:
ctx.ui.formatted_output(unicode(metadata.package)) ctx.ui.formatted_output(str(metadata.package))
if packagedb: if packagedb:
revdeps = [name for name, dep in packagedb.get_rev_deps(metadata.package.name)] revdeps = [name for name, dep in packagedb.get_rev_deps(metadata.package.name)]
ctx.ui.formatted_output(" ".join((_("Reverse Dependencies:"), util.strlist(revdeps)))) ctx.ui.formatted_output(" ".join((_("Reverse Dependencies:"), util.strlist(revdeps))))
print print()
def print_specdata(self, spec, sourcedb=None): def print_specdata(self, spec, sourcedb=None):
src = spec.source src = spec.source
if ctx.get_option('short'): 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: else:
ctx.ui.formatted_output(unicode(spec)) ctx.ui.formatted_output(str(spec))
if sourcedb: if sourcedb:
revdeps = [name for name, dep in sourcedb.get_rev_deps(spec.source.name)] revdeps = [name for name, dep in sourcedb.get_rev_deps(spec.source.name)]
print _('Reverse Build Dependencies:'), util.strlist(revdeps) print(_('Reverse Build Dependencies:'), util.strlist(revdeps))
print print()
def pisifile_info(self, package): def pisifile_info(self, package):
metadata, files = pisi.api.info_file(package) metadata, files = pisi.api.info_file(package)
+2 -3
View File
@@ -14,14 +14,14 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
import pisi.api import pisi.api
import pisi.db import pisi.db
class Install(command.PackageOp): class Install(command.PackageOp, metaclass=command.autocommand):
__doc__ = _("""Install PiSi packages __doc__ = _("""Install PiSi packages
Usage: install <package1> <package2> ... <packagen> 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 You can also specify components instead of package names, which will be
expanded to package names. expanded to package names.
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(Install, self).__init__(args) super(Install, self).__init__(args)
+5 -6
View File
@@ -14,7 +14,7 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
@@ -22,7 +22,7 @@ import pisi.util as util
import pisi.api import pisi.api
import pisi.db import pisi.db
class ListAvailable(command.Command): class ListAvailable(command.Command, metaclass=command.autocommand):
__doc__ = _("""List available packages in the repositories __doc__ = _("""List available packages in the repositories
Usage: list-available [ <repo1> <repo2> ... repon ] 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 repositories. If no repository is specified, we list packages in
all repositories. all repositories.
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(ListAvailable, self).__init__(args) super(ListAvailable, self).__init__(args)
@@ -73,7 +72,7 @@ all repositories.
if component: if component:
try: try:
l = self.componentdb.get_packages(component, repo=repo, walk=True) l = self.componentdb.get_packages(component, repo=repo, walk=True)
except Exception, e: except Exception as e:
return return
else: else:
l = pisi.api.list_available(repo) l = pisi.api.list_available(repo)
@@ -97,7 +96,7 @@ all repositories.
package.name = util.colorize(package.name, 'brightwhite') package.name = util.colorize(package.name, 'brightwhite')
if self.options.long: if self.options.long:
ctx.ui.info(unicode(package)+'\n') ctx.ui.info(str(package)+'\n')
else: else:
package.name += ' ' * max(0, maxlen - len(p)) 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 import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
import pisi.db import pisi.db
class ListComponents(command.Command): class ListComponents(command.Command, metaclass=command.autocommand):
__doc__ = _("""List available components __doc__ = _("""List available components
Usage: list-components Usage: list-components
@@ -28,7 +28,6 @@ Usage: list-components
Gives a brief list of PiSi components published in the Gives a brief list of PiSi components published in the
repositories. repositories.
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(ListComponents, self).__init__(args) super(ListComponents, self).__init__(args)
@@ -53,10 +52,10 @@ repositories.
for p in l: for p in l:
component = self.componentdb.get_component(p) component = self.componentdb.get_component(p)
if self.options.long: if self.options.long:
ctx.ui.info(unicode(component)) ctx.ui.info(str(component))
else: else:
lenp = len(p) lenp = len(p)
#if p in installed_list: #if p in installed_list:
# p = util.colorize(p, 'cyan') # p = util.colorize(p, 'cyan')
p = p + ' ' * max(0, 15 - lenp) 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 import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
import pisi.db import pisi.db
class ListInstalled(command.Command): class ListInstalled(command.Command, metaclass=command.autocommand):
__doc__ = _("""Print the list of all installed packages __doc__ = _("""Print the list of all installed packages
Usage: list-installed Usage: list-installed
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(ListInstalled, self).__init__(args) super(ListInstalled, self).__init__(args)
self.installdb = pisi.db.installdb.InstallDB() self.installdb = pisi.db.installdb.InstallDB()
@@ -76,15 +74,15 @@ Usage: list-installed
if self.options.install_info: if self.options.install_info:
ctx.ui.info(_('Package Name |St| Version| Rel.| Distro| Date')) ctx.ui.info(_('Package Name |St| Version| Rel.| Distro| Date'))
print '===========================================================================' print('===========================================================================')
for pkg in installed: for pkg in installed:
package = self.installdb.get_package(pkg) package = self.installdb.get_package(pkg)
inst_info = self.installdb.get_info(pkg) inst_info = self.installdb.get_info(pkg)
if self.options.long: if self.options.long:
ctx.ui.info(unicode(package)) ctx.ui.info(str(package))
ctx.ui.info(unicode(inst_info)) ctx.ui.info(str(inst_info))
elif self.options.install_info: elif self.options.install_info:
ctx.ui.info('%-20s |%s' % (package.name, inst_info.one_liner())) ctx.ui.info('%-20s |%s' % (package.name, inst_info.one_liner()))
else: else:
package.name = package.name + ' ' * (maxlen - len(package.name)) 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 import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
import pisi.api import pisi.api
import pisi.db import pisi.db
class ListNewest(command.Command): class ListNewest(command.Command, metaclass=command.autocommand):
__doc__ = _("""List newest packages in the repositories __doc__ = _("""List newest packages in the repositories
Usage: list-newest [ <repo1> <repo2> ... repon ] 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 repositories. If no repository is specified, we list the new
packages from all repositories. packages from all repositories.
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(ListNewest, self).__init__(args) super(ListNewest, self).__init__(args)
@@ -85,7 +84,7 @@ packages from all repositories.
package = self.packagedb.get_package(p, repo) package = self.packagedb.get_package(p, repo)
lenp = len(p) lenp = len(p)
p = p + ' ' * max(0, maxlen - lenp) 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 import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
import pisi.api import pisi.api
class ListPending(command.Command): class ListPending(command.Command, metaclass=command.autocommand):
__doc__ = _("""List pending packages __doc__ = _("""List pending packages
Lists packages waiting to be configured. Lists packages waiting to be configured.
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(ListPending, self).__init__(args) super(ListPending, self).__init__(args)
@@ -36,6 +35,6 @@ Lists packages waiting to be configured.
A = pisi.api.list_pending() A = pisi.api.list_pending()
if len(A): if len(A):
for p in pisi.api.generate_pending_order(A): for p in pisi.api.generate_pending_order(A):
print p print(p)
else: else:
ctx.ui.info(_('There are no packages waiting to be configured')) ctx.ui.info(_('There are no packages waiting to be configured'))
+3 -4
View File
@@ -12,21 +12,20 @@
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
import pisi.util as util import pisi.util as util
import pisi.db import pisi.db
class ListRepo(command.Command): class ListRepo(command.Command, metaclass=command.autocommand):
__doc__ = _("""List repositories __doc__ = _("""List repositories
Usage: list-repo Usage: list-repo
Lists currently tracked repositories. Lists currently tracked repositories.
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(ListRepo, self).__init__(args) super(ListRepo, self).__init__(args)
@@ -43,5 +42,5 @@ Lists currently tracked repositories.
ctx.ui.info(util.colorize(_("%s [%s]") % (repo, active), 'green')) ctx.ui.info(util.colorize(_("%s [%s]") % (repo, active), 'green'))
else: else:
ctx.ui.info(util.colorize(_("%s [%s]") % (repo, active), 'red')) 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 import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
import pisi.db import pisi.db
class ListSources(command.Command): class ListSources(command.Command, metaclass=command.autocommand):
__doc__ = _("""List available sources __doc__ = _("""List available sources
Usage: list-sources Usage: list-sources
Gives a brief list of sources published in the repositories. Gives a brief list of sources published in the repositories.
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(ListSources, self).__init__(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) sf, repo = self.sourcedb.get_spec_repo(p)
if self.options.long: if self.options.long:
ctx.ui.info('[Repository: ' + repo + ']') ctx.ui.info('[Repository: ' + repo + ']')
ctx.ui.info(unicode(sf.source)) ctx.ui.info(str(sf.source))
else: else:
lenp = len(p) lenp = len(p)
#if p in installed_list: #if p in installed_list:
# p = util.colorize(p, 'cyan') # p = util.colorize(p, 'cyan')
p = p + ' ' * max(0, 15 - lenp) 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 import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.blacklist import pisi.blacklist
@@ -22,14 +22,13 @@ import pisi.context as ctx
import pisi.api import pisi.api
import pisi.db import pisi.db
class ListUpgrades(command.Command): class ListUpgrades(command.Command, metaclass=command.autocommand):
__doc__ = _("""List packages to be upgraded __doc__ = _("""List packages to be upgraded
Usage: list-upgrades Usage: list-upgrades
Lists the packages that will be upgraded. Lists the packages that will be upgraded.
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(ListUpgrades, self).__init__(args) super(ListUpgrades, self).__init__(args)
@@ -71,15 +70,15 @@ Lists the packages that will be upgraded.
if self.options.install_info: if self.options.install_info:
ctx.ui.info(_('Package Name |St| Version| Rel.| Distro| Date')) ctx.ui.info(_('Package Name |St| Version| Rel.| Distro| Date'))
print '===========================================================================' print('===========================================================================')
for pkg in upgradable_pkgs: for pkg in upgradable_pkgs:
package = self.installdb.get_package(pkg) package = self.installdb.get_package(pkg)
inst_info = self.installdb.get_info(pkg) inst_info = self.installdb.get_info(pkg)
if self.options.long: if self.options.long:
ctx.ui.info(package) ctx.ui.info(package)
print inst_info print(inst_info)
elif self.options.install_info: elif self.options.install_info:
ctx.ui.info('%-20s |%s ' % (package.name, inst_info.one_liner())) ctx.ui.info('%-20s |%s ' % (package.name, inst_info.one_liner()))
else: else:
package.name = package.name + ' ' * (maxlen - len(package.name)) 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 import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.cli import pisi.cli
@@ -66,7 +66,7 @@ class PreParser(optparse.OptionParser):
optparse.OptionParser.__init__(self, usage=pisi.cli.help.usage_text, version=version) optparse.OptionParser.__init__(self, usage=pisi.cli.help.usage_text, version=version)
def error(self, msg): def error(self, msg):
raise ParserError, msg raise ParserError(msg)
def parse_args(self, args=None): def parse_args(self, args=None):
self.opts = [] self.opts = []
+2 -3
View File
@@ -14,13 +14,13 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
import pisi.api import pisi.api
class RebuildDb(command.Command): class RebuildDb(command.Command, metaclass=command.autocommand):
__doc__ = _("""Rebuild Databases __doc__ = _("""Rebuild Databases
Usage: rebuilddb [ <package1> <package2> ... <packagen> ] 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 If package specs are given, they should be the names of package
dirs under /var/lib/pisi dirs under /var/lib/pisi
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(RebuildDb, self).__init__(args) super(RebuildDb, self).__init__(args)
+2 -3
View File
@@ -14,14 +14,14 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
import pisi.api import pisi.api
import pisi.db import pisi.db
class Remove(command.PackageOp): class Remove(command.PackageOp, metaclass=command.autocommand):
__doc__ = _("""Remove PiSi packages __doc__ = _("""Remove PiSi packages
Usage: remove <package1> <package2> ... <packagen> 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 You can also specify components instead of package names, which will be
expanded to package names. expanded to package names.
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(Remove, self).__init__(args) super(Remove, self).__init__(args)
+2 -3
View File
@@ -12,19 +12,18 @@
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.api import pisi.api
class RemoveRepo(command.Command): class RemoveRepo(command.Command, metaclass=command.autocommand):
__doc__ = _("""Remove repositories __doc__ = _("""Remove repositories
Usage: remove-repo <repo1> <repo2> ... <repon> Usage: remove-repo <repo1> <repo2> ... <repon>
Remove all repository information from the system. Remove all repository information from the system.
""") """)
__metaclass__ = command.autocommand
def __init__(self,args): def __init__(self,args):
super(RemoveRepo, self).__init__(args) super(RemoveRepo, self).__init__(args)
+3 -4
View File
@@ -15,13 +15,13 @@ import re
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
import pisi.db import pisi.db
class Search(command.Command): class Search(command.Command, metaclass=command.autocommand):
__doc__ = _("""Search packages __doc__ = _("""Search packages
Usage: search <term1> <term2> ... <termn> 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 options to search in install database or source
database. database.
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(Search, self).__init__(args) super(Search, self).__init__(args)
@@ -101,7 +100,7 @@ database.
lenp = len(name) lenp = len(name)
name = replace.sub(pisi.util.colorize(r"\1", "brightred"), 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])) summary = replace.sub(pisi.util.colorize(r"\1", "brightred"), str(summary[lang]))
else: else:
summary = replace.sub(pisi.util.colorize(r"\1", "brightred"), str(summary)) summary = replace.sub(pisi.util.colorize(r"\1", "brightred"), str(summary))
+2 -3
View File
@@ -14,20 +14,19 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.context as ctx import pisi.context as ctx
import pisi.cli.command as command import pisi.cli.command as command
class SearchFile(command.Command): class SearchFile(command.Command, metaclass=command.autocommand):
__doc__ = _("""Search for a file __doc__ = _("""Search for a file
Usage: search-file <path1> <path2> ... <pathn> Usage: search-file <path1> <path2> ... <pathn>
Finds the installed package which contains the specified file. Finds the installed package which contains the specified file.
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(SearchFile, self).__init__(args) super(SearchFile, self).__init__(args)
+2 -3
View File
@@ -14,13 +14,13 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
import pisi.api import pisi.api
class UpdateRepo(command.Command): class UpdateRepo(command.Command, metaclass=command.autocommand):
__doc__ = _("""Update repository databases __doc__ = _("""Update repository databases
Usage: update-repo [<repo1> <repo2> ... <repon>] Usage: update-repo [<repo1> <repo2> ... <repon>]
@@ -30,7 +30,6 @@ Usage: update-repo [<repo1> <repo2> ... <repon>]
Synchronizes the PiSi databases with the current repository. Synchronizes the PiSi databases with the current repository.
If no repository is given, all repositories are updated. If no repository is given, all repositories are updated.
""") """)
__metaclass__ = command.autocommand
def __init__(self,args): def __init__(self,args):
super(UpdateRepo, self).__init__(args) super(UpdateRepo, self).__init__(args)
+2 -3
View File
@@ -14,14 +14,14 @@ import optparse
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.cli.command as command import pisi.cli.command as command
import pisi.context as ctx import pisi.context as ctx
import pisi.api import pisi.api
import pisi.db import pisi.db
class Upgrade(command.PackageOp): class Upgrade(command.PackageOp, metaclass=command.autocommand):
__doc__ = _("""Upgrade PiSi packages __doc__ = _("""Upgrade PiSi packages
Usage: Upgrade [<package1> <package2> ... <packagen>] 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 You can also specify components instead of package names, which will be
expanded to package names. expanded to package names.
""") """)
__metaclass__ = command.autocommand
def __init__(self, args): def __init__(self, args):
super(Upgrade, self).__init__(args) super(Upgrade, self).__init__(args)
+12 -12
View File
@@ -16,7 +16,7 @@ import string
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.context as ctx import pisi.context as ctx
@@ -79,9 +79,9 @@ def get_link():
link = comar.Link(socket=sockname, alternate=alternate) link = comar.Link(socket=sockname, alternate=alternate)
link.setLocale() link.setLocale()
return link return link
except dbus.DBusException, e: except dbus.DBusException as e:
exceptions.append(str(e)) exceptions.append(str(e))
except Exception, e: except Exception as e:
exceptions.append(str(e)) exceptions.append(str(e))
time.sleep(0.2) time.sleep(0.2)
timeout -= 0.2 timeout -= 0.2
@@ -115,12 +115,12 @@ def post_install(package_name, provided_scripts,
try: try:
link.register(script_name, script.om, link.register(script_name, script.om,
os.path.join(scriptpath, script.script)) os.path.join(scriptpath, script.script))
except dbus.DBusException, exception: except dbus.DBusException as exception:
raise Error(_("Script error: %s") % exception) raise Error(_("Script error: %s") % exception)
if script.om == "System.Service": if script.om == "System.Service":
try: try:
link.System.Service[script_name].registerState() link.System.Service[script_name].registerState()
except dbus.DBusException, exception: except dbus.DBusException as exception:
raise Error(_("Script error: %s") % exception) raise Error(_("Script error: %s") % exception)
ctx.ui.debug(_("Calling post install handlers")) ctx.ui.debug(_("Calling post install handlers"))
@@ -130,7 +130,7 @@ def post_install(package_name, provided_scripts,
metapath, metapath,
filepath, filepath,
timeout=ctx.dbus_timeout) timeout=ctx.dbus_timeout)
except dbus.DBusException, exception: except dbus.DBusException as exception:
# Do nothing if setupPackage method is not defined # Do nothing if setupPackage method is not defined
# in package script # in package script
if not is_method_missing(exception): if not is_method_missing(exception):
@@ -147,7 +147,7 @@ def post_install(package_name, provided_scripts,
link.System.Package[package_name].postInstall( link.System.Package[package_name].postInstall(
fromVersion, fromRelease, toVersion, toRelease, fromVersion, fromRelease, toVersion, toRelease,
timeout=ctx.dbus_timeout) timeout=ctx.dbus_timeout)
except dbus.DBusException, exception: except dbus.DBusException as exception:
# Do nothing if postInstall method is not defined in package script # Do nothing if postInstall method is not defined in package script
if not is_method_missing(exception): if not is_method_missing(exception):
raise Error(_("Script error: %s") % exception) raise Error(_("Script error: %s") % exception)
@@ -166,7 +166,7 @@ def pre_remove(package_name, metapath, filepath):
try: try:
link.System.Package[package_name].preRemove( link.System.Package[package_name].preRemove(
timeout=ctx.dbus_timeout) timeout=ctx.dbus_timeout)
except dbus.DBusException, exception: except dbus.DBusException as exception:
# Do nothing if preRemove method is not defined in package script # Do nothing if preRemove method is not defined in package script
if not is_method_missing(exception): if not is_method_missing(exception):
raise Error(_("Script error: %s") % exception) raise Error(_("Script error: %s") % exception)
@@ -176,7 +176,7 @@ def pre_remove(package_name, metapath, filepath):
try: try:
link.System.PackageHandler[handler].cleanupPackage( link.System.PackageHandler[handler].cleanupPackage(
metapath, filepath, timeout=ctx.dbus_timeout) metapath, filepath, timeout=ctx.dbus_timeout)
except dbus.DBusException, exception: except dbus.DBusException as exception:
# Do nothing if cleanupPackage method is not defined # Do nothing if cleanupPackage method is not defined
# in package script # in package script
if not is_method_missing(exception): if not is_method_missing(exception):
@@ -199,7 +199,7 @@ def post_remove(package_name, metapath, filepath, provided_scripts=[]):
try: try:
link.System.Package[package_name].postRemove( link.System.Package[package_name].postRemove(
timeout=ctx.dbus_timeout) timeout=ctx.dbus_timeout)
except dbus.DBusException, exception: except dbus.DBusException as exception:
# Do nothing if postRemove method is not defined in package script # Do nothing if postRemove method is not defined in package script
if not is_method_missing(exception): if not is_method_missing(exception):
raise Error(_("Script error: %s") % exception) raise Error(_("Script error: %s") % exception)
@@ -209,7 +209,7 @@ def post_remove(package_name, metapath, filepath, provided_scripts=[]):
try: try:
link.System.PackageHandler[handler].postCleanupPackage( link.System.PackageHandler[handler].postCleanupPackage(
metapath, filepath, timeout=ctx.dbus_timeout) metapath, filepath, timeout=ctx.dbus_timeout)
except dbus.DBusException, exception: except dbus.DBusException as exception:
# Do nothing if postCleanupPackage method is not defined # Do nothing if postCleanupPackage method is not defined
# in package script # in package script
if not is_method_missing(exception): if not is_method_missing(exception):
@@ -219,5 +219,5 @@ def post_remove(package_name, metapath, filepath, provided_scripts=[]):
for scr in scripts: for scr in scripts:
try: try:
link.remove(scr, timeout=ctx.dbus_timeout) link.remove(scr, timeout=ctx.dbus_timeout)
except dbus.DBusException, exception: except dbus.DBusException as exception:
raise Error(_("Script error: %s") % exception) raise Error(_("Script error: %s") % exception)
+7 -17
View File
@@ -13,22 +13,18 @@
import pisi.pxml.xmlfile as xmlfile import pisi.pxml.xmlfile as xmlfile
import pisi.pxml.autoxml as autoxml import pisi.pxml.autoxml as autoxml
class Error(object): class Error(object, metaclass=autoxml.autoxml):
__metaclass__ = autoxml.autoxml pass
class Obsolete: class Obsolete(metaclass=autoxml.autoxml):
__metaclass__ = autoxml.autoxml
s_Package = [autoxml.String, autoxml.mandatory] s_Package = [autoxml.String, autoxml.mandatory]
def __str__(self): def __str__(self):
return self.package return self.package
class Distribution(xmlfile.XmlFile): class Distribution(xmlfile.XmlFile, metaclass=autoxml.autoxml):
__metaclass__ = autoxml.autoxml
tag = "PISI" tag = "PISI"
@@ -43,11 +39,9 @@ class Distribution(xmlfile.XmlFile):
t_Obsoletes = [ [Obsolete], autoxml.optional, "Obsoletes/Package"] t_Obsoletes = [ [Obsolete], autoxml.optional, "Obsoletes/Package"]
class Maintainer(xmlfile.XmlFile): class Maintainer(xmlfile.XmlFile, metaclass=autoxml.autoxml):
"representation for component responsibles" "representation for component responsibles"
__metaclass__ = autoxml.autoxml
t_Name = [autoxml.Text, autoxml.mandatory] t_Name = [autoxml.Text, autoxml.mandatory]
t_Email = [autoxml.String, autoxml.mandatory] t_Email = [autoxml.String, autoxml.mandatory]
@@ -55,11 +49,9 @@ class Maintainer(xmlfile.XmlFile):
s = "%s <%s>" % (self.name, self.email) s = "%s <%s>" % (self.name, self.email)
return s return s
class Component(xmlfile.XmlFile): class Component(xmlfile.XmlFile, metaclass=autoxml.autoxml):
"representation for component declarations" "representation for component declarations"
__metaclass__ = autoxml.autoxml
t_Name = [autoxml.String, autoxml.mandatory] # fully qualified name t_Name = [autoxml.String, autoxml.mandatory] # fully qualified name
# component name in other languages, for instance in Turkish # 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"] t_Sources = [ [autoxml.String], autoxml.optional, "Parts/Source"]
class Components(xmlfile.XmlFile): class Components(xmlfile.XmlFile, metaclass=autoxml.autoxml):
"representation for component declarations" "representation for component declarations"
__metaclass__ = autoxml.autoxml
tag = "PISI" tag = "PISI"
t_Components = [ [Component], autoxml.optional, "Components/Component" ] t_Components = [ [Component], autoxml.optional, "Components/Component" ]
+4 -6
View File
@@ -20,7 +20,7 @@ import copy
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.context as ctx import pisi.context as ctx
@@ -32,7 +32,7 @@ class Error(pisi.Error):
class Options(object): class Options(object):
def __getattr__(self, name): def __getattr__(self, name):
if not self.__dict__.has_key(name): if name not in self.__dict__:
return None return None
else: else:
return self.__dict__[name] return self.__dict__[name]
@@ -40,11 +40,9 @@ class Options(object):
def __setattr__(self, name, value): def __setattr__(self, name, value):
self.__dict__[name] = value self.__dict__[name] = value
class Config(object): class Config(object, metaclass=pisi.util.Singleton):
"""Config Singleton""" """Config Singleton"""
__metaclass__ = pisi.util.Singleton
def __init__(self, options = Options()): def __init__(self, options = Options()):
self.set_options(options) self.set_options(options)
self.values = pisi.configfile.ConfigurationFile("/etc/pisi/pisi.conf") self.values = pisi.configfile.ConfigurationFile("/etc/pisi/pisi.conf")
@@ -137,7 +135,7 @@ class Config(object):
def tmp_dir(self): def tmp_dir(self):
sysdir = self.subdir(self.values.dirs.tmp_dir) 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']) userdir = self.subdir('/tmp/pisi-' + os.environ['USER'])
else: else:
userdir = self.subdir('/tmp/pisi-root') userdir = self.subdir('/tmp/pisi-root')
+16 -16
View File
@@ -60,12 +60,12 @@
import os import os
import re import re
import StringIO import io
import ConfigParser import configparser
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
@@ -150,7 +150,7 @@ class ConfigurationSection(object):
self.defaults = DirectoriesDefaults self.defaults = DirectoriesDefaults
else: else:
e = _("No section by name '%s'") % section e = _("No section by name '%s'") % section
raise Error, e raise Error(e)
self.section = section self.section = section
@@ -182,26 +182,26 @@ class ConfigurationSection(object):
class ConfigurationFile(object): class ConfigurationFile(object):
"""Parse and get configuration values from the configuration file""" """Parse and get configuration values from the configuration file"""
def __init__(self, filePath): def __init__(self, filePath):
self.parser = ConfigParser.ConfigParser() self.parser = configparser.ConfigParser()
self.filePath = filePath self.filePath = filePath
self.parser.read(self.filePath) self.parser.read(self.filePath)
try: try:
generalitems = self.parser.items("general") generalitems = self.parser.items("general")
except ConfigParser.NoSectionError: except configparser.NoSectionError:
generalitems = [] generalitems = []
self.general = ConfigurationSection("general", generalitems) self.general = ConfigurationSection("general", generalitems)
try: try:
builditems = self.parser.items("build") builditems = self.parser.items("build")
except ConfigParser.NoSectionError: except configparser.NoSectionError:
builditems = [] builditems = []
self.build = ConfigurationSection("build", builditems) self.build = ConfigurationSection("build", builditems)
try: try:
dirsitems = self.parser.items("directories") dirsitems = self.parser.items("directories")
except ConfigParser.NoSectionError: except configparser.NoSectionError:
dirsitems = [] dirsitems = []
self.dirs = ConfigurationSection("directories", dirsitems) self.dirs = ConfigurationSection("directories", dirsitems)
@@ -213,7 +213,7 @@ class ConfigurationFile(object):
def get(self, section, option): def get(self, section, option):
try: try:
return self.parser.get(section, option) return self.parser.get(section, option)
except ConfigParser.NoOptionError: except configparser.NoOptionError:
return None return None
def set(self, section, option, value): def set(self, section, option, value):
@@ -221,7 +221,7 @@ class ConfigurationFile(object):
def write_config(self, add_missing=True): def write_config(self, add_missing=True):
sections = {} sections = {}
current = StringIO.StringIO() current = io.StringIO()
replacement = [current] replacement = [current]
sect = None sect = None
opt = None opt = None
@@ -269,10 +269,10 @@ class ConfigurationFile(object):
if sect: if sect:
sections[sect] = current sections[sect] = current
sect = mo.group('header') sect = mo.group('header')
current = StringIO.StringIO() current = io.StringIO()
replacement.append(current) replacement.append(current)
sects = self.parser.sections() sects = self.parser.sections()
sects.append(ConfigParser.DEFAULTSECT) sects.append(configparser.DEFAULTSECT)
if sect in sects: if sect in sects:
current.write(line) current.write(line)
# So sections can't start with a continuation line: # So sections can't start with a continuation line:
@@ -307,14 +307,14 @@ class ConfigurationFile(object):
# Add any new sections. # Add any new sections.
sects = self.parser.sections() sects = self.parser.sections()
if len(self.parser._defaults) > 0: if len(self.parser._defaults) > 0:
sects.append(ConfigParser.DEFAULTSECT) sects.append(configparser.DEFAULTSECT)
sects.sort() sects.sort()
for sect in sects: for sect in sects:
if sect == ConfigParser.DEFAULTSECT: if sect == configparser.DEFAULTSECT:
opts = self.parser._defaults.keys() opts = list(self.parser._defaults.keys())
else: else:
# Must use _section here to avoid defaults. # Must use _section here to avoid defaults.
opts = self.parser._sections[sect].keys() opts = list(self.parser._sections[sect].keys())
opts.sort() opts.sort()
if sect in sections: if sect in sections:
output = sections[sect] or current output = sections[sect] or current
+5 -5
View File
@@ -14,7 +14,7 @@
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.relation import pisi.relation
@@ -70,13 +70,13 @@ def calculate_conflicts(order, packagedb):
# check if any package has conflicts with the installed packages # check if any package has conflicts with the installed packages
conflicts = check_installed(pkg, order) conflicts = check_installed(pkg, order)
if conflicts: if conflicts:
conflicting_pairs[x] = map(lambda c:str(c), conflicts) conflicting_pairs[x] = [str(c) for c in conflicts]
conflicting_pkgs = conflicting_pkgs.union(map(lambda c:c.package, conflicts)) conflicting_pkgs = conflicting_pkgs.union([c.package for c in conflicts])
# now check if any package has conflicts with each other # 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() 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) conflicted = package_conflicts(p, pkg.conflicts)
if conflicted: if conflicted:
conflicts_inorder_i.add(str(conflicted)) conflicts_inorder_i.add(str(conflicted))
+8 -10
View File
@@ -16,7 +16,7 @@ defined."""
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
from pisi.util import Singleton from pisi.util import Singleton
@@ -26,22 +26,20 @@ class _constant:
pass pass
def __setattr__(self, name, value): def __setattr__(self, name, value):
if self.__dict__.has_key(name): if name in self.__dict__:
raise self.ConstError, _("Can't rebind constant: %s") % name raise self.ConstError(_("Can't rebind constant: %s") % name)
# Binding an attribute once to a const is available # Binding an attribute once to a const is available
self.__dict__[name] = value self.__dict__[name] = value
def __delattr__(self, name): def __delattr__(self, name):
if self.__dict__.has_key(name): if name in self.__dict__:
raise self.ConstError, _("Can't unbind constant: %s") % name raise self.ConstError(_("Can't unbind constant: %s") % name)
# we don't have an attribute by this 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" "Pisi Constants Singleton"
__metaclass__ = Singleton
__c = _constant() __c = _constant()
def __init__(self): def __init__(self):
@@ -99,7 +97,7 @@ class Constants:
self.__c.repos = "repos" self.__c.repos = "repos"
#file/directory permissions #file/directory permissions
self.__c.umask = 0022 self.__c.umask = 0o022
# functions in actions_file # functions in actions_file
self.__c.setup_func = "setup" self.__c.setup_func = "setup"
+8 -8
View File
@@ -13,7 +13,7 @@
import re import re
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.db.repodb import pisi.db.repodb
@@ -57,7 +57,7 @@ class ComponentDB(lazydb.LazyDB):
return components return components
def __generate_components(self, doc): 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): def has_component(self, name, repo = None):
return self.cdb.has_item(name, repo) return self.cdb.has_item(name, repo)
@@ -74,9 +74,9 @@ class ComponentDB(lazydb.LazyDB):
lang = pisi.pxml.autoxml.LocalText.get_lang() lang = pisi.pxml.autoxml.LocalText.get_lang()
found = [] found = []
for name, xml in self.cdb.get_items_iter(repo): 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(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) found.append(name)
return found return found
@@ -132,7 +132,7 @@ class ComponentDB(lazydb.LazyDB):
packages = [] packages = []
packages.extend(component.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: for sub in sub_components:
try: try:
packages.extend(self.get_component(sub, repo).packages) packages.extend(self.get_component(sub, repo).packages)
@@ -152,7 +152,7 @@ class ComponentDB(lazydb.LazyDB):
packages = [] packages = []
packages.extend(component.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: for sub in sub_components:
try: try:
packages.extend(self.get_union_component(sub).packages) packages.extend(self.get_union_component(sub).packages)
@@ -173,7 +173,7 @@ class ComponentDB(lazydb.LazyDB):
sources = [] sources = []
sources.extend(component.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: for sub in sub_components:
try: try:
sources.extend(self.get_component(sub, repo).sources) sources.extend(self.get_component(sub, repo).sources)
@@ -193,7 +193,7 @@ class ComponentDB(lazydb.LazyDB):
sources = [] sources = []
sources.extend(component.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: for sub in sub_components:
try: try:
sources.extend(self.get_union_component(sub).sources) sources.extend(self.get_union_component(sub).sources)
+5 -5
View File
@@ -32,10 +32,10 @@ class FilesDB(lazydb.LazyDB):
self.__check_filesdb() self.__check_filesdb()
def has_file(self, path): 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): 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): def search_file(self, term):
if self.has_file(term): if self.has_file(term):
@@ -56,12 +56,12 @@ class FilesDB(lazydb.LazyDB):
self.__check_filesdb() self.__check_filesdb()
for f in files.list: 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): def remove_files(self, files):
for f in files: for f in files:
if self.filesdb.has_key(hashlib.md5(f.path).digest()): if hashlib.md5(f.path.encode()).hexdigest() in self.filesdb:
del self.filesdb[hashlib.md5(f.path).digest()] del self.filesdb[hashlib.md5(f.path.encode()).hexdigest()]
def destroy(self): def destroy(self):
files_db = os.path.join(ctx.config.info_dir(), ctx.const.files_db) files_db = os.path.join(ctx.config.info_dir(), ctx.const.files_db)
+2 -2
View File
@@ -12,7 +12,7 @@
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.db.repodb import pisi.db.repodb
@@ -52,7 +52,7 @@ class GroupDB(lazydb.LazyDB):
return groups return groups
def __generate_groups(self, doc): 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): def has_group(self, name, repo = None):
return self.gdb.has_item(name, repo) return self.gdb.has_item(name, repo)
+4 -5
View File
@@ -23,9 +23,8 @@ class HistoryDB(lazydb.LazyDB):
self.history = pisi.history.History() self.history = pisi.history.History()
def __generate_history(self): def __generate_history(self):
logs = filter(lambda x:x.endswith(".xml"), os.listdir(ctx.config.history_dir())) logs = list(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.sort(key=lambda x: int(x.split("_")[0]), reverse=True)
logs.reverse()
return logs return logs
def create_history(self, operation): def create_history(self, operation):
@@ -93,7 +92,7 @@ class HistoryDB(lazydb.LazyDB):
return allconfigs return allconfigs
def get_till_operation(self, operation): 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 return
for log in self.__logs: for log in self.__logs:
@@ -112,7 +111,7 @@ class HistoryDB(lazydb.LazyDB):
yield hist.operation yield hist.operation
def get_last_repo_update(self, last=1): 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() repoupdates.reverse()
if not len(repoupdates) >= 2: if not len(repoupdates) >= 2:
return None return None
+12 -12
View File
@@ -17,7 +17,7 @@ import os
import re import re
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import piksemel import piksemel
@@ -73,7 +73,7 @@ class InstallDB(lazydb.LazyDB):
name, version, release = dirname.rsplit("-", 2) name, version, release = dirname.rsplit("-", 2)
return name, version + "-" + release 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): def __get_marked_packages(self, _type):
info_path = os.path.join(ctx.config.info_dir(), _type) info_path = os.path.join(ctx.config.info_dir(), _type)
@@ -113,10 +113,10 @@ class InstallDB(lazydb.LazyDB):
return revdeps return revdeps
def list_installed(self): def list_installed(self):
return self.installed_db.keys() return list(self.installed_db.keys())
def has_package(self, package): 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): def list_installed_with_build_host(self, build_host):
build_host_re = re.compile("<BuildHost>(.*?)</BuildHost>") build_host_re = re.compile("<BuildHost>(.*?)</BuildHost>")
@@ -166,7 +166,7 @@ class InstallDB(lazydb.LazyDB):
def get_config_files(self, package): def get_config_files(self, package):
files = self.get_files(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): def search_package(self, terms, lang=None, fields=None):
""" """
@@ -187,12 +187,12 @@ class InstallDB(lazydb.LazyDB):
found = [] found = []
for name in self.list_installed(): for name in self.list_installed():
xml = open(os.path.join(self.package_path(name), ctx.const.metadata_xml)).read() 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 \ re.compile(term, re.I).search(name)) or \
(fields['summary'] and \ (fields['summary'] and \
re.compile(resum % (lang, term), re.I).search(xml)) or \ re.compile(resum % (lang, term), re.I).search(xml)) or \
(fields['desc'] and \ (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) found.append(name)
return found return found
@@ -243,7 +243,7 @@ class InstallDB(lazydb.LazyDB):
package_revdeps = self.rev_deps_db.get(name) package_revdeps = self.rev_deps_db.get(name)
if package_revdeps: if package_revdeps:
for pkg, dep in package_revdeps.items(): for pkg, dep in list(package_revdeps.items()):
dependency = self.__create_dependency(dep) dependency = self.__create_dependency(dep)
rev_deps.append((pkg, dependency)) rev_deps.append((pkg, dependency))
@@ -275,7 +275,7 @@ class InstallDB(lazydb.LazyDB):
def add_package(self, pkginfo): def add_package(self, pkginfo):
# Cleanup old revdep info # 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: if pkginfo.name in revdep_info:
del revdep_info[pkginfo.name] del revdep_info[pkginfo.name]
@@ -283,11 +283,11 @@ class InstallDB(lazydb.LazyDB):
self.__add_to_revdeps(pkginfo.name, self.rev_deps_db) self.__add_to_revdeps(pkginfo.name, self.rev_deps_db)
def remove_package(self, package_name): 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] del self.installed_db[package_name]
# Cleanup revdep info # 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: if package_name in revdep_info:
del revdep_info[package_name] del revdep_info[package_name]
@@ -329,7 +329,7 @@ class InstallDB(lazydb.LazyDB):
def package_path(self, package): 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])) return os.path.join(ctx.config.packages_dir(), "%s-%s" % (package, self.installed_db[package]))
raise Exception(_('Package %s is not installed') % package) raise Exception(_('Package %s is not installed') % package)
+13 -15
View File
@@ -12,8 +12,10 @@
import gzip import gzip
import gettext import gettext
import zlib
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.db import pisi.db
@@ -23,27 +25,27 @@ class ItemByRepo:
self.compressed = compressed self.compressed = compressed
def has_repo(self, repo): def has_repo(self, repo):
return self.dbobj.has_key(repo) return repo in self.dbobj
def has_item(self, item, repo=None): def has_item(self, item, repo=None):
for r in self.item_repos(repo): 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 True
return False return False
def which_repo(self, item): def which_repo(self, item):
for r in pisi.db.repodb.RepoDB().list_repos(): 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 return r
raise Exception(_("%s not found in any repository.") % str(item)) raise Exception(_("%s not found in any repository.") % str(item))
def get_item_repo(self, item, repo=None): def get_item_repo(self, item, repo=None):
for r in self.item_repos(repo): 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: if self.compressed:
return gzip.zlib.decompress(self.dbobj[r][item]), r return zlib.decompress(self.dbobj[r][item]), r
else: else:
return self.dbobj[r][item], r return self.dbobj[r][item], r
@@ -59,8 +61,8 @@ class ItemByRepo:
if not self.has_repo(r): if not self.has_repo(r):
raise Exception(_('Repository %s does not exist.') % repo) raise Exception(_('Repository %s does not exist.') % repo)
if self.dbobj.has_key(r): if r in self.dbobj:
items.extend(self.dbobj[r].keys()) items.extend(list(self.dbobj[r].keys()))
return list(set(items)) return list(set(items))
@@ -70,7 +72,7 @@ class ItemByRepo:
if not self.has_repo(r): if not self.has_repo(r):
raise Exception(_('Repository %s does not exist.') % repo) raise Exception(_('Repository %s does not exist.') % repo)
if self.dbobj.has_key(r): if r in self.dbobj:
items.extend(self.dbobj[r]) items.extend(self.dbobj[r])
return list(set(items)) return list(set(items))
@@ -80,12 +82,8 @@ class ItemByRepo:
if not self.has_repo(r): if not self.has_repo(r):
raise Exception(_('Repository %s does not exist.') % repo) raise Exception(_('Repository %s does not exist.') % repo)
if self.compressed: for item, data in self.dbobj[r].items():
for item in self.dbobj[r].keys(): yield item, zlib.decompress(data) if self.compressed else data
yield item, gzip.zlib.decompress(self.dbobj[r][item])
else:
for item in self.dbobj[r].keys():
yield item, self.dbobj[r][item]
def item_repos(self, repo=None): def item_repos(self, repo=None):
repos = pisi.db.repodb.RepoDB().list_repos() repos = pisi.db.repodb.RepoDB().list_repos()
+9 -9
View File
@@ -11,14 +11,14 @@
# #
import os import os
import cPickle import pickle
import time import time
import pisi.context as ctx import pisi.context as ctx
import pisi.util as util import pisi.util as util
import string import string
# lower borks for international locales. What we want is ascii lower. # 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): class Singleton(object):
_the_instances = {} _the_instances = {}
@@ -39,7 +39,7 @@ class LazyDB(Singleton):
cache_version = "2.4" cache_version = "2.4"
def __init__(self, cacheable=False, cachedir=None): def __init__(self, cacheable=False, cachedir=None):
if not self.__dict__.has_key("initialized"): if "initialized" not in self.__dict__:
self.initialized = False self.initialized = False
self.cacheable = cacheable self.cacheable = cacheable
self.cachedir = cachedir self.cachedir = cachedir
@@ -65,8 +65,8 @@ class LazyDB(Singleton):
f.write(LazyDB.cache_version) f.write(LazyDB.cache_version)
f.flush() f.flush()
os.fsync(f.fileno()) os.fsync(f.fileno())
cPickle.dump(self._instance().__dict__, pickle.dump(self._instance().__dict__,
file(self.__cache_file(), 'wb'), 1) open(self.__cache_file(), 'wb'), 1)
def cache_valid(self): def cache_valid(self):
if not self.cachedir: if not self.cachedir:
@@ -83,9 +83,9 @@ class LazyDB(Singleton):
def cache_load(self): def cache_load(self):
if os.path.exists(self.__cache_file()) and self.cache_valid(): if os.path.exists(self.__cache_file()) and self.cache_valid():
try: 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 return True
except (cPickle.UnpicklingError, EOFError): except (pickle.UnpicklingError, EOFError):
if os.access(ctx.config.cache_root_dir(), os.W_OK): if os.access(ctx.config.cache_root_dir(), os.W_OK):
os.unlink(self.__cache_file()) os.unlink(self.__cache_file())
return False return False
@@ -116,7 +116,7 @@ class LazyDB(Singleton):
ctx.ui.debug("%s initialized in %s." % (self.__class__.__name__, end - start)) ctx.ui.debug("%s initialized in %s." % (self.__class__.__name__, end - start))
self.initialized = True self.initialized = True
if not self.__dict__.has_key(attr): if attr not in self.__dict__:
raise AttributeError, attr raise AttributeError(attr)
return self.__dict__[attr] return self.__dict__[attr]
+9 -9
View File
@@ -16,7 +16,7 @@ import gzip
import gettext import gettext
import datetime import datetime
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import piksemel import piksemel
@@ -62,10 +62,10 @@ class PackageDB(lazydb.LazyDB):
if not obsoletes or src_repo: if not obsoletes or src_repo:
return [] 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): 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): def __generate_revdeps(self, doc):
revdeps = {} revdeps = {}
@@ -92,9 +92,9 @@ class PackageDB(lazydb.LazyDB):
found = [] found = []
for name in packages: for name in packages:
xml = self.pdb.get_item(name) 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(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) found.append(name)
return found return found
@@ -116,12 +116,12 @@ class PackageDB(lazydb.LazyDB):
fields = {'name': True, 'summary': True, 'desc': True} fields = {'name': True, 'summary': True, 'desc': True}
found = [] found = []
for name, xml in self.pdb.get_items_iter(repo): 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 \ re.compile(term, re.I).search(name)) or \
(fields['summary'] and \ (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 \ (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) found.append(name)
return found return found
@@ -201,7 +201,7 @@ class PackageDB(lazydb.LazyDB):
for pkg_name in self.rpdb.get_list_item(): for pkg_name in self.rpdb.get_list_item():
xml = self.pdb.get_item(pkg_name, repo) xml = self.pdb.get_item(pkg_name, repo)
package = piksemel.parseString(xml) package = piksemel.parseString(xml.decode())
replaces_tag = package.getTag("Replaces") replaces_tag = package.getTag("Replaces")
if replaces_tag: if replaces_tag:
for node in replaces_tag.tags("Package"): for node in replaces_tag.tags("Package"):
+11 -7
View File
@@ -12,7 +12,7 @@
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import os import os
@@ -35,7 +35,7 @@ class Repo:
def __init__(self, indexuri): def __init__(self, indexuri):
self.indexuri = indexuri self.indexuri = indexuri
medias = (cd, usb, remote, local) = range(4) medias = (cd, usb, remote, local) = list(range(4))
class RepoOrder: class RepoOrder:
@@ -106,14 +106,16 @@ class RepoOrder:
#FIXME: get media order from pisi.conf #FIXME: get media order from pisi.conf
for m in ["cd", "usb", "remote", "local"]: for m in ["cd", "usb", "remote", "local"]:
if self.repos.has_key(m): if m in self.repos:
order.extend(self.repos[m]) order.extend(self.repos[m])
return order return order
def _update(self, doc): def _update(self, doc):
repos_file = os.path.join(ctx.config.info_dir(), ctx.const.repos) repos_file_path = os.path.join(ctx.config.info_dir(), ctx.const.repos)
open(repos_file, "w").write("%s\n" % doc.toPrettyString()) repo_file = open(repos_file_path, "w")
repo_file.write("%s\n" % doc.toPrettyString())
repo_file.close()
self._doc = None self._doc = None
self.repos = self._get_repos() self.repos = self._get_repos()
@@ -173,7 +175,7 @@ class RepoDB(lazydb.LazyDB):
try: try:
return piksemel.parse(index_path) 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.")) raise RepoError(_("Error parsing repository index information. Index file does not exist or is malformed."))
def get_repo(self, repo): def get_repo(self, repo):
@@ -185,7 +187,9 @@ class RepoDB(lazydb.LazyDB):
raise RepoError(_("Repository %s does not exist.") % repo) raise RepoError(_("Repository %s does not exist.") % repo)
urifile_path = pisi.util.join_path(ctx.config.index_dir(), repo, "uri") 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() return uri.rstrip()
def add_repo(self, name, repo_info, at = None): 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"): for spec in doc.tags("SpecFile"):
src_name = spec.getTag("Source").getTagData("Name") 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"): for package in spec.tags("Package"):
pkgstosrc[package.getTagData("Name")] = src_name pkgstosrc[package.getTagData("Name")] = src_name
@@ -97,12 +97,12 @@ class SourceDB(lazydb.LazyDB):
lang = pisi.pxml.autoxml.LocalText.get_lang() lang = pisi.pxml.autoxml.LocalText.get_lang()
found = [] found = []
for name, xml in self.sdb.get_items_iter(repo): 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 \ re.compile(term, re.I).search(name)) or \
(fields['summary'] and \ (fields['summary'] and \
re.compile(resum % (lang, term), re.I).search(xml)) or \ re.compile(resum % (lang, term), re.I).search(xml)) or \
(fields['desc'] and \ (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) found.append(name)
return found return found
+2 -2
View File
@@ -14,7 +14,7 @@
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.relation import pisi.relation
import pisi.db import pisi.db
@@ -40,7 +40,7 @@ class Dependency(pisi.relation.Relation):
return self.package return self.package
def satisfied_by_dict_repo(self, dict_repo): 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 return False
else: else:
pkg = dict_repo[self.package] pkg = dict_repo[self.package]
+6 -6
View File
@@ -23,7 +23,7 @@ import shutil
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# pisi modules # pisi modules
import pisi import pisi
@@ -166,7 +166,7 @@ class Fetcher:
reget = self._test_range_support(), reget = self._test_range_support(),
copy_local = 1, copy_local = 1,
user_agent = 'PiSi Fetcher/' + pisi.__version__) 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)) raise FetchError(_('Could not fetch destination file "%s": %s') % (self.url.get_uri(), e))
if os.stat(self.partial_file).st_size == 0: if os.stat(self.partial_file).st_size == 0:
@@ -220,17 +220,17 @@ class Fetcher:
if not os.path.exists(self.partial_file): if not os.path.exists(self.partial_file):
return None return None
import urllib2 import urllib.request, urllib.error, urllib.parse
try: try:
file_obj = urllib2.urlopen(urllib2.Request(self.url.get_uri())) file_obj = urllib.request.urlopen(urllib.request.Request(self.url.get_uri()))
except urllib2.URLError: except urllib.error.URLError:
ctx.ui.debug(_("Remote file can not be reached. Previously downloaded part of the file will be removed.")) ctx.ui.debug(_("Remote file can not be reached. Previously downloaded part of the file will be removed."))
os.remove(self.partial_file) os.remove(self.partial_file)
return None return None
headers = file_obj.info() headers = file_obj.info()
file_obj.close() file_obj.close()
if headers.has_key('Content-Length'): if 'Content-Length' in headers:
return 'simple' return 'simple'
else: else:
ctx.ui.debug(_("Server doesn't support partial downloads. Previously downloaded part of the file will be over-written.")) 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 import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.uri import pisi.uri
@@ -57,8 +57,8 @@ class File:
COMPRESSION_TYPE_BZ2 = 1 COMPRESSION_TYPE_BZ2 = 1
COMPRESSION_TYPE_XZ = 2 COMPRESSION_TYPE_XZ = 2
(read, write) = range(2) # modes (read, write) = list(range(2)) # modes
(detached, whatelse) = range(2) (detached, whatelse) = list(range(2))
__compressed_file_extensions = {".xz": COMPRESSION_TYPE_XZ, __compressed_file_extensions = {".xz": COMPRESSION_TYPE_XZ,
".bz2": COMPRESSION_TYPE_BZ2} ".bz2": COMPRESSION_TYPE_BZ2}
@@ -66,7 +66,7 @@ class File:
@staticmethod @staticmethod
def make_uri(uri): def make_uri(uri):
"handle URI arg" "handle URI arg"
if isinstance(uri, basestring): if isinstance(uri, str):
uri = pisi.uri.URI(uri) uri = pisi.uri.URI(uri)
elif not isinstance(uri, pisi.uri.URI): elif not isinstance(uri, pisi.uri.URI):
raise Error(_("uri must have type either URI or string")) raise Error(_("uri must have type either URI or string"))
@@ -75,7 +75,7 @@ class File:
@staticmethod @staticmethod
def choose_method(filename, compress): def choose_method(filename, compress):
if compress == File.COMPRESSION_TYPE_AUTO: 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): if filename.endswith(ext):
return method return method
@@ -92,7 +92,7 @@ class File:
compress = File.choose_method(localfile, compress) compress = File.choose_method(localfile, compress)
if compress == File.COMPRESSION_TYPE_XZ: if compress == File.COMPRESSION_TYPE_XZ:
import lzma import lzma
open(localfile[:-3], "w").write(lzma.LZMAFile(localfile).read()) open(localfile[:-3], "wb").write(lzma.LZMAFile(localfile).read())
localfile = localfile[:-3] localfile = localfile[:-3]
elif compress == File.COMPRESSION_TYPE_BZ2: elif compress == File.COMPRESSION_TYPE_BZ2:
import bz2 import bz2
@@ -115,7 +115,7 @@ class File:
if sha1sum: if sha1sum:
sha1filename = File.download(pisi.uri.URI(uri.get_uri() + '.sha1sum'), transfer_dir) sha1filename = File.download(pisi.uri.URI(uri.get_uri() + '.sha1sum'), transfer_dir)
sha1f = file(sha1filename) sha1f = open(sha1filename)
newsha1 = sha1f.read().split("\n")[0] newsha1 = sha1f.read().split("\n")[0]
if uri.is_remote_file() or copylocal: 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? # TODO: code to use old .sha1sum file, is this a necessary optimization?
#oldsha1fn = localfile + '.sha1sum' #oldsha1fn = localfile + '.sha1sum'
#if os.exists(oldsha1fn): #if os.exists(oldsha1fn):
#oldsha1 = file(oldsha1fn).readlines()[0] #oldsha1 = open(oldsha1fn).readlines()[0]
if sha1sum and os.path.exists(origfile): if sha1sum and os.path.exists(origfile):
oldsha1 = pisi.util.sha1_file(origfile) oldsha1 = pisi.util.sha1_file(origfile)
if (newsha1 == oldsha1): if (newsha1 == oldsha1):
@@ -202,7 +202,7 @@ class File:
access = 'r' access = 'r'
else: else:
access = 'w' access = 'w'
self.__file__ = file(localfile, access) self.__file__ = open(localfile, access)
self.localfile = localfile self.localfile = localfile
def local_file(self): def local_file(self):
@@ -233,12 +233,12 @@ class File:
if self.sha1sum: if self.sha1sum:
sha1 = pisi.util.sha1_file(self.localfile) sha1 = pisi.util.sha1_file(self.localfile)
cs = file(self.localfile + '.sha1sum', 'w') cs = open(self.localfile + '.sha1sum', 'w')
cs.write(sha1) cs.write(sha1)
cs.close() cs.close()
for compressed_file in compressed_files: for compressed_file in compressed_files:
sha1 = pisi.util.sha1_file(compressed_file) sha1 = pisi.util.sha1_file(compressed_file)
cs = file(compressed_file + '.sha1sum', 'w') cs = open(compressed_file + '.sha1sum', 'w')
cs.write(sha1) cs.write(sha1)
cs.close() cs.close()
@@ -256,7 +256,7 @@ class File:
sigfilename = File.download(pisi.uri.URI(uri + '.sig'), transfer_dir) sigfilename = File.download(pisi.uri.URI(uri + '.sig'), transfer_dir)
except KeyboardInterrupt: except KeyboardInterrupt:
raise 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) raise NoSignatureFound(uri)
if os.system('gpg --verify ' + sigfilename) != 0: if os.system('gpg --verify ' + sigfilename) != 0:
raise InvalidSignature(uri) raise InvalidSignature(uri)
@@ -271,8 +271,8 @@ class File:
def isatty(self): def isatty(self):
return self.__file__.isatty() return self.__file__.isatty()
def next(self): def __next__(self):
return self.__file__.next() return next(self.__file__)
def read(self, size = None): def read(self, size = None):
if size: if size:
@@ -293,7 +293,7 @@ class File:
return self.__file__.readlines() return self.__file__.readlines()
def xreadlines(self): def xreadlines(self):
return self.__file__.xreadlines() return self.__file__
def seek(self, offset, whence=0): def seek(self, offset, whence=0):
self.__file__.seek(offset, whence) 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 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""" """File holds the information for a File node/tag in files.xml"""
__metaclass__ = autoxml.autoxml
t_Path = [ autoxml.String, autoxml.mandatory ] t_Path = [ autoxml.String, autoxml.mandatory ]
t_Type = [ autoxml.String, autoxml.mandatory ] t_Type = [ autoxml.String, autoxml.mandatory ]
t_Size = [ autoxml.Long, autoxml.optional ] t_Size = [ autoxml.Long, autoxml.optional ]
@@ -36,9 +34,7 @@ class FileInfo:
return s return s
class Files(autoxml.xmlfile.XmlFile): class Files(autoxml.xmlfile.XmlFile, metaclass=autoxml.autoxml):
__metaclass__ = autoxml.autoxml
tag = "Files" tag = "Files"
+1 -1
View File
@@ -16,7 +16,7 @@ import pisi
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
class CycleException(pisi.Exception): class CycleException(pisi.Exception):
def __init__(self, cycle): def __init__(self, cycle):
+7 -10
View File
@@ -14,25 +14,22 @@ import pisi
import pisi.pxml.xmlfile as xmlfile import pisi.pxml.xmlfile as xmlfile
import pisi.pxml.autoxml as autoxml import pisi.pxml.autoxml as autoxml
class Error(pisi.Error): class Error(pisi.Error):
pass pass
__metaclass__ = autoxml.autoxml
class Group(xmlfile.XmlFile): class Group(xmlfile.XmlFile, metaclass=autoxml.autoxml):
"representation for group declarations" """Representation for group declarations"""
__metaclass__ = autoxml.autoxml
t_Name = [autoxml.String, autoxml.mandatory] t_Name = [autoxml.String, autoxml.mandatory]
t_LocalName = [autoxml.LocalText, 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" 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 time
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.pxml.autoxml as autoxml import pisi.pxml.autoxml as autoxml
import pisi.pxml.xmlfile as xmlfile import pisi.pxml.xmlfile as xmlfile
import pisi.context as ctx import pisi.context as ctx
__metaclass__ = autoxml.autoxml
class PackageInfo: class PackageInfo(metaclass=autoxml.autoxml):
a_version = [autoxml.String, autoxml.mandatory] a_version = [autoxml.String, autoxml.mandatory]
a_release = [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)) return "-".join((self.version, self.release, distro_id, arch))
class Repo: class Repo(metaclass=autoxml.autoxml):
a_operation = [autoxml.String, autoxml.mandatory] a_operation = [autoxml.String, autoxml.mandatory]
t_Name = [autoxml.String, autoxml.mandatory] t_Name = [autoxml.String, autoxml.mandatory]
@@ -50,7 +49,7 @@ class Repo:
elif self.operation == "remove": elif self.operation == "remove":
pass # TBD pass # TBD
class Package: class Package(metaclass=autoxml.autoxml):
a_operation = [autoxml.String, autoxml.mandatory] a_operation = [autoxml.String, autoxml.mandatory]
a_type = [autoxml.String, autoxml.optional] a_type = [autoxml.String, autoxml.optional]
@@ -78,7 +77,8 @@ class Package:
else: else:
return "" return ""
class Operation:
class Operation(metaclass=autoxml.autoxml):
a_type = [autoxml.String, autoxml.mandatory] a_type = [autoxml.String, autoxml.mandatory]
a_date = [autoxml.String, autoxml.mandatory] a_date = [autoxml.String, autoxml.mandatory]
@@ -90,9 +90,8 @@ class Operation:
def __str__(self): def __str__(self):
return self.type return self.type
class History(xmlfile.XmlFile):
__metaclass__ = autoxml.autoxml class History(xmlfile.XmlFile, metaclass=autoxml.autoxml):
tag = "PISI" tag = "PISI"
@@ -148,10 +147,10 @@ class History(xmlfile.XmlFile):
def _get_latest(self): 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: if not files:
return "001" 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("_") no, opxml = files[-1].split("_")
return "%03d" % (int(no) + 1) return "%03d" % (int(no) + 1)
+7 -9
View File
@@ -18,7 +18,7 @@ import multiprocessing
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.context as ctx import pisi.context as ctx
@@ -37,9 +37,7 @@ import pisi.operations.build
class Error(pisi.Error): class Error(pisi.Error):
pass pass
class Index(xmlfile.XmlFile): class Index(xmlfile.XmlFile, metaclass=autoxml.autoxml):
__metaclass__ = autoxml.autoxml
tag = "PISI" tag = "PISI"
t_Distribution = [ component.Distribution, autoxml.optional ] t_Distribution = [ component.Distribution, autoxml.optional ]
@@ -67,7 +65,7 @@ class Index(xmlfile.XmlFile):
pisi.util.ensure_dirs(tmpdir) pisi.util.ensure_dirs(tmpdir)
# write uri # 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.write(uri) # uri
urlfile.close() urlfile.close()
@@ -136,7 +134,7 @@ class Index(xmlfile.XmlFile):
raise raise
try: try:
obsoletes_list = map(str, self.distribution.obsoletes) obsoletes_list = list(map(str, self.distribution.obsoletes))
except AttributeError: except AttributeError:
obsoletes_list = [] obsoletes_list = []
@@ -178,7 +176,7 @@ def add_package(params):
package = pisi.package.Package(path, 'r') package = pisi.package.Package(path, 'r')
md = package.get_metadata() 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) md.package.packageHash = util.sha1_file(path)
if ctx.config.options and ctx.config.options.absolute_urls: if ctx.config.options and ctx.config.options.absolute_urls:
md.package.packageURI = os.path.realpath(path) md.package.packageURI = os.path.realpath(path)
@@ -190,7 +188,7 @@ def add_package(params):
if md.errors(): if md.errors():
ctx.ui.info("") ctx.ui.info("")
ctx.ui.error(_('Package %s: metadata corrupt, skipping...') % md.package.name) ctx.ui.error(_('Package %s: metadata corrupt, skipping...') % md.package.name)
ctx.ui.error(unicode(Error(*errs))) ctx.ui.error(str(Error(*errs)))
else: else:
# No need to carry these with index (#3965) # No need to carry these with index (#3965)
md.package.files = None md.package.files = None
@@ -211,7 +209,7 @@ def add_package(params):
delta = metadata.Delta() delta = metadata.Delta()
delta.packageURI = util.removepathprefix(repo_uri, delta_path) 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.packageHash = util.sha1_file(delta_path)
delta.releaseFrom = src_release delta.releaseFrom = src_release
+6 -10
View File
@@ -19,32 +19,29 @@ a package index.
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.specfile as specfile import pisi.specfile as specfile
import pisi.pxml.xmlfile as xmlfile import pisi.pxml.xmlfile as xmlfile
import pisi.pxml.autoxml as autoxml import pisi.pxml.autoxml as autoxml
import pisi.util as util import pisi.util as util
class Delta:
__metaclass__ = autoxml.autoxml
class Delta(metaclass=autoxml.autoxml):
t_PackageURI = [ autoxml.String, autoxml.optional] t_PackageURI = [ autoxml.String, autoxml.optional]
t_PackageSize = [ autoxml.Long, autoxml.optional] t_PackageSize = [ autoxml.Long, autoxml.optional]
t_PackageHash = [ autoxml.String, autoxml.optional, "SHA1Sum" ] t_PackageHash = [ autoxml.String, autoxml.optional, "SHA1Sum" ]
a_buildFrom = [autoxml.String, autoxml.optional] a_buildFrom = [autoxml.String, autoxml.optional]
a_releaseFrom = [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_Name = [autoxml.String, autoxml.mandatory]
t_Homepage = [autoxml.String, autoxml.optional] t_Homepage = [autoxml.String, autoxml.optional]
t_Packager = [specfile.Packager, autoxml.mandatory] 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_Build = [ autoxml.Integer, autoxml.optional]
t_BuildHost = [autoxml.String, autoxml.optional] t_BuildHost = [autoxml.String, autoxml.optional]
t_Distribution = [ autoxml.String, autoxml.mandatory] t_Distribution = [ autoxml.String, autoxml.mandatory]
@@ -87,12 +84,11 @@ class Package(specfile.Package, xmlfile.XmlFile):
return s return s
class MetaData(xmlfile.XmlFile):
class MetaData(xmlfile.XmlFile, metaclass=autoxml.autoxml):
"""Package metadata. Metadata is composed of Specfile and various """Package metadata. Metadata is composed of Specfile and various
other information. A metadata has two parts, Source and Package.""" other information. A metadata has two parts, Source and Package."""
__metaclass__ = autoxml.autoxml
tag = "PISI" tag = "PISI"
t_Source = [ Source, autoxml.mandatory] t_Source = [ Source, autoxml.mandatory]
+3 -3
View File
@@ -15,7 +15,7 @@ import pisi.context as ctx
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
class Mirrors: class Mirrors:
def __init__(self, config=ctx.const.mirrors_conf): def __init__(self, config=ctx.const.mirrors_conf):
@@ -23,13 +23,13 @@ class Mirrors:
self._parse(config) self._parse(config)
def get_mirrors(self, name): def get_mirrors(self, name):
if self.mirrors.has_key(name): if name in self.mirrors:
return list(self.mirrors[name]) return list(self.mirrors[name])
return None return None
def _add_mirror(self, name, url): def _add_mirror(self, name, url):
if self.mirrors.has_key(name): if name in self.mirrors:
self.mirrors[name].append(url) self.mirrors[name].append(url)
else: else:
self.mirrors[name] = [url] self.mirrors[name] = [url]
+3 -5
View File
@@ -8,10 +8,10 @@ class autoprop(type):
def __init__(cls, name, bases, dict): def __init__(cls, name, bases, dict):
super(autoprop, cls).__init__(name, bases, dict) super(autoprop, cls).__init__(name, bases, dict)
props = {} props = {}
for name in dict.keys(): for name in list(dict.keys()):
if name.startswith("_get_") or name.startswith("_set_"): if name.startswith("_get_") or name.startswith("_set_"):
props[name[5:]] = 1 props[name[5:]] = 1
for name in props.keys(): for name in list(props.keys()):
fget = getattr(cls, "_get_%s" % name, None) fget = getattr(cls, "_get_%s" % name, None)
fset = getattr(cls, "_set_%s" % name, None) fset = getattr(cls, "_set_%s" % name, None)
setattr(cls, name, property(fget, fset)) setattr(cls, name, property(fget, fset))
@@ -32,8 +32,6 @@ class autoeq(type):
return self.__dict__ == other.__dict__ return self.__dict__ == other.__dict__
cls.__eq__ = equal cls.__eq__ = equal
class Struct: class Struct(metaclass=autoeq):
__metaclass__ = autoeq
def __init__(self, **entries): def __init__(self, **entries):
self.__dict__.update(entries) self.__dict__.update(entries)
+26 -28
View File
@@ -22,7 +22,7 @@ import fnmatch
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.specfile import pisi.specfile
@@ -129,14 +129,14 @@ def exclude_special_files(filepath, fileinfo, ag):
# patches, PiSi removes wrong paths... # patches, PiSi removes wrong paths...
if re.match(patterns["libtool"], fileinfo) and \ if re.match(patterns["libtool"], fileinfo) and \
not os.path.islink(filepath): 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("-L%s/\S*" % ctx.config.tmp_dir(), "", ladata)
new_ladata = re.sub("%s/\S*/install/" % ctx.config.tmp_dir(), "/", new_ladata = re.sub("%s/\S*/install/" % ctx.config.tmp_dir(), "/",
new_ladata) new_ladata)
if new_ladata != 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: if name in keeplist:
continue continue
@@ -592,7 +592,7 @@ class Builder:
abandoned_files.append(fpath) abandoned_files.append(fpath)
len_install_dir = len(install_dir) 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): def copy_additional_source_files(self):
# store additional files # store additional files
@@ -611,10 +611,10 @@ class Builder:
try: try:
buf = open(fname).read() buf = open(fname).read()
return compile(buf, fname, "exec") return compile(buf, fname, "exec")
except IOError, e: except IOError as e:
raise Error(_("Unable to read Actions Script (%s): %s") raise Error(_("Unable to read Actions Script (%s): %s")
% (fname, e)) % (fname, e))
except SyntaxError, e: except SyntaxError as e:
raise Error(_("SyntaxError in Actions Script (%s): %s") raise Error(_("SyntaxError in Actions Script (%s): %s")
% (fname, e)) % (fname, e))
@@ -625,8 +625,8 @@ class Builder:
try: try:
localSymbols = globalSymbols = {} localSymbols = globalSymbols = {}
exec compiled_script in localSymbols, globalSymbols exec(compiled_script, localSymbols, globalSymbols)
except Exception, e: except Exception as e:
import traceback import traceback
traceback.print_exc(e) traceback.print_exc(e)
raise ActionScriptException raise ActionScriptException
@@ -644,10 +644,10 @@ class Builder:
try: try:
buf = open(fname).read() buf = open(fname).read()
compile(buf, "error", "exec") compile(buf, "error", "exec")
except IOError, e: except IOError as e:
raise Error(_("Unable to read COMAR script (%s): %s") raise Error(_("Unable to read COMAR script (%s): %s")
% (fname, e)) % (fname, e))
except SyntaxError, e: except SyntaxError as e:
raise Error(_("SyntaxError in COMAR file (%s): %s") raise Error(_("SyntaxError in COMAR file (%s): %s")
% (fname, e)) % (fname, e))
@@ -711,7 +711,7 @@ class Builder:
valid_paths = [self.pkg_dir()] valid_paths = [self.pkg_dir()]
conf_file = ctx.const.sandbox_conf conf_file = ctx.const.sandbox_conf
if os.path.exists(conf_file): if os.path.exists(conf_file):
for line in file(conf_file): for line in open(conf_file):
line = line.strip() line = line.strip()
if len(line) > 0 and not line.startswith("#"): if len(line) > 0 and not line.startswith("#"):
if line.startswith("~"): if line.startswith("~"):
@@ -728,7 +728,7 @@ class Builder:
logger=self.log_sandbox_violation) logger=self.log_sandbox_violation)
# Retcode can be 0 while there is a sanbox violation, so only # Retcode can be 0 while there is a sanbox violation, so only
# look for violations to correctly handle it # look for violations to correctly handle it
if ret.violations != []: if ret.violations:
ctx.ui.error(_("Sandbox violation result:")) ctx.ui.error(_("Sandbox violation result:"))
for result in ret.violations: for result in ret.violations:
ctx.ui.error("%s (%s -> %s)" % (result[0], 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]) build_deps_names = set([x.package for x in build_deps])
devel_deps_names = set(self.componentdb.get_component('system.devel').packages) devel_deps_names = set(self.componentdb.get_component('system.devel').packages)
extra_names = devel_deps_names - build_deps_names 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: if extra_names:
ctx.ui.warning(_('Safety switch: following extra packages in system.devel will be installed: ') + ctx.ui.warning(_('Safety switch: following extra packages in system.devel will be installed: ') +
util.strlist(extra_names)) util.strlist(extra_names))
@@ -867,8 +867,8 @@ class Builder:
static_package_obj = pisi.specfile.Package() static_package_obj = pisi.specfile.Package()
static_package_obj.name = self.spec.source.name + ctx.const.static_name_suffix 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. # 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.summary['en'] = '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.description['en'] = 'Ar files for %s' % (self.spec.source.name)
static_package_obj.partOf = self.spec.source.partOf static_package_obj.partOf = self.spec.source.partOf
for f in ar_files: for f in ar_files:
static_package_obj.files.append(pisi.specfile.Path(path=f[len(self.pkg_install_dir()):], fileType="library")) 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.debug_package = True
debug_package_obj.name = package.name + ctx.const.debug_name_suffix debug_package_obj.name = package.name + ctx.const.debug_name_suffix
# FIXME: find a better way to deal with the summary and description constants. # 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.summary['en'] = 'Debug files for %s' % (package.name)
debug_package_obj.description['en'] = u'Debug files for %s' % (package.name) debug_package_obj.description['en'] = 'Debug files for %s' % (package.name)
debug_package_obj.partOf = package.partOf debug_package_obj.partOf = package.partOf
dependency = pisi.dependency.Dependency() dependency = pisi.dependency.Dependency()
@@ -920,7 +920,7 @@ class Builder:
for fileinfo in self.files.list: for fileinfo in self.files.list:
size += fileinfo.size size += fileinfo.size
metadata.package.installedSize = long(size) metadata.package.installedSize = int(size)
self.metadata = metadata self.metadata = metadata
@@ -957,7 +957,7 @@ class Builder:
continue continue
frpath = util.removepathprefix(install_dir, fpath) # relative path frpath = util.removepathprefix(install_dir, fpath) # relative path
ftype, permanent = get_file_type(frpath, package.files) 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): if not os.path.islink(fpath):
st = os.stat(fpath) st = os.stat(fpath)
else: else:
@@ -976,7 +976,7 @@ class Builder:
add_path(path) add_path(path)
files = pisi.files.Files() files = pisi.files.Files()
for fileinfo in d.itervalues(): for fileinfo in d.values():
files.append(fileinfo) files.append(fileinfo)
files_xml_path = util.join_path(self.pkg_dir(), ctx.const.files_xml) 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() install_dir = self.pkg_install_dir()
import magic import magic
ms = magic.open(magic.MAGIC_NONE) ms = magic.Magic()
ms.load()
for root, dirs, files in os.walk(install_dir): for root, dirs, files in os.walk(install_dir):
for fn in files: for fn in files:
filepath = util.join_path(root, fn) filepath = util.join_path(root, fn)
fileinfo = ms.file(filepath) fileinfo = ms.from_file(filepath)
strip_debug_action(filepath, fileinfo, install_dir, self.actionGlobals) strip_debug_action(filepath, fileinfo, install_dir, self.actionGlobals)
exclude_special_files(filepath, fileinfo, self.actionGlobals) exclude_special_files(filepath, fileinfo, self.actionGlobals)
ms.close()
def build_packages(self): def build_packages(self):
"""Build each package defined in PSPEC file. After this process there """Build each package defined in PSPEC file. After this process there
@@ -1190,7 +1188,7 @@ class Builder:
old_packages = {} 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: if old_release in old_packages:
continue continue
@@ -1228,7 +1226,7 @@ class Builder:
old_packages.update(found_old_packages) old_packages.update(found_old_packages)
from pisi.operations.delta import create_delta_packages_from_obj 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, package,
self.specdir) self.specdir)
@@ -1242,7 +1240,7 @@ def build(pspec):
pb = Builder.from_name(pspec) pb = Builder.from_name(pspec)
try: try:
pb.build() pb.build()
except ActionScriptException, e: except ActionScriptException as e:
ctx.ui.error(_("Action script error caught.")) ctx.ui.error(_("Action script error caught."))
raise e raise e
finally: finally:
+3 -3
View File
@@ -15,7 +15,7 @@ import pisi.context as ctx
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
def file_corrupted(pfile): def file_corrupted(pfile):
path = os.path.join(ctx.config.dest_dir(), pfile.path) path = os.path.join(ctx.config.dest_dir(), pfile.path)
@@ -26,7 +26,7 @@ def file_corrupted(pfile):
try: try:
if pisi.util.sha1_file(path) != pfile.hash: if pisi.util.sha1_file(path) != pfile.hash:
return True return True
except pisi.util.FilePermissionDeniedError, e: except pisi.util.FilePermissionDeniedError as e:
raise e raise e
return False return False
@@ -51,7 +51,7 @@ def check_files(files, check_config=False):
try: try:
is_file_corrupted = file_corrupted(f) 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 # Can't read file, probably because of permissions, skip
results['denied'].append(f.path) results['denied'].append(f.path)
+2 -2
View File
@@ -13,7 +13,7 @@ import os
import gettext import gettext
__trans = gettext.translation("pisi", fallback=True) __trans = gettext.translation("pisi", fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi.context as ctx import pisi.context as ctx
import pisi.package import pisi.package
@@ -181,7 +181,7 @@ def find_relocations(oldfiles, newfiles):
files_old.setdefault(f.hash, []).append(f) files_old.setdefault(f.hash, []).append(f)
relocations = [] relocations = []
for h in files_new.keys(): for h in list(files_new.keys()):
if h and h in files_old: if h and h in files_old:
old_paths = [x.path for x in files_old[h]] old_paths = [x.path for x in files_old[h]]
for i in range(len(files_new[h])): for i in range(len(files_new[h])):
+1 -1
View File
@@ -14,7 +14,7 @@ import sys
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.operations import pisi.operations
+2 -2
View File
@@ -14,7 +14,7 @@ import os
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.context as ctx import pisi.context as ctx
@@ -53,7 +53,7 @@ def check_conflicts(order, packagedb):
if pkg_conflicts: if pkg_conflicts:
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])) conflicts += _("[%s conflicts with: %s]\n") % (pkg, util.strlist(pkg_conflicts[pkg]))
ctx.ui.info(_("The following packages have conflicts:\n%s") % ctx.ui.info(_("The following packages have conflicts:\n%s") %
+2 -2
View File
@@ -12,7 +12,7 @@
import os import os
import gettext import gettext
__trans = gettext.translation("pisi", fallback=True) __trans = gettext.translation("pisi", fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.context as ctx import pisi.context as ctx
@@ -87,7 +87,7 @@ def fetch_remote_file(package, errors):
if not os.path.exists(filepath): if not os.path.exists(filepath):
try: try:
pisi.fetcher.fetch_url(uri, dest, ctx.ui.Progress) pisi.fetcher.fetch_url(uri, dest, ctx.ui.Progress)
except pisi.fetcher.FetchError, e: except pisi.fetcher.FetchError as e:
errors.append(package) errors.append(package)
ctx.ui.info(pisi.util.colorize(_("%s could not be found") % (package), "red")) ctx.ui.info(pisi.util.colorize(_("%s could not be found") % (package), "red"))
return False return False
+5 -5
View File
@@ -16,7 +16,7 @@ import zipfile
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.context as ctx import pisi.context as ctx
@@ -41,7 +41,7 @@ def install_pkg_names(A, reinstall = False):
# filter packages that are already installed # filter packages that are already installed
if not reinstall: 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 d = A - Ap
if len(d) > 0: if len(d) > 0:
ctx.ui.warning(_("The following package(s) are already installed " 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 # check packages' DistributionReleases and Architecture
if not ctx.get_option('ignore_check'): if not ctx.get_option('ignore_check'):
for x in d_t.keys(): for x in list(d_t.keys()):
pkg = d_t[x] pkg = d_t[x]
if pkg.distributionRelease != ctx.config.values.general.distribution_release: if pkg.distributionRelease != ctx.config.values.general.distribution_release:
raise pisi.Error(_('Package %s is not compatible with your distribution release %s %s.') \ 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 # that aren't already satisfied and try to install them
# from the repository # from the repository
dep_unsatis = [] dep_unsatis = []
for name in d_t.keys(): for name in list(d_t.keys()):
pkg = d_t[name] pkg = d_t[name]
deps = pkg.runtimeDependencies() deps = pkg.runtimeDependencies()
for dep in deps: for dep in deps:
@@ -207,7 +207,7 @@ def install_pkg_files(package_URIs, reinstall = False):
packagedb = PackageDB() packagedb = PackageDB()
A = d_t.keys() A = list(d_t.keys())
if len(A)==0: if len(A)==0:
ctx.ui.info(_('No packages to install.')) ctx.ui.info(_('No packages to install.'))
+2 -2
View File
@@ -14,7 +14,7 @@ import sys
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.context as ctx import pisi.context as ctx
@@ -122,7 +122,7 @@ def remove_conflicting_packages(conflicts):
def remove_obsoleted_packages(): def remove_obsoleted_packages():
installdb = pisi.db.installdb.InstallDB() installdb = pisi.db.installdb.InstallDB()
packagedb = pisi.db.packagedb.PackageDB() 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 obsoletes:
if remove(obsoletes, ignore_dep=True, ignore_safety=True): if remove(obsoletes, ignore_dep=True, ignore_safety=True):
raise Exception(_("Obsoleted packages remaining")) raise Exception(_("Obsoleted packages remaining"))
+8 -8
View File
@@ -14,7 +14,7 @@ import sys
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.ui as ui import pisi.ui as ui
@@ -40,7 +40,7 @@ def check_update_actions(packages):
version, release, build = installdb.get_version(package) version, release, build = installdb.get_version(package)
pkg_actions = pkg.get_update_actions(release) 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, []) item = actions.setdefault(action_name, [])
for action_target in action_targets: for action_target in action_targets:
item.append((package, action_target)) item.append((package, action_target))
@@ -72,7 +72,7 @@ def find_upgrades(packages, replaces):
Ap = [] Ap = []
for i_pkg in packages: 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 # Replaced packages will be forced for upgrade, cause replaced packages are marked as obsoleted also. So we
# pass them. # pass them.
continue 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). # 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). # 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) A |= upgrade_base(A)
@@ -170,7 +170,7 @@ def upgrade(A=[], repo=None):
needs_confirm = check_update_actions(order) needs_confirm = check_update_actions(order)
# NOTE: replaces.values() was already flattened above, it can be reused # 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.")) ctx.ui.warning(_("There are extra packages due to dependencies."))
needs_confirm = True needs_confirm = True
@@ -226,7 +226,7 @@ def plan_upgrade(A, force_replaced=True, replaces=None):
if force_replaced: if force_replaced:
if replaces is None: if replaces is None:
replaces = packagedb.get_replaces() 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 # find the "install closure" graph of G_f by package
# set A using packagedb # 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 not ctx.config.values.general.ignore_safety and not ctx.get_option('ignore_safety'):
if componentdb.has_component('system.base'): if componentdb.has_component('system.base'):
systembase = set(componentdb.get_union_component('system.base').packages) 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) extra_installs = pisi.blacklist.exclude_from(extra_installs, ctx.const.blacklist)
if extra_installs: if extra_installs:
ctx.ui.warning(_("Safety switch forces the installation of " ctx.ui.warning(_("Safety switch forces the installation of "
"following packages:")) "following packages:"))
ctx.ui.info(util.format_by_columns(sorted(extra_installs))) ctx.ui.info(util.format_by_columns(sorted(extra_installs)))
G_f, install_order = operations.install.plan_install_pkg_names(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 = [] upgrade_order = []
extra_upgrades = pisi.blacklist.exclude_from(extra_upgrades, ctx.const.blacklist) extra_upgrades = pisi.blacklist.exclude_from(extra_upgrades, ctx.const.blacklist)
+4 -4
View File
@@ -16,7 +16,7 @@ import os.path
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import pisi.context as ctx import pisi.context as ctx
@@ -26,7 +26,7 @@ import pisi.metadata
import pisi.file import pisi.file
import pisi.files import pisi.files
import pisi.util as util import pisi.util as util
import fetcher from . import fetcher
class Error(pisi.Error): class Error(pisi.Error):
@@ -64,7 +64,7 @@ class Package:
try: try:
self.impl = archive.ArchiveZip(self.filepath, 'zip', mode) self.impl = archive.ArchiveZip(self.filepath, 'zip', mode)
except IOError, e: except IOError as e:
raise Error(_("Cannot open package file: %s") % e) raise Error(_("Cannot open package file: %s") % e)
self.install_archive = None self.install_archive = None
@@ -217,7 +217,7 @@ class Package:
if os.path.isfile(tarinfo.name) or os.path.islink(tarinfo.name): if os.path.isfile(tarinfo.name) or os.path.islink(tarinfo.name):
try: try:
os.unlink(tarinfo.name) os.unlink(tarinfo.name)
except OSError, e: except OSError as e:
ctx.ui.warning(e) ctx.ui.warning(e)
else: else:
+1 -1
View File
@@ -12,7 +12,7 @@
"""PiSi package relation graph that represents the state of packagedb""" """PiSi package relation graph that represents the state of packagedb"""
import graph from . import graph
# Cache the results from packagedb queries in a graph # Cache the results from packagedb queries in a graph
+55 -56
View File
@@ -24,13 +24,13 @@ import locale
import types import types
import formatter import formatter
import sys import sys
import StringIO import io
import inspect import inspect
import re import re
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
# PiSi # PiSi
import pisi import pisi
@@ -45,15 +45,15 @@ class Error(pisi.Error):
# requirement specs # requirement specs
mandatory, optional = range(2) # poor man's enum mandatory, optional = list(range(2)) # poor man's enum
# basic types # basic types
String = types.StringType String = str
Text = types.UnicodeType Text = str
Integer = types.IntType Integer = int
Long = types.LongType Long = int
Float = types.FloatType Float = float
#class datatype(type): #class datatype(type):
# def __init__(cls, name, bases, dict): # def __init__(cls, name, bases, dict):
@@ -91,7 +91,7 @@ class LocalText(dict):
def encode(self, node, errs): def encode(self, node, errs):
assert self.tag != '' assert self.tag != ''
for key in self.iterkeys(): for key in self.keys():
newnode = xmlext.addNode(node, self.tag) newnode = xmlext.addNode(node, self.tag)
xmlext.setNodeAttribute(newnode, 'xml:lang', key) xmlext.setNodeAttribute(newnode, 'xml:lang', key)
xmlext.addText(newnode, '', self[key]) xmlext.addText(newnode, '', self[key])
@@ -109,25 +109,25 @@ class LocalText(dict):
return lang[0:2] return lang[0:2]
except KeyboardInterrupt: except KeyboardInterrupt:
raise 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')) raise Error(_('LocalText: unable to get either current or default locale'))
def errors(self, where = unicode()): def errors(self, where = str()):
errs = [] errs = []
langs = [ LocalText.get_lang(), 'en', 'tr', ] 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")) 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 #FIXME: check if all entries are unicode
return errs return errs
def format(self, f, errs): def format(self, f, errs):
L = LocalText.get_lang() L = LocalText.get_lang()
if self.has_key(L): if L in self:
f.add_flowing_data(self[L]) f.add_flowing_data(self[L])
elif self.has_key('en'): elif 'en' in self:
# fallback to English, blah # fallback to English, blah
f.add_flowing_data(self['en']) f.add_flowing_data(self['en'])
elif self.has_key('tr'): elif 'tr' in self:
# fallback to Turkish # fallback to Turkish
f.add_flowing_data(self['tr']) f.add_flowing_data(self['tr'])
else: else:
@@ -145,16 +145,16 @@ class LocalText(dict):
def __str__(self): def __str__(self):
L = LocalText.get_lang() L = LocalText.get_lang()
if self.has_key(L): if L in self:
return unicode(self[L]) return str(self[L])
elif self.has_key('en'): elif 'en' in self:
# fallback to English, blah # fallback to English, blah
return unicode(self['en']) return str(self['en'])
elif self.has_key('tr'): elif 'tr' in self:
# fallback to Turkish # fallback to Turkish
return unicode(self['tr']) return str(self['tr'])
else: else:
return unicode() return str()
class Writer(formatter.DumbWriter): class Writer(formatter.DumbWriter):
"""adds unicode support""" """adds unicode support"""
@@ -163,7 +163,7 @@ class Writer(formatter.DumbWriter):
formatter.DumbWriter.__init__(self, file, maxcol) formatter.DumbWriter.__init__(self, file, maxcol)
def send_literal_data(self, data): def send_literal_data(self, data):
self.file.write(data.encode("utf-8")) self.file.write(data)
i = data.rfind('\n') i = data.rfind('\n')
if i >= 0: if i >= 0:
self.col = 0 self.col = 0
@@ -252,13 +252,13 @@ class autoxml(oo.autosuper, oo.autoprop):
xmlfile_support = xmlfile.XmlFile in bases 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 #TODO: initialize class attribute __xml_tags
#setattr(cls, 'xml_variables', []) #setattr(cls, 'xml_variables', [])
# default class tag is class name # default class tag is class name
if not dict.has_key('tag'): if 'tag' not in dict:
cls.tag = name cls.tag = name
# generate helper routines, for each XML component # 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 fn = re.compile('\s*([tas]_[a-zA-Z]+).*').findall
inspect.linecache.clearcache() inspect.linecache.clearcache()
lines = filter(fn, inspect.getsourcelines(cls)[0]) lines = list(filter(fn, inspect.getsourcelines(cls)[0]))
decl_order = map(lambda x:x.split()[0], lines) decl_order = [x.split()[0] for x in lines]
except IOError: except IOError:
decl_order = dict.keys() decl_order = list(dict.keys())
# there should be at most one str member, and it should be # there should be at most one str member, and it should be
# the first to process # 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 # 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: if len(str_members)>1:
raise Error('Only one str member can be defined') raise Error('Only one str member can be defined')
elif len(str_members)==1: elif len(str_members)==1:
@@ -317,7 +317,7 @@ class autoxml(oo.autosuper, oo.autoprop):
def initialize(self, uri = None, keepDoc = False, tmpDir = '/tmp', def initialize(self, uri = None, keepDoc = False, tmpDir = '/tmp',
**args): **args):
if xmlfile_support: if xmlfile_support:
if args.has_key('tag'): if 'tag' in args:
xmlfile.XmlFile.__init__(self, tag = args['tag']) xmlfile.XmlFile.__init__(self, tag = args['tag'])
else: else:
xmlfile.XmlFile.__init__(self, tag = cls.tag) xmlfile.XmlFile.__init__(self, tag = cls.tag)
@@ -325,7 +325,7 @@ class autoxml(oo.autosuper, oo.autoprop):
base.__init__(self) base.__init__(self)
for init in inits: for init in inits:
init(self) init(self)
for x in args.iterkeys(): for x in args.keys():
setattr(self, x, args[x]) setattr(self, x, args[x])
# init hook # init hook
if hasattr(self, 'init'): if hasattr(self, 'init'):
@@ -336,7 +336,7 @@ class autoxml(oo.autosuper, oo.autoprop):
cls.__init__ = initialize cls.__init__ = initialize
cls.decoders = decoders 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: for base in cls.autoxml_bases:
base.decode(self, node, errs, where) base.decode(self, node, errs, where)
for decode_member in decoders:#self.__class__.decoders: for decode_member in decoders:#self.__class__.decoders:
@@ -356,7 +356,7 @@ class autoxml(oo.autosuper, oo.autoprop):
cls.encode = encode cls.encode = encode
cls.errorss = errorss cls.errorss = errorss
def errors(self, where = unicode(name)): def errors(self, where=name):
errs = [] errs = []
for base in cls.autoxml_bases: for base in cls.autoxml_bases:
errs.extend(base.errors(self, where)) errs.extend(base.errors(self, where))
@@ -389,16 +389,16 @@ class autoxml(oo.autosuper, oo.autoprop):
for x in errs: for x in errs:
ctx.ui.warning(x) ctx.ui.warning(x)
cls.print_text = print_text cls.print_text = print_text
if not dict.has_key('__str__'): if '__str__' not in dict:
def str(self): def str(self):
strfile = StringIO.StringIO() strfile = io.StringIO()
self.print_text(strfile) self.print_text(strfile)
str = strfile.getvalue() str = strfile.getvalue()
strfile.close() strfile.close()
return str return str
cls.__str__ = str cls.__str__ = str
if not dict.has_key('__eq__'): if '__eq__' not in dict:
def equal(self, other): def equal(self, other):
# handle None # handle None
if other ==None: if other ==None:
@@ -409,7 +409,7 @@ class autoxml(oo.autosuper, oo.autoprop):
return False return False
except KeyboardInterrupt: except KeyboardInterrupt:
raise 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 False
return True return True
def notequal(self, other): def notequal(self, other):
@@ -508,8 +508,8 @@ class autoxml(oo.autosuper, oo.autoprop):
def gen_tag(cls, tag, spec): def gen_tag(cls, tag, spec):
"""generate readers and writers for the tag""" """generate readers and writers for the tag"""
tag_type = spec[0] tag_type = spec[0]
if type(tag_type) is types.TypeType and \ if type(tag_type) is type and \
autoxml.basic_cons_map.has_key(tag_type): tag_type in autoxml.basic_cons_map:
def readtext(node, tagpath): def readtext(node, tagpath):
#print 'read tag', node, tagpath #print 'read tag', node, tagpath
return xmlext.getNodeText(node, tagpath) return xmlext.getNodeText(node, tagpath)
@@ -517,11 +517,11 @@ class autoxml(oo.autosuper, oo.autoprop):
#print 'write tag', node, tagpath, text #print 'write tag', node, tagpath, text
xmlext.addText(node, tagpath, text) xmlext.addText(node, tagpath, text)
return cls.gen_anon_basic(tag, spec, readtext, writetext) 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) return cls.gen_list_tag(tag, spec)
elif tag_type is LocalText: elif tag_type is LocalText:
return cls.gen_insetclass_tag(tag, spec) 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) return cls.gen_class_tag(tag, spec)
else: else:
raise Error(_('gen_tag: unrecognized tag type %s in spec') % 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): def decode(self, node, errs, where):
"""decode component from DOM node""" """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): def encode(self, node, errs):
"""encode self inside, possibly new, DOM node using xml""" """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" "returns split of the tag path into last tag and the rest"
try: try:
lastsep = tagpath.rindex('/') lastsep = tagpath.rindex('/')
except ValueError, e: except ValueError as e:
return ('', tagpath) return ('', tagpath)
return (tagpath[:lastsep], tagpath[lastsep+1:]) return (tagpath[:lastsep], tagpath[lastsep+1:])
@@ -651,7 +651,7 @@ class autoxml(oo.autosuper, oo.autoprop):
value = autoxml.basic_cons_map[token_type](text) value = autoxml.basic_cons_map[token_type](text)
except KeyboardInterrupt: except KeyboardInterrupt:
raise 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 value = None
errs.append(where + ': ' + _('Type mismatch: read text cannot be decoded')) errs.append(where + ': ' + _('Type mismatch: read text cannot be decoded'))
return value return value
@@ -663,7 +663,7 @@ class autoxml(oo.autosuper, oo.autoprop):
def encode(node, value, errs): def encode(node, value, errs):
"""encode given value inside DOM node""" """encode given value inside DOM node"""
if value is not None: if value is not None:
writetext(node, token, unicode(value)) writetext(node, token, str(value))
else: else:
if req == mandatory: if req == mandatory:
errs.append(_('Mandatory token %s not available') % token) errs.append(_('Mandatory token %s not available') % token)
@@ -677,7 +677,7 @@ class autoxml(oo.autosuper, oo.autoprop):
def format(value, f, errs): def format(value, f, errs):
"""format value for pretty printing""" """format value for pretty printing"""
f.add_literal_data(unicode(value)) f.add_literal_data(str(value))
return initialize, decode, encode, errors, format return initialize, decode, encode, errors, format
@@ -687,7 +687,7 @@ class autoxml(oo.autosuper, oo.autoprop):
def make_object(): def make_object():
obj = tag_type.__new__(tag_type) obj = tag_type.__new__(tag_type)
obj.__init__(tag=tag, req=req) obj.__init__()
return obj return obj
def init(): def init():
@@ -765,7 +765,7 @@ class autoxml(oo.autosuper, oo.autoprop):
for node in nodes: for node in nodes:
dummy = xmlext.newNode(node, "Dummy") dummy = xmlext.newNode(node, "Dummy")
xmlext.addNode(dummy, '', node) 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))) #l.append(decode_item(node, errs, where + unicode("[%s]" % ix)))
ix += 1 ix += 1
return l return l
@@ -855,12 +855,11 @@ class autoxml(oo.autosuper, oo.autoprop):
if req == mandatory: if req == mandatory:
errs.append(_('Mandatory argument not available')) errs.append(_('Mandatory argument not available'))
return (init, decode, encode, errors, format) return init, decode, encode, errors, format
basic_cons_map = { basic_cons_map = {
types.StringType : str, bytes: str,
types.UnicodeType : unicode, str: str,
types.IntType : int, int: int,
types.FloatType : float, float: float,
types.LongType : long }
}
+2 -2
View File
@@ -24,7 +24,7 @@
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.gettext
import pisi import pisi
import piksemel as iks import piksemel as iks
@@ -39,7 +39,7 @@ def getAllNodes(node, tagPath):
return [] return []
nodeList = [node] # basis case nodeList = [node] # basis case
for tag in tags: for tag in tags:
results = map(lambda x: getTagByName(x, tag), nodeList) results = [getTagByName(x, tag) for x in nodeList]
nodeList = [] nodeList = []
for x in results: for x in results:
nodeList.extend(x) nodeList.extend(x)

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