Some minor refactorings
authorkarltk <karltk@gentoo.org>
Mon, 11 Oct 2004 15:31:10 +0000 (15:31 -0000)
committerkarltk <karltk@gentoo.org>
Mon, 11 Oct 2004 15:31:10 +0000 (15:31 -0000)
svn path=/; revision=153

trunk/src/gentoolkit/ChangeLog
trunk/src/gentoolkit/Makefile
trunk/src/gentoolkit/__init__.py
trunk/src/gentoolkit/helpers.py [new file with mode: 0644]
trunk/src/gentoolkit/package.py [moved from trunk/src/gentoolkit/gentoolkit.py with 52% similarity]

index 72b05fe6ff277bcd444231660aad74adfc90bf4c..3b09ff5cdbfd2d3dc16b819d59ac5d40133f3d30 100644 (file)
@@ -1,3 +1,6 @@
+2004-10-11: Karl Trygve Kalleberg <karltk@gentoo.org>
+       * Split gentoolkit.py into helpers.py and package.py
+
 2004-10-10: Karl Trygve Kalleberg <karltk@gentoo.org>
        * Fixed is_overlay() to report properly, #53432.
 
index 9da3da770a2e2f5a657c9be2c1cdb3348a80610b..84981a2a9f2d25fb5ff946751c74fbde047ec6dc 100644 (file)
@@ -11,13 +11,12 @@ all:
 
 dist:
        mkdir -p ../../${distdir}/src/gentoolkit
-       cp Makefile AUTHORS README ChangeLog TODO gentoolkit.py pprinter.py __init__.py ../../${distdir}/src/gentoolkit/
+       cp Makefile AUTHORS README ChangeLog TODO package.py helpers.py pprinter.py __init__.py ../../${distdir}/src/gentoolkit/
 
 install:
        install -d $(docdir)/gentoolkit
        install -m 0644 AUTHORS README TODO ChangeLog $(docdir)/gentoolkit/
        install -d $(DESTDIR)/usr/lib/gentoolkit/pym/gentoolkit
-       install -m 0644 gentoolkit.py $(DESTDIR)/usr/lib/gentoolkit/pym/gentoolkit/
-       install -m 0644 pprinter.py $(DESTDIR)/usr/lib/gentoolkit/pym/gentoolkit/
+       install -m 0644 package.py pprinter.py package.py $(DESTDIR)/usr/lib/gentoolkit/pym/gentoolkit/
        install -m 0644 __init__.py $(DESTDIR)/usr/lib/gentoolkit/pym/gentoolkit/
        
