* trailing whitespace cleanups

This commit is contained in:
Faik Uygur
2006-10-30 17:21:31 +00:00
parent c1bb4a2698
commit effe4d5615
56 changed files with 428 additions and 443 deletions
+3 -3
View File
@@ -57,7 +57,7 @@ def configure(parameters = ''):
'''configure source with given parameters = "--with-nls --with-libusb --with-something-usefull"''' '''configure source with given parameters = "--with-nls --with-libusb --with-something-usefull"'''
if can_access_file('configure'): if can_access_file('configure'):
gnuconfig_update() gnuconfig_update()
args = './configure \ args = './configure \
--prefix=/%s \ --prefix=/%s \
--host=%s \ --host=%s \
@@ -70,7 +70,7 @@ def configure(parameters = ''):
get.HOST(), get.manDIR(), \ get.HOST(), get.manDIR(), \
get.infoDIR(), get.dataDIR(), \ get.infoDIR(), get.dataDIR(), \
get.confDIR(), get.localstateDIR(), parameters) get.confDIR(), get.localstateDIR(), parameters)
if system(args): if system(args):
raise ConfigureError(_('Configure failed.')) raise ConfigureError(_('Configure failed.'))
else: else:
@@ -138,7 +138,7 @@ def rawInstall(parameters = '', argument = 'install'):
fixInfoDir() fixInfoDir()
def aclocal(parameters = ''): def aclocal(parameters = ''):
'''generates an aclocal.m4 based on the contents of configure.in.''' '''generates an aclocal.m4 based on the contents of configure.in.'''
if system('aclocal %s' % parameters): if system('aclocal %s' % parameters):
raise RunTimeError(_('Running aclocal failed.')) raise RunTimeError(_('Running aclocal failed.'))
+1 -1
View File
@@ -74,7 +74,7 @@ class uniq:
if i == prev: if i == prev:
continue continue
except NameError: except NameError:
pass pass
prev = i prev = i
yield i yield i
uniq = uniq() uniq = uniq()
+4 -4
View File
@@ -30,7 +30,7 @@ class BinutilsError(pisi.actionsapi.Error):
self.value = value self.value = value
ctx.ui.error(value) ctx.ui.error(value)
# Globals # Globals
env = pisi.actionsapi.variables.glb.env env = pisi.actionsapi.variables.glb.env
dirs = pisi.actionsapi.variables.glb.dirs dirs = pisi.actionsapi.variables.glb.dirs
@@ -62,7 +62,7 @@ def ENV(environ):
def pkgDIR(): def pkgDIR():
'''returns the path of binary packages''' '''returns the path of binary packages'''
'''Default: /var/cache/pisi/packages''' '''Default: /var/cache/pisi/packages'''
return env.pkg_dir return env.pkg_dir
def workDIR(): def workDIR():
@@ -90,13 +90,13 @@ def srcDIR():
return '%s-%s' % (env.src_name, env.src_version) return '%s-%s' % (env.src_name, env.src_version)
# Build Related Functions # Build Related Functions
def HOST(): def HOST():
return env.host return env.host
def CHOST(): def CHOST():
# FIXME: Currently it behave same as HOST, # FIXME: Currently it behave same as HOST,
# but will be used for cross-compiling when PİSİ ready... # but will be used for cross-compiling when PİSİ ready...
return env.host return env.host
def CFLAGS(): def CFLAGS():
+1 -1
View File
@@ -74,7 +74,7 @@ def make(parameters = ''):
def install(parameters = 'install'): def install(parameters = 'install'):
if can_access_file('Makefile'): if can_access_file('Makefile'):
args = 'make DESTDIR=%s destdir=%s %s' % (get.installDIR(), get.installDIR(), parameters) args = 'make DESTDIR=%s destdir=%s %s' % (get.installDIR(), get.installDIR(), parameters)
if system(args): if system(args):
raise InstallError(_('Install failed.')) raise InstallError(_('Install failed.'))
else: else:
+17 -17
View File
@@ -39,24 +39,24 @@ def dobin(sourceFile, destinationDirectory = '/usr/bin'):
'''insert a executable file into /bin or /usr/bin''' '''insert a executable file into /bin or /usr/bin'''
''' example call: pisitools.dobin("bin/xloadimage", "/bin", "xload") ''' ''' example call: pisitools.dobin("bin/xloadimage", "/bin", "xload") '''
executable_insinto(join_path(get.installDIR(), destinationDirectory), sourceFile) executable_insinto(join_path(get.installDIR(), destinationDirectory), sourceFile)
def dodir(destinationDirectory): def dodir(destinationDirectory):
'''creates a directory tree''' '''creates a directory tree'''
makedirs(join_path(get.installDIR(), destinationDirectory)) makedirs(join_path(get.installDIR(), destinationDirectory))
def dodoc(*sourceFiles): def dodoc(*sourceFiles):
'''inserts the files in the list of files into /usr/share/doc/PACKAGE''' '''inserts the files in the list of files into /usr/share/doc/PACKAGE'''
readable_insinto(join_path(get.installDIR(), join_path('/usr/share/doc', get.srcTAG())), *sourceFiles) readable_insinto(join_path(get.installDIR(), join_path('/usr/share/doc', get.srcTAG())), *sourceFiles)
def doexe(sourceFile, destinationDirectory): def doexe(sourceFile, destinationDirectory):
'''insert a executable file into destination directory''' '''insert a executable file into destination directory'''
''' example call: pisitools.doexe("kde-3.4.sh", "/etc/X11/Sessions")''' ''' example call: pisitools.doexe("kde-3.4.sh", "/etc/X11/Sessions")'''
executable_insinto(join_path(get.installDIR(), destinationDirectory), sourceFile) executable_insinto(join_path(get.installDIR(), destinationDirectory), sourceFile)
def dohtml(*sourceFiles): def dohtml(*sourceFiles):
'''inserts the files in the list of files into /usr/share/doc/PACKAGE/html''' '''inserts the files in the list of files into /usr/share/doc/PACKAGE/html'''
''' example call: pisitools.dohtml("doc/doxygen/html/*")''' ''' example call: pisitools.dohtml("doc/doxygen/html/*")'''
destionationDirectory = join_path(get.installDIR(), 'usr/share/doc' ,get.srcTAG(), 'html') destionationDirectory = join_path(get.installDIR(), 'usr/share/doc' ,get.srcTAG(), 'html')
@@ -83,17 +83,17 @@ def doinfo(*sourceFiles):
def dolib(sourceFile, destinationDirectory = '/usr/lib'): def dolib(sourceFile, destinationDirectory = '/usr/lib'):
'''insert the library into /usr/lib''' '''insert the library into /usr/lib'''
'''example call: pisitools.dolib_a("libz.a")''' '''example call: pisitools.dolib_a("libz.a")'''
'''example call: pisitools.dolib_a("libz.so")''' '''example call: pisitools.dolib_a("libz.so")'''
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, 755) lib_insinto(sourceFile, destinationDirectory, 755)
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'''
'''example call: pisitools.dolib_a("staticlib/libvga.a")''' '''example call: pisitools.dolib_a("staticlib/libvga.a")'''
sourceFile = join_path(os.getcwd(), sourceFile) sourceFile = join_path(os.getcwd(), sourceFile)
destinationDirectory = join_path(get.installDIR(), destinationDirectory) destinationDirectory = join_path(get.installDIR(), destinationDirectory)
@@ -102,7 +102,7 @@ def dolib_a(sourceFile, destinationDirectory = '/usr/lib'):
def dolib_so(sourceFile, destinationDirectory = '/usr/lib'): def dolib_so(sourceFile, destinationDirectory = '/usr/lib'):
'''insert the static library into /usr/lib with permission 0755''' '''insert the static library into /usr/lib with permission 0755'''
'''example call: pisitools.dolib_so("pppd/plugins/minconn.so")''' '''example call: pisitools.dolib_so("pppd/plugins/minconn.so")'''
sourceFile = join_path(os.getcwd(), sourceFile) sourceFile = join_path(os.getcwd(), sourceFile)
destinationDirectory = join_path(get.installDIR(), destinationDirectory) destinationDirectory = join_path(get.installDIR(), destinationDirectory)
@@ -124,8 +124,8 @@ def doman(*sourceFiles):
source[source.rindex('.')+1:] source[source.rindex('.')+1:]
except ValueError: except ValueError:
error(_('ActionsAPI [doman]: Wrong man page file: %s') % (source)) error(_('ActionsAPI [doman]: Wrong man page file: %s') % (source))
makedirs(join_path(manDIR, '/man%s' % pageDirectory)) makedirs(join_path(manDIR, '/man%s' % pageDirectory))
system('install -m0644 %s %s' % (source, join_path(manDIR, '/man%s' % pageDirectory))) system('install -m0644 %s %s' % (source, join_path(manDIR, '/man%s' % pageDirectory)))
def domo(sourceFile, locale, destinationFile ): def domo(sourceFile, locale, destinationFile ):
@@ -139,11 +139,11 @@ def domo(sourceFile, locale, destinationFile ):
def domove(sourceFile, destination, destinationFile = ''): def domove(sourceFile, destination, destinationFile = ''):
'''moves sourceFile/Directory into destinationFile/Directory''' '''moves sourceFile/Directory into destinationFile/Directory'''
''' example call: pisitools.domove("/usr/bin/bash", "/bin/bash")''' ''' example call: pisitools.domove("/usr/bin/bash", "/bin/bash")'''
''' example call: pisitools.domove("/usr/bin/", "/usr/sbin")''' ''' example call: pisitools.domove("/usr/bin/", "/usr/sbin")'''
makedirs(join_path(get.installDIR(), destination)) makedirs(join_path(get.installDIR(), destination))
for filePath in glob.glob(join_path(get.installDIR(), sourceFile)): for filePath in glob.glob(join_path(get.installDIR(), sourceFile)):
if not destinationFile: if not destinationFile:
move(filePath, join_path(get.installDIR(), join_path(destination, os.path.basename(filePath)))) move(filePath, join_path(get.installDIR(), join_path(destination, os.path.basename(filePath))))
@@ -152,20 +152,20 @@ def domove(sourceFile, destination, destinationFile = ''):
def rename(sourceFile, destinationFile): def rename(sourceFile, destinationFile):
''' renames sourceFile as destinationFile''' ''' renames sourceFile as destinationFile'''
''' example call: pisitools.rename("/usr/bin/bash", "bash.old") ''' ''' example call: pisitools.rename("/usr/bin/bash", "bash.old") '''
''' the result of the previous example would be "/usr/bin/bash.old" ''' ''' the result of the previous example would be "/usr/bin/bash.old" '''
baseDir = os.path.dirname(sourceFile) baseDir = os.path.dirname(sourceFile)
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: except OSError:
error(_('ActionsAPI [rename]: No such file or directory: %s') % (sourceFile)) error(_('ActionsAPI [rename]: No such file or directory: %s') % (sourceFile))
def dosed(sourceFiles, findPattern, replacePattern = ''): def dosed(sourceFiles, findPattern, replacePattern = ''):
'''replaces patterns in sourceFiles''' '''replaces patterns in sourceFiles'''
''' example call: pisitools.dosed("/etc/passwd", "caglar", "cem")''' ''' example call: pisitools.dosed("/etc/passwd", "caglar", "cem")'''
''' example call: pisitools.dosed("/etc/passwd", "caglar")''' ''' example call: pisitools.dosed("/etc/passwd", "caglar")'''
''' example call: pisitools.dosed("/etc/pass*", "caglar")''' ''' example call: pisitools.dosed("/etc/pass*", "caglar")'''
@@ -182,10 +182,10 @@ def dosed(sourceFiles, findPattern, replacePattern = ''):
def dosbin(sourceFile, destinationDirectory = '/usr/sbin'): def dosbin(sourceFile, destinationDirectory = '/usr/sbin'):
'''insert a executable file into /sbin or /usr/sbin''' '''insert a executable file into /sbin or /usr/sbin'''
''' example call: pisitools.dobin("bin/xloadimage", "/sbin") ''' ''' example call: pisitools.dobin("bin/xloadimage", "/sbin") '''
executable_insinto(join_path(get.installDIR(), destinationDirectory), sourceFile) executable_insinto(join_path(get.installDIR(), destinationDirectory), sourceFile)
def dosym(sourceFile, destinationFile): def dosym(sourceFile, destinationFile):
'''creates soft link between sourceFile and destinationFile''' '''creates soft link between sourceFile and destinationFile'''
+2 -2
View File
@@ -31,7 +31,7 @@ class FileError(pisi.actionsapi.Error):
pisi.actionsapi.Error.__init__(self, value) pisi.actionsapi.Error.__init__(self, value)
self.value = value self.value = value
ctx.ui.error(value) ctx.ui.error(value)
class ArgumentError(pisi.actionsapi.Error): class ArgumentError(pisi.actionsapi.Error):
def __init__(self, value=''): def __init__(self, value=''):
pisi.actionsapi.Error.__init__(self, value) pisi.actionsapi.Error.__init__(self, value)
@@ -73,7 +73,7 @@ def lib_insinto(sourceFile, destinationDirectory, permission = 0644):
if not can_access_directory(destinationDirectory): if not can_access_directory(destinationDirectory):
makedirs(destinationDirectory) makedirs(destinationDirectory)
if os.path.islink(sourceFile): if os.path.islink(sourceFile):
os.symlink(os.path.realpath(sourceFile), os.path.join(destinationDirectory, sourceFile)) os.symlink(os.path.realpath(sourceFile), os.path.join(destinationDirectory, sourceFile))
else: else:
+1 -1
View File
@@ -106,7 +106,7 @@ def unlinkDir(sourceDirectory):
except OSError: except OSError:
error(_('ActionsAPI [unlinkDir]: Operation not permitted: %s') % (sourceDirectory)) error(_('ActionsAPI [unlinkDir]: Operation not permitted: %s') % (sourceDirectory))
elif isFile(sourceDirectory): elif isFile(sourceDirectory):
pass pass
else: else:
error(_('ActionsAPI [unlinkDir]: Directory %s doesn\'t exists.') % (sourceDirectory)) error(_('ActionsAPI [unlinkDir]: Directory %s doesn\'t exists.') % (sourceDirectory))
+8 -8
View File
@@ -56,7 +56,7 @@ def init(database = True, write = True,
"""Initialize PiSi subsystem""" """Initialize PiSi subsystem"""
# UI comes first # UI comes first
if ui is None: if ui is None:
from pisi.cli import CLI from pisi.cli import CLI
if options: if options:
@@ -167,7 +167,7 @@ def package_graph(A, repo = pisi.itembyrepodb.installed, ignore_installed = Fals
be added.""" be added."""
ctx.ui.debug('A = %s' % str(A)) ctx.ui.debug('A = %s' % str(A))
# try to construct a pisi graph of packages to # try to construct a pisi graph of packages to
# install / reinstall # install / reinstall
@@ -283,7 +283,7 @@ def info(package, installed = False):
return info_file(package) return info_file(package)
else: else:
return info_name(package, installed) return info_name(package, installed)
def info_file(package_fn): def info_file(package_fn):
from package import Package from package import Package
@@ -301,7 +301,7 @@ def info_name(package_name, installed=False):
else: else:
package, repo = ctx.packagedb.get_package_repo(package_name, pisi.itembyrepodb.repos) package, repo = ctx.packagedb.get_package_repo(package_name, pisi.itembyrepodb.repos)
repostr = repo repostr = repo
from pisi.metadata import MetaData from pisi.metadata import MetaData
metadata = MetaData() metadata = MetaData()
metadata.package = package metadata.package = package
@@ -353,7 +353,7 @@ def check(package):
for file in files.list: for file in files.list:
if file.hash and file.type != "config" \ if file.hash and file.type != "config" \
and not os.path.islink('/' + file.path): and not os.path.islink('/' + file.path):
ctx.ui.info(_("Checking /%s ") % file.path, noln=True, verbose=True) ctx.ui.info(_("Checking /%s ") % file.path, noln=True, verbose=True)
if file.hash != util.sha1_file('/' + file.path): if file.hash != util.sha1_file('/' + file.path):
corrupt.append(file) corrupt.append(file)
ctx.ui.info(_("\nCorrupt file: %s") % file, noln=True) ctx.ui.info(_("\nCorrupt file: %s") % file, noln=True)
@@ -392,7 +392,7 @@ def remove_repo(name):
pisi.util.clean_dir(os.path.join(ctx.config.index_dir(), name)) pisi.util.clean_dir(os.path.join(ctx.config.index_dir(), name))
ctx.ui.info(_('Repo %s removed from system.') % name) ctx.ui.info(_('Repo %s removed from system.') % name)
else: else:
ctx.ui.error(_('Repository %s does not exist. Cannot remove.') ctx.ui.error(_('Repository %s does not exist. Cannot remove.')
% name) % name)
def list_repos(): def list_repos():
@@ -420,7 +420,7 @@ def update_repo(repo, force=False):
ctx.ui.warning(e) ctx.ui.warning(e)
ctx.txn_proc(lambda txn : index.update_db(repo, txn=txn)) ctx.txn_proc(lambda txn : index.update_db(repo, txn=txn))
ctx.ui.info(_('* Package database updated.')) ctx.ui.info(_('* Package database updated.'))
else: else:
raise Error(_('No repository named %s found.') % repo) raise Error(_('No repository named %s found.') % repo)
@@ -431,7 +431,7 @@ def delete_cache():
def rebuild_repo(repo): def rebuild_repo(repo):
ctx.ui.info(_('* Rebuilding \'%s\' named repo... ') % repo) ctx.ui.info(_('* Rebuilding \'%s\' named repo... ') % repo)
if ctx.repodb.has_repo(repo): if ctx.repodb.has_repo(repo):
repouri = URI(ctx.repodb.get_repo(repo).indexuri.get_uri()) repouri = URI(ctx.repodb.get_repo(repo).indexuri.get_uri())
indexname = repouri.filename() indexname = repouri.filename()
+21 -22
View File
@@ -35,7 +35,6 @@ class LZMAError(pisi.Error):
def __init__(self, err): def __init__(self, err):
pisi.Error.__init__(self, _("An error has occured while running LZMA:\n%s") % err) pisi.Error.__init__(self, _("An error has occured while running LZMA:\n%s") % err)
class ArchiveBase(object): class ArchiveBase(object):
"""Base class for Archive classes.""" """Base class for Archive classes."""
def __init__(self, file_path, atype): def __init__(self, file_path, atype):
@@ -69,7 +68,7 @@ class ArchiveBinary(ArchiveBase):
class ArchiveTar(ArchiveBase): class ArchiveTar(ArchiveBase):
"""ArchiveTar handles tar archives depending on the compression """ArchiveTar handles tar archives depending on the compression
type. Provides access to tar, tar.gz and tar.bz2 files. type. Provides access to tar, tar.gz and tar.bz2 files.
This class provides the unpack magic for tar archives.""" This class provides the unpack magic for tar archives."""
def __init__(self, file_path, arch_type = "tar", no_same_permissions = True): def __init__(self, file_path, arch_type = "tar", no_same_permissions = True):
@@ -151,7 +150,7 @@ class ArchiveTar(ArchiveBase):
else: else:
raise ArchiveError(_("Archive type not recognized")) raise ArchiveError(_("Archive type not recognized"))
self.tar = tarfile.open(self.file_path, wmode) self.tar = tarfile.open(self.file_path, wmode)
self.tar.add(file_name, arc_name) self.tar.add(file_name, arc_name)
def close(self): def close(self):
@@ -173,9 +172,9 @@ class MyZipFile(zipfile.ZipFile):
def decompressToFile(self, name, outname): def decompressToFile(self, name, outname):
import zlib import zlib
import binascii import binascii
block_size = 1024 * 1024 * 2 block_size = 1024 * 1024 * 2
if self.mode not in ("r", "a"): if self.mode not in ("r", "a"):
raise RuntimeError, 'read() requires mode "r" or "a"' raise RuntimeError, 'read() requires mode "r" or "a"'
if not self.fp: if not self.fp:
@@ -184,9 +183,9 @@ class MyZipFile(zipfile.ZipFile):
zinfo = self.getinfo(name) zinfo = self.getinfo(name)
filepos = self.fp.tell() filepos = self.fp.tell()
self.fp.seek(zinfo.file_offset, 0) self.fp.seek(zinfo.file_offset, 0)
destfile = file(outname, 'wb') destfile = file(outname, 'wb')
if zinfo.compress_type == zipfile.ZIP_STORED: if zinfo.compress_type == zipfile.ZIP_STORED:
total_read = 0 total_read = 0
crc = None crc = None
@@ -209,13 +208,13 @@ class MyZipFile(zipfile.ZipFile):
raise BadZipfile, \ raise BadZipfile, \
"Unsupported compression method %d for file %s" % \ "Unsupported compression method %d for file %s" % \
(zinfo.compress_type, name) (zinfo.compress_type, name)
if not zlib: if not zlib:
raise RuntimeError, \ raise RuntimeError, \
"De-compression requires the (missing) zlib module" "De-compression requires the (missing) zlib module"
# zlib compress/decompress code by Jeremy Hylton of CNRI # zlib compress/decompress code by Jeremy Hylton of CNRI
dc = zlib.decompressobj(-15) dc = zlib.decompressobj(-15)
total_read = 0 total_read = 0
crc = None crc = None
while total_read < zinfo.compress_size: while total_read < zinfo.compress_size:
@@ -229,7 +228,7 @@ class MyZipFile(zipfile.ZipFile):
crc = binascii.crc32(dcbuff, crc) crc = binascii.crc32(dcbuff, crc)
else: else:
crc = binascii.crc32(dcbuff) crc = binascii.crc32(dcbuff)
# need to feed in unused pad byte so that zlib won't choke # need to feed in unused pad byte so that zlib won't choke
ex = dc.decompress(dc.unconsumed_tail + 'Z') + dc.flush() ex = dc.decompress(dc.unconsumed_tail + 'Z') + dc.flush()
if ex: if ex:
@@ -238,23 +237,23 @@ class MyZipFile(zipfile.ZipFile):
else: else:
crc = binascii.crc32(ex) crc = binascii.crc32(ex)
destfile.write(ex) destfile.write(ex)
if crc and crc != zinfo.CRC: if crc and crc != zinfo.CRC:
raise zipfile.BadZipfile, "Bad CRC-32 for file %s" % name raise zipfile.BadZipfile, "Bad CRC-32 for file %s" % name
destfile.close() destfile.close()
self.fp.seek(filepos, 0) self.fp.seek(filepos, 0)
class ArchiveZip(ArchiveBase): class ArchiveZip(ArchiveBase):
"""ArchiveZip handles zip archives. """ArchiveZip handles zip archives.
Being a zip archive PiSi packages also use this class Being a zip archive PiSi packages also use this class
extensively. This class provides unpacking and packing magic for extensively. This class provides unpacking and packing magic for
zip archives.""" zip archives."""
symmagic = 2716663808 #long of hex val '0xA1ED0000L' symmagic = 2716663808 #long of hex val '0xA1ED0000L'
def __init__(self, file_path, arch_type = "zip", mode = 'r'): def __init__(self, file_path, arch_type = "zip", mode = 'r'):
super(ArchiveZip, self).__init__(file_path, arch_type) super(ArchiveZip, self).__init__(file_path, arch_type)
@@ -280,7 +279,7 @@ class ArchiveZip(ArchiveBase):
attr = zipfile.ZipInfo() attr = zipfile.ZipInfo()
attr.filename = file_name attr.filename = file_name
attr.create_system = 3 attr.create_system = 3
attr.external_attr = self.symmagic attr.external_attr = self.symmagic
self.zip_obj.writestr(attr, dest) self.zip_obj.writestr(attr, dest)
else: else:
self.zip_obj.write(file_name, arc_name, zipfile.ZIP_DEFLATED) self.zip_obj.write(file_name, arc_name, zipfile.ZIP_DEFLATED)
@@ -313,7 +312,7 @@ class ArchiveZip(ArchiveBase):
def unpack_file_cond(self, pred, target_dir, archive_root = ''): def unpack_file_cond(self, pred, target_dir, archive_root = ''):
"""Unpack/Extract files according to predicate function """Unpack/Extract files according to predicate function
pred: filename -> bool pred: filename -> bool
unpacks stuff into target_dir and only extracts files unpacks stuff into target_dir and only extracts files
from archive_root, treating it as the archive root""" from archive_root, treating it as the archive root"""
zip_obj = self.zip_obj zip_obj = self.zip_obj
@@ -322,7 +321,7 @@ class ArchiveZip(ArchiveBase):
# below code removes that, so we find it here # below code removes that, so we find it here
is_dir = info.filename.endswith('/') is_dir = info.filename.endswith('/')
# calculate output file name # calculate output file name
if archive_root == '': if archive_root == '':
outpath = info.filename outpath = info.filename
@@ -346,7 +345,7 @@ class ArchiveZip(ArchiveBase):
perm |= 0x00000100 perm |= 0x00000100
os.chmod(d, perm) os.chmod(d, perm)
continue continue
# check that output dir is present # check that output dir is present
util.check_dir(os.path.dirname(ofile)) util.check_dir(os.path.dirname(ofile))
@@ -354,7 +353,7 @@ class ArchiveZip(ArchiveBase):
# (also check for islink? for broken symlinks...) # (also check for islink? for broken symlinks...)
if os.path.isfile(ofile) or os.path.islink(ofile): if os.path.isfile(ofile) or os.path.islink(ofile):
os.remove(ofile) os.remove(ofile)
if info.external_attr == self.symmagic: if info.external_attr == self.symmagic:
if os.path.isdir(ofile): if os.path.isdir(ofile):
shutil.rmtree(ofile) # a rare case, the file used to be a dir, now it is a symlink! shutil.rmtree(ofile) # a rare case, the file used to be a dir, now it is a symlink!
@@ -382,7 +381,7 @@ class ArchiveZip(ArchiveBase):
self.unpack_file_cond(lambda f: True, target_dir) self.unpack_file_cond(lambda f: True, target_dir)
self.close() self.close()
return return
class Archive: class Archive:
@@ -394,7 +393,7 @@ class Archive:
targz, tarbz2, zip, tar""" targz, tarbz2, zip, tar"""
handlers = { handlers = {
'targz': ArchiveTar, 'targz': ArchiveTar,
'tarbz2': ArchiveTar, 'tarbz2': ArchiveTar,
'tarlzma': ArchiveTar, 'tarlzma': ArchiveTar,
'tar': ArchiveTar, 'tar': ArchiveTar,
+3 -3
View File
@@ -307,7 +307,7 @@ class Install(AtomicOperation):
# get config path lists # get config path lists
newconfig = set(map(lambda x: str(x.path), new)) newconfig = set(map(lambda x: str(x.path), new))
oldconfig = set(map(lambda x: str(x.path), old)) oldconfig = set(map(lambda x: str(x.path), old))
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 = filter(lambda x: x.path in config_overlaps, old)
@@ -422,8 +422,8 @@ class Remove(AtomicOperation):
for fileinfo in self.files.list: for fileinfo in self.files.list:
self.remove_file(fileinfo) self.remove_file(fileinfo)
removed += 1 removed += 1
ctx.ui.display_progress(operation = "removing", ctx.ui.display_progress(operation = "removing",
percent = progress.update(removed), percent = progress.update(removed),
info = _("Removing package %s") % self.package_name) info = _("Removing package %s") % self.package_name)
txn = ctx.dbenv.txn_begin() txn = ctx.dbenv.txn_begin()
+38 -39
View File
@@ -44,18 +44,18 @@ import pisi.actionsapi.variables
class Error(pisi.Error): class Error(pisi.Error):
pass pass
# Helper Functions # Helper Functions
def get_file_type(path, pinfo_list, install_dir): def get_file_type(path, pinfo_list, install_dir):
"""Return the file type of a path according to the given PathInfo """Return the file type of a path according to the given PathInfo
list""" list"""
Match = lambda x: [match for match in glob.glob(install_dir + x) if join(install_dir, path).find(match) > -1] Match = lambda x: [match for match in glob.glob(install_dir + x) if join(install_dir, path).find(match) > -1]
def Sort(x): def Sort(x):
x.sort(reverse=True) x.sort(reverse=True)
return x return x
best_matched_path = Sort([pinfo.path for pinfo in pinfo_list if Match(pinfo.path)])[0] best_matched_path = Sort([pinfo.path for pinfo in pinfo_list if Match(pinfo.path)])[0]
info = [pinfo for pinfo in pinfo_list if best_matched_path == pinfo.path][0] info = [pinfo for pinfo in pinfo_list if best_matched_path == pinfo.path][0]
return info.fileType, info.permanent return info.fileType, info.permanent
@@ -77,7 +77,7 @@ def check_path_collision(package, pkgList):
# path.path: /usr/share/doc # path.path: /usr/share/doc
if (path.path.endswith(ctx.const.ar_file_suffix) and ctx.get_option('create_static')) or \ if (path.path.endswith(ctx.const.ar_file_suffix) and ctx.get_option('create_static')) or \
(path.path.endswith(ctx.const.debug_file_suffix) and ctx.config.values.build.generatedebug): (path.path.endswith(ctx.const.debug_file_suffix) and ctx.config.values.build.generatedebug):
# don't throw collision error for these files. # don't throw collision error for these files.
# we'll handle this in gen_files_xml.. # we'll handle this in gen_files_xml..
continue continue
if util.subpath(pinfo.path, path.path): if util.subpath(pinfo.path, path.path):
@@ -97,7 +97,7 @@ class Builder:
# find package in repository # find package in repository
sf, reponame = ctx.sourcedb.get_spec_repo(name) sf, reponame = ctx.sourcedb.get_spec_repo(name)
src = sf.source src = sf.source
if src: if src:
src_uri = URI(src.sourceURI) src_uri = URI(src.sourceURI)
if src_uri.is_absolute_path(): if src_uri.is_absolute_path():
@@ -107,13 +107,13 @@ class Builder:
#FIXME: don't use dirname to work on URLs #FIXME: don't use dirname to work on URLs
src_path = os.path.join(os.path.dirname(repo.indexuri.get_uri()), src_path = os.path.join(os.path.dirname(repo.indexuri.get_uri()),
str(src_uri.path())) str(src_uri.path()))
ctx.ui.debug(_("Source URI: %s") % src_path) ctx.ui.debug(_("Source URI: %s") % src_path)
return Builder(src_path) return Builder(src_path)
else: else:
raise Error(_("Source %s not found in any active repository.") % name) raise Error(_("Source %s not found in any active repository.") % name)
def __init__(self, specuri): def __init__(self, specuri):
# process args # process args
@@ -154,7 +154,7 @@ class Builder:
self.spec.getSourceVersion() + '-' + self.spec.getSourceRelease() self.spec.getSourceVersion() + '-' + self.spec.getSourceRelease()
return util.join_path(ctx.config.dest_dir(), ctx.config.values.dirs.tmp_dir, return util.join_path(ctx.config.dest_dir(), ctx.config.values.dirs.tmp_dir,
packageDir) packageDir)
def pkg_work_dir(self): def pkg_work_dir(self):
return self.pkg_dir() + ctx.const.work_dir_suffix return self.pkg_dir() + ctx.const.work_dir_suffix
@@ -178,10 +178,10 @@ class Builder:
"""Build the package in one shot.""" """Build the package in one shot."""
ctx.ui.status(_("Building PiSi source package: %s") % self.spec.source.name) ctx.ui.status(_("Building PiSi source package: %s") % self.spec.source.name)
self.compile_action_script() self.compile_action_script()
self.compile_comar_script() self.compile_comar_script()
# check if all patch files exists, if there are missing no need to unpack! # check if all patch files exists, if there are missing no need to unpack!
self.patch_exists() self.patch_exists()
@@ -246,13 +246,13 @@ class Builder:
def fetch_actionsfile(self): def fetch_actionsfile(self):
actionsuri = join(self.specdiruri, ctx.const.actions_file) actionsuri = join(self.specdiruri, ctx.const.actions_file)
self.download(actionsuri, self.destdir) self.download(actionsuri, self.destdir)
def fetch_patches(self): def fetch_patches(self):
spec = self.spec spec = self.spec
for patch in spec.source.patches: for patch in spec.source.patches:
file_name = basename(patch.filename) file_name = basename(patch.filename)
dir_name = dirname(patch.filename) dir_name = dirname(patch.filename)
patchuri = join(self.specdiruri, patchuri = join(self.specdiruri,
ctx.const.files_dir, dir_name, file_name) ctx.const.files_dir, dir_name, file_name)
self.download(patchuri, join(self.destdir, ctx.const.files_dir, dir_name)) self.download(patchuri, join(self.destdir, ctx.const.files_dir, dir_name))
@@ -270,7 +270,7 @@ class Builder:
for afile in pkg.additionalFiles: for afile in pkg.additionalFiles:
file_name = basename(afile.filename) file_name = basename(afile.filename)
dir_name = dirname(afile.filename) dir_name = dirname(afile.filename)
afileuri = join(self.specdiruri, afileuri = join(self.specdiruri,
ctx.const.files_dir, dir_name, file_name) ctx.const.files_dir, dir_name, file_name)
self.download(afileuri, join(self.destdir, ctx.const.files_dir, dir_name)) self.download(afileuri, join(self.destdir, ctx.const.files_dir, dir_name))
@@ -323,11 +323,11 @@ class Builder:
def run_install_action(self): def run_install_action(self):
ctx.ui.action(_("Installing...")) ctx.ui.action(_("Installing..."))
# Before install make sure install_dir is clean # Before install make sure install_dir is clean
if os.path.exists(self.pkg_install_dir()): if os.path.exists(self.pkg_install_dir()):
util.clean_dir(self.pkg_install_dir()) util.clean_dir(self.pkg_install_dir())
# install function is mandatory! # install function is mandatory!
self.run_action_function(ctx.const.install_func, True) self.run_action_function(ctx.const.install_func, True)
self.set_state("installaction") self.set_state("installaction")
@@ -393,11 +393,11 @@ class Builder:
workdir = self.actionGlobals['WorkDir'] workdir = self.actionGlobals['WorkDir']
except KeyError: except KeyError:
workdir = self.spec.source.name + "-" + self.spec.getSourceVersion() workdir = self.spec.source.name + "-" + self.spec.getSourceVersion()
return util.join_path(self.pkg_work_dir(), workdir) return util.join_path(self.pkg_work_dir(), workdir)
def run_action_function(self, func, mandatory=False): def run_action_function(self, func, mandatory=False):
"""Calls the corresponding function in actions.py. """Calls the corresponding function in actions.py.
If mandatory parameter is True, and function is not present in If mandatory parameter is True, and function is not present in
actionLocals pisi.build.Error will be raised.""" actionLocals pisi.build.Error will be raised."""
@@ -441,14 +441,14 @@ class Builder:
for dep in build_deps: for dep in build_deps:
if not dependency.installed_satisfies_dep(dep): if not dependency.installed_satisfies_dep(dep):
dep_unsatis.append(dep) dep_unsatis.append(dep)
if dep_unsatis: if dep_unsatis:
ctx.ui.info(_("Unsatisfied Build Dependencies:") + ' ' ctx.ui.info(_("Unsatisfied Build Dependencies:") + ' '
+ util.strlist([str(x) for x in dep_unsatis]) ) + util.strlist([str(x) for x in dep_unsatis]) )
def fail(): def fail():
raise Error(_('Cannot build package due to unsatisfied build dependencies')) raise Error(_('Cannot build package due to unsatisfied build dependencies'))
if ctx.config.get_option('no_install'): if ctx.config.get_option('no_install'):
fail() fail()
@@ -564,7 +564,7 @@ class Builder:
metadata.package.distributionRelease = ctx.config.values.general.distribution_release metadata.package.distributionRelease = ctx.config.values.general.distribution_release
metadata.package.architecture = "Any" metadata.package.architecture = "Any"
metadata.package.packageFormat = ctx.get_option('package_format') metadata.package.packageFormat = ctx.get_option('package_format')
size = 0 size = 0
if package.debug_package: if package.debug_package:
d = self.pkg_debug_dir() d = self.pkg_debug_dir()
@@ -579,7 +579,6 @@ class Builder:
self.metadata = metadata self.metadata = metadata
def gen_files_xml(self, package): def gen_files_xml(self, package):
"""Generates files.xml using the path definitions in specfile and """Generates files.xml using the path definitions in specfile and
the files produced by the build system.""" the files produced by the build system."""
@@ -601,7 +600,7 @@ class Builder:
d = {} d = {}
def add_path(path): def add_path(path):
# add the files under material path # add the files under material path
for fpath, fhash in util.get_file_hashes(path, collisions, install_dir): for fpath, fhash in util.get_file_hashes(path, collisions, install_dir):
if ctx.get_option('create_static') \ if ctx.get_option('create_static') \
and fpath.endswith(ctx.const.ar_file_suffix) \ and fpath.endswith(ctx.const.ar_file_suffix) \
@@ -613,7 +612,7 @@ class Builder:
frpath = util.removepathprefix(install_dir, fpath) # relative path frpath = util.removepathprefix(install_dir, fpath) # relative path
ftype, permanent = get_file_type(frpath, package.files, install_dir) ftype, permanent = get_file_type(frpath, package.files, install_dir)
fsize = util.dir_size(fpath) fsize = util.dir_size(fpath)
d[frpath] = FileInfo(path=frpath, type=ftype, permanent=permanent, d[frpath] = FileInfo(path=frpath, type=ftype, permanent=permanent,
size=fsize, hash=fhash) size=fsize, hash=fhash)
for pinfo in package.files: for pinfo in package.files:
@@ -638,9 +637,9 @@ class Builder:
return True return True
return False return False
# find previous build in packages dir # find previous build in packages dir
found = [] found = []
def locate_old_package(old_package_fn): def locate_old_package(old_package_fn):
if util.is_package_name(os.path.basename(old_package_fn), package_name): if util.is_package_name(os.path.basename(old_package_fn), package_name):
try: try:
@@ -682,13 +681,13 @@ class Builder:
# compare old files.xml with the new one.. # compare old files.xml with the new one..
old_pkg = Package(old_package_fn, 'r') old_pkg = Package(old_package_fn, 'r')
old_pkg.read(util.join_path(ctx.config.tmp_dir(), 'oldpkg')) old_pkg.read(util.join_path(ctx.config.tmp_dir(), 'oldpkg'))
changed = False changed = False
fnew = self.files.list fnew = self.files.list
fold = old_pkg.files.list fold = old_pkg.files.list
fold.sort(lambda x,y : cmp(x.path,y.path)) fold.sort(lambda x,y : cmp(x.path,y.path))
fnew.sort(lambda x,y : cmp(x.path,y.path)) fnew.sort(lambda x,y : cmp(x.path,y.path))
if len(fnew) != len(fold): if len(fnew) != len(fold):
changed = True changed = True
else: else:
@@ -702,7 +701,7 @@ class Builder:
if fo.hash != fn.hash: if fo.hash != fn.hash:
changed = True changed = True
break break
if metadata_changed(old_pkg.metadata, self.metadata): if metadata_changed(old_pkg.metadata, self.metadata):
changed = True changed = True
@@ -711,7 +710,7 @@ class Builder:
old_build = None old_build = None
ctx.ui.debug('old build number: %s' % old_build) ctx.ui.debug('old build number: %s' % old_build)
# set build number # set build number
if old_build is None: if old_build is None:
ctx.ui.warning(_('(old package lacks a build no, setting build no to 1.)')) ctx.ui.warning(_('(old package lacks a build no, setting build no to 1.)'))
@@ -782,7 +781,7 @@ class Builder:
# mode is octal! # mode is octal!
os.chmod(dest, int(afile.permission, 8)) os.chmod(dest, int(afile.permission, 8))
os.chdir(c) os.chdir(c)
ctx.ui.action(_("** Building package %s") % package.name); ctx.ui.action(_("** Building package %s") % package.name);
ctx.ui.info(_("Generating %s,") % ctx.const.files_xml) ctx.ui.info(_("Generating %s,") % ctx.const.files_xml)
@@ -797,7 +796,7 @@ class Builder:
ctx.ui.warning(_('Build number is not available. For repo builds you must enable buildno in pisi.conf.')) ctx.ui.warning(_('Build number is not available. For repo builds you must enable buildno in pisi.conf.'))
else: else:
build_no, old_build_no = self.calc_build_no(package.name) build_no, old_build_no = self.calc_build_no(package.name)
self.metadata.package.build = build_no self.metadata.package.build = build_no
self.metadata.write(util.join_path(self.pkg_dir(), ctx.const.metadata_xml)) self.metadata.write(util.join_path(self.pkg_dir(), ctx.const.metadata_xml))
@@ -825,7 +824,7 @@ class Builder:
# add xmls and files # add xmls and files
os.chdir(self.pkg_dir()) os.chdir(self.pkg_dir())
pkg.add_to_package(ctx.const.metadata_xml) pkg.add_to_package(ctx.const.metadata_xml)
pkg.add_to_package(ctx.const.files_xml) pkg.add_to_package(ctx.const.files_xml)
@@ -867,9 +866,9 @@ class Builder:
for f in abandoned_files: for f in abandoned_files:
ctx.ui.info(' - %s' % (f)) ctx.ui.info(' - %s' % (f))
else: else:
ctx.ui.warning(_('All of the files under the install dir (%s) has been collected by package(s)') ctx.ui.warning(_('All of the files under the install dir (%s) has been collected by package(s)')
% (install_dir)) % (install_dir))
if ctx.config.values.general.autoclean is True: if ctx.config.values.general.autoclean is True:
ctx.ui.info(_("Cleaning Build Directory...")) ctx.ui.info(_("Cleaning Build Directory..."))
util.clean_dir(self.pkg_dir()) util.clean_dir(self.pkg_dir())
@@ -927,7 +926,7 @@ def __buildState_buildaction(pb, last):
pb.run_build_action() pb.run_build_action()
def __buildState_installaction(pb, last): def __buildState_installaction(pb, last):
if order[last] < order["buildaction"]: if order[last] < order["buildaction"]:
__buildState_buildaction(pb, last) __buildState_buildaction(pb, last)
pb.run_install_action() pb.run_install_action()
@@ -946,7 +945,7 @@ def build_until(pspec, state):
pb.compile_action_script() pb.compile_action_script()
pb.compile_comar_script() pb.compile_comar_script()
last = pb.get_state() last = pb.get_state()
ctx.ui.info("Last state was %s"%last) ctx.ui.info("Last state was %s"%last)
@@ -963,7 +962,7 @@ def build_until(pspec, state):
if state == "setup": if state == "setup":
__buildState_setupaction(pb, last) __buildState_setupaction(pb, last)
return return
if state == "build": if state == "build":
__buildState_buildaction(pb, last) __buildState_buildaction(pb, last)
return return
+3 -3
View File
@@ -54,7 +54,7 @@ class CLI(UI):
util.xterm_title_reset() util.xterm_title_reset()
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()): if type(msg)==type(unicode()):
msg = msg.encode('utf-8') msg = msg.encode('utf-8')
if err: if err:
@@ -108,7 +108,7 @@ class CLI(UI):
return opts(opt-1) return opts(opt-1)
except (Exception,e): except (Exception,e):
pass pass
def confirm(self, msg): def confirm(self, msg):
msg = unicode(msg) msg = unicode(msg)
if ctx.config.options and ctx.config.options.yes_all: if ctx.config.options and ctx.config.options.yes_all:
@@ -129,7 +129,7 @@ class CLI(UI):
if operation == "removing": if operation == "removing":
return return
elif operation == "fetching": elif operation == "fetching":
totalsize = '%.1f %s' % pisi.util.human_readable_size(ka['total_size']) totalsize = '%.1f %s' % pisi.util.human_readable_size(ka['total_size'])
out = '\r%-30.30s (%s)%3d%% %9.2f %s [%s]' % \ out = '\r%-30.30s (%s)%3d%% %9.2f %s [%s]' % \
(ka['filename'], totalsize, percent, (ka['filename'], totalsize, percent,
ka['rate'], ka['symbol'], ka['eta']) ka['rate'], ka['symbol'], ka['eta'])
+9 -9
View File
@@ -38,14 +38,14 @@ colors = {'black' : "\033[30m",
'underlinemagenta' : "\033[04;35m", 'underlinemagenta' : "\033[04;35m",
'underlinecyan' : "\033[04;36m", 'underlinecyan' : "\033[04;36m",
'underlinewhite' : "\033[04;37m", 'underlinewhite' : "\033[04;37m",
'blinkingblack' : "\033[05;30m", 'blinkingblack' : "\033[05;30m",
'blinkingred' : "\033[05;31m", 'blinkingred' : "\033[05;31m",
'blinkinggreen' : "\033[05;32m", 'blinkinggreen' : "\033[05;32m",
'blinkingyellow' : "\033[05;33m", 'blinkingyellow' : "\033[05;33m",
'blinkingblue' : "\033[05;34m", 'blinkingblue' : "\033[05;34m",
'blinkingmagenta' : "\033[05;35m", 'blinkingmagenta' : "\033[05;35m",
'blinkingcyan' : "\033[05;36m", 'blinkingcyan' : "\033[05;36m",
'blinkingwhite' : "\033[05;37m", 'blinkingwhite' : "\033[05;37m",
'backgroundblack' : "\033[07;30m", 'backgroundblack' : "\033[07;30m",
'backgroundred' : "\033[07;31m", 'backgroundred' : "\033[07;31m",
'backgroundgreen' : "\033[07;32m", 'backgroundgreen' : "\033[07;32m",
@@ -53,7 +53,7 @@ colors = {'black' : "\033[30m",
'backgroundblue' : "\033[07;34m", 'backgroundblue' : "\033[07;34m",
'backgroundmagenta' : "\033[07;35m", 'backgroundmagenta' : "\033[07;35m",
'backgroundcyan' : "\033[07;36m", 'backgroundcyan' : "\033[07;36m",
'backgroundwhite' : "\033[07;37m", 'backgroundwhite' : "\033[07;37m",
'default' : "\033[0m" } 'default' : "\033[0m" }
def colorize(msg, color): def colorize(msg, color):
+61 -65
View File
@@ -12,7 +12,7 @@
import sys import sys
from optparse import OptionParser, OptionGroup, HelpFormatter from optparse import OptionParser, OptionGroup, HelpFormatter
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.ugettext
@@ -115,10 +115,10 @@ 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 Command.cmd_dict.has_key(cmd):
return Command.cmd_dict[cmd](args) return Command.cmd_dict[cmd](args)
if fail: if fail:
raise Error(_("Unrecognized command: %s") % cmd) raise Error(_("Unrecognized command: %s") % cmd)
else: else:
@@ -138,7 +138,7 @@ class Command(object):
(self.options, self.args) = self.parser.parse_args(args) (self.options, self.args) = self.parser.parse_args(args)
if self.args: if self.args:
self.args.pop(0) # exclude command arg self.args.pop(0) # exclude command arg
self.process_opts() self.process_opts()
def commonopts(self): def commonopts(self):
@@ -172,7 +172,7 @@ class Command(object):
def process_opts(self): def process_opts(self):
self.check_auth_info() self.check_auth_info()
# make destdir absolute # make destdir absolute
if self.options.destdir: if self.options.destdir:
dir = str(self.options.destdir) dir = str(self.options.destdir)
@@ -197,7 +197,7 @@ class Command(object):
if username and password: if username and password:
self.options.authinfo = (username, password) self.options.authinfo = (username, password)
return return
if username and not password: if username and not password:
from getpass import getpass from getpass import getpass
password = getpass(_("Password: ")) password = getpass(_("Password: "))
@@ -207,7 +207,7 @@ class Command(object):
def init(self, database = True, write = True): def init(self, database = True, write = True):
"""initialize PiSi components""" """initialize PiSi components"""
# NB: command imports here or in the command class run fxns # NB: command imports here or in the command class run fxns
import pisi.api import pisi.api
pisi.api.init(database = database, write = write, options = self.options, pisi.api.init(database = database, write = write, options = self.options,
@@ -216,7 +216,7 @@ class Command(object):
def finalize(self): def finalize(self):
"""do cleanup work for PiSi components""" """do cleanup work for PiSi components"""
pisi.api.finalize() pisi.api.finalize()
def get_name(self): def get_name(self):
return self.__class__.name return self.__class__.name
@@ -256,7 +256,7 @@ class autocommand(type):
add_cmd(longname) add_cmd(longname)
if shortname: if shortname:
add_cmd(shortname) add_cmd(shortname)
class Help(Command): class Help(Command):
"""Prints help for given commands """Prints help for given commands
@@ -281,14 +281,14 @@ If run without parameters, it prints the general help."""
self.parser.set_usage(usage_text) self.parser.set_usage(usage_text)
pisi.cli.printu(self.parser.format_help()) pisi.cli.printu(self.parser.format_help())
return return
self.init(database = False, write = False) self.init(database = False, write = False)
for arg in self.args: for arg in self.args:
obj = Command.get_command(arg, True) obj = Command.get_command(arg, True)
obj.help() obj.help()
ctx.ui.info('') ctx.ui.info('')
self.finalize() self.finalize()
@@ -315,11 +315,11 @@ This command deletes unused locks from the database directory."""
class DeleteCache(Command): class DeleteCache(Command):
"""Delete cache files """Delete cache files
Usage: delete-cache Usage: delete-cache
Sources, packages and temporary files are stored 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__ = autocommand __metaclass__ = autocommand
@@ -349,7 +349,7 @@ the package in graphviz format to 'pgraph.dot'.
def __init__(self, args=None): def __init__(self, args=None):
super(Graph, self).__init__(args) super(Graph, self).__init__(args)
def options(self): def options(self):
group = OptionGroup(self.parser, _("graph options")) group = OptionGroup(self.parser, _("graph options"))
@@ -392,7 +392,7 @@ the package in graphviz format to 'pgraph.dot'.
ctx.ui.info(_('Plotting a graph of relations among all installed packages')) ctx.ui.info(_('Plotting a graph of relations among all installed packages'))
a = ctx.installdb.list_installed() a = ctx.installdb.list_installed()
repo = pisi.itembyrepodb.installed repo = pisi.itembyrepodb.installed
g = pisi.api.package_graph(a, repo = repo, g = pisi.api.package_graph(a, repo = repo,
ignore_installed = ctx.get_option('ignore_installed')) ignore_installed = ctx.get_option('ignore_installed'))
g.write_graphviz(file(ctx.get_option('output'), 'w')) g.write_graphviz(file(ctx.get_option('output'), 'w'))
self.finalize() self.finalize()
@@ -455,17 +455,17 @@ to be downloaded from a repository containing sources.
def add_steps_options(self): def add_steps_options(self):
group = OptionGroup(self.parser, _("build steps")) group = OptionGroup(self.parser, _("build steps"))
group.add_option("--fetch", dest="until", action="store_const", group.add_option("--fetch", dest="until", action="store_const",
const="fetch", help=_("Break build after fetching the source archive")) const="fetch", help=_("Break build after fetching the source archive"))
group.add_option("--unpack", dest="until", action="store_const", group.add_option("--unpack", dest="until", action="store_const",
const="unpack", help=_("Break build after unpacking the source archive, checking sha1sum and applying patches")) const="unpack", help=_("Break build after unpacking the source archive, checking sha1sum and applying patches"))
group.add_option("--setup", dest="until", action="store_const", group.add_option("--setup", dest="until", action="store_const",
const="setup", help=_("Break build after running configure step")) const="setup", help=_("Break build after running configure step"))
group.add_option("--build", dest="until", action="store_const", group.add_option("--build", dest="until", action="store_const",
const="build", help=_("Break build after running compile step")) const="build", help=_("Break build after running compile step"))
group.add_option("--install", dest="until", action="store_const", group.add_option("--install", dest="until", action="store_const",
const="install", help=_("Break build after running install step")) const="install", help=_("Break build after running install step"))
group.add_option("--package", dest="until", action="store_const", group.add_option("--package", dest="until", action="store_const",
const="package", help=_("create PiSi package")) const="package", help=_("create PiSi package"))
self.parser.add_option_group(group) self.parser.add_option_group(group)
@@ -481,7 +481,7 @@ to be downloaded from a repository containing sources.
if ctx.get_option('package_format') not in Build.package_formats: if ctx.get_option('package_format') not in Build.package_formats:
raise Error(_('package_format must be one of %s ') % pisi.util.strlist(Build.package_formats)) raise Error(_('package_format must be one of %s ') % pisi.util.strlist(Build.package_formats))
if ctx.get_option('output_dir'): if ctx.get_option('output_dir'):
ctx.ui.info(_('Output directory: %s') % ctx.config.options.output_dir) ctx.ui.info(_('Output directory: %s') % ctx.config.options.output_dir)
else: else:
@@ -490,18 +490,17 @@ to be downloaded from a repository containing sources.
for x in self.args: for x in self.args:
if ctx.get_option('until'): if ctx.get_option('until'):
pisi.api.build_until(x, ctx.get_option('until')) pisi.api.build_until(x, ctx.get_option('until'))
else: else:
pisi.api.build(x) pisi.api.build(x)
self.finalize() self.finalize()
class Emerge(Build): class Emerge(Build):
"""Build and install PiSi source packages from repository """Build and install PiSi source packages from repository
Usage: emerge <sourcename> ... Usage: emerge <sourcename> ...
You should give the name of a source package to be You should give the name of a source package to be
downloaded from a repository containing sources. downloaded from a repository containing sources.
You can also give the name of a component. You can also give the name of a component.
@@ -515,7 +514,7 @@ You can also give the name of a component.
name = ("emerge", "em") name = ("emerge", "em")
def options(self): def options(self):
group = OptionGroup(self.parser, _("emerge options")) group = OptionGroup(self.parser, _("emerge options"))
super(Emerge, self).add_options(group) super(Emerge, self).add_options(group)
group.add_option("--ignore-file-conflicts", action="store_true", group.add_option("--ignore-file-conflicts", action="store_true",
@@ -525,7 +524,7 @@ You can also give the name of a component.
group.add_option("--ignore-comar", action="store_true", group.add_option("--ignore-comar", action="store_true",
default=False, help=_("Bypass comar configuration agent")) default=False, help=_("Bypass comar configuration agent"))
self.parser.add_option_group(group) self.parser.add_option_group(group)
def run(self): def run(self):
if not self.args: if not self.args:
self.help() self.help()
@@ -560,7 +559,7 @@ class PackageOp(Command):
def init(self): def init(self):
super(PackageOp, self).init(True) super(PackageOp, self).init(True)
def finalize(self): def finalize(self):
#self.finalize_db() #self.finalize_db()
pass pass
@@ -619,7 +618,7 @@ Usage: Upgrade [<package1> <package2> ... <packagen>]
Upgrades the entire system if no package names are given Upgrades the entire system if no package names are given
You may use only package names to specify packages because You may use only package names to specify packages because
the package upgrade operation is defined only with respect the package upgrade operation is defined only with respect
to repositories. If you have specified a package name, it to repositories. If you have specified a package name, it
should exist in the package repositories. If you just want to should exist in the package repositories. If you just want to
reinstall a package from a PiSi file, use the install command. reinstall a package from a PiSi file, use the install command.
@@ -637,7 +636,7 @@ expanded to package names.
def options(self): def options(self):
group = OptionGroup(self.parser, _("upgrade options")) group = OptionGroup(self.parser, _("upgrade options"))
super(Upgrade, self).options(group) super(Upgrade, self).options(group)
buildno_opts(self, group) buildno_opts(self, group)
group.add_option("--security-only", action="store_true", group.add_option("--security-only", action="store_true",
@@ -693,7 +692,7 @@ expanded to package names.
def run(self): def run(self):
self.init() self.init()
if not ctx.get_option('bypass_update_repo'): if not ctx.get_option('bypass_update_repo'):
ctx.ui.info(_('Updating repositories')) ctx.ui.info(_('Updating repositories'))
repos = ctx.repodb.list() repos = ctx.repodb.list()
@@ -701,7 +700,7 @@ expanded to package names.
pisi.api.update_repo(repo) pisi.api.update_repo(repo)
else: else:
ctx.ui.info(_('Will not update repositories')) ctx.ui.info(_('Will not update repositories'))
if not self.args: if not self.args:
packages = ctx.installdb.list_installed() packages = ctx.installdb.list_installed()
else: else:
@@ -756,9 +755,9 @@ class ConfigurePending(PackageOp):
If COMAR configuration of some packages were not If COMAR configuration of some packages were not
done at installation time, they are added to a list done at installation time, they are added to a list
of packages waiting to be configured. This command of packages waiting to be configured. This command
configures those packages. configures those packages.
""" """
__metaclass__ = autocommand __metaclass__ = autocommand
def __init__(self, args): def __init__(self, args):
@@ -783,7 +782,7 @@ class Info(Command):
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__ = autocommand __metaclass__ = autocommand
@@ -793,7 +792,7 @@ Usage: info <package1> <package2> ... <packagen>
name = ("info", None) name = ("info", None)
def options(self): def options(self):
group = OptionGroup(self.parser, _("info options")) group = OptionGroup(self.parser, _("info options"))
self.add_options(group) self.add_options(group)
self.parser.add_option_group(group) self.parser.add_option_group(group)
@@ -813,14 +812,14 @@ Usage: info <package1> <package2> ... <packagen>
def run(self): def run(self):
self.init(database = True, write = False) self.init(database = True, write = False)
if len(self.args) == 0: if len(self.args) == 0:
self.help() self.help()
return return
index = pisi.index.Index() index = pisi.index.Index()
index.distribution = None index.distribution = None
for arg in self.args: for arg in self.args:
if ctx.componentdb.has_component(arg): if ctx.componentdb.has_component(arg):
component = ctx.componentdb.get_union_comp(arg) component = ctx.componentdb.get_union_comp(arg)
@@ -830,8 +829,8 @@ Usage: info <package1> <package2> ... <packagen>
if not self.options.short: if not self.options.short:
ctx.ui.info(unicode(component)) ctx.ui.info(unicode(component))
else: else:
ctx.ui.info("%s - %s" % (component.name, component.summary)) ctx.ui.info("%s - %s" % (component.name, component.summary))
else: # then assume it was a package else: # then assume it was a package
if self.options.xml: if self.options.xml:
index.packages.append(pisi.api.info(arg)[0].package) index.packages.append(pisi.api.info(arg)[0].package)
else: else:
@@ -858,7 +857,7 @@ Usage: info <package1> <package2> ... <packagen>
else: else:
ctx.ui.info(_('Installed package:')) ctx.ui.info(_('Installed package:'))
self.print_pkginfo(metadata, files,pisi.itembyrepodb.installed) self.print_pkginfo(metadata, files,pisi.itembyrepodb.installed)
if ctx.packagedb.has_package(arg): if ctx.packagedb.has_package(arg):
metadata, files = pisi.api.info_name(arg, False) metadata, files = pisi.api.info_name(arg, False)
if self.options.short: if self.options.short:
@@ -876,7 +875,7 @@ Usage: info <package1> <package2> ... <packagen>
else: else:
ctx.ui.info(unicode(metadata.package)) ctx.ui.info(unicode(metadata.package))
if repo: if repo:
revdeps = [x[0] for x in revdeps = [x[0] for x in
ctx.packagedb.get_rev_deps(metadata.package.name, repo)] ctx.packagedb.get_rev_deps(metadata.package.name, repo)]
print _('Reverse Dependencies:'), util.strlist(revdeps) print _('Reverse Dependencies:'), util.strlist(revdeps)
if self.options.files or self.options.files_path: if self.options.files or self.options.files_path:
@@ -974,7 +973,7 @@ everything in a single index file.
self.parser.add_option_group(group) self.parser.add_option_group(group)
def run(self): def run(self):
self.init(database = True, write = False) self.init(database = True, write = False)
from pisi.api import index from pisi.api import index
if len(self.args)>0: if len(self.args)>0:
@@ -990,7 +989,7 @@ everything in a single index file.
class ListInstalled(Command): class ListInstalled(Command):
"""Print the list of all installed packages """Print the list of all installed packages
Usage: list-installed Usage: list-installed
""" """
@@ -1042,7 +1041,6 @@ Usage: list-installed
ctx.ui.info('%15s - %s' % (package.name, unicode(package.summary))) ctx.ui.info('%15s - %s' % (package.name, unicode(package.summary)))
self.finalize() self.finalize()
class RebuildDb(Command): class RebuildDb(Command):
"""Rebuild Databases """Rebuild Databases
@@ -1050,7 +1048,7 @@ Usage: rebuilddb [ <package1> <package2> ... <packagen> ]
Rebuilds the PiSi databases 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__ = autocommand __metaclass__ = autocommand
@@ -1068,7 +1066,7 @@ dirs under /var/lib/pisi
default=False, help=_("Rebuild files database")) default=False, help=_("Rebuild files database"))
self.parser.add_option_group(group) self.parser.add_option_group(group)
def run(self): def run(self):
if self.args: if self.args:
self.init(database=True) self.init(database=True)
@@ -1100,11 +1098,11 @@ If no repository is given, all repositories are updated.
name = ("update-repo", "ur") name = ("update-repo", "ur")
def options(self): def options(self):
group = OptionGroup(self.parser, _("update-repo options")) group = OptionGroup(self.parser, _("update-repo options"))
group.add_option("-f", "--force", action="store_true", group.add_option("-f", "--force", action="store_true",
default=False, default=False,
help=_("Update database in any case")) help=_("Update database in any case"))
self.parser.add_option_group(group) self.parser.add_option_group(group)
@@ -1145,7 +1143,7 @@ NB: We support only local files (e.g., /a/b/c) and http:// URIs at the moment
group = OptionGroup(self.parser, _("add-repo options")) group = OptionGroup(self.parser, _("add-repo options"))
group.add_option("--at", action="store", group.add_option("--at", action="store",
type="int", default=None, type="int", default=None,
help=_("Add repository at given position (0 is first)")) help=_("Add repository at given position (0 is first)"))
self.parser.add_option_group(group) self.parser.add_option_group(group)
@@ -1228,7 +1226,7 @@ Usage: list-available [ <repo1> <repo2> ... repon ]
Gives a brief list of PiSi packages published in the specified 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__ = autocommand __metaclass__ = autocommand
@@ -1254,7 +1252,7 @@ all repositories.
if not (ctx.get_option('no_color') or ctx.config.get_option('uninstalled')): if not (ctx.get_option('no_color') or ctx.config.get_option('uninstalled')):
ctx.ui.info(colorize(_('Installed packages are shown in this color'), 'green')) ctx.ui.info(colorize(_('Installed packages are shown in this color'), 'green'))
if self.args: if self.args:
for arg in self.args: for arg in self.args:
self.print_packages(arg) self.print_packages(arg)
@@ -1287,13 +1285,12 @@ all repositories.
p = p + ' ' * max(0, 15 - lenp) p = p + ' ' * max(0, 15 - lenp)
ctx.ui.info('%s - %s ' % (p, unicode(package.summary))) ctx.ui.info('%s - %s ' % (p, unicode(package.summary)))
class ListComponents(Command): class ListComponents(Command):
"""List available components """List available components
Usage: list-components 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__ = autocommand __metaclass__ = autocommand
@@ -1404,7 +1401,7 @@ Lists the packages that will be upgraded.
upgradable_pkgs = list(set(upgradable_pkgs) & set(component_pkgs)) upgradable_pkgs = list(set(upgradable_pkgs) & set(component_pkgs))
if not upgradable_pkgs: if not upgradable_pkgs:
ctx.ui.info(_('No packages to upgrade.')) ctx.ui.info(_('No packages to upgrade.'))
upgradable_pkgs.sort() upgradable_pkgs.sort()
if self.options.install_info: if self.options.install_info:
@@ -1425,7 +1422,7 @@ Lists the packages that will be upgraded.
class ListPending(Command): class ListPending(Command):
"""List pending packages """List pending packages
Lists packages waiting to be configured. Lists packages waiting to be configured.
""" """
@@ -1433,7 +1430,7 @@ Lists packages waiting to be configured.
def __init__(self, args): def __init__(self, args):
super(ListPending, self).__init__(args) super(ListPending, self).__init__(args)
name = ("list-pending", "lp") name = ("list-pending", "lp")
def run(self): def run(self):
@@ -1457,7 +1454,7 @@ in summary, description, and package name fields.
def __init__(self, args): def __init__(self, args):
super(Search, self).__init__(args) super(Search, self).__init__(args)
name = ("search", "sr") name = ("search", "sr")
def options(self): def options(self):
@@ -1507,7 +1504,7 @@ Finds the installed package which contains the specified file.
def __init__(self, args): def __init__(self, args):
super(SearchFile, self).__init__(args) super(SearchFile, self).__init__(args)
name = ("search-file", "sf") name = ("search-file", "sf")
def options(self): def options(self):
@@ -1520,7 +1517,6 @@ Finds the installed package which contains the specified file.
default=False, help=_("Show only package name")) default=False, help=_("Show only package name"))
self.parser.add_option_group(group) self.parser.add_option_group(group)
# what does exact mean? -- exa # what does exact mean? -- exa
@staticmethod @staticmethod
def search_exact(path): def search_exact(path):
@@ -1552,8 +1548,8 @@ Finds the installed package which contains the specified file.
if not self.args: if not self.args:
self.help() self.help()
return return
# search among existing files # search among existing files
for path in self.args: for path in self.args:
if not ctx.config.options.quiet: if not ctx.config.options.quiet:
@@ -1566,7 +1562,7 @@ Finds the installed package which contains the specified file.
self.finalize() self.finalize()
# texts # texts
usage_text1 = _("""%prog [options] <command> [arguments] usage_text1 = _("""%prog [options] <command> [arguments]
where <command> is one of: where <command> is one of:
+1 -1
View File
@@ -12,7 +12,7 @@
import sys import sys
from optparse import OptionParser from optparse import OptionParser
import gettext import gettext
__trans = gettext.translation('pisi', fallback=True) __trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext _ = __trans.ugettext
+7 -7
View File
@@ -75,7 +75,7 @@ def wait_for_result(com, package_name=None):
if ctx.keyboard_interrupt_pending(): if ctx.keyboard_interrupt_pending():
return return
raise Error, _("connection with comar unexpectedly closed") raise Error, _("connection with comar unexpectedly closed")
cmd = reply[0] cmd = reply[0]
if cmd == com.RESULT and not multiple: if cmd == com.RESULT and not multiple:
return return
@@ -99,18 +99,18 @@ def post_install(package_name, provided_scripts, scriptpath, metapath, filepath)
ctx.ui.info(_("Configuring package")) ctx.ui.info(_("Configuring package"))
self_post = False self_post = False
com = make_com() com = make_com()
for script in provided_scripts: for script in provided_scripts:
ctx.ui.debug(_("Registering %s comar script") % script.om) ctx.ui.debug(_("Registering %s comar script") % script.om)
if script.om == "System.Package": if script.om == "System.Package":
self_post = True self_post = True
com.register(script.om, package_name, os.path.join(scriptpath, script.script)) com.register(script.om, package_name, os.path.join(scriptpath, script.script))
wait_for_result(com) wait_for_result(com)
ctx.ui.debug(_("Calling post install handlers")) ctx.ui.debug(_("Calling post install handlers"))
com.call("System.PackageHandler.setupPackage", [ "metapath", metapath, "filepath", filepath ]) com.call("System.PackageHandler.setupPackage", [ "metapath", metapath, "filepath", filepath ])
wait_for_result(com) wait_for_result(com)
if self_post: if self_post:
ctx.ui.debug(_("Running package's post install script")) ctx.ui.debug(_("Running package's post install script"))
com.call_package("System.Package.postInstall", package_name) com.call_package("System.Package.postInstall", package_name)
@@ -119,15 +119,15 @@ def post_install(package_name, provided_scripts, scriptpath, metapath, filepath)
def pre_remove(package_name, metapath, filepath): def pre_remove(package_name, metapath, filepath):
ctx.ui.info(_("Configuring package for removal")) ctx.ui.info(_("Configuring package for removal"))
com = make_com() com = make_com()
ctx.ui.debug(_("Running package's pre remove script")) ctx.ui.debug(_("Running package's pre remove script"))
com.call_package("System.Package.preRemove", package_name) com.call_package("System.Package.preRemove", package_name)
wait_for_result(com) wait_for_result(com)
ctx.ui.debug(_("Calling pre remove handlers")) ctx.ui.debug(_("Calling pre remove handlers"))
com.call("System.PackageHandler.cleanupPackage", [ "metapath", metapath, "filepath", filepath ]) com.call("System.PackageHandler.cleanupPackage", [ "metapath", metapath, "filepath", filepath ])
wait_for_result(com) wait_for_result(com)
ctx.ui.debug(_("Unregistering comar scripts")) ctx.ui.debug(_("Unregistering comar scripts"))
com.remove(package_name) com.remove(package_name)
wait_for_result(com) wait_for_result(com)
+12 -12
View File
@@ -40,7 +40,7 @@ class Distribution(xmlfile.XmlFile):
t_Type = [autoxml.Text, autoxml.mandatory] t_Type = [autoxml.Text, autoxml.mandatory]
t_Dependencies = [ [autoxml.Text], autoxml.optional, "Dependencies/Distribution"] t_Dependencies = [ [autoxml.Text], autoxml.optional, "Dependencies/Distribution"]
t_BinaryName = [autoxml.Text, autoxml.optional] # name of repository (binary distro) t_BinaryName = [autoxml.Text, autoxml.optional] # name of repository (binary distro)
t_Architecture = [autoxml.Text, autoxml.optional] # architecture identifier t_Architecture = [autoxml.Text, autoxml.optional] # architecture identifier
@@ -50,24 +50,24 @@ class Component(xmlfile.XmlFile):
__metaclass__ = autoxml.autoxml __metaclass__ = autoxml.autoxml
tag = "PISI" tag = "PISI"
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
# LocalName for system.base could be sistem.taban or "Taban Sistem", # LocalName for system.base could be sistem.taban or "Taban Sistem",
# this could be useful for GUIs # this could be useful for GUIs
t_LocalName = [autoxml.LocalText, autoxml.mandatory] t_LocalName = [autoxml.LocalText, autoxml.mandatory]
# Information about the component # Information about the component
t_Summary = [autoxml.LocalText, autoxml.mandatory] t_Summary = [autoxml.LocalText, autoxml.mandatory]
t_Description = [autoxml.LocalText, autoxml.mandatory] t_Description = [autoxml.LocalText, autoxml.mandatory]
#t_Icon = [autoxml.Binary, autoxml.mandatory] #t_Icon = [autoxml.Binary, autoxml.mandatory]
# Dependencies to other components # Dependencies to other components
t_Dependencies = [ [autoxml.String], autoxml.optional, "Dependencies/Component"] t_Dependencies = [ [autoxml.String], autoxml.optional, "Dependencies/Component"]
# the parts of this component. # the parts of this component.
# to be filled by the component database, thus it is optional. # to be filled by the component database, thus it is optional.
t_Packages = [ [autoxml.String], autoxml.optional, "Parts/Package"] t_Packages = [ [autoxml.String], autoxml.optional, "Parts/Package"]
@@ -75,7 +75,7 @@ class Component(xmlfile.XmlFile):
class ComponentDB(object): class ComponentDB(object):
"""a database of components""" """a database of components"""
def __init__(self): def __init__(self):
self.d = ItemByRepoDB('component') self.d = ItemByRepoDB('component')
@@ -128,7 +128,7 @@ class ComponentDB(object):
component = self.get_component(component_name, repo, txn) component = self.get_component(component_name, repo, txn)
if not walk: if not walk:
return component.packages return component.packages
packages = [] packages = []
packages.extend(component.packages) packages.extend(component.packages)
@@ -142,7 +142,7 @@ class ComponentDB(object):
parent_name = ".".join(component.name.split(".")[:-1]) parent_name = ".".join(component.name.split(".")[:-1])
if not parent_name: # root component if not parent_name: # root component
return return
if self.has_component(parent_name, repo, txn): if self.has_component(parent_name, repo, txn):
parent = self.get_component(parent_name, repo, txn) parent = self.get_component(parent_name, repo, txn)
else: else:
@@ -186,7 +186,7 @@ class ComponentDB(object):
if package in component.packages: if package in component.packages:
component.packages.remove(package) component.packages.remove(package)
self.d.add_item(component_name, component, repo, txn) # update self.d.add_item(component_name, component, repo, txn) # update
ctx.txn_proc(lambda x: proc(txn, repo), txn) ctx.txn_proc(lambda x: proc(txn, repo), txn)
def add_spec(self, component_name, spec, repo, txn = None): def add_spec(self, component_name, spec, repo, txn = None):
@@ -211,9 +211,9 @@ class ComponentDB(object):
if spec in component.sources: if spec in component.sources:
component.sources.remove(spec) component.sources.remove(spec)
self.d.add_item(component_name, component, repo, txn) # update self.d.add_item(component_name, component, repo, txn) # update
ctx.txn_proc(lambda x: proc(txn, repo), txn) ctx.txn_proc(lambda x: proc(txn, repo), txn)
def clear(self, txn = None): def clear(self, txn = None):
self.d.clear(txn) self.d.clear(txn)
+1 -1
View File
@@ -40,7 +40,7 @@ class Options(object):
class Config(object): class Config(object):
"""Config Singleton""" """Config Singleton"""
def __init__(self, options = Options()): def __init__(self, options = Options()):
self.options = options self.options = options
self.values = ConfigurationFile("/etc/pisi/pisi.conf") self.values = ConfigurationFile("/etc/pisi/pisi.conf")
+2 -3
View File
@@ -68,7 +68,7 @@ class GeneralDefaults:
class BuildDefaults: class BuildDefaults:
"""Default values for [build] section""" """Default values for [build] section"""
host = "i686-pc-linux-gnu" host = "i686-pc-linux-gnu"
jobs = "-j1" jobs = "-j1"
generateDebug = False generateDebug = False
cflags = "-mtune=i686 -O2 -pipe -fomit-frame-pointer" cflags = "-mtune=i686 -O2 -pipe -fomit-frame-pointer"
cxxflags = "-mtune=i686 -O2 -pipe -fomit-frame-pointer" cxxflags = "-mtune=i686 -O2 -pipe -fomit-frame-pointer"
@@ -94,7 +94,7 @@ class ConfigurationSection(object):
file, using defaults (above) as a fallback.""" file, using defaults (above) as a fallback."""
def __init__(self, section, items=[]): def __init__(self, section, items=[]):
self.items = items self.items = items
if section == "general": if section == "general":
self.defaults = GeneralDefaults self.defaults = GeneralDefaults
elif section == "build": elif section == "build":
@@ -131,7 +131,6 @@ class ConfigurationSection(object):
# string. Like; ["default"]... # string. Like; ["default"]...
def __getitem__(self, key): def __getitem__(self, key):
return self.__getattr__(key) return self.__getattr__(key)
class ConfigurationFile(object): class ConfigurationFile(object):
"""Parse and get configuration values from the configuration file""" """Parse and get configuration values from the configuration file"""
+5 -5
View File
@@ -25,7 +25,7 @@ import pisi.itembyrepodb
class Conflict: class Conflict:
__metaclass__ = autoxml.autoxml __metaclass__ = autoxml.autoxml
s_Package = [autoxml.String, autoxml.mandatory] s_Package = [autoxml.String, autoxml.mandatory]
a_version = [autoxml.String, autoxml.optional] a_version = [autoxml.String, autoxml.optional]
a_versionFrom = [autoxml.String, autoxml.optional] a_versionFrom = [autoxml.String, autoxml.optional]
@@ -58,15 +58,15 @@ class Conflict:
ret &= v <= Version(self.versionTo) ret &= v <= Version(self.versionTo)
r = Version(release) r = Version(release)
if self.release: if self.release:
ret &= r == Version(self.release) ret &= r == Version(self.release)
if self.releaseFrom: if self.releaseFrom:
ret &= r >= Version(self.releaseFrom) ret &= r >= Version(self.releaseFrom)
if self.releaseTo: if self.releaseTo:
ret &= r <= Version(self.releaseTo) ret &= r <= Version(self.releaseTo)
return ret return ret
def installed_package_conflicts(confinfo): def installed_package_conflicts(confinfo):
"""determine if an installed package in *repository* conflicts with """determine if an installed package in *repository* conflicts with
given conflicting spec""" given conflicting spec"""
pkg_name = confinfo.package pkg_name = confinfo.package
if not ctx.installdb.is_installed(pkg_name): if not ctx.installdb.is_installed(pkg_name):
+3 -3
View File
@@ -10,7 +10,7 @@
# Please read the COPYING file. # Please read the COPYING file.
# #
"""PiSi constants. """PiSi constants.
If you have a "magic" constant value this is where it should be If you have a "magic" constant value this is where it should be
defined.""" defined."""
@@ -66,9 +66,9 @@ class Constants:
# file/directory names # file/directory names
#note: these don't seem very well, constants are used #note: these don't seem very well, constants are used
#when it is easier/more meaningful to write the constant name, or #when it is easier/more meaningful to write the constant name, or
#when the constant is bound to change later on. #when the constant is bound to change later on.
#in some places literals are just as good, for instance #in some places literals are just as good, for instance
#when constant is the same as string. readability is important... #when constant is the same as string. readability is important...
self.__c.actions_file = "actions.py" self.__c.actions_file = "actions.py"
self.__c.files_dir = "files" self.__c.files_dir = "files"
+4 -4
View File
@@ -64,7 +64,7 @@ class DBShelf:
allowed_chars = string.letters + string.digits + '-' allowed_chars = string.letters + string.digits + '-'
def check_key(key): def check_key(key):
return pisi.util.all(lambda x: x in allowed_chars, key) return pisi.util.all(lambda x: x in allowed_chars, key)
def has_key(self, key, txn = None): def has_key(self, key, txn = None):
if txn: if txn:
return self.db.has_key(key, txn) return self.db.has_key(key, txn)
@@ -87,7 +87,7 @@ class DBShelf:
return retval return retval
else: else:
return proc(txn) return proc(txn)
def decode(self, data): def decode(self, data):
try: try:
return cPickle.loads(data) return cPickle.loads(data)
@@ -102,7 +102,7 @@ class DBShelf:
for x in self.keys(txn): for x in self.keys(txn):
self.db.delete(x, txn) self.db.delete(x, txn)
self.txn_proc(proc, txn) self.txn_proc(proc, txn)
def delete(self, x, txn): def delete(self, x, txn):
def proc(txn): def proc(txn):
self.db.delete(x, txn) self.db.delete(x, txn)
@@ -121,7 +121,7 @@ class DBShelf:
def __len__(self): def __len__(self):
return len(self.db) return len(self.db)
def __getitem__(self, key): def __getitem__(self, key):
def proc(txn): def proc(txn):
data = self.db.get(key) data = self.db.get(key)
+5 -5
View File
@@ -26,7 +26,7 @@ import pisi.itembyrepodb
class Dependency: class Dependency:
__metaclass__ = autoxml.autoxml __metaclass__ = autoxml.autoxml
s_Package = [autoxml.String, autoxml.mandatory] s_Package = [autoxml.String, autoxml.mandatory]
a_version = [autoxml.String, autoxml.optional] a_version = [autoxml.String, autoxml.optional]
a_versionFrom = [autoxml.String, autoxml.optional] a_versionFrom = [autoxml.String, autoxml.optional]
@@ -59,11 +59,11 @@ class Dependency:
ret &= v <= Version(self.versionTo) ret &= v <= Version(self.versionTo)
r = Version(release) r = Version(release)
if self.release: if self.release:
ret &= r == Version(self.release) ret &= r == Version(self.release)
if self.releaseFrom: if self.releaseFrom:
ret &= r >= Version(self.releaseFrom) ret &= r >= Version(self.releaseFrom)
if self.releaseTo: if self.releaseTo:
ret &= r <= Version(self.releaseTo) ret &= r <= Version(self.releaseTo)
return ret return ret
def dict_satisfies_dep(dict, depinfo): def dict_satisfies_dep(dict, depinfo):
@@ -111,7 +111,7 @@ def satisfies_runtime_deps(pkg):
return satisfies_dependencies(pkg, deps) return satisfies_dependencies(pkg, deps)
def installable(pkg): def installable(pkg):
"""calculate if pkg name is installable currently """calculate if pkg name is installable currently
which means it has to satisfy both install and runtime dependencies""" which means it has to satisfy both install and runtime dependencies"""
if not ctx.packagedb.has_package(pkg): if not ctx.packagedb.has_package(pkg):
ctx.ui.info(_("Package %s is not present in the package database") % pkg); ctx.ui.info(_("Package %s is not present in the package database") % pkg);
+10 -10
View File
@@ -59,7 +59,7 @@ class Fetcher:
def __init__(self, url, destdir, resume = True): def __init__(self, url, destdir, resume = True):
if not isinstance(url, URI): if not isinstance(url, URI):
url = URI(url) url = URI(url)
if ctx.config.get_option("authinfo"): if ctx.config.get_option("authinfo"):
url.set_auth_info(ctx.config.get_option("authinfo")) url.set_auth_info(ctx.config.get_option("authinfo"))
@@ -84,7 +84,7 @@ class Fetcher:
self.err(_('Access denied to write to destination directory: "%s"') % (self.destdir)) self.err(_('Access denied to write to destination directory: "%s"') % (self.destdir))
archive_file = os.path.join(self.destdir, self.url.filename()) archive_file = os.path.join(self.destdir, self.url.filename())
if os.path.exists(archive_file) and not os.access(archive_file, os.W_OK): if os.path.exists(archive_file) and not os.access(archive_file, os.W_OK):
self.err(_('Access denied to destination file: "%s"') % (archive_file)) self.err(_('Access denied to destination file: "%s"') % (archive_file))
@@ -101,7 +101,7 @@ class Fetcher:
move(partial_file, archive_file) move(partial_file, archive_file)
return archive_file return archive_file
def _do_grab(self, fileURI, dest, total_size): def _do_grab(self, fileURI, dest, total_size):
bs, tt, = 1024, int(time()) bs, tt, = 1024, int(time())
@@ -200,7 +200,7 @@ class Fetcher:
if flag: if flag:
if os.stat(archive_file).st_size == 0: if os.stat(archive_file).st_size == 0:
os.remove(archive_file) os.remove(archive_file)
try: try:
total_size = int(headers['Content-Length']) + self.exist_size total_size = int(headers['Content-Length']) + self.exist_size
except KeyboardInterrupt: except KeyboardInterrupt:
@@ -251,7 +251,7 @@ class Fetcher:
raise FetchError(error) raise FetchError(error)
class HTTPRangeHandler(urllib2.BaseHandler): class HTTPRangeHandler(urllib2.BaseHandler):
""" """
to override the urllib2 error: 'Error 206: Partial Content' to override the urllib2 error: 'Error 206: Partial Content'
this reponse from the HTTP server is already what we expected to get. this reponse from the HTTP server is already what we expected to get.
Don't give up, resume downloading.. Don't give up, resume downloading..
@@ -294,7 +294,7 @@ class FTPRangeHandler(urllib2.FTPHandler):
if attr.lower() == 'type' and \ if attr.lower() == 'type' and \
value in ('a', 'A', 'i', 'I', 'd', 'D'): value in ('a', 'A', 'i', 'I', 'd', 'D'):
type = value.upper() type = value.upper()
rawr = req.headers.get('Range', None) rawr = req.headers.get('Range', None)
if rawr: if rawr:
rest = int(rawr.split("=")[1].rstrip("-")) rest = int(rawr.split("=")[1].rstrip("-"))
@@ -302,7 +302,7 @@ class FTPRangeHandler(urllib2.FTPHandler):
rest = 0 rest = 0
fp, retrlen = fw.retrfile(file, type, rest) fp, retrlen = fw.retrfile(file, type, rest)
fb, lb = rest, retrlen fb, lb = rest, retrlen
if retrlen is None or retrlen == 0: if retrlen is None or retrlen == 0:
raise RangeError raise RangeError
@@ -310,7 +310,7 @@ class FTPRangeHandler(urllib2.FTPHandler):
if retrlen < 0: if retrlen < 0:
# beginning of range is larger than file # beginning of range is larger than file
raise RangeError raise RangeError
headers = '' headers = ''
mtype = guess_type(req.get_full_url())[0] mtype = guess_type(req.get_full_url())[0]
if mtype: if mtype:
@@ -318,9 +318,9 @@ class FTPRangeHandler(urllib2.FTPHandler):
if retrlen is not None and retrlen >= 0: if retrlen is not None and retrlen >= 0:
headers += 'Content-Length: %d\n' % retrlen headers += 'Content-Length: %d\n' % retrlen
try: try:
from cStringIO import StringIO from cStringIO import StringIO
except ImportError, msg: except ImportError, msg:
from StringIO import StringIO from StringIO import StringIO
return urllib.addinfourl(fp, Message(StringIO(headers)), req.get_full_url()) return urllib.addinfourl(fp, Message(StringIO(headers)), req.get_full_url())
+13 -14
View File
@@ -35,14 +35,14 @@ import pisi.context as ctx
class AlreadyHaveException(pisi.Exception): class AlreadyHaveException(pisi.Exception):
def __init__(self, url, localfile): def __init__(self, url, localfile):
pisi.Exception.__init__(self, "URL %s already downloaded as %s" % (url, localfile)) pisi.Exception.__init__(self, "URL %s already downloaded as %s" % (url, localfile))
self.url = url self.url = url
self.localfile = localfile self.localfile = localfile
class NoSignatureFound(pisi.Exception): class NoSignatureFound(pisi.Exception):
def __init__(self, url): def __init__(self, url):
pisi.Exception.__init__(self, "No signature found for %s" % url) pisi.Exception.__init__(self, "No signature found for %s" % url)
self.url = url self.url = url
class Error(pisi.Error): class Error(pisi.Error):
pass pass
@@ -65,7 +65,7 @@ class File:
elif not isinstance(uri, URI): elif not isinstance(uri, URI):
raise Error(_("uri must have type either URI or string")) raise Error(_("uri must have type either URI or string"))
return uri return uri
@staticmethod @staticmethod
def choose_method(filename, compress): def choose_method(filename, compress):
# this is really simple (^_^) -- exa # this is really simple (^_^) -- exa
@@ -90,7 +90,7 @@ class File:
return localfile return localfile
@staticmethod @staticmethod
def download(uri, transfer_dir = "/tmp", sha1sum = False, def download(uri, transfer_dir = "/tmp", sha1sum = False,
compress = None, sign = None, copylocal = False): compress = None, sign = None, copylocal = False):
assert isinstance(uri, URI) assert isinstance(uri, URI)
@@ -139,7 +139,7 @@ class File:
return localfile return localfile
def __init__(self, uri, mode, transfer_dir = "/tmp", def __init__(self, uri, mode, transfer_dir = "/tmp",
sha1sum = False, compress = None, sign = None): sha1sum = False, compress = None, sign = None):
"it is pointless to open a file without a URI and a mode" "it is pointless to open a file without a URI and a mode"
@@ -147,7 +147,6 @@ class File:
self.sha1sum = sha1sum self.sha1sum = sha1sum
self.compress = compress self.compress = compress
self.sign = sign self.sign = sign
uri = File.make_uri(uri) uri = File.make_uri(uri)
if mode==File.read or mode==File.write: if mode==File.read or mode==File.write:
@@ -217,7 +216,7 @@ class File:
if os.system('gpg --verify ' + sigfilename) != 0: if os.system('gpg --verify ' + sigfilename) != 0:
raise InvalidSignature(uri) raise InvalidSignature(uri)
# everything is all right here # everything is all right here
def flush(self): def flush(self):
self.__file__.flush() self.__file__.flush()
@@ -229,7 +228,7 @@ class File:
def next(self): def next(self):
return self.__file__.next() return self.__file__.next()
def read(self, size = None): def read(self, size = None):
if size: if size:
return self.__file__.read(size) return self.__file__.read(size)
@@ -241,25 +240,25 @@ class File:
return self.__file__.readline(size) return self.__file__.readline(size)
else: else:
return self.__file__.readline() return self.__file__.readline()
def readlines(self, size = None): def readlines(self, size = None):
if size: if size:
return self.__file__.readlines(size) return self.__file__.readlines(size)
else: else:
return self.__file__.readlines() return self.__file__.readlines()
def xreadlines(self): def xreadlines(self):
return self.__file__.xreadlines() return self.__file__.xreadlines()
def seek(self, offset, whence=0): def seek(self, offset, whence=0):
self.__file__.seek(offset, whence) self.__file__.seek(offset, whence)
def tell(self): def tell(self):
return self.__file__.tell() return self.__file__.tell()
def truncate(self): def truncate(self):
self.__file__.truncate() self.__file__.truncate()
def write(self, str): def write(self, str):
self.__file__.write(str) self.__file__.write(str)
+1 -1
View File
@@ -37,7 +37,7 @@ class Digraph(object):
self.__adj = {} self.__adj = {}
self.__vdata = {} self.__vdata = {}
self.__edata = {} self.__edata = {}
def vertices(self): def vertices(self):
"return set of vertex descriptors" "return set of vertex descriptors"
return self.__v return self.__v
+3 -4
View File
@@ -36,7 +36,6 @@ import pisi.specfile as specfile
class Error(pisi.Error): class Error(pisi.Error):
pass pass
class Index(XmlFile): class Index(XmlFile):
__metaclass__ = autoxml.autoxml __metaclass__ = autoxml.autoxml
@@ -53,7 +52,7 @@ class Index(XmlFile):
return self.distribution.name + self.distribution.repositoryname return self.distribution.name + self.distribution.repositoryname
def read_uri(self, uri, tmpdir, force = False): def read_uri(self, uri, tmpdir, force = False):
self.read(uri, tmpDir=tmpdir, sha1sum=not force, self.read(uri, tmpDir=tmpdir, sha1sum=not force,
compress=File.auto, sign=File.detached, copylocal = True) compress=File.auto, sign=File.detached, copylocal = True)
# read index for a given repo, force means download even if remote not updated # read index for a given repo, force means download even if remote not updated
@@ -78,7 +77,7 @@ class Index(XmlFile):
# and what do we do with it? move it to index dir properly # and what do we do with it? move it to index dir properly
newtmpdir = os.path.join(ctx.config.index_dir(), repo) newtmpdir = os.path.join(ctx.config.index_dir(), repo)
pisi.util.clean_dir(newtmpdir) # replace newtmpdir pisi.util.clean_dir(newtmpdir) # replace newtmpdir
shutil.move(tmpdir, newtmpdir) shutil.move(tmpdir, newtmpdir)
def check_signature(self, filename, repo): def check_signature(self, filename, repo):
tmpdir = os.path.join(ctx.config.index_dir(), repo) tmpdir = os.path.join(ctx.config.index_dir(), repo)
@@ -109,7 +108,7 @@ class Index(XmlFile):
def update_progress(): def update_progress():
self.processed += 1 self.processed += 1
ctx.ui.display_progress(operation = "updatingrepo", ctx.ui.display_progress(operation = "updatingrepo",
percent = self.progress.update(self.processed), percent = self.progress.update(self.processed),
info = _("Updating package database of %s") % repo) info = _("Updating package database of %s") % repo)
ctx.componentdb.remove_repo(repo, txn=txn) ctx.componentdb.remove_repo(repo, txn=txn)
+5 -5
View File
@@ -35,7 +35,7 @@ class InstallDBError(pisi.Error):
class InstallInfo: class InstallInfo:
# some data is replicated from packagedb # some data is replicated from packagedb
# we store as an object, hey, we can waste O(1) space. # we store as an object, hey, we can waste O(1) space.
# this is also easier to modify in the future, without # this is also easier to modify in the future, without
# requiring database upgrades! wow! # requiring database upgrades! wow!
@@ -54,10 +54,10 @@ class InstallInfo:
self.build, self.distribution, self.build, self.distribution,
time_str) time_str)
return s return s
state_map = { 'i': _('installed'), 'ip':_('installed-pending'), state_map = { 'i': _('installed'), 'ip':_('installed-pending'),
'r':_('removed'), 'p': _('purged') } 'r':_('removed'), 'p': _('purged') }
def __str__(self): def __str__(self):
s = _("State: %s\nVersion: %s, Release: %s, Build: %s\n") % \ s = _("State: %s\nVersion: %s, Release: %s, Build: %s\n") % \
(InstallInfo.state_map[self.state], self.version, (InstallInfo.state_map[self.state], self.version,
@@ -92,7 +92,7 @@ class InstallDB:
return files return files
def pkg_dir(self, pkg, version, release): def pkg_dir(self, pkg, version, release):
return join(ctx.config.lib_dir(), 'package', return join(ctx.config.lib_dir(), 'package',
pkg + '-' + version + '-' + release) pkg + '-' + version + '-' + release)
def is_recorded(self, pkg, txn = None): def is_recorded(self, pkg, txn = None):
@@ -145,7 +145,7 @@ class InstallDB:
else: else:
return False return False
def install(self, pkg, version, release, build, distro = "", def install(self, pkg, version, release, build, distro = "",
config_later = False, rebuild=False, txn = None): config_later = False, rebuild=False, txn = None):
"""install package with specific version, release, build""" """install package with specific version, release, build"""
pkg = str(pkg) pkg = str(pkg)
+9 -9
View File
@@ -25,7 +25,7 @@ import pisi.lockeddbshelve as shelve
installed, thirdparty, repos, all = range(1, 5) installed, thirdparty, repos, all = range(1, 5)
"""installed and thirdparty are special databases to keep track """installed and thirdparty are special databases to keep track
of already installed stuff and third party stuff not in any real repository. of already installed stuff and third party stuff not in any real repository.
repos means search in repositories only, and all means search in repos means search in repositories only, and all means search in
repositories and special databases (called tracking databases) repositories and special databases (called tracking databases)
@@ -36,7 +36,7 @@ class Error(pisi.Error):
class NotfoundError(pisi.Error): class NotfoundError(pisi.Error):
pass pass
class ItemByRepoDB(object): class ItemByRepoDB(object):
def __init__(self, name): def __init__(self, name):
@@ -45,7 +45,7 @@ class ItemByRepoDB(object):
def close(self): def close(self):
self.d.close() self.d.close()
def clear(self, txn = None): def clear(self, txn = None):
self.d.clear(txn=txn) self.d.clear(txn=txn)
@@ -70,7 +70,7 @@ class ItemByRepoDB(object):
# if x.startsWith('repo-'): # if x.startsWith('repo-'):
# return True # return True
#return False #return False
def list_if(self, pred): def list_if(self, pred):
return [ k for k,data in self.d.items() if pred(k, data)] return [ k for k,data in self.d.items() if pred(k, data)]
@@ -108,7 +108,7 @@ class ItemByRepoDB(object):
assert type(repo) == type("") assert type(repo) == type("")
repo='repo-'+repo repo='repo-'+repo
return repo return repo
def str_repo(self, str): def str_repo(self, str):
if str.startswith('repo-'): if str.startswith('repo-'):
return str[5:] return str[5:]
@@ -151,7 +151,7 @@ class ItemByRepoDB(object):
return (s[repostr], repo) return (s[repostr], repo)
raise NotfoundError(_('Key %s in repo %s not found') % (name, repo)) raise NotfoundError(_('Key %s in repo %s not found') % (name, repo))
#return None #return None
return self.d.txn_proc(proc, txn) return self.d.txn_proc(proc, txn)
def get_item(self, name, repo = None, txn = None): def get_item(self, name, repo = None, txn = None):
@@ -172,7 +172,7 @@ class ItemByRepoDB(object):
return repo return repo
else: else:
return None return None
def add_item(self, name, obj, repo, txn = None): def add_item(self, name, obj, repo, txn = None):
assert not repo in [all, repos] assert not repo in [all, repos]
repostr = self.repo_str(repo) repostr = self.repo_str(repo)
@@ -184,13 +184,13 @@ class ItemByRepoDB(object):
s[ repostr ] = obj s[ repostr ] = obj
self.d.put(name, s, txn) self.d.put(name, s, txn)
self.d.txn_proc(proc, txn) self.d.txn_proc(proc, txn)
def remove_item_repo(self, name, repo, txn = None): def remove_item_repo(self, name, repo, txn = None):
assert not repo in [all, repos] assert not repo in [all, repos]
name = str(name) name = str(name)
def p(txn): def p(txn):
s = self.d.get(name, txn) s = self.d.get(name, txn)
repostr = self.repo_str(repo) repostr = self.repo_str(repo)
if s.has_key(repostr): if s.has_key(repostr):
del s[repostr] del s[repostr]
if not len(s): if not len(s):
+2 -2
View File
@@ -71,7 +71,7 @@ def lock_dbenv():
raise Error(_("Another instance of PiSi is running. Only one instance is allowed to modify the PiSi database at a time.")) raise Error(_("Another instance of PiSi is running. Only one instance is allowed to modify the PiSi database at a time."))
# write: write access to database environment # write: write access to database environment
# writeversion: would you like to be able # writeversion: would you like to be able
def init_dbenv(write=False, writeversion=False): def init_dbenv(write=False, writeversion=False):
if os.access(pisi.context.config.db_dir(), os.R_OK): if os.access(pisi.context.config.db_dir(), os.R_OK):
# try to read version # try to read version
@@ -121,7 +121,7 @@ class LockedDBShelf(shelve.DBShelf):
pass pass
def open(self, filename, dbname, filetype, flags=db.DB_CREATE, mode=0644): def open(self, filename, dbname, filetype, flags=db.DB_CREATE, mode=0644):
self.filename = filename self.filename = filename
self.closed = False self.closed = False
if type(flags) == type(''): if type(flags) == type(''):
sflag = flags sflag = flags
+1 -1
View File
@@ -48,7 +48,7 @@ class Package(specfile.Package):
t_PackageFormat = [ autoxml.String, autoxml.optional] t_PackageFormat = [ autoxml.String, autoxml.optional]
t_Source = [ Source, autoxml.optional] t_Source = [ Source, autoxml.optional]
def decode_hook(self, node, errs, where): def decode_hook(self, node, errs, where):
self.version = self.history[0].version self.version = self.history[0].version
self.release = self.history[0].release self.release = self.history[0].release
+2 -2
View File
@@ -20,7 +20,7 @@ class autosuper(type):
def __init__(cls, name, bases, dict): def __init__(cls, name, bases, dict):
super(autosuper, cls).__init__(name, bases, dict) super(autosuper, cls).__init__(name, bases, dict)
setattr(cls, "_%s__super" % name, super(cls)) setattr(cls, "_%s__super" % name, super(cls))
class autosuprop(autosuper, autoprop): class autosuprop(autosuper, autoprop):
pass pass
@@ -34,6 +34,6 @@ class autoeq(type):
class Struct: class Struct:
__metaclass__ = autoeq __metaclass__ = autoeq
def __init__(self, **entries): def __init__(self, **entries):
self.__dict__.update(entries) self.__dict__.update(entries)
+51 -51
View File
@@ -97,7 +97,7 @@ def install_pkg_files(package_URIs):
for x in package_URIs: for x in package_URIs:
atomicoperations.install_single_file(x) atomicoperations.install_single_file(x)
return # short circuit return # short circuit
# read the package information into memory first # read the package information into memory first
# regardless of which distribution they come from # regardless of which distribution they come from
d_t = {} d_t = {}
@@ -114,9 +114,9 @@ def install_pkg_files(package_URIs):
# or packages to be installed? # or packages to be installed?
return dependency.installed_satisfies_dep(dep) \ return dependency.installed_satisfies_dep(dep) \
or dependency.dict_satisfies_dep(d_t, dep) or dependency.dict_satisfies_dep(d_t, dep)
# for this case, we have to determine the dependencies # for this case, we have to determine the dependencies
# 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 d_t.keys():
@@ -142,21 +142,21 @@ in the respective order to satisfy extra dependencies:
class PackageDB: class PackageDB:
def get_package(self, key, repo = None): def get_package(self, key, repo = None):
return d_t[str(key)] return d_t[str(key)]
packagedb = PackageDB() packagedb = PackageDB()
A = d_t.keys() A = 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.'))
return return
# try to construct a pisi graph of packages to # try to construct a pisi graph of packages to
# install / reinstall # install / reinstall
G_f = pgraph.PGraph(packagedb) # construct G_f G_f = pgraph.PGraph(packagedb) # construct G_f
# 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
for x in A: for x in A:
G_f.add_package(x) G_f.add_package(x)
@@ -185,12 +185,12 @@ in the respective order to satisfy extra dependencies:
return return
ctx.ui.notify(ui.packagestogo, order = order) ctx.ui.notify(ui.packagestogo, order = order)
for x in order: for x in order:
atomicoperations.install_single_file(dfn[x]) atomicoperations.install_single_file(dfn[x])
pisi_installed = ctx.installdb.is_installed('pisi') pisi_installed = ctx.installdb.is_installed('pisi')
if 'pisi' in order and pisi_installed: if 'pisi' in order and pisi_installed:
upgrade_pisi() upgrade_pisi()
@@ -243,7 +243,7 @@ def check_conflicts(order, packagedb):
(C, D, pkg_conflicts) = calculate_conflicts(order, packagedb) (C, D, pkg_conflicts) = calculate_conflicts(order, packagedb)
if D: if D:
raise Error(_("Selected packages [%s] are in conflict with each other.") % raise Error(_("Selected packages [%s] are in conflict with each other.") %
util.strlist(list(D))) util.strlist(list(D)))
if pkg_conflicts: if pkg_conflicts:
@@ -314,7 +314,7 @@ def install_pkg_names(A, reinstall = False):
# A was a list, remove duplicates and expand components # A was a list, remove duplicates and expand components
A_0 = A = expand_components(set(A)) A_0 = A = expand_components(set(A))
ctx.ui.debug('A = %s' % str(A)) ctx.ui.debug('A = %s' % str(A))
# filter packages that are already installed # filter packages that are already installed
if not reinstall: if not reinstall:
Ap = set(filter(lambda x: not ctx.installdb.is_installed(x), A)) Ap = set(filter(lambda x: not ctx.installdb.is_installed(x), A))
@@ -329,7 +329,7 @@ def install_pkg_names(A, reinstall = False):
return return
A |= upgrade_base(A) A |= upgrade_base(A)
if not ctx.config.get_option('ignore_dependency'): if not ctx.config.get_option('ignore_dependency'):
G_f, order = plan_install_pkg_names(A) G_f, order = plan_install_pkg_names(A)
else: else:
@@ -350,14 +350,14 @@ def install_pkg_names(A, reinstall = False):
if set(order) - A_0: if set(order) - A_0:
if not ctx.ui.confirm(_('There are extra packages due to dependencies. Do you want to continue?')): if not ctx.ui.confirm(_('There are extra packages due to dependencies. Do you want to continue?')):
return False return False
ctx.ui.notify(ui.packagestogo, order = order) ctx.ui.notify(ui.packagestogo, order = order)
pisi_installed = ctx.installdb.is_installed('pisi') pisi_installed = ctx.installdb.is_installed('pisi')
for x in order: for x in order:
atomicoperations.install_single_name(x, True) # allow reinstalls here atomicoperations.install_single_name(x, True) # allow reinstalls here
if 'pisi' in order and pisi_installed: if 'pisi' in order and pisi_installed:
upgrade_pisi() upgrade_pisi()
@@ -367,12 +367,12 @@ def plan_install_pkg_names(A, ignore_package_conflicts = False):
G_f = pgraph.PGraph(ctx.packagedb) # construct G_f G_f = pgraph.PGraph(ctx.packagedb) # construct G_f
# 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
for x in A: for x in A:
G_f.add_package(x) G_f.add_package(x)
B = A B = A
while len(B) > 0: while len(B) > 0:
Bp = set() Bp = set()
for x in B: for x in B:
@@ -401,21 +401,21 @@ def upgrade(A):
def upgrade_pkg_names(A = []): def upgrade_pkg_names(A = []):
"""Re-installs packages from the repository, trying to perform """Re-installs packages from the repository, trying to perform
a minimum or maximum number of upgrades according to options.""" a minimum or maximum number of upgrades according to options."""
ignore_build = ctx.get_option('ignore_build_no') ignore_build = ctx.get_option('ignore_build_no')
security_only = ctx.get_option('security_only') security_only = ctx.get_option('security_only')
if not A: if not A:
# if A is empty, then upgrade all packages # if A is empty, then upgrade all packages
A = ctx.installdb.list_installed() A = ctx.installdb.list_installed()
A_0 = A = expand_components(set(A)) A_0 = A = expand_components(set(A))
Ap = [] Ap = []
for x in A: for x in A:
if x.endswith(ctx.const.package_suffix): if x.endswith(ctx.const.package_suffix):
ctx.ui.debug(_("Warning: package *name* ends with '.pisi'")) ctx.ui.debug(_("Warning: package *name* ends with '.pisi'"))
if not ctx.installdb.is_installed(x): if not ctx.installdb.is_installed(x):
ctx.ui.info(_('Package %s is not installed.') % x, True) ctx.ui.info(_('Package %s is not installed.') % x, True)
continue continue
@@ -430,7 +430,7 @@ def upgrade_pkg_names(A = []):
updates = [i for i in pkg.history if Version(i.release) > Version(release)] updates = [i for i in pkg.history if Version(i.release) > Version(release)]
if not pisi.util.any(lambda i:i.type == 'security', updates): if not pisi.util.any(lambda i:i.type == 'security', updates):
continue continue
if ignore_build or (not build) or (not pkg.build): if ignore_build or (not build) or (not pkg.build):
if Version(release) < Version(pkg.release): if Version(release) < Version(pkg.release):
Ap.append(x) Ap.append(x)
@@ -443,18 +443,18 @@ def upgrade_pkg_names(A = []):
else: else:
ctx.ui.info(_('Package %s is already at the latest build %s.') ctx.ui.info(_('Package %s is already at the latest build %s.')
% (pkg.name, pkg.build), True) % (pkg.name, pkg.build), True)
A = set(Ap) A = set(Ap)
if len(A)==0: if len(A)==0:
ctx.ui.info(_('No packages to upgrade.')) ctx.ui.info(_('No packages to upgrade.'))
return True return True
A |= upgrade_base(A) A |= upgrade_base(A)
ctx.ui.debug('A = %s' % str(A)) ctx.ui.debug('A = %s' % str(A))
if not ctx.config.get_option('ignore_dependency'): if not ctx.config.get_option('ignore_dependency'):
G_f, order = plan_upgrade(A, ignore_build) G_f, order = plan_upgrade(A, ignore_build)
else: else:
@@ -470,7 +470,7 @@ def upgrade_pkg_names(A = []):
total_size = sum([ctx.packagedb.get_package(p).packageSize for p in order]) total_size = sum([ctx.packagedb.get_package(p).packageSize for p in order])
total_size, symbol = util.human_readable_size(total_size) total_size, symbol = util.human_readable_size(total_size)
ctx.ui.info(_('Total size of packages: %.2f %s') % (total_size, symbol)) ctx.ui.info(_('Total size of packages: %.2f %s') % (total_size, symbol))
if ctx.get_option('dry_run'): if ctx.get_option('dry_run'):
return return
@@ -496,7 +496,7 @@ def upgrade_pkg_names(A = []):
for path in paths: for path in paths:
install_op = atomicoperations.Install(path, ignore_file_conflicts = True) install_op = atomicoperations.Install(path, ignore_file_conflicts = True)
install_op.install(True) install_op.install(True)
if 'pisi' in order: if 'pisi' in order:
upgrade_pisi() upgrade_pisi()
@@ -505,15 +505,15 @@ def plan_upgrade(A, ignore_build = False):
# install / reinstall # install / reinstall
packagedb = ctx.packagedb packagedb = ctx.packagedb
G_f = pgraph.PGraph(packagedb) # construct G_f G_f = pgraph.PGraph(packagedb) # construct G_f
# 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
for x in A: for x in A:
G_f.add_package(x) G_f.add_package(x)
B = A B = A
# TODO: conflicts # TODO: conflicts
while len(B) > 0: while len(B) > 0:
@@ -571,9 +571,9 @@ def plan_upgrade(A, ignore_build = False):
def remove(A, ignore_dep = False, ignore_safety = False): def remove(A, ignore_dep = False, ignore_safety = False):
"""remove set A of packages from system (A is a list of package names)""" """remove set A of packages from system (A is a list of package names)"""
A = [str(x) for x in A] A = [str(x) for x in A]
# filter packages that are not installed # filter packages that are not installed
A_0 = A = expand_components(set(A)) A_0 = A = expand_components(set(A))
@@ -613,7 +613,7 @@ in the respective order to satisfy dependencies:
if not ctx.ui.confirm(_('Do you want to continue?')): if not ctx.ui.confirm(_('Do you want to continue?')):
ctx.ui.warning(_('Package removal declined')) ctx.ui.warning(_('Package removal declined'))
return False return False
if ctx.get_option('dry_run'): if ctx.get_option('dry_run'):
return return
@@ -631,7 +631,7 @@ def plan_remove(A):
G_f = pgraph.PGraph(ctx.packagedb, pisi.itembyrepodb.installed) # construct G_f G_f = pgraph.PGraph(ctx.packagedb, pisi.itembyrepodb.installed) # construct G_f
# 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
for x in A: for x in A:
G_f.add_package(x) G_f.add_package(x)
@@ -670,13 +670,13 @@ def emerge(A, rebuild_all = False):
A = [str(x) for x in A] A = [str(x) for x in A]
A_0 = A = expand_src_components(set(A)) A_0 = A = expand_src_components(set(A))
ctx.ui.debug('A = %s' % str(A)) ctx.ui.debug('A = %s' % str(A))
if len(A)==0: if len(A)==0:
ctx.ui.info(_('No packages to emerge.')) ctx.ui.info(_('No packages to emerge.'))
return return
#A |= upgrade_base(A) #A |= upgrade_base(A)
# FIXME: Errr... order_build changes type conditionally and this # FIXME: Errr... order_build changes type conditionally and this
# is not good. - baris # is not good. - baris
if not ctx.config.get_option('ignore_dependency'): if not ctx.config.get_option('ignore_dependency'):
@@ -687,7 +687,7 @@ def emerge(A, rebuild_all = False):
order_build = A order_build = A
if order_inst: if order_inst:
ctx.ui.info(_("""The following minimal list of packages will be installed ctx.ui.info(_("""The following minimal list of packages will be installed
from repository in the respective order to satisfy dependencies: from repository in the respective order to satisfy dependencies:
""") + util.strlist(order_inst)) """) + util.strlist(order_inst))
ctx.ui.info(_("""The following minimal list of packages will be built and ctx.ui.info(_("""The following minimal list of packages will be built and
@@ -700,7 +700,7 @@ installed in the respective order to satisfy dependencies:
if len(order_inst) + len(order_build) > len(A_0): if len(order_inst) + len(order_build) > len(A_0):
if not ctx.ui.confirm(_('There are extra packages due to dependencies. Do you want to continue?')): if not ctx.ui.confirm(_('There are extra packages due to dependencies. Do you want to continue?')):
return False return False
ctx.ui.notify(ui.packagestogo, order = order_inst) ctx.ui.notify(ui.packagestogo, order = order_inst)
pisi_installed = ctx.installdb.is_installed('pisi') pisi_installed = ctx.installdb.is_installed('pisi')
@@ -709,7 +709,7 @@ installed in the respective order to satisfy dependencies:
atomicoperations.install_single_name(x) atomicoperations.install_single_name(x)
#ctx.ui.notify(ui.packagestogo, order = order_build) #ctx.ui.notify(ui.packagestogo, order = order_build)
for x in order_build: for x in order_build:
package_names = atomicoperations.build(x)[0] package_names = atomicoperations.build(x)[0]
install_pkg_files(package_names) # handle inter-package deps here install_pkg_files(package_names) # handle inter-package deps here
@@ -726,7 +726,7 @@ def plan_emerge(A, rebuild_all):
# try to construct a pisi graph of packages to # try to construct a pisi graph of packages to
# install / reinstall # install / reinstall
G_f = pisi.graph.Digraph() G_f = pisi.graph.Digraph()
def get_spec(name): def get_spec(name):
if ctx.sourcedb.has_spec(name): if ctx.sourcedb.has_spec(name):
@@ -739,15 +739,15 @@ def plan_emerge(A, rebuild_all):
if not str(src.name) in G_f.vertices(): if not str(src.name) in G_f.vertices():
G_f.add_vertex(str(src.name), (src.version, src.release)) G_f.add_vertex(str(src.name), (src.version, src.release))
def pkgtosrc(pkg): def pkgtosrc(pkg):
return ctx.sourcedb.pkgtosrc(pkg) return ctx.sourcedb.pkgtosrc(pkg)
# setup first # setup first
#specfiles = [ ctx.sourcedb.get_source(x)[1] for x in A ] #specfiles = [ ctx.sourcedb.get_source(x)[1] for x in A ]
#pkgtosrc = {} #pkgtosrc = {}
B = A B = A
install_list = set() install_list = set()
while len(B) > 0: while len(B) > 0:
Bp = set() Bp = set()
for x in B: for x in B:
@@ -756,7 +756,7 @@ def plan_emerge(A, rebuild_all):
add_src(src) add_src(src)
# add dependencies # add dependencies
def process_dep(dep): def process_dep(dep):
if not dependency.installed_satisfies_dep(dep): if not dependency.installed_satisfies_dep(dep):
if dependency.repo_satisfies_dep(dep): if dependency.repo_satisfies_dep(dep):
@@ -771,17 +771,17 @@ def plan_emerge(A, rebuild_all):
for builddep in src.buildDependencies: for builddep in src.buildDependencies:
process_dep(builddep) process_dep(builddep)
for pkg in sf.packages: for pkg in sf.packages:
for rtdep in pkg.packageDependencies: for rtdep in pkg.packageDependencies:
process_dep(rtdep) process_dep(rtdep)
B = Bp B = Bp
if ctx.config.get_option('debug'): if ctx.config.get_option('debug'):
G_f.write_graphviz(sys.stdout) G_f.write_graphviz(sys.stdout)
order_build = G_f.topological_sort() order_build = G_f.topological_sort()
order_build.reverse() order_build.reverse()
G_f2, order_inst = plan_install_pkg_names(install_list) G_f2, order_inst = plan_install_pkg_names(install_list)
return G_f, order_inst, order_build return G_f, order_inst, order_build
+5 -5
View File
@@ -36,17 +36,17 @@ class Package:
def __init__(self, packagefn, mode='r'): def __init__(self, packagefn, mode='r'):
self.filepath = packagefn self.filepath = packagefn
url = URI(packagefn) url = URI(packagefn)
if url.is_remote_file(): if url.is_remote_file():
self.fetch_remote_file(url) self.fetch_remote_file(url)
self.impl = archive.ArchiveZip(self.filepath, 'zip', mode) self.impl = archive.ArchiveZip(self.filepath, 'zip', mode)
def fetch_remote_file(self, url): def fetch_remote_file(self, url):
from fetcher import fetch_url from fetcher import fetch_url
dest = ctx.config.packages_dir() dest = ctx.config.packages_dir()
self.filepath = join(dest, url.filename()) self.filepath = join(dest, url.filename())
#FIXME: also check sha1sum #FIXME: also check sha1sum
if not exists(self.filepath): if not exists(self.filepath):
try: try:
@@ -98,7 +98,7 @@ class Package:
unpacks the *contents* of directory archiveroot/dir inside outdir unpacks the *contents* of directory archiveroot/dir inside outdir
this is the function used by the installer""" this is the function used by the installer"""
self.impl.unpack_dir_flat(dir, outdir) self.impl.unpack_dir_flat(dir, outdir)
def extract_pisi_files(self, outdir): def extract_pisi_files(self, outdir):
"""Extract PiSi control files: metadata.xml, files.xml, """Extract PiSi control files: metadata.xml, files.xml,
action scripts, etc.""" action scripts, etc."""
@@ -135,7 +135,7 @@ class Package:
self.files.read( join(outdir, ctx.const.files_xml) ) self.files.read( join(outdir, ctx.const.files_xml) )
if self.files.errors(): if self.files.errors():
raise Error, _("Invalid %s") % ctx.const.files_xml raise Error, _("Invalid %s") % ctx.const.files_xml
def pkg_dir(self): def pkg_dir(self):
packageDir = self.metadata.package.name + '-' \ packageDir = self.metadata.package.name + '-' \
+ self.metadata.package.version + '-' \ + self.metadata.package.version + '-' \
+9 -9
View File
@@ -41,17 +41,17 @@ class NotfoundError(pisi.Error):
self.pkg = pkg self.pkg = pkg
class PackageDB(object): class PackageDB(object):
"""PackageDB class provides an interface to the package database """PackageDB class provides an interface to the package database
using shelf objects""" using shelf objects"""
def __init__(self): def __init__(self):
self.d = ItemByRepoDB('package') self.d = ItemByRepoDB('package')
self.dr = ItemByRepoDB('revdep') self.dr = ItemByRepoDB('revdep')
def close(self): def close(self):
self.d.close() self.d.close()
self.dr.close() self.dr.close()
def destroy(self): def destroy(self):
self.d.destroy() self.d.destroy()
self.dr.destroy() self.dr.destroy()
@@ -89,7 +89,7 @@ class PackageDB(object):
def add_package(self, package_info, repo, txn = None): def add_package(self, package_info, repo, txn = None):
name = str(package_info.name) name = str(package_info.name)
def proc(txn): def proc(txn):
self.d.add_item(name, package_info, repo, txn) self.d.add_item(name, package_info, repo, txn)
for dep in package_info.runtimeDependencies(): for dep in package_info.runtimeDependencies():
@@ -129,9 +129,9 @@ class PackageDB(object):
revdep = filter(lambda (n,d):n!=name, revdep) revdep = filter(lambda (n,d):n!=name, revdep)
if revdep: if revdep:
self.dr.add_item(dep_name, revdep, repo, txn) self.dr.add_item(dep_name, revdep, repo, txn)
else: else:
# Bug 3558: removal of revdep list of a package from revdepdb # Bug 3558: removal of revdep list of a package from revdepdb
# should only be done by the list members (dep. packages), not # should only be done by the list members (dep. packages), not
# the package itself. So if a package is removed, it is removed # the package itself. So if a package is removed, it is removed
# from packagedb but its revdepdb part may still exist, until # from packagedb but its revdepdb part may still exist, until
# all the list members are removed. # all the list members are removed.
@@ -149,7 +149,7 @@ class PackageDB(object):
def remove_repo(self, repo, txn = None): def remove_repo(self, repo, txn = None):
def proc(txn): def proc(txn):
self.d.remove_repo(repo, txn=txn) self.d.remove_repo(repo, txn=txn)
self.dr.remove_repo(repo, txn=txn) self.dr.remove_repo(repo, txn=txn)
self.d.txn_proc(proc, txn) self.d.txn_proc(proc, txn)
pkgdb = None pkgdb = None
+5 -5
View File
@@ -19,7 +19,7 @@ from graph import *
# Cache the results from packagedb queries in a graph # Cache the results from packagedb queries in a graph
class PGraph(Digraph): class PGraph(Digraph):
def __init__(self, packagedb, repo = pisi.itembyrepodb.repos): def __init__(self, packagedb, repo = pisi.itembyrepodb.repos):
super(PGraph, self).__init__() super(PGraph, self).__init__()
self.packagedb = packagedb self.packagedb = packagedb
@@ -37,7 +37,7 @@ class PGraph(Digraph):
pkg2data = None pkg2data = None
if not pkg2name in self.vertices(): if not pkg2name in self.vertices():
pkg2 = self.packagedb.get_package(pkg2name, self.repo) pkg2 = self.packagedb.get_package(pkg2name, self.repo)
pkg2data = (pkg2.version, pkg2.release) pkg2data = (pkg2.version, pkg2.release)
self.add_edge(str(pkg1name), str(pkg2name), ('d', None), self.add_edge(str(pkg1name), str(pkg2name), ('d', None),
pkg1data, pkg2data ) pkg1data, pkg2data )
@@ -45,7 +45,7 @@ class PGraph(Digraph):
pkg1data = None pkg1data = None
if not pkg in self.vertices(): if not pkg in self.vertices():
pkg1 = self.packagedb.get_package(pkg, self.repo) pkg1 = self.packagedb.get_package(pkg, self.repo)
pkg1data = (pkg1.version, pkg1.release) pkg1data = (pkg1.version, pkg1.release)
pkg2data = None pkg2data = None
if not depinfo.package in self.vertices(): if not depinfo.package in self.vertices():
pkg2 = self.packagedb.get_package(depinfo.package, self.repo) pkg2 = self.packagedb.get_package(depinfo.package, self.repo)
@@ -61,7 +61,7 @@ class PGraph(Digraph):
pkg2data = None pkg2data = None
if not depinfo.package in self.vertices(): if not depinfo.package in self.vertices():
pkg2 = self.packagedb.get_package(pkg, self.repo) pkg2 = self.packagedb.get_package(pkg, self.repo)
pkg2data = (pkg2.version, pkg2.release) pkg2data = (pkg2.version, pkg2.release)
self.add_edge(str(depinfo.package), str(pkg), ('d', depinfo), self.add_edge(str(depinfo.package), str(pkg), ('d', depinfo),
pkg1data, pkg2data ) pkg1data, pkg2data )
@@ -69,7 +69,7 @@ class PGraph(Digraph):
pkg1data = None pkg1data = None
if not pkg in self.vertices(): if not pkg in self.vertices():
pkg1 = self.packagedb.get_package(pkg, self.repo) pkg1 = self.packagedb.get_package(pkg, self.repo)
pkg1data = (pkg1.version, pkg1.release) pkg1data = (pkg1.version, pkg1.release)
pkg2data = None pkg2data = None
if not pkg in self.vertices(): if not pkg in self.vertices():
pkg2 = self.packagedb.get_package(conflinfo.package, self.repo) pkg2 = self.packagedb.get_package(conflinfo.package, self.repo)
+34 -37
View File
@@ -16,7 +16,7 @@
high-level XML processing prototype that Gurer prepared. high-level XML processing prototype that Gurer prepared.
Method names are mixedCase for compatibility with minidom, Method names are mixedCase for compatibility with minidom,
an old library. an old library.
""" """
# System # System
@@ -67,7 +67,7 @@ class LocalText(dict):
self.tag = tag self.tag = tag
self.req = req self.req = req
dict.__init__(self) dict.__init__(self)
def decode(self, node, errs, where = ""): def decode(self, node, errs, where = ""):
# flags, tag name, instance attribute # flags, tag name, instance attribute
assert self.tag != '' assert self.tag != ''
@@ -171,7 +171,6 @@ class Writer(formatter.DumbWriter):
self.col = self.col + len(data) self.col = self.col + len(data)
self.atbreak = 0 self.atbreak = 0
class autoxml(oo.autosuper, oo.autoprop): class autoxml(oo.autosuper, oo.autoprop):
"""High-level automatic XML transformation interface for xmlfile. """High-level automatic XML transformation interface for xmlfile.
The idea is to declare a class for each XML tag. Inside the The idea is to declare a class for each XML tag. Inside the
@@ -182,17 +181,17 @@ class autoxml(oo.autosuper, oo.autoprop):
__metaclass__ = autoxml __metaclass__ = autoxml
t_Name = [xmlfile.Text, xmlfile.mandatory] t_Name = [xmlfile.Text, xmlfile.mandatory]
a_Type = [xmlfile.Integer, xmlfile.optional] a_Type = [xmlfile.Integer, xmlfile.optional]
This class defines a tag and an attribute nested in Employee This class defines a tag and an attribute nested in Employee
class. Name is a string and type is an integer, called basic class. Name is a string and type is an integer, called basic
types. types.
While the tag is mandatory, the attribute may be left out. While the tag is mandatory, the attribute may be left out.
Other basic types supported are: xmlfile.Float, xmlfile.Double Other basic types supported are: xmlfile.Float, xmlfile.Double
and (not implemented yet): xmlfile.Binary and (not implemented yet): xmlfile.Binary
By default, the class name is taken as the corresponding tag, By default, the class name is taken as the corresponding tag,
which may be overridden by defining a tag attribute. Thus, which may be overridden by defining a tag attribute. Thus,
the same tag may also be written as: the same tag may also be written as:
class EmployeeXML: class EmployeeXML:
@@ -240,9 +239,8 @@ class autoxml(oo.autosuper, oo.autoprop):
You see, it works like magic, when it works of course. All of it You see, it works like magic, when it works of course. All of it
done without a single brain exploding. done without a single brain exploding.
"""
"""
def __init__(cls, name, bases, dict): def __init__(cls, name, bases, dict):
"""entry point for metaclass code""" """entry point for metaclass code"""
@@ -259,7 +257,7 @@ class autoxml(oo.autosuper, oo.autoprop):
#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 not dict.has_key('tag'):
cls.tag = name cls.tag = name
# generate helper routines, for each XML component # generate helper routines, for each XML component
@@ -275,24 +273,24 @@ class autoxml(oo.autosuper, oo.autoprop):
from inspect import getsourcelines from inspect import getsourcelines
from itertools import ifilter from itertools import ifilter
import re import re
fn = re.compile('\s*([tas]_[a-zA-Z]+).*').findall fn = re.compile('\s*([tas]_[a-zA-Z]+).*').findall
lines = filter(fn, getsourcelines(cls)[0]) lines = filter(fn, getsourcelines(cls)[0])
decl_order = map(lambda x:x.split()[0], lines) decl_order = map(lambda x:x.split()[0], lines)
# 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 = filter(lambda x: not x.startswith('s_'), decl_order)
# find string member # find string member
str_members = filter(lambda x:x.startswith('s_'), decl_order) str_members = filter(lambda x:x.startswith('s_'), decl_order)
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:
order.insert(0, str_members[0]) order.insert(0, str_members[0])
for var in order: for var in order:
if var.startswith('t_') or var.startswith('a_') or var.startswith('s_'): if var.startswith('t_') or var.startswith('a_') or var.startswith('s_'):
name = var[2:] name = var[2:]
@@ -395,7 +393,7 @@ class autoxml(oo.autosuper, oo.autoprop):
strfile.close() strfile.close()
return str return str
cls.__str__ = str cls.__str__ = str
if not dict.has_key('__eq__'): if not dict.has_key('__eq__'):
def equal(self, other): def equal(self, other):
# handle None # handle None
@@ -413,8 +411,8 @@ class autoxml(oo.autosuper, oo.autoprop):
def notequal(self, other): def notequal(self, other):
return not self.__eq__(other) return not self.__eq__(other)
cls.__eq__ = equal cls.__eq__ = equal
cls.__ne__ = notequal cls.__ne__ = notequal
if xmlfile_support: if xmlfile_support:
def parse(self, xml, keepDoc = False): def parse(self, xml, keepDoc = False):
"parse XML string and decode it into a python object" "parse XML string and decode it into a python object"
@@ -454,7 +452,7 @@ class autoxml(oo.autosuper, oo.autoprop):
if errs: if errs:
errs.append(_("autoxml.read: File '%s' has errors") % uri) errs.append(_("autoxml.read: File '%s' has errors") % uri)
raise Error(*errs) raise Error(*errs)
def write(self, uri, keepDoc = False, tmpDir = '/tmp', def write(self, uri, keepDoc = False, tmpDir = '/tmp',
sha1sum = False, compress = None, sign = None): sha1sum = False, compress = None, sign = None):
"encode the contents of the python object into an XML file" "encode the contents of the python object into an XML file"
@@ -473,11 +471,10 @@ class autoxml(oo.autosuper, oo.autoprop):
self.writexml(uri, tmpDir, sha1sum=sha1sum, compress=compress, sign=sign) self.writexml(uri, tmpDir, sha1sum=sha1sum, compress=compress, sign=sign)
if not keepDoc: if not keepDoc:
self.unlink() # get rid of the tree self.unlink() # get rid of the tree
cls.read = read cls.read = read
cls.write = write cls.write = write
cls.parse = parse cls.parse = parse
def gen_attr_member(cls, attr): def gen_attr_member(cls, attr):
"""generate readers and writers for an attribute member""" """generate readers and writers for an attribute member"""
@@ -546,11 +543,11 @@ class autoxml(oo.autosuper, oo.autoprop):
def init(self): def init(self):
"""initialize component""" """initialize component"""
setattr(self, name, init_a()) setattr(self, name, init_a())
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 + '.' + unicode(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"""
if hasattr(self, name): if hasattr(self, name):
@@ -558,7 +555,7 @@ class autoxml(oo.autosuper, oo.autoprop):
else: else:
value = None value = None
encode_a(node, value, errs) encode_a(node, value, errs)
def errors(self, where): def errors(self, where):
"""return errors in the object""" """return errors in the object"""
errs = [] errs = []
@@ -569,7 +566,7 @@ class autoxml(oo.autosuper, oo.autoprop):
if req == mandatory: if req == mandatory:
errs.append(where + ': ' + _('Mandatory variable %s not available') % name) errs.append(where + ': ' + _('Mandatory variable %s not available') % name)
return errs return errs
def format(self, f, errs): def format(self, f, errs):
if hasattr(self, name): if hasattr(self, name):
value = getattr(self,name) value = getattr(self,name)
@@ -579,7 +576,7 @@ class autoxml(oo.autosuper, oo.autoprop):
else: else:
if req == mandatory: if req == mandatory:
errs.append(_('Mandatory variable %s not available') % name) errs.append(_('Mandatory variable %s not available') % name)
return (name, init, decode, encode, errors, format) return (name, init, decode, encode, errors, format)
def mixed_case(cls, identifier): def mixed_case(cls, identifier):
@@ -614,7 +611,7 @@ class autoxml(oo.autosuper, oo.autoprop):
# if list of class, by default nested like in most PSPEC # if list of class, by default nested like in most PSPEC
path = token + '/' + token_type[0].tag path = token + '/' + token_type[0].tag
else: else:
# if list of ordinary type, just take the name for # if list of ordinary type, just take the name for
path = token path = token
elif type(token_type) is autoxml: elif type(token_type) is autoxml:
# if a class, by default its tag # if a class, by default its tag
@@ -630,9 +627,9 @@ class autoxml(oo.autosuper, oo.autoprop):
so that we can invoke it from the complex types such as Class so that we can invoke it from the complex types such as Class
and List. The readtext and writetext arguments achieve and List. The readtext and writetext arguments achieve
the DOM text access for this datatype.""" the DOM text access for this datatype."""
name, token_type, req, tagpath = cls.parse_spec(token, spec) name, token_type, req, tagpath = cls.parse_spec(token, spec)
def initialize(): def initialize():
"""default value for all basic types is None""" """default value for all basic types is None"""
return None return None
@@ -666,8 +663,8 @@ class autoxml(oo.autosuper, oo.autoprop):
def errors(value, where): def errors(value, where):
errs = [] errs = []
if value and not isinstance(value, token_type): if value and not isinstance(value, token_type):
errs.append(where + ': ' + _('Type mismatch. Expected %s, got %s') % errs.append(where + ': ' + _('Type mismatch. Expected %s, got %s') %
(token_type, type(value)) ) (token_type, type(value)) )
return errs return errs
def format(value, f, errs): def format(value, f, errs):
@@ -701,7 +698,7 @@ class autoxml(oo.autosuper, oo.autoprop):
if req == mandatory: if req == mandatory:
errs.append(where + ': ' + _('Mandatory argument not available')) errs.append(where + ': ' + _('Mandatory argument not available'))
return None return None
def encode(node, obj, errs): def encode(node, obj, errs):
if node and obj: if node and obj:
try: try:
@@ -716,10 +713,10 @@ class autoxml(oo.autosuper, oo.autoprop):
else: else:
if req == mandatory: if req == mandatory:
errs.append(_('Mandatory argument not available')) errs.append(_('Mandatory argument not available'))
def errors(obj, where): def errors(obj, where):
return obj.errors(where) return obj.errors(where)
def format(obj, f, errs): def format(obj, f, errs):
try: try:
obj.format(f, errs) obj.format(f, errs)
@@ -792,8 +789,8 @@ class autoxml(oo.autosuper, oo.autoprop):
def gen_insetclass_tag(cls, tag, spec): def gen_insetclass_tag(cls, tag, spec):
"""generate a class datatype that is highly integrated """generate a class datatype that is highly integrated
don't worry if that means nothing to you. this is a silly don't worry if that means nothing to you. this is a silly
hack to implement local text quickly. it's not the most hack to implement local text quickly. it's not the most
elegant thing in the world. it's basically a copy of elegant thing in the world. it's basically a copy of
class tag""" class tag"""
name, tag_type, req, path = cls.parse_spec(tag, spec) name, tag_type, req, path = cls.parse_spec(tag, spec)
+2 -2
View File
@@ -90,7 +90,7 @@ def getNode(node, tagpath):
if tagpath == "": if tagpath == "":
return node return node
assert type(tagpath)==str assert type(tagpath)==str
tags = tagpath.split('/') tags = tagpath.split('/')
assert len(tags)>0 assert len(tags)>0
@@ -135,7 +135,7 @@ def addNode(node, tagpath, newnode = None, branch=True):
else: else:
addTagPath(node, [], newnode) addTagPath(node, [], newnode)
return node #FIXME: is this correct!?!? return node #FIXME: is this correct!?!?
assert len(tags)>0 # we want a chain assert len(tags)>0 # we want a chain
# iterative code to search for the path # iterative code to search for the path
+3 -3
View File
@@ -62,7 +62,7 @@ class XmlFile(object):
return self.doc return self.doc
except Exception, e: except Exception, e:
raise Error(_("String '%s' has invalid XML") % (xml)) raise Error(_("String '%s' has invalid XML") % (xml))
def readxmlfile(self, file): def readxmlfile(self, file):
raise Exception("not implemented") raise Exception("not implemented")
try: try:
@@ -72,11 +72,11 @@ class XmlFile(object):
raise Error(_("File '%s' has invalid XML") % (localpath) ) raise Error(_("File '%s' has invalid XML") % (localpath) )
def readxml(self, uri, tmpDir='/tmp', sha1sum=False, def readxml(self, uri, tmpDir='/tmp', sha1sum=False,
compress=None, sign=None, copylocal = False): compress=None, sign=None, copylocal = False):
uri = File.make_uri(uri) uri = File.make_uri(uri)
#try: #try:
localpath = File.download(uri, tmpDir, sha1sum=sha1sum, localpath = File.download(uri, tmpDir, sha1sum=sha1sum,
compress=compress,sign=sign, copylocal=copylocal) compress=compress,sign=sign, copylocal=copylocal)
#except IOError, e: #except IOError, e:
# raise Error(_("Cannot read URI %s: %s") % (uri, unicode(e)) ) # raise Error(_("Cannot read URI %s: %s") % (uri, unicode(e)) )
+2 -2
View File
@@ -22,7 +22,7 @@ import pisi.context as ctx
import pisi.packagedb as packagedb import pisi.packagedb as packagedb
import pisi.util as util import pisi.util as util
from pisi.uri import URI from pisi.uri import URI
class Error(pisi.Error): class Error(pisi.Error):
pass pass
@@ -108,7 +108,7 @@ def init():
db = RepoDB() db = RepoDB()
return db return db
def finalize(): def finalize():
global db global db
+1 -1
View File
@@ -25,6 +25,6 @@ def install():
def __init__(self, name, filepath): def __init__(self, name, filepath):
self.name = name self.name = name
self.filepath = filepath self.filepath = filepath
def write(self): def write(self):
open(self.filepath, "w").write(self.template % self.name) open(self.filepath, "w").write(self.template % self.name)
+3 -4
View File
@@ -40,7 +40,7 @@ class Package:
def create_package(self): def create_package(self):
pspec = Pspec(self.name, consts.pspec_path) pspec = Pspec(self.name, consts.pspec_path)
pspec.set_source(consts.homepage, consts.summary % self.name, pspec.set_source(consts.homepage, consts.summary % self.name,
consts.description % self.name, consts.license, self.partOf) consts.description % self.name, consts.license, self.partOf)
pspec.set_packager(consts.packager_name, consts.packager_email) pspec.set_packager(consts.packager_name, consts.packager_email)
pspec.set_archive(consts.skel_sha1sum, consts.skel_type, consts.skel_uri) pspec.set_archive(consts.skel_sha1sum, consts.skel_type, consts.skel_uri)
@@ -67,7 +67,7 @@ class Package:
raise Exception(_("No pisi package: %s* found.") % pkg) raise Exception(_("No pisi package: %s* found.") % pkg)
return os.path.basename(found[0]) return os.path.basename(found[0])
def version_bump(self, *args): def version_bump(self, *args):
for with in args: for with in args:
if with.types == CONFLICT and with.action == ADDED: if with.types == CONFLICT and with.action == ADDED:
@@ -78,7 +78,7 @@ class Package:
if with.types == DEPENDENCY and with.action == ADDED: if with.types == DEPENDENCY and with.action == ADDED:
self.pspec.add_dependencies(with.data) self.pspec.add_dependencies(with.data)
if with.types == DEPENDENCY and with.action == REMOVED: if with.types == DEPENDENCY and with.action == REMOVED:
self.pspec.remove_dependencies(with.data) self.pspec.remove_dependencies(with.data)
@@ -93,4 +93,3 @@ class Package:
if __name__ == "__main__": if __name__ == "__main__":
p = Package("w0rmux", [], [], "0.7") p = Package("w0rmux", [], [], "0.7")
p.version_bump() p.version_bump()
+2 -2
View File
@@ -31,11 +31,11 @@ def repo_added_package(package, *args):
partOf = "None" partOf = "None"
dependencies = [] dependencies = []
conflicts = [] conflicts = []
for with in args: for with in args:
if with.types == CONFLICT and with.action == INIT: if with.types == CONFLICT and with.action == INIT:
conflicts = with.data conflicts = with.data
if with.types == DEPENDENCY and with.action == INIT: if with.types == DEPENDENCY and with.action == INIT:
dependencies = with.data dependencies = with.data
+4 -4
View File
@@ -56,8 +56,8 @@ def with_added_conflict(package, **kw):
return with_action(CONFLICT, ADDED, [package]) return with_action(CONFLICT, ADDED, [package])
if (kw.has_key("versionFrom") or if (kw.has_key("versionFrom") or
kw.has_key("versionTo") or kw.has_key("versionTo") or
kw.has_key("version") or kw.has_key("version") or
kw.has_key("releaseFrom") or kw.has_key("releaseFrom") or
kw.has_key("releaseTo") or kw.has_key("releaseTo") or
kw.has_key("release")): kw.has_key("release")):
@@ -73,8 +73,8 @@ def with_added_dependency(package, **kw):
return with_action(DEPENDENCY, ADDED, [package]) return with_action(DEPENDENCY, ADDED, [package])
if (kw.has_key("versionFrom") or if (kw.has_key("versionFrom") or
kw.has_key("versionTo") or kw.has_key("versionTo") or
kw.has_key("version") or kw.has_key("version") or
kw.has_key("releaseFrom") or kw.has_key("releaseFrom") or
kw.has_key("releaseTo") or kw.has_key("releaseTo") or
kw.has_key("release")): kw.has_key("release")):
+6 -6
View File
@@ -26,10 +26,10 @@ import preprocess as p
def init(ids, langs): def init(ids, langs):
"initialize databases" "initialize databases"
assert type(ids)==type([]) assert type(ids)==type([])
assert type(langs)==type([]) assert type(langs)==type([])
ctx.invidx = {} ctx.invidx = {}
for id in ids: for id in ids:
ctx.invidx[id] = {} ctx.invidx[id] = {}
@@ -38,19 +38,19 @@ def init(ids, langs):
def finalize(): def finalize():
import pisi.context as ctx import pisi.context as ctx
if ctx.invidx: if ctx.invidx:
for id in ctx.invidx.iterkeys(): for id in ctx.invidx.iterkeys():
for lang in ctx.invidx[id].iterkeys(): for lang in ctx.invidx[id].iterkeys():
ctx.invidx[id][lang].close() ctx.invidx[id][lang].close()
ctx.invidx = {} ctx.invidx = {}
def add_doc(id, lang, docid, str, repo = None, txn = None): def add_doc(id, lang, docid, str, repo = None, txn = None):
terms = p.preprocess(lang, str) terms = p.preprocess(lang, str)
ctx.invidx[id][lang].add_doc(docid, terms, repo=repo, txn=txn) ctx.invidx[id][lang].add_doc(docid, terms, repo=repo, txn=txn)
def remove_doc(id, lang, docid, str, repo = None, txn = None): def remove_doc(id, lang, docid, str, repo = None, txn = None):
terms = p.preprocess(lang, str) terms = p.preprocess(lang, str)
ctx.invidx[id][lang].remove_doc(docid, terms, repo = repo, txn = txn) ctx.invidx[id][lang].remove_doc(docid, terms, repo = repo, txn = txn)
def query_terms(id, lang, terms, repo = None, txn = None): def query_terms(id, lang, terms, repo = None, txn = None):
+2 -2
View File
@@ -18,7 +18,7 @@ import pisi.itembyrepodb as itembyrepodb
class InvertedIndex(object): class InvertedIndex(object):
"""a database of term -> set of documents""" """a database of term -> set of documents"""
def __init__(self, id, lang): def __init__(self, id, lang):
self.d = ItemByRepoDB('ii-%s-%s' % (id, lang)) self.d = ItemByRepoDB('ii-%s-%s' % (id, lang))
@@ -75,7 +75,7 @@ class InvertedIndex(object):
def remove_doc(self, doc, terms,repo=None, txn=None): def remove_doc(self, doc, terms,repo=None, txn=None):
def f(txn): def f(txn):
for term_i in terms: for term_i in terms:
term_i = shelve.LockedDBShelf.encodekey(term_i) term_i = shelve.LockedDBShelf.encodekey(term_i)
term_i_docs = self.get_term(term_i,repo=repo, txn=txn) term_i_docs = self.get_term(term_i,repo=repo, txn=txn)
if doc in term_i_docs: if doc in term_i_docs:
term_i_docs.remove(doc) term_i_docs.remove(doc)
+4 -4
View File
@@ -19,12 +19,12 @@ def lowly_python(str):
else: else:
lowly = c.lower() lowly = c.lower()
return c return c
r = "" r = ""
for c in str: for c in str:
r += lowly_char(c) r += lowly_char(c)
return r return r
def lower(lang, str): def lower(lang, str):
if lang=='tr': if lang=='tr':
return lowly_python(str) return lowly_python(str)
@@ -33,8 +33,8 @@ def lower(lang, str):
def preprocess(lang, str): def preprocess(lang, str):
terms = tokenize.tokenize(lang, str) terms = tokenize.tokenize(lang, str)
# normalize # normalize
terms = map(lambda x: lower(lang, x), terms) terms = map(lambda x: lower(lang, x), terms)
return terms return terms
+1 -1
View File
@@ -24,7 +24,7 @@ def tokenize(lang, str):
token = unicode() token = unicode()
else: else:
token += x token += x
if token: if token:
tokens.append(token) tokens.append(token)
+1 -1
View File
@@ -30,7 +30,7 @@ class SignalHandler:
def signal_handler(self, sig, frame): def signal_handler(self, sig, frame):
signal.signal(sig, signal.SIG_IGN) signal.signal(sig, signal.SIG_IGN)
self.signals[sig].pending = True self.signals[sig].pending = True
def disable_signal(self, sig): def disable_signal(self, sig):
if sig not in self.signals.keys(): if sig not in self.signals.keys():
self.signals[sig] = Signal(sig) self.signals[sig] = Signal(sig)
+1 -1
View File
@@ -101,6 +101,6 @@ class SourceArchive:
# check archive file's integrity # check archive file's integrity
if not util.check_file_hash(self.archiveFile, self.archive.sha1sum): if not util.check_file_hash(self.archiveFile, self.archive.sha1sum):
raise Error, _("unpack: check_file_hash failed") raise Error, _("unpack: check_file_hash failed")
archive = Archive(self.archiveFile, self.archive.type) archive = Archive(self.archiveFile, self.archive.type)
archive.unpack(self.pkg_work_dir, clean_dir) archive.unpack(self.pkg_work_dir, clean_dir)
+6 -6
View File
@@ -15,7 +15,7 @@ package source database
interface for update/query to local package repository interface for update/query to local package repository
we basically store everything in sourceinfo class we basically store everything in sourceinfo class
yes, we are cheap yes, we are cheap
to handle multiple repositories, for sources, we to handle multiple repositories, for sources, we
store a set of repositories in which the source appears. store a set of repositories in which the source appears.
the actual guy to take is determined from the repo order. the actual guy to take is determined from the repo order.
""" """
@@ -66,17 +66,17 @@ class SourceDB(object):
def pkgtosrc(self, name, txn = None): def pkgtosrc(self, name, txn = None):
return self.dpkgtosrc.get_item(name, txn=txn) return self.dpkgtosrc.get_item(name, txn=txn)
def add_spec(self, spec, repo, txn = None): def add_spec(self, spec, repo, txn = None):
assert not spec.errors() assert not spec.errors()
name = str(spec.source.name) name = str(spec.source.name)
def proc(txn): def proc(txn):
self.d.add_item(name, spec, repo, txn) self.d.add_item(name, spec, repo, txn)
for pkg in spec.packages: for pkg in spec.packages:
self.dpkgtosrc.add_item(pkg.name, name, repo, txn) self.dpkgtosrc.add_item(pkg.name, name, repo, txn)
ctx.componentdb.add_spec(spec.source.partOf, spec.source.name, repo, txn) ctx.componentdb.add_spec(spec.source.partOf, spec.source.name, repo, txn)
self.d.txn_proc(proc, txn) self.d.txn_proc(proc, txn)
def remove_spec(self, name, repo, txn = None): def remove_spec(self, name, repo, txn = None):
name = str(name) name = str(name)
def proc(txn): def proc(txn):
@@ -86,13 +86,13 @@ class SourceDB(object):
for pkg in spec.packages: for pkg in spec.packages:
self.dpkgtosrc.remove_item_repo(pkg.name, repo, txn) self.dpkgtosrc.remove_item_repo(pkg.name, repo, txn)
ctx.componentdb.remove_spec(spec.source.partOf, spec.source.name, repo, txn) ctx.componentdb.remove_spec(spec.source.partOf, spec.source.name, repo, txn)
self.d.txn_proc(proc, txn) self.d.txn_proc(proc, txn)
def remove_repo(self, repo, txn = None): def remove_repo(self, repo, txn = None):
def proc(txn): def proc(txn):
self.d.remove_repo(repo, txn=txn) self.d.remove_repo(repo, txn=txn)
self.dpkgtosrc.remove_repo(repo, txn=txn) self.dpkgtosrc.remove_repo(repo, txn=txn)
self.d.txn_proc(proc, txn) self.d.txn_proc(proc, txn)
sourcedb = None sourcedb = None
+2 -3
View File
@@ -64,7 +64,7 @@ class AdditionalFile:
class Patch: class Patch:
s_Filename = [autoxml.String, autoxml.mandatory] s_Filename = [autoxml.String, autoxml.mandatory]
a_compressionType = [autoxml.String, autoxml.optional] a_compressionType = [autoxml.String, autoxml.optional]
a_level = [autoxml.Integer, autoxml.optional] a_level = [autoxml.Integer, autoxml.optional]
@@ -87,7 +87,7 @@ class Patch:
class Update: class Update:
a_release = [autoxml.String, autoxml.mandatory] a_release = [autoxml.String, autoxml.mandatory]
a_type = [autoxml.String, autoxml.optional] a_type = [autoxml.String, autoxml.optional]
t_Date = [autoxml.String, autoxml.mandatory] t_Date = [autoxml.String, autoxml.mandatory]
@@ -128,7 +128,6 @@ class ComarProvide:
s += ' (' + self.om + ')' s += ' (' + self.om + ')'
return s return s
class Archive: class Archive:
s_uri = [ autoxml.String, autoxml.mandatory ] s_uri = [ autoxml.String, autoxml.mandatory ]
+3 -3
View File
@@ -17,7 +17,7 @@ import sys
import pisi import pisi
import pisi.context as ctx import pisi.context as ctx
(installed, upgraded, removed, installing, removing, configuring, configured, extracting, (installed, upgraded, removed, installing, removing, configuring, configured, extracting,
downloading, packagestogo, updatingrepo) = range(11) downloading, packagestogo, updatingrepo) = range(11)
class UI(object): class UI(object):
@@ -43,7 +43,7 @@ class UI(object):
def __init__(self, debuggy = False, verbose = False): def __init__(self, debuggy = False, verbose = False):
self.show_debug = debuggy self.show_debug = debuggy
self.show_verbose = verbose self.show_verbose = verbose
def close(self): def close(self):
"cleanup stuff here" "cleanup stuff here"
pass pass
@@ -95,7 +95,7 @@ class UI(object):
def status(self, msg = None): def status(self, msg = None):
"set status, if not given clear it" "set status, if not given clear it"
pass pass
def notify(self, event, **keywords): def notify(self, event, **keywords):
"notify UI of a significant event" "notify UI of a significant event"
pass pass
+2 -2
View File
@@ -68,13 +68,13 @@ class URI(object):
def is_remote_file(self): def is_remote_file(self):
return not self.is_local_file() return not self.is_local_file()
def is_absolute_path(self): def is_absolute_path(self):
return util.absolute_path(self.__path) return util.absolute_path(self.__path)
def is_relative_path(self): def is_relative_path(self):
return not self.is_absolute_path() return not self.is_absolute_path()
def set_auth_info(self, authTuple): def set_auth_info(self, authTuple):
if not isinstance(authTuple, tuple): if not isinstance(authTuple, tuple):
raise Exception, _("setAuthInfo needs a tuple (user, pass)") raise Exception, _("setAuthInfo needs a tuple (user, pass)")
+17 -18
View File
@@ -45,20 +45,20 @@ class FileError(Error):
class Checks: class Checks:
def __init__(self): def __init__(self):
self.list = [] self.list = []
def add(self, err): def add(self, err):
self.list.append(err) self.list.append(err)
def join(self, list): def join(self, list):
self.list.extend(list) self.list.extend(list)
def has_tag(self, var, section, name): def has_tag(self, var, section, name):
if not var: if not var:
self.list.append(_("%s section should have a '%s' tag") % (section, name)) self.list.append(_("%s section should have a '%s' tag") % (section, name))
def has_error(): def has_error():
return len(self.list)>0 return len(self.list)>0
def print_errors(list): def print_errors(list):
for x in list: for x in list:
ctx.ui.error(x) ctx.ui.error(x)
@@ -137,7 +137,7 @@ def human_readable_rate(size = 0):
def run_batch(cmd): def run_batch(cmd):
"""run command and report return value and output""" """run command and report return value and output"""
ctx.ui.info(_('Running ') + cmd, verbose=True) ctx.ui.info(_('Running ') + cmd, verbose=True)
p = subprocess.Popen(cmd, shell=True, p = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate() out, err = p.communicate()
ctx.ui.debug(_('return value for "%s" is %s') % (cmd, p.returncode)) ctx.ui.debug(_('return value for "%s" is %s') % (cmd, p.returncode))
@@ -147,7 +147,7 @@ def run_batch(cmd):
class TeeOutFile: class TeeOutFile:
def __init__(self, file): def __init__(self, file):
self.file = file self.file = file
def write(self, str): def write(self, str):
self.write(str) self.write(str)
ctx.ui.debug(str) ctx.ui.debug(str)
@@ -174,12 +174,11 @@ def run_logged(cmd):
stderr = subprocess.STDOUT stderr = subprocess.STDOUT
p = subprocess.Popen(cmd, shell=True, stdout=stdout, stderr=stderr) p = subprocess.Popen(cmd, shell=True, stdout=stdout, stderr=stderr)
out, err = p.communicate() out, err = p.communicate()
ctx.ui.debug(_('return value for "%s" is %s') % (cmd, p.returncode)) ctx.ui.debug(_('return value for "%s" is %s') % (cmd, p.returncode))
return p.returncode return p.returncode
###################### ######################
# Terminal functions # # Terminal functions #
###################### ######################
@@ -487,14 +486,14 @@ def do_patch(sourceDir, patchFile, level = 0, target = ''):
"""simple function to apply patches..""" """simple function to apply patches.."""
cwd = os.getcwd() cwd = os.getcwd()
os.chdir(sourceDir) os.chdir(sourceDir)
if level == None: if level == None:
level = 0 level = 0
if target == None: if target == None:
target = '' target = ''
check_file(patchFile) check_file(patchFile)
(ret, out, err) = run_batch("patch -p%d %s < %s" % (ret, out, err) = run_batch("patch -p%d %s < %s" %
(level, target, patchFile)) (level, target, patchFile))
if ret: if ret:
if out is None and err is None: if out is None and err is None:
@@ -510,13 +509,13 @@ def strip_directory(top, excludelist=[]):
for root, dirs, files in os.walk(top): for root, dirs, files in os.walk(top):
for fn in files: for fn in files:
frpath = join_path(root, fn) frpath = join_path(root, fn)
drpath = join_path(os.path.dirname(top), drpath = join_path(os.path.dirname(top),
ctx.const.debug_dir_suffix, ctx.const.debug_dir_suffix,
remove_prefix(top, frpath)) remove_prefix(top, frpath))
# Some upstream sources have buggy libtool and ltmain.sh with them, # Some upstream sources have buggy libtool and ltmain.sh with them,
# which causes wrong path entries in *.la files. And these wrong path # which causes wrong path entries in *.la files. And these wrong path
# entries sometimes triggers compile-time errors or linkage problems. # entries sometimes triggers compile-time errors or linkage problems.
# Instead of patching all these buggy sources and maintain these patches, # Instead of patching all these buggy sources and maintain these patches,
# PiSi removes wrong paths... # PiSi removes wrong paths...
extension = os.path.splitext(frpath)[1] extension = os.path.splitext(frpath)[1]
@@ -524,7 +523,7 @@ def strip_directory(top, excludelist=[]):
# FIXME: I'm regular expr. idiot, so one can convert this to python... # FIXME: I'm regular expr. idiot, so one can convert this to python...
os.system("sed -i -e 's~-L/var/tmp/pisi/[[:graph:]]*~~g' %s" % frpath) os.system("sed -i -e 's~-L/var/tmp/pisi/[[:graph:]]*~~g' %s" % frpath)
os.system("sed -i -e 's~/var/tmp/pisi/[[:graph:]]*/install/~/~g' %s" % frpath) os.system("sed -i -e 's~/var/tmp/pisi/[[:graph:]]*/install/~/~g' %s" % frpath)
# real path in .pisi package # real path in .pisi package
p = '/' + removepathprefix(top, frpath) p = '/' + removepathprefix(top, frpath)
strip = True strip = True
@@ -536,7 +535,7 @@ def strip_directory(top, excludelist=[]):
if strip: if strip:
if strip_file(frpath, drpath): if strip_file(frpath, drpath):
ctx.ui.debug("%s [%s]" %(p, "stripped")) ctx.ui.debug("%s [%s]" %(p, "stripped"))
def strip_file(filepath, outpath): def strip_file(filepath, outpath):
"""strip a file""" """strip a file"""
@@ -555,7 +554,7 @@ def strip_file(filepath, outpath):
ret = p.close() ret = p.close()
if ret: if ret:
ctx.ui.warning(_("objcopy (keep-debug) command failed for file '%s'!") % f) ctx.ui.warning(_("objcopy (keep-debug) command failed for file '%s'!") % f)
"""mark binary/shared objects to use file.debug""" """mark binary/shared objects to use file.debug"""
p = os.popen("objcopy --add-gnu-debuglink=%s%s %s" % (o, ctx.const.debug_file_suffix, f)) p = os.popen("objcopy --add-gnu-debuglink=%s%s %s" % (o, ctx.const.debug_file_suffix, f))
ret = p.close() ret = p.close()
@@ -647,5 +646,5 @@ def parse_package_name(package_name):
name.append(part) name.append(part)
name = "-".join(name) name = "-".join(name)
version = package_name[len(name) + 1:] version = package_name[len(name) + 1:]
return (name, version) return (name, version)
+4 -4
View File
@@ -66,7 +66,7 @@ class VersionItem:
# longer match is correct # longer match is correct
if len(keyword) > len(self._keyword): if len(keyword) > len(self._keyword):
self._keyword = keyword self._keyword = keyword
if self._keyword == "NOKEY": if self._keyword == "NOKEY":
if len(itemstring) == 1 and itemstring in string.ascii_letters: if len(itemstring) == 1 and itemstring in string.ascii_letters:
# single letter version item ('a' to 'Z') # single letter version item ('a' to 'Z')
@@ -137,7 +137,7 @@ class Version:
# They are special and used for build and release no separation. # They are special and used for build and release no separation.
if verstring.count("-") > maxdashes: if verstring.count("-") > maxdashes:
raise VersionException("%s is not a valid PiSi version format" % verstring) raise VersionException("%s is not a valid PiSi version format" % verstring)
verchunks = verstring.split("-") verchunks = verstring.split("-")
verchunks.extend("0" * (maxdashes - verstring.count("-"))) verchunks.extend("0" * (maxdashes - verstring.count("-")))
(version, release, build) = verchunks (version, release, build) = verchunks
@@ -176,7 +176,7 @@ class Version:
# pad the short version string with zeros # pad the short version string with zeros
if len(lhs) < len(rhs): if len(lhs) < len(rhs):
lhs.extend( [VersionItem('0')] * (len(rhs) - len(lhs)) ) lhs.extend( [VersionItem('0')] * (len(rhs) - len(lhs)) )
elif len(lhs) > len(rhs): elif len(lhs) > len(rhs):
rhs.extend( [VersionItem('0')] * (len(lhs) - len(rhs)) ) rhs.extend( [VersionItem('0')] * (len(lhs) - len(rhs)) )
# now let's iterate from left to right in version items # now let's iterate from left to right in version items
for (litem, ritem) in zip(lhs, rhs): for (litem, ritem) in zip(lhs, rhs):
@@ -201,7 +201,7 @@ class Version:
def __le__(self,rhs): def __le__(self,rhs):
return self.compare(rhs) <= 0 return self.compare(rhs) <= 0
def __gt__(self,rhs): def __gt__(self,rhs):
return self.compare(rhs) > 0 return self.compare(rhs) > 0