index 42b757066a4dce55eff042bd22e582cd49397e35..9982d58518ff4f5356f1f6f888fefd2833d5a31d 100644 (file)
@@ -1 +1,38 @@
-from gentoolkit import *
\ No newline at end of file
+#!/usr/bin/python
+#
+# Copyright 2003-2004 Karl Trygve Kalleberg
+# Copyright 2003-2004 Gentoo Technologies, Inc.
+# Distributed under the terms of the GNU General Public License v2
+#
+# $Header$
+# Author: Karl Trygve Kalleberg <karltk@gentoo.org>
+#
+# Portions written ripped from 
+# - etcat, by Alistair Tse <liquidx@gentoo.org>
+#
+
+__author__ = "Karl Trygve Kalleberg"
+__email__ = "karltk@gentoo.org"
+__version__ = "0.1.0"
+__productname__ = "gentoolkit"
+__description__ = "Gentoolkit Common Library"
+
+import os
+import sys
+sys.path.insert(0, "/usr/lib/portage/pym")
+import portage
+import re
+import string
+import types
+
+settings = portage.config(clone=portage.settings)
+porttree = portage.db[portage.root]["porttree"]
+vartree  = portage.db[portage.root]["vartree"]
+virtuals = portage.db[portage.root]["virtuals"]
+
+Config = {
+    "verbosityLevel": 3
+}
+
+from helpers import *
+from package import *
diff --git a/trunk/src/gentoolkit/helpers.py b/trunk/src/gentoolkit/helpers.py
new file mode 100644 (file)
index 0000000..bbb0cd9
--- /dev/null
@@ -0,0 +1,139 @@
+#! /usr/bin/python2
+#
+# Copyright(c) 2004, Karl Trygve Kalleberg <karltk@gentoo.org>
+# Copyright(c) 2004, Gentoo Foundation
+#
+# Licensed under the GNU General Public License, v2
+#
+# $Header$
+
+def find_packages(search_key, masked=False):
+    """Returns a list of Package objects that matched the search key."""
+    try:
+        if masked:
+            t=portage.portdb.xmatch("match-all", search_key)
+        else:
+            t=portage.portdb.match(search_key)
+    # catch the "amgigous package" Exception
+    except ValueError, e:
+        if type(e[0]) == types.ListType:
+            t=[]
+            for cp in e[0]:
+                if masked:
+                    t += portage.portdb.xmatch("match-all", cp)
+                else:
+                    t += portage.portdb.match(cp)
+        else:
+            raise ValueError(e)
+    return [Package(x) for x in t]
+
+def find_installed_packages(search_key, masked=False):
+    """Returns a list of Package objects that matched the search key."""
+    try:
+            t = vartree.dbapi.match(search_key)
+    # catch the "amgigous package" Exception
+    except ValueError, e:
+        if type(e[0]) == types.ListType:
+            t=[]
+            for cp in e[0]:
+                t += vartree.dbapi.match(cp)
+        else:
+            raise ValueError(e)
+    return [Package(x) for x in t]
+
+def find_best_match(search_key):
+    """Returns a Package object for the best available installed candidate that
+    matched the search key. Doesn't handle virtuals perfectly"""
+    # FIXME: How should we handled versioned virtuals??
+    cat,pkg,ver,rev=split_package_name(search_key)
+    if cat == "virtual":
+        t=vartree.dep_bestmatch(cat+"/"+pkg)
+    else:
+        t=vartree.dep_bestmatch(search_key)
+    if t:
+        return Package(t)
+    return None
+
+def find_system_packages(prefilter=None):
+    """Returns a tuple of lists, first list is resolved system packages,
+    second is a list of unresolved packages."""
+    pkglist = settings.packages
+    resolved = []
+    unresolved = []
+    for x in pkglist:
+        cpv = x.strip()
+        if len(cpv) and cpv[0] == "*":
+            pkg = find_best_match(cpv)
+            if pkg:
+                resolved.append(pkg)
+            else:
+                unresolved.append(cpv)
+    return (resolved, unresolved)
+
+def find_world_packages(prefilter=None):
+    """Returns a tuple of lists, first list is resolved world packages,
+    seond is unresolved package names."""
+    f = open(portage.root+"var/cache/edb/world")
+    pkglist = f.readlines()
+    resolved = []
+    unresolved = []
+    for x in pkglist:
+        cpv = x.strip()
+        if len(cpv) and cpv[0] != "#":
+            pkg = find_best_match(cpv)
+            if pkg:
+                resolved.append(pkg)
+            else:
+                unresolved.append(cpv)
+    return (resolved,unresolved)
+
+def find_all_installed_packages(prefilter=None):
+    """Returns a list of all installed packages, after applying the prefilter
+    function"""
+    t=vartree.dbapi.cpv_all()
+    if prefilter:
+        t=filter(prefilter,t)
+    return [Package(x) for x in t]
+
+def find_all_uninstalled_packages(prefilter=None):
+    """Returns a list of all uninstalled packages, after applying the prefilter
+    function"""
+    alist = find_all_packages(prefilter)
+    return [x for x in alist if not x.is_installed()]
+
+def find_all_packages(prefilter=None):
+    """Returns a list of all known packages, installed or not, after applying
+    the prefilter function"""
+    t=portage.portdb.cp_all()
+    if prefilter:
+        t=filter(prefilter,t)
+    t2=[]
+    for x in t:
+        t2 += portage.portdb.cp_list(x)
+    return [Package(x) for x in t2]
+
+def split_package_name(name):
+    """Returns a list on the form [category, name, version, revision]. Revision will
+    be 'r0' if none can be inferred. Category and version will be empty, if none can
+    be inferred."""
+    r=portage.catpkgsplit(name)
+    if not r:
+        r=name.split("/")
+        if len(r) == 1:
+            return ["",name,"","r0"]
+        else:
+            return r + ["","r0"]
+    if r[0] == 'null':
+        r[0] = ''
+    return r
+
+def sort_package_list(pkglist):
+    """Returns the list ordered in the same way portage would do with lowest version
+    at the head of the list."""
+    pkglist.sort(Package.compare_version)
+    return pkglist
+
+if __name__ == "__main__":
+    print "This module is for import only"
+
+
similarity index 52%
rename from trunk/src/gentoolkit/gentoolkit.py
rename to trunk/src/gentoolkit/package.py
index 07eea39bac1d5efb5ccd2f3101aeaf9a461a7cac..f45d719e88a8cd9b6342444441a5021bb0c6e198 100644 (file)
@@ -1,47 +1,17 @@
-#!/usr/bin/python
+#! /usr/bin/python2
 #
-# Copyright 2003-2004 Karl Trygve Kalleberg
-# Copyright 2003-2004 Gentoo Technologies, Inc.
-# Distributed under the terms of the GNU General Public License v2
+# Copyright(c) 2004, Karl Trygve Kalleberg <karltk@gentoo.org>
+# Copyright(c) 2004, Gentoo Foundation
 #
-# $Header$
-# Author: Karl Trygve Kalleberg <karltk@gentoo.org>
-#
-# Portions written ripped from 
-# - etcat, by Alistair Tse <liquidx@gentoo.org>
-#
-
-__author__ = "Karl Trygve Kalleberg"
-__email__ = "karltk@gentoo.org"
-__version__ = "0.1.0"
-__productname__ = "gentoolkit"
-__description__ = "Gentoolkit Common Library"
-
-import os
-import sys
-sys.path.insert(0, "/usr/lib/portage/pym")
-import portage
-import re
-import string
-import types
-
-settings = portage.config(clone=portage.settings)
-porttree = portage.db[portage.root]["porttree"]
-vartree  = portage.db[portage.root]["vartree"]
-virtuals = portage.db[portage.root]["virtuals"]
-
-Config = {
-       "verbosityLevel": 3
-}
-       
-# Nomenclature:
+# Licensed under the GNU General Public License, v2
 #
-# CPV - category/package-version
+# $Header$
 
 class Package:
        """Package descriptor. Contains convenience functions for querying the
        state of a package, its contents, name manipulation, ebuild info and
        similar."""
+
        def __init__(self,cpv):
                self._cpv = cpv
                self._scpv = portage.catpkgsplit(self._cpv)
@@ -50,43 +20,53 @@ class Package:
                self._db = None
                settings.setcpv(self._cpv)
                self._settings = portage.config(clone=settings)
+
        def get_name(self):
                """Returns base name of package, no category nor version"""
                return self._scpv[1]
+
        def get_version(self):
                """Returns version of package, with revision number"""
                v=self._scpv[2]
                if self._scpv[3] != "r0":
                        v+="-"+self._scpv[3]
                return v
+
        def get_category(self):
                """Returns category of package"""
                return self._scpv[0]
+
        def get_settings(self, key):
                """Returns the value of the given key for this package (useful 
                for package.* files."""
                return self._settings[key]
+
        def get_cpv(self):
                """Returns full Category/Package-Version string"""
                return self._cpv
+
        def get_provides(self):
                """Return a list of provides, if any"""
                return vartree.get_provides(self._cpv)
+
        def get_dependants(self):
                """Retrieves a list of CPVs for all packages depending on this one"""
                raise "Not implemented yet!"
+
        def get_runtime_deps(self):
                """Returns a linearised list of first-level compile time dependencies for this package, on
                the form [(comparator, [use flags], cpv), ...]"""
                cd=self.get_env_var("RDEPEND").split()
                r,i=self._parse_deps(cd)
                return r
+
        def get_compiletime_deps(self):
                """Returns a linearised list of first-level compile time dependencies for this package, on
                the form [(comparator, [use flags], cpv), ...]"""
                rd=self.get_env_var("DEPEND").split()
                r,i=self._parse_deps(rd)
                return r
+
        def _parse_deps(self,deps,curuse=[],level=0):
                # store (comparator, [use predicates], cpv)
                r=[]
@@ -112,30 +92,36 @@ class Package:
                        r.append((cmp,curuse,tok))
                        i+=1
                return r,i
+
        def is_installed(self):
                """Returns true if this package is installed (merged)"""
                self._initdb()
                return os.path.exists(self._db.getpath())
+
        def is_overlay(self):
                dir,ovl=portage.portdb.findname2(self._cpv)
                return ovl != settings["PORTDIR"]
+
        def is_masked(self):
                """Returns true if this package is masked against installation. Note: We blindly assume that
                the package actually exists on disk somewhere."""
                unmasked = portage.portdb.xmatch("match-visible", "=" + self._cpv)
                return self._cpv not in unmasked
+
        def get_ebuild_path(self,in_vartree=0):
                """Returns the complete path to the .ebuild file"""
                if in_vartree:
                        return vartree.getebuildpath(self._cpv)
                else:
                        return portage.portdb.findname(self._cpv)
+
        def get_package_path(self):
                """Returns the path to where the ChangeLog, Manifest, .ebuild files reside"""
                p=self.get_ebuild_path()
                sp=p.split("/")
                if len(sp):
                        return string.join(sp[:-1],"/")
+
        def get_env_var(self, var):
                """Returns one of the predefined env vars DEPEND, RDEPEND, SRC_URI,...."""
                mytree = vartree
@@ -147,12 +133,14 @@ class Package:
                if len(r)!=1:
                        raise "Should only get one element!"
                return r[0]
+
        def get_use_flags(self):
                """Returns the USE flags active at time of installation"""
                self._initdb()
                if self.is_installed():
                        return self._db.getfile("USE")
                return ""
+
        def get_contents(self):
                """Returns the full contents, as a dictionary, on the form
                [ '/bin/foo' : [ 'obj', '1052505381', '45ca8b8975d5094cd75bdc61e9933691' ], ... ]"""
@@ -160,6 +148,7 @@ class Package:
                if self.is_installed():
                        return self._db.getcontents()
                return {}               
+
        def compare_version(self,other):
                """Compares this package's version to another's CPV; returns -1, 0, 1"""
                v1=self._scpv
@@ -167,6 +156,7 @@ class Package:
                if v1[0] != v2[0] or v1[1] != v2[1]:
                        return 0
                return portage.pkgcmp(v1[1:],v2[1:])
+
        def size(self):
                """Estimates the installed size of the contents of this package, if possible.
                Returns [size, number of files in total, number of uncounted files]"""
@@ -189,139 +179,3 @@ class Package:
                        cat=self.get_category()
                        pnv=self.get_name()+"-"+self.get_version()
                        self._db=portage.dblink(cat,pnv,"/",settings)
-
-
-#
-# Global helper functions
-#
-
-def find_packages(search_key, masked=False):
-       """Returns a list of Package objects that matched the search key."""
-       try:
-               if masked:
-                       t=portage.portdb.xmatch("match-all", search_key)
-               else:
-                       t=portage.portdb.match(search_key)
-       # catch the "amgigous package" Exception
-       except ValueError, e:
-               if type(e[0]) == types.ListType:
-                       t=[]
-                       for cp in e[0]:
-                               if masked:
-                                       t += portage.portdb.xmatch("match-all", cp)
-                               else:
-                                       t += portage.portdb.match(cp)
-               else:
-                       raise ValueError(e)
-       return [Package(x) for x in t]
-
-def find_installed_packages(search_key, masked=False):
-       """Returns a list of Package objects that matched the search key."""
-       try:
-                       t = vartree.dbapi.match(search_key)
-       # catch the "amgigous package" Exception
-       except ValueError, e:
-               if type(e[0]) == types.ListType:
-                       t=[]
-                       for cp in e[0]:
-                               t += vartree.dbapi.match(cp)
-               else:
-                       raise ValueError(e)
-       return [Package(x) for x in t]
-
-def find_best_match(search_key):
-       """Returns a Package object for the best available installed candidate that
-       matched the search key. Doesn't handle virtuals perfectly"""
-       # FIXME: How should we handled versioned virtuals??
-       cat,pkg,ver,rev=split_package_name(search_key)
-       if cat == "virtual":
-               t=vartree.dep_bestmatch(cat+"/"+pkg)
-       else:
-               t=vartree.dep_bestmatch(search_key)
-       if t:
-               return Package(t)
-       return None
-
-def find_system_packages(prefilter=None):
-       """Returns a tuple of lists, first list is resolved system packages,
-       second is a list of unresolved packages."""
-       pkglist = settings.packages
-       resolved = []
-       unresolved = []
-       for x in pkglist:
-               cpv = x.strip()
-               if len(cpv) and cpv[0] == "*":
-                       pkg = find_best_match(cpv)
-                       if pkg:
-                               resolved.append(pkg)
-                       else:
-                               unresolved.append(cpv)
-       return (resolved, unresolved)
-
-def find_world_packages(prefilter=None):
-       """Returns a tuple of lists, first list is resolved world packages,
-       seond is unresolved package names."""
-       f = open(portage.root+"var/cache/edb/world")
-       pkglist = f.readlines()
-       resolved = []
-       unresolved = []
-       for x in pkglist:
-               cpv = x.strip()
-               if len(cpv) and cpv[0] != "#":
-                       pkg = find_best_match(cpv)
-                       if pkg:
-                               resolved.append(pkg)
-                       else:
-                               unresolved.append(cpv)
-       return (resolved,unresolved)
-
-def find_all_installed_packages(prefilter=None):
-       """Returns a list of all installed packages, after applying the prefilter
-       function"""
-       t=vartree.dbapi.cpv_all()
-       if prefilter:
-               t=filter(prefilter,t)
-       return [Package(x) for x in t]
-
-def find_all_uninstalled_packages(prefilter=None):
-       """Returns a list of all uninstalled packages, after applying the prefilter
-       function"""
-       alist = find_all_packages(prefilter)
-       return [x for x in alist if not x.is_installed()]
-
-def find_all_packages(prefilter=None):
-       """Returns a list of all known packages, installed or not, after applying
-       the prefilter function"""
-       t=portage.portdb.cp_all()
-       if prefilter:
-               t=filter(prefilter,t)
-       t2=[]
-       for x in t:
-               t2 += portage.portdb.cp_list(x)
-       return [Package(x) for x in t2]
-
-def split_package_name(name):
-       """Returns a list on the form [category, name, version, revision]. Revision will
-       be 'r0' if none can be inferred. Category and version will be empty, if none can
-       be inferred."""
-       r=portage.catpkgsplit(name)
-       if not r:
-               r=name.split("/")
-               if len(r) == 1:
-                       return ["",name,"","r0"]
-               else:
-                       return r + ["","r0"]
-       if r[0] == 'null':
-               r[0] = ''
-       return r
-
-def sort_package_list(pkglist):
-       """Returns the list ordered in the same way portage would do with lowest version
-       at the head of the list."""
-       pkglist.sort(Package.compare_version)
-       return pkglist
-
-if __name__ == "__main__":
-       print "This module is for import only"
-
-