From 6c3e74bdf3a8bd6aced0a2ddb38c1cc7b22ec655 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Apr 2009 18:19:41 +0200 Subject: * doc/source/conf.py: Do not require python-debian anymore Try to get the release from the information in the environment variable DEBVER, which is exported in debian/rules. If it is not set, use python-debian to read the release from the changelog. --- doc/source/conf.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) (limited to 'doc/source') diff --git a/doc/source/conf.py b/doc/source/conf.py index 40154a6f..52c8a21b 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -60,13 +60,16 @@ copyright = u'2009, Julian Andres Klode ' # |version| and |release|, also used in various other places throughout the # built documents. # -from debian_bundle.changelog import Changelog -changes = Changelog(open('../../debian/changelog')) -# The short X.Y version. -version = '.'.join(changes.full_version.split('.')[:2]) -# The full version, including alpha/beta/rc tags. -release = changes.full_version +try: + release=os.environ['DEBVER'] +except KeyError: + from debian_bundle.changelog import Changelog + changes = Changelog(open('../../debian/changelog')) + # The full version, including alpha/beta/rc tags. + release = changes.full_version + +version = '.'.join(release.split('.')[:3]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -- cgit v1.2.3 From 506cb021d62e643fba38ddb4b84572a86cb3a3ba Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Apr 2009 18:27:43 +0200 Subject: * python/tag.cc: Support 'key in mapping' for TagSections Support the replacement of mapping.has_key() for sections, and update the usage in apt/package.py and apt/debfile accordingly. This is implemented by extending the TagSecType with sequence methods, but only settings the contains method there. The TagSecGetAttr() function has been removed and replaced by the use of the tp_methods slot. --- apt/debfile.py | 10 +++++----- apt/package.py | 4 ++-- debian/changelog | 7 +++++++ doc/source/apt_pkg/cache.rst | 4 ++++ python/apt_pkgmodule.cc | 4 ++++ python/tag.cc | 47 +++++++++++++++++++++++++++++--------------- 6 files changed, 53 insertions(+), 23 deletions(-) (limited to 'doc/source') diff --git a/apt/debfile.py b/apt/debfile.py index 0406a250..8d4f534c 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -463,18 +463,18 @@ class DscSrcPackage(DebPackage): try: while tagfile.Step() == 1: for tag in depends_tags: - if not sec.has_key(tag): + if not tag in sec: continue self._depends.extend(apt_pkg.ParseSrcDepends(sec[tag])) for tag in conflicts_tags: - if not sec.has_key(tag): + if not tag in sec: continue self._conflicts.extend(apt_pkg.ParseSrcDepends(sec[tag])) - if sec.has_key('Source'): + if 'Source' in sec: self.pkgname = sec['Source'] - if sec.has_key('Binary'): + if 'Binary' in sec: self.binaries = sec['Binary'].split(', ') - if sec.has_key('Version'): + if 'Version' in sec: self._sections['Version'] = sec['Version'] finally: del sec diff --git a/apt/package.py b/apt/package.py index ec88a456..e308da4b 100644 --- a/apt/package.py +++ b/apt/package.py @@ -157,7 +157,7 @@ class Record(object): return self._rec[key] def __contains__(self, key): - return self._rec.has_key(key) + return key in self._rec def __iter__(self): return iter(self._rec.keys()) @@ -176,7 +176,7 @@ class Record(object): def has_key(self, key): """deprecated form of 'key in x'.""" - return self._rec.has_key(key) + return key in self._rec class Version(object): diff --git a/debian/changelog b/debian/changelog index 83b00150..f623254e 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,10 @@ +python-apt (0.7.11) UNRELEASED; urgency=low + + * python/tag.cc: + - Support 'key in mapping' for TagSections + + -- Julian Andres Klode Mon, 13 Apr 2009 18:08:10 +0200 + python-apt (0.7.10.3) unstable; urgency=low * apt/package.py: Handle cases where no candidate is available, by returning diff --git a/doc/source/apt_pkg/cache.rst b/doc/source/apt_pkg/cache.rst index af67d82f..146c2c2a 100644 --- a/doc/source/apt_pkg/cache.rst +++ b/doc/source/apt_pkg/cache.rst @@ -1199,6 +1199,10 @@ broken dependencies: Return the value of the field at *key*. If *key* is not available, raise :exc:`KeyError`. + .. describe:: key in section + + Return ``True`` if *section* has a key *key*, else ``False``. + .. method:: Bytes The number of bytes in the section. diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 86732781..34669fd5 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -472,6 +472,10 @@ static void AddInt(PyObject *Dict,const char *Itm,unsigned long I) extern "C" void initapt_pkg() { + // Finalize our types to add slots, etc. + if (PyType_Ready(&TagSecType) == -1) return; + + // Initialize the module PyObject *Module = Py_InitModule("apt_pkg",methods); PyObject *Dict = PyModule_GetDict(Module); diff --git a/python/tag.cc b/python/tag.cc index 217be290..cab32370 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -174,6 +174,16 @@ static PyObject *TagSecExists(PyObject *Self,PyObject *Args) return Py_BuildValue("i",1); } +static int TagSecContains(PyObject *Self,PyObject *Arg) +{ + char *Name = PyString_AsString(Arg); + const char *Start; + const char *Stop; + if (GetCpp(Self).Find(Name,Start,Stop) == false) + return 0; + return 1; +} + static char *doc_Bytes = "Bytes() -> integer"; static PyObject *TagSecBytes(PyObject *Self,PyObject *Args) { @@ -365,36 +375,41 @@ static PyMethodDef TagSecMethods[] = {} }; -// TagSecGetAttr - Get an attribute - variable/method /*{{{*/ -// --------------------------------------------------------------------- -/* */ -static PyObject *TagSecGetAttr(PyObject *Self,char *Name) -{ - return Py_FindMethod(TagSecMethods,Self,Name); -} - /*}}}*/ -// Type for a Tag Section + +PySequenceMethods TagSecSeqMeth = {0,0,0,0,0,0,0,TagSecContains,0,0}; PyMappingMethods TagSecMapMeth = {TagSecLength,TagSecMap,0}; PyTypeObject TagSecType = { PyObject_HEAD_INIT(&PyType_Type) - 0, // ob_size - "TagSection", // tp_name + 0, // ob_size + "TagSection", // tp_name sizeof(TagSecData), // tp_basicsize 0, // tp_itemsize // Methods TagSecFree, // tp_dealloc - 0, // tp_print - TagSecGetAttr, // tp_getattr + 0, // tp_print + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number - 0, // tp_as_sequence + &TagSecSeqMeth, // tp_as_sequence &TagSecMapMeth, // tp_as_mapping 0, // tp_hash - 0, // tp_call - TagSecStr, // tp_str + 0, // tp_call + TagSecStr, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "TagSection Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + TagSecMethods // tp_methods }; // Method table for the Tag File object -- cgit v1.2.3 From ccd98916ba50c7583f354e0d3487ffb0830103f0 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Apr 2009 20:00:09 +0200 Subject: * python/configuration.cc: Support the 'in' operator for Configuration Support the replacement of mapping.has_key() for Configuration,ConfigurationPtr and ConfigurationSub objects. This is implemented by extending the various types with the tp_as_sequence slot, which refers to a PySequenceMethods containing only this method. The CnfGetAttr() function has been removed and replaced by the use of the tp_method slot. This helps the py3k port because the previously used Py_FindMethod() is not avilable anymore. This completes the support of the 'in' operator in all python-apt objects, which makes it even easier to convert python-apt-using applications to py3k once python-apt supports it, as 2to3 converts 'm.has_key(k)' to 'k in m'. Also finalize the types in apt_pkgmodule.cc and add the new 'key in conf' description to the documentation. --- debian/changelog | 4 +-- doc/source/apt_pkg/cache.rst | 4 +++ python/apt_pkgmodule.cc | 3 ++ python/configuration.cc | 70 ++++++++++++++++++++++++++++++++++---------- 4 files changed, 64 insertions(+), 17 deletions(-) (limited to 'doc/source') diff --git a/debian/changelog b/debian/changelog index 29927989..261ff7bd 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,7 +1,7 @@ python-apt (0.7.11) UNRELEASED; urgency=low - * python/tag.cc: - - Support 'key in mapping' for TagSections + * Support the 'in' operator (e.g. "k in d") in Configuration{,Ptr,Sub} + objects (e.g. apt_pkg.Config) and in TagSections (apt_pkg.ParseSection()) * Replace support for file objects with a more generic support for any object providing a fileno() method and for file descriptors (integers). * Add support for the Breaks fields diff --git a/doc/source/apt_pkg/cache.rst b/doc/source/apt_pkg/cache.rst index 146c2c2a..3ecbf069 100644 --- a/doc/source/apt_pkg/cache.rst +++ b/doc/source/apt_pkg/cache.rst @@ -117,6 +117,10 @@ Classes in apt_pkg The Configuration objects store the configuration of apt. + .. describe:: key in conf + + Return ``True`` if *conf* has a key *key*, else ``False``. + .. describe:: conf[key] Return the value of the option given key *key*. If it does not diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 10d98911..3d043179 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -475,6 +475,9 @@ extern "C" void initapt_pkg() // Finalize our types to add slots, etc. if (PyType_Ready(&TagSecType) == -1) return; if (PyType_Ready(&TagFileType) == -1) return; + if (PyType_Ready(&ConfigurationType) == -1) return; + if (PyType_Ready(&ConfigurationPtrType) == -1) return; + if (PyType_Ready(&ConfigurationSubType) == -1) return; // Initialize the module PyObject *Module = Py_InitModule("apt_pkg",methods); diff --git a/python/configuration.cc b/python/configuration.cc index 21f70bc1..a95ac029 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -128,6 +128,11 @@ static PyObject *CnfExists(PyObject *Self,PyObject *Args) return Py_BuildValue("i",(int)GetSelf(Self).Exists(Name)); } +static int CnfContains(PyObject *Self,PyObject *Arg) +{ + return (int)GetSelf(Self).Exists(PyString_AsString(Arg)); +} + static char *doc_Clear = "Clear(Name) -> None"; static PyObject *CnfClear(PyObject *Self,PyObject *Args) { @@ -470,34 +475,41 @@ static PyMethodDef CnfMethods[] = {} }; -// CnfGetAttr - Get an attribute - variable/method /*{{{*/ -// --------------------------------------------------------------------- -/* */ -static PyObject *CnfGetAttr(PyObject *Self,char *Name) -{ - return Py_FindMethod(CnfMethods,Self,Name); -} - // Type for a Normal Configuration object +static PySequenceMethods ConfigurationSeq = {0,0,0,0,0,0,0,CnfContains,0,0}; static PyMappingMethods ConfigurationMap = {0,CnfMap,CnfMapSet}; PyTypeObject ConfigurationType = { PyObject_HEAD_INIT(&PyType_Type) - 0, // ob_size + 0, // ob_size "Configuration", // tp_name sizeof(CppPyObject), // tp_basicsize 0, // tp_itemsize // Methods CppDealloc, // tp_dealloc 0, // tp_print - CnfGetAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number - 0, // tp_as_sequence + &ConfigurationSeq, // tp_as_sequence &ConfigurationMap, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "Configuration Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + CnfMethods, // tp_methods }; PyTypeObject ConfigurationPtrType = @@ -510,14 +522,28 @@ PyTypeObject ConfigurationPtrType = // Methods (destructor)PyObject_Free, // tp_dealloc 0, // tp_print - CnfGetAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number - 0, // tp_as_sequence + &ConfigurationSeq, // tp_as_sequence &ConfigurationMap, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "ConfigurationPtr Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + CnfMethods, // tp_methods }; PyTypeObject ConfigurationSubType = @@ -530,13 +556,27 @@ PyTypeObject ConfigurationSubType = // Methods CnfSubFree, // tp_dealloc 0, // tp_print - CnfGetAttr, // tp_getattr + 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number - 0, // tp_as_sequence + &ConfigurationSeq, // tp_as_sequence &ConfigurationMap, // tp_as_mapping 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "ConfigurationSub Object", // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + CnfMethods, // tp_methods }; -- cgit v1.2.3 From 8d59817045630f8cf695f9673bde484727189a49 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Apr 2009 20:19:03 +0200 Subject: * doc/source/apt_pkg/cache.rst: Add .. versionadded:: 0.7.11 to the documentation --- doc/source/apt_pkg/cache.rst | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'doc/source') diff --git a/doc/source/apt_pkg/cache.rst b/doc/source/apt_pkg/cache.rst index 3ecbf069..93f8dc2d 100644 --- a/doc/source/apt_pkg/cache.rst +++ b/doc/source/apt_pkg/cache.rst @@ -121,6 +121,8 @@ Classes in apt_pkg Return ``True`` if *conf* has a key *key*, else ``False``. + .. versionadded:: 0.7.11 + .. describe:: conf[key] Return the value of the option given key *key*. If it does not @@ -1207,6 +1209,8 @@ broken dependencies: Return ``True`` if *section* has a key *key*, else ``False``. + .. versionadded:: 0.7.11 + .. method:: Bytes The number of bytes in the section. -- cgit v1.2.3 From ae7f143f8162d10c7bd834e8877e42674fdb646f Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Apr 2009 22:37:20 +0200 Subject: * doc: Documentation updates Extended the documentation, renamed 'Coding for python-apt' to 'Contributing to python-apt' and other stuff. --- apt/package.py | 221 +++++++++++++++++++++++++++------------- doc/source/apt_inst.rst | 40 ++++++-- doc/source/apt_pkg/cache.rst | 4 + doc/source/apt_pkg/index.rst | 233 ++++++++++++++++++++++++++++++++++--------- doc/source/coding.rst | 168 ------------------------------- doc/source/contributing.rst | 160 +++++++++++++++++++++++++++++ doc/source/index.rst | 2 +- 7 files changed, 535 insertions(+), 293 deletions(-) delete mode 100644 doc/source/coding.rst create mode 100644 doc/source/contributing.rst (limited to 'doc/source') diff --git a/apt/package.py b/apt/package.py index e308da4b..5adef15c 100644 --- a/apt/package.py +++ b/apt/package.py @@ -42,7 +42,7 @@ def _(string): def _file_is_same(path, size, md5): - """Return True if the file is the same.""" + """Return ``True`` if the file is the same.""" if (os.path.exists(path) and os.path.getsize(path) == size and apt_pkg.md5sum(open(path)) == md5): return True @@ -96,7 +96,7 @@ class DeprecatedProperty(property): def __init__(self, fget=None, fset=None, fdel=None, doc=None): property.__init__(self, fget, fset, fdel, doc) - self.__doc__ = ':Deprecated: ' + (doc or fget.__doc__ or '') + self.__doc__ = (doc or fget.__doc__ or '') def __get__(self, obj, type=None): if obj is not None: @@ -168,21 +168,21 @@ class Record(object): yield key, self._rec[key] def get(self, key, default=None): - """Return record[key] if key in record, else `default`. + """Return record[key] if key in record, else *default*. - The parameter `default` must be either a string or None. + The parameter *default* must be either a string or None. """ return self._rec.get(key, default) def has_key(self, key): - """deprecated form of 'key in x'.""" + """deprecated form of ``key in x``.""" return key in self._rec class Version(object): """Representation of a package version. - :since: 0.7.9 + .. versionadded:: 0.7.9 """ def __init__(self, package, cand): @@ -352,26 +352,41 @@ class Version(object): @property def filename(self): - """Return the path to the file inside the archive.""" + """Return the path to the file inside the archive. + + .. versionadded:: 0.7.10 + """ return self._records.FileName @property def md5(self): - """Return the md5sum of the binary.""" + """Return the md5sum of the binary. + + .. versionadded:: 0.7.10 + """ return self._records.MD5Hash @property def sha1(self): - """Return the sha1sum of the binary.""" + """Return the sha1sum of the binary. + + .. versionadded:: 0.7.10 + """ return self._records.SHA1Hash @property def sha256(self): - """Return the sha1sum of the binary.""" + """Return the sha256sum of the binary. + + .. versionadded:: 0.7.10 + """ return self._records.SHA256Hash def _uris(self): - """Return an iterator over all available urls.""" + """Return an iterator over all available urls. + + .. versionadded:: 0.7.10 + """ for (packagefile, index) in self._cand.FileList: indexfile = self.package._pcache._list.FindIndex(packagefile) if indexfile: @@ -379,23 +394,31 @@ class Version(object): @property def uris(self): - """Return a list of all available uris for the binary.""" + """Return a list of all available uris for the binary. + + .. versionadded:: 0.7.10 + """ return list(self._uris()) @property def uri(self): - """Return a single URI for the binary.""" + """Return a single URI for the binary. + + .. versionadded:: 0.7.10 + """ return self._uris().next() def fetch_binary(self, destdir='', progress=None): """Fetch the binary version of the package. - The parameter 'destdir' specifies the directory where the package will + The parameter *destdir* specifies the directory where the package will be fetched to. - The parameter 'progress' may refer to an apt.progress.FetchProgress() + The parameter *progress* may refer to an apt.progress.FetchProgress() object. If not specified or None, apt.progress.TextFetchProgress() is used. + + .. versionadded:: 0.7.10 """ base = os.path.basename(self._records.FileName) destfile = os.path.join(destdir, base) @@ -415,18 +438,18 @@ class Version(object): def fetch_source(self, destdir="", progress=None, unpack=True): """Get the source code of a package. - The parameter 'destdir' specifies the directory where the source will + The parameter *destdir* specifies the directory where the source will be fetched to. - The parameter 'progress' may refer to an apt.progress.FetchProgress() + The parameter *progress* may refer to an apt.progress.FetchProgress() object. If not specified or None, apt.progress.TextFetchProgress() is used. - The parameter 'unpack' describes whether the source should be unpacked - (True) or not (False). By default, it is unpacked. + The parameter *unpack* describes whether the source should be unpacked + (``True``) or not (``False``). By default, it is unpacked. - If 'unpack' is True, the path to the extracted directory is returned. - Otherwise, the path to the .dsc file is returned. + If *unpack* is ``True``, the path to the extracted directory is + returned. Otherwise, the path to the .dsc file is returned. """ src = apt_pkg.GetPkgSrcRecords() acq = apt_pkg.GetAcquire(progress or apt.progress.TextFetchProgress()) @@ -490,7 +513,8 @@ class Package(object): def candidate(self): """Return the candidate version of the package. - :since: 0.7.9""" + .. versionadded:: 0.7.9 + """ cand = self._pcache._depcache.GetCandidateVer(self._pkg) if cand is not None: return Version(self, cand) @@ -499,7 +523,8 @@ class Package(object): def installed(self): """Return the currently installed version of the package. - :since: 0.7.9""" + .. versionadded:: 0.7.9 + """ if self._pkg.CurrentVer is not None: return Version(self, self._pkg.CurrentVer) @@ -525,42 +550,62 @@ class Package(object): def installedVersion(self): """Return the installed version as string. - Deprecated, please use installed.version instead.""" + .. deprecated:: 0.7.9""" return getattr(self.installed, 'version', None) @DeprecatedProperty def candidateVersion(self): - """Return the candidate version as string.""" + """Return the candidate version as string. + + .. deprecated:: 0.7.9""" return getattr(self.candidate, "version", None) @DeprecatedProperty def candidateDependencies(self): - """Return a list of candidate dependencies.""" + """Return a list of candidate dependencies. + + .. deprecated:: 0.7.9 + """ return getattr(self.candidate, "dependencies", None) @DeprecatedProperty def installedDependencies(self): - """Return a list of installed dependencies.""" + """Return a list of installed dependencies. + + .. deprecated:: 0.7.9 + """ return getattr(self.installed, 'dependencies', []) @DeprecatedProperty def architecture(self): - """Return the Architecture of the package""" + """Return the Architecture of the package. + + .. deprecated:: 0.7.9 + """ return getattr(self.candidate, "architecture", None) @DeprecatedProperty def candidateDownloadable(self): - """Return True if the candidate is downloadable.""" + """Return ``True`` if the candidate is downloadable. + + .. deprecated:: 0.7.9 + """ return getattr(self.candidate, "downloadable", None) @DeprecatedProperty def installedDownloadable(self): - """Return True if the installed version is downloadable.""" + """Return ``True`` if the installed version is downloadable. + + .. deprecated:: 0.7.9 + """ return getattr(self.installed, 'downloadable', False) @DeprecatedProperty def sourcePackageName(self): - """Return the source package name as string.""" + """Return the source package name as string. + + .. deprecated:: 0.7.9 + """ try: return self.candidate._records.SourcePkg or self._pkg.Name except AttributeError: @@ -571,7 +616,10 @@ class Package(object): @DeprecatedProperty def homepage(self): - """Return the homepage field as string.""" + """Return the homepage field as string. + + .. deprecated:: 0.7.9 + """ return getattr(self.candidate, "homepage", None) @property @@ -581,17 +629,27 @@ class Package(object): @DeprecatedProperty def priority(self): - """Return the priority (of the candidate version).""" + """Return the priority (of the candidate version). + + .. deprecated:: 0.7.9 + """ return getattr(self.candidate, "priority", None) @DeprecatedProperty def installedPriority(self): - """Return the priority (of the installed version).""" + """Return the priority (of the installed version). + + + .. deprecated:: 0.7.9 + """ return getattr(self.installed, 'priority', None) @DeprecatedProperty def summary(self): - """Return the short description (one line summary).""" + """Return the short description (one line summary). + + .. deprecated:: 0.7.9 + """ return getattr(self.candidate, "summary", None) @DeprecatedProperty @@ -602,44 +660,52 @@ class Package(object): (Chapter 5.6.13). See http://www.debian.org/doc/debian-policy/ch-controlfields.html for more information. + + .. deprecated:: 0.7.9 """ return getattr(self.candidate, "description", None) @DeprecatedProperty def rawDescription(self): - """return the long description (raw).""" + """return the long description (raw). + + .. deprecated:: 0.7.9""" return getattr(self.candidate, "raw_description", None) @DeprecatedProperty def candidateRecord(self): - """Return the Record of the candidate version of the package.""" + """Return the Record of the candidate version of the package. + + .. deprecated:: 0.7.9""" return getattr(self.candidate, "record", None) @DeprecatedProperty def installedRecord(self): - """Return the Record of the candidate version of the package.""" + """Return the Record of the candidate version of the package. + + .. deprecated:: 0.7.9""" return getattr(self.installed, 'record', '') # depcache states @property def markedInstall(self): - """Return True if the package is marked for install.""" + """Return ``True`` if the package is marked for install.""" return self._pcache._depcache.MarkedInstall(self._pkg) @property def markedUpgrade(self): - """Return True if the package is marked for upgrade.""" + """Return ``True`` if the package is marked for upgrade.""" return self._pcache._depcache.MarkedUpgrade(self._pkg) @property def markedDelete(self): - """Return True if the package is marked for delete.""" + """Return ``True`` if the package is marked for delete.""" return self._pcache._depcache.MarkedDelete(self._pkg) @property def markedKeep(self): - """Return True if the package is marked for keep.""" + """Return ``True`` if the package is marked for keep.""" return self._pcache._depcache.MarkedKeep(self._pkg) @property @@ -649,23 +715,23 @@ class Package(object): @property def markedReinstall(self): - """Return True if the package is marked for reinstall.""" + """Return ``True`` if the package is marked for reinstall.""" return self._pcache._depcache.MarkedReinstall(self._pkg) @property def isInstalled(self): - """Return True if the package is installed.""" + """Return ``True`` if the package is installed.""" return (self._pkg.CurrentVer is not None) @property def isUpgradable(self): - """Return True if the package is upgradable.""" + """Return ``True`` if the package is upgradable.""" return (self.isInstalled and self._pcache._depcache.IsUpgradable(self._pkg)) @property def isAutoRemovable(self): - """Return True if the package is no longer required. + """Return ``True`` if the package is no longer required. If the package has been installed automatically as a dependency of another package, and if no packages depend on it anymore, the package @@ -677,22 +743,35 @@ class Package(object): @DeprecatedProperty def packageSize(self): - """Return the size of the candidate deb package.""" + """Return the size of the candidate deb package. + + .. deprecated:: 0.7.9 + """ return getattr(self.candidate, "size", None) @DeprecatedProperty def installedPackageSize(self): - """Return the size of the installed deb package.""" + """Return the size of the installed deb package. + + .. deprecated:: 0.7.9 + """ return getattr(self.installed, 'size', 0) @DeprecatedProperty def candidateInstalledSize(self): - """Return the size of the candidate installed package.""" + """Return the size of the candidate installed package. + + .. deprecated:: 0.7.9 + """ return getattr(self.candidate, "installed_size", None) @DeprecatedProperty def installedSize(self): - """Return the size of the currently installed package.""" + """Return the size of the currently installed package. + + + .. deprecated:: 0.7.9 + """ return getattr(self.installed, 'installed_size', 0) @property @@ -717,15 +796,16 @@ class Package(object): Download the changelog of the package and return it as unicode string. - The parameter `uri` refers to the uri of the changelog file. It may + The parameter *uri* refers to the uri of the changelog file. It may contain multiple named variables which will be substitued. These variables are (src_section, prefix, src_pkg, src_ver). An example is - the Ubuntu changelog: + the Ubuntu changelog:: + "http://changelogs.ubuntu.com/changelogs/pool" \\ "/%(src_section)s/%(prefix)s/%(src_pkg)s" \\ "/%(src_pkg)s_%(src_ver)s/changelog" - The parameter `cancel_lock` refers to an instance of threading.Lock, + The parameter *cancel_lock* refers to an instance of threading.Lock, which if set, prevents the download. """ # Return a cached changelog if available @@ -866,14 +946,17 @@ class Package(object): @DeprecatedProperty def candidateOrigin(self): - """Return a list of Origin() objects for the candidate version.""" + """Return a list of `Origin()` objects for the candidate version. + + .. deprecated:: 0.7.9 + """ return getattr(self.candidate, "origins", None) @property def versions(self): """Return a list of versions. - :since: 0.7.9 + .. versionadded:: 0.7.9 """ return [Version(self, ver) for ver in self._pkg.VersionList] @@ -888,11 +971,11 @@ class Package(object): def markDelete(self, autoFix=True, purge=False): """Mark a package for install. - If autoFix is True, the resolver will be run, trying to fix broken - packages. This is the default. + If *autoFix* is ``True``, the resolver will be run, trying to fix + broken packages. This is the default. - If purge is True, remove the configuration files of the package as - well. The default is to keep the configuration. + If *purge* is ``True``, remove the configuration files of the package + as well. The default is to keep the configuration. """ self._pcache.cachePreChange() self._pcache._depcache.MarkDelete(self._pkg, purge) @@ -909,16 +992,16 @@ class Package(object): def markInstall(self, autoFix=True, autoInst=True, fromUser=True): """Mark a package for install. - If autoFix is True, the resolver will be run, trying to fix broken - packages. This is the default. + If *autoFix* is ``True``, the resolver will be run, trying to fix + broken packages. This is the default. - If autoInst is True, the dependencies of the packages will be installed - automatically. This is the default. + If *autoInst* is ``True``, the dependencies of the packages will be + installed automatically. This is the default. - If fromUser is True, this package will not be marked as automatically - installed. This is the default. Set it to False if you want to be able - to remove the package at a later stage if no other package depends on - it. + If *fromUser* is ``True``, this package will not be marked as + automatically installed. This is the default. Set it to False if you + want to be able to automatically remove the package at a later stage + when no other package depends on it. """ self._pcache.cachePreChange() self._pcache._depcache.MarkInstall(self._pkg, autoInst, fromUser) @@ -942,10 +1025,10 @@ class Package(object): def commit(self, fprogress, iprogress): """Commit the changes. - The parameter `fprogress` refers to a FetchProgress() object, as + The parameter *fprogress* refers to a FetchProgress() object, as found in apt.progress. - The parameter `iprogress` refers to an InstallProgress() object, as + The parameter *iprogress* refers to an InstallProgress() object, as found in apt.progress. """ self._pcache._depcache.Commit(fprogress, iprogress) diff --git a/doc/source/apt_inst.rst b/doc/source/apt_inst.rst index 97705f61..999d074e 100644 --- a/doc/source/apt_inst.rst +++ b/doc/source/apt_inst.rst @@ -11,7 +11,12 @@ Checking packages .. function:: arCheckMember(file, membername) Check if the member specified by the parameter *membername* exists in - the AR file referenced by the :class:`file` object *file*. + the AR file referenced by the parameter *file*, which may be a + :class:`file()` object, a file descriptor, or anything implementing a + :meth:`fileno` method. + + .. versionchanged:: 0.7.11 + Added support for file descriptors and objects implementing a :meth:`fileno` method. Listing contents @@ -19,8 +24,9 @@ Listing contents .. function:: debExtract(file, func, chunk) Call the function referenced by *func* for each member of the tar file - *chunk* which is contained in the AR file referenced by the file object - *file*. + *chunk* which is contained in the AR file referenced by the parameter + *file*, which may be a :class:`file()` object, a file descriptor, or + anything implementing a :meth:`fileno` method. An example would be:: @@ -28,12 +34,21 @@ Listing contents See :ref:`emulating-dpkg-contents` for a more detailed example. + .. versionchanged:: 0.7.11 + Added support for file descriptors and objects implementing a :meth:`fileno` method. + .. function:: tarExtract(file,func,comp) Call the function *func* for each member of the tar file *file*. - *Comp* is a string determining the compressor used. Possible options are - "lzma", "bzip2" and "gzip". + The parameter *comp* is a string determining the compressor used. Possible + options are "lzma", "bzip2" and "gzip". + + The parameter *file* may be a :class:`file()` object, a file descriptor, or + anything implementing a :meth:`fileno` method. + + .. versionchanged:: 0.7.11 + Added support for file descriptors and objects implementing a :meth:`fileno` method. Callback @@ -56,6 +71,9 @@ Extracting contents Extract the archive referenced by the :class:`file` object *file* into the directory specified by *rootdir*. + The parameter *file* may be a :class:`file()` object, a file descriptor, or + anything implementing a :meth:`fileno` method. + See :ref:`emulating-dpkg-extract` for an example. .. warning:: @@ -63,16 +81,24 @@ Extracting contents If the directory given by *rootdir* does not exist, the package is extracted into the current directory. + .. versionchanged:: 0.7.11 + Added support for file descriptors and objects implementing a :meth:`fileno` method. + .. function:: debExtractControl(file[, member='control']) - Return the indicated file from the control tar. The default is 'control'. + Return the indicated file as a string from the control tar. The default + is 'control'. + + The parameter *file* may be a :class:`file()` object, a file descriptor, or + anything implementing a :meth:`fileno` method. If you want to print the control file of a given package, you could do something like:: print debExtractControl(open("package.deb")) - :return: The contents of the file, as :class:`str`. + .. versionchanged:: 0.7.11 + Added support for file descriptors and objects implementing a :meth:`fileno` method. .. _emulating-dpkg-extract: diff --git a/doc/source/apt_pkg/cache.rst b/doc/source/apt_pkg/cache.rst index 93f8dc2d..86515569 100644 --- a/doc/source/apt_pkg/cache.rst +++ b/doc/source/apt_pkg/cache.rst @@ -207,6 +207,8 @@ Classes in apt_pkg Return whether the configuration contains the key *key*. + .. deprecated:: 0.7.11 + .. method:: get(key[, default='']) This behaves just like :meth:`dict.get` and :meth:`Configuration.Find`, @@ -1234,6 +1236,8 @@ broken dependencies: Check whether the field with named by *key* exists. + .. deprecated:: 0.7.11 + .. method:: keys() Return a list of keys in the section. diff --git a/doc/source/apt_pkg/index.rst b/doc/source/apt_pkg/index.rst index 6e7b772e..38310bb5 100644 --- a/doc/source/apt_pkg/index.rst +++ b/doc/source/apt_pkg/index.rst @@ -17,6 +17,8 @@ the beginning. Module Initialization --------------------- +Initialization is needed for most functions, but not for all of them. Some can +be called without having run init*(), but will not return the expected value. .. function:: initConfig @@ -89,9 +91,6 @@ Object initialization Return a new :class:`PkgSrcRecords` object. -.. function:: newConfiguration() - - Return a new :class:`Configuration` object. The Acquire interface @@ -164,46 +163,197 @@ of the ones provides in Python's :mod:`hashlib` module. Return the md5sum of the object. *object* may either be a string, in which case the md5sum of the string is returned, or a :class:`file()` - object, in which case the md5sum of its contents is returned. + object (or a file descriptor), in which case the md5sum of its contents is + returned. + + .. versionchanged:: 0.7.11 + Added support for using file descriptors. .. function:: sha1sum(object) Return the sha1sum of the object. *object* may either be a string, in which case the sha1sum of the string is returned, or a :class:`file()` - object, in which case the sha1sum of its contents is returned. + object (or a file descriptor), in which case the sha1sum of its contents + is returned. + + .. versionchanged:: 0.7.11 + Added support for using file descriptors. .. function:: sha256sum(object) Return the sha256sum of the object. *object* may either be a string, in which case the sha256sum of the string is returned, or a :class:`file()` - object, in which case the sha256sum of its contents is returned. + object (or a file descriptor), in which case the sha256sum of its contents + is returned. + + .. versionchanged:: 0.7.11 + Added support for using file descriptors. + +Debian control files +-------------------- +.. function:: ParseSection(text) + + Parse the string given in the parameter *text* and return a + :class:`TagSection` object. + +.. function:: ParseTagFile(file) + + Parse the given *file* and return a :class:`TagFile()` object. *file* may + be a :class:`file()` object, a file descriptor, or anything providing a + :meth:`fileno()` method. + + .. versionchanged:: 0.7.11 + Added support for using file descriptors. + +.. autofunction:: RewriteSection(section, order, rewrite_list) + +.. data:: RewritePackageOrder + + The order in which the information for binary packages should be rewritten, + i.e. the order in which the fields should appear. + +.. data:: RewriteSourceOrder + + The order in which the information for source packages should be rewritten, + i.e. the order in which the fields should appear. + +Dependencies +------------ +.. function:: CheckDep(pkgver, op, depver) + + Check that the dependency requirements consisting of op and depver can be + satisfied by the version pkgver. + + Example:: + + >>> bool(apt_pkg.CheckDep("1.0", ">=", "1")) + True + +.. function:: ParseDepends(depends) + + Parse the string *depends* which contains dependency information as + specified in Debian Policy, Section 7.1. + + Returns a list. The members of this list are lists themselves and contain + one or more tuples in the format ``(package,version,operation)`` for every + 'or'-option given, e.g.:: + + >>> apt_pkg.ParseDepends("PkgA (>= VerA) | PkgB (>= VerB)") + [[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]] + +.. function:: ParseSrcDepends(depends) + + Parse the string *depends* which contains dependency information as + specified in Debian Policy, Section 7.1. + + Returns a list. The members of this list are lists themselves and contain + one or more tuples in the format ``(package,version,operation)`` for every + 'or'-option given, e.g.:: + + >>> apt_pkg.ParseDepends("PkgA (>= VerA) | PkgB (>= VerB)") + [[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]] + + + Furthemore, this function also supports to limit the architectures, as + used in e.g. Build-Depends:: + + >>> apt_pkg.ParseSrcDepends("a (>= 01) [i386 amd64]") + [[('a', '01', '>=')]] + + +Configuration +------------- + +.. data:: Config + + A :class:`Configuration()`-like object with the default configuration. This + is implemented in the :class:`ConfigurationPtr` class, which has the same + API like the :class:`Configuration` class. + +.. function:: newConfiguration() + + Return a new :class:`Configuration` object. + +.. function:: ReadConfigFile(configuration, filename) + + Read the configuration file specified by the parameter *filename* and add + the settings therein to the :class:`Configuration()` object specified by + the parameter *configuration* + +.. function:: ReadConfigDir(configuration, dirname) + + Read configuration files in the directory specified by the parameter + *dirname* and add the settings therein to the :class:`Configuration()` + object specified by the parameter *configuration*. + +.. function:: ReadConfigFileISC(configuration, filename) + + Read the configuration file specified by the parameter *filename* and add + the settings therein to the :class:`Configuration()` object specified by + the parameter *configuration* + +.. function:: ParseCommandLine(configuration,options,argv) + + This function is like getopt except it manipulates a configuration space. + output is a list of non-option arguments (filenames, etc). *options* is a + list of tuples of the form ``(‘c’,”long-opt or None”, + ”Configuration::Variable”,”optional type”)``. + + Where ``type`` may be one of HasArg, IntLevel, Boolean, InvBoolean, + ConfigFile, or ArbItem. The default is Boolean. + +Locking +-------- + +.. function:: GetLock(filename) + + Create an empty file at the path specified by the parameter *filename* and + lock it. + + While the file is locked by a process, calling this function in another + process returns ``-1``. + + When the lock is not required anymore, the file descriptor should be closed + using :func:`os.close`. + +.. function:: PkgSystemLock() + + Lock the global pkgsystem. + +.. function:: PkgSystemUnLock() + + Unlock the global pkgsystem. Other functions ---------------- +.. function:: Base64Encode(string) + + Encode the given string using base64, e.g:: + + >>> apt_pkg.Base64Encode(u"A") + 'QQ==' -.. note:: - - This documentation is (in parts) created automatically, and still needs to - be improved. - -.. autofunction:: Base64Encode -.. autofunction:: CheckDep -.. autofunction:: CheckDomainList -.. autofunction:: DeQuoteString -.. autofunction:: GetLock - -.. autofunction:: ParseCommandLine -.. autofunction:: ParseDepends -.. autofunction:: ParseSection -.. autofunction:: ParseSrcDepends -.. autofunction:: ParseTagFile -.. autofunction:: PkgSystemLock -.. autofunction:: PkgSystemUnLock -.. autofunction:: QuoteString -.. autofunction:: ReadConfigFile -.. autofunction:: ReadConfigDir() -.. autofunction:: ReadConfigFileISC -.. autofunction:: RewriteSection + +.. function:: CheckDomainList(host, list) + + See if Host is in a ',' seperated list, e.g.:: + + apt_pkg.CheckDomainList("alioth.debian.org","debian.net,debian.org") + +.. function:: DeQuoteString(string) + + Dequote the string specified by the parameter *string*, e.g.:: + + >>> apt_pkg.DeQuoteString("%61%70%74%20is%20cool") + 'apt is cool' + +.. function:: QuoteString(string, repl) + + For every character listed in the string *repl*, replace all occurences in + the string *string* with the correct HTTP encoded value: + + >>> apt_pkg.QuoteString("apt is cool","apt") + '%61%70%74%20is%20cool' .. function:: SizeToStr(size) @@ -271,8 +421,6 @@ Other functions >>> apt_pkg.TimeToStr(3601) '1h0min1s' - - .. function:: UpstreamVersion(version) Return the string *version*, eliminating everything following the last @@ -305,23 +453,12 @@ Other functions ===== ============================================= -Data ------ - -.. data:: Config - - An :class:`Configuration()` object with the default configuration. Actually, - this is a bit different object, but it is compatible. - -.. data:: RewritePackageOrder - -.. data:: RewriteSourceOrder .. _CurStates: Package States -^^^^^^^^^^^^^^^ +--------------- .. data:: CurStateConfigFiles .. data:: CurStateHalfConfigured .. data:: CurStateHalfInstalled @@ -333,7 +470,7 @@ Package States Dependency types -^^^^^^^^^^^^^^^^ +---------------- .. data:: DepConflicts .. data:: DepDepends .. data:: DepObsoletes @@ -345,7 +482,7 @@ Dependency types .. _InstStates: Installed states -^^^^^^^^^^^^^^^^^ +----------------- .. data:: InstStateHold .. data:: InstStateHoldReInstReq .. data:: InstStateOk @@ -354,7 +491,7 @@ Installed states .. _Priorities: Priorities -^^^^^^^^^^ +---------- .. data:: PriExtra .. data:: PriImportant .. data:: PriOptional @@ -365,7 +502,7 @@ Priorities .. _SelStates: Select states -^^^^^^^^^^^^^^ +-------------- .. data:: SelStateDeInstall .. data:: SelStateHold .. data:: SelStateInstall @@ -374,7 +511,7 @@ Select states Build information -^^^^^^^^^^^^^^^^^ +----------------- .. data:: Date The date on which this extension has been compiled. diff --git a/doc/source/coding.rst b/doc/source/coding.rst deleted file mode 100644 index 1357ce14..00000000 --- a/doc/source/coding.rst +++ /dev/null @@ -1,168 +0,0 @@ -Coding for python-apt -====================== -Let's say you need a new feature, you can develop it, and you want to get it -included in python-apt. Then be sure to follow the following guidelines. - -Available branches -------------------- -First of all, let's talk a bit about the bzr branches of python-apt. In the -following parts, we will assume that you use bzr to create your changes and -submit them. - -**mvo:** http://people.ubuntu.com/~mvo/bzr/python-apt/mvo - This is Michael Vogt's branch. Most of the development of apt happens here, - as he is the lead maintainer of python-apt. - - This branch is also available from Launchpads super mirror, via - ``lp:python-apt``. Checkouts from Launchpad are generally faster and can - use the bzr protocoll. - - VCS-Browser: https://code.launchpad.net/~mvo/python-apt/python-apt--mvo - -**debian-sid:** http://bzr.debian.org/apt/python-apt/debian-sid - This is the official Debian branch of python-apt. All code which will be - uploaded to Debian is here. It is not as up-to-date as the mvo branch, - because this branch often gets updated just right before the release - happens. - - VCS-Browser: http://bzr.debian.org/loggerhead/apt/python-apt/debian-sid/changes - -**jak:** http://bzr.debian.org/users/jak/python-apt/jak - This is Julian Andres Klode's (the documentation author's) branch. This - is the place where cleanup and documentation updates happen. It is based - off debian-sid or mvo. - - VCS-Browser: http://bzr.debian.org/loggerhead/users/jak/python-apt/jak/changes - -**ubuntu:** ``lp:~ubuntu-core-dev/python-apt/ubuntu`` - This is the official Ubuntu development branch. The same notes apply as - for the debian-sid branch above. - - VCS-Browser: https://code.launchpad.net/~ubuntu-core-dev/python-apt/ubuntu - - -C++ Coding style ----------------- -When you work on the C++ code in the python/ directory, you should follow some -basic rules. - -The indentation of the code is a bit non-standard. We currently use 3 spaces -indentation for the C++ code. - -When you create new functions, you should follow some naming conventions. All -C++ functions are named according to the ``CamelCase`` convention. - -The resulting Python functions should be ``CamelCase`` as well in apt_pkg, or -``mixedCase`` in apt_inst. The same applies for variables, parameters, -attributes, etc. - -.. note:: - - This coding style guidelines are incomplete. If you have any questions - send an email to deity@lists.debian.org. - -.. note:: - - The coding style may be changed completely during the port to Python 3.0. - But this will not happen very soon. - - -Python Coding Style -------------------- -The coding style for all code written in python is :PEP:`8`. For modules added -from version 0.7.9 on, there are no exceptions. - -Modules introduced prior to 0.7.9 use mixedCase names for methods, functions -and variables. These names will be replaced by names conforming to :PEP:`8` -in a future release of python-apt. - -Therefore, try to reduce the introduction of the mixedName code to the absolute -minimum (sometimes you can also use shorter names). - -To prepare the port to Python 3.0, code should not use any functionality which -is deprecated as of Python 2.6. - -The has_key() functionality may be used only on TagSection objects; as they -provide no other way to do this. If someone is willing to adapt TagSection to -support ``key in mapping`` and ``iter(mapping)``, this would be great. - -.. note:: - - You can use the tool pep8.py from http://svn.browsershots.org/trunk/devtools/pep8/ - to validate your code. Please also run pylint, pychecker, and pyflakes and - fix all new **errors** they report (undefined names, etc.). - -Submitting your patch ---------------------- -First of all, the patch you create should be based against the debian-sid -branch of python-apt. - -Once you have made your change, check that it: - - * conforms to :PEP:`8` (checked with pep8.py). It should, at least not - introduce new errors. (and never have whitespace at end of line) - * produces no new errors in pychecker, pyflakes and pylint (unless you - can't fix them, but please tell so when requesting the merge, so it can - be fixed before hitting one of the main branches). - * does not change the behaviour of existing code in a non-compatible way. - -If your change follows all points of the checklist, you can commit it to your -repository. (You could commit it first, and check later, and then commit the -fixes, but commits should be logical and it makes no sense to have to commits -for one logical unit). - -Once you have made all your changes, you can run ``bzr send -o patch-name`` -to create a so called *merge-directive*, which contains your changes and -allows us to preserve the history of your changes. (But please replace patch-name -with something useful). - -Now report a bug against the python-apt package, attach the merge directive -you created in the previous step, and tag it with 'patch'. It might also be -a good idea to prefix the bug report with '[PATCH]'. - -If your patch introduces new functions, parameters, etc. , but does not update -the content of this documentation, please CC. jak@debian.org, and add a short -notice to the bug report. Also see `Documentation updates` - -Once your patch got merged, you can *pull* the branch into which it has been -merged into your local one. If you have made changes since you submitted your -patch, you may need to *merge* the branch instead. - -.. note:: - - If you plan to work on python-apt for a longer time, it may be a good - idea to publish your branch somewhere. Alioth (http://alioth.debian.org) - and Launchpad (https://launchpad.net) provide bzr hosting. You can also - use any webspace with ftp or sftp connection (for the upload). Then you do - not need to send *merge directives*, but you can point to your branch - instead. - - -Documentation updates ---------------------- -If you want to update the documentation, please follow the procedure as written -above. But please CC: jak@debian.org in the bug report. - -You can send your content in plain text, but reStructuredText is the preferred -format. I (Julian Andres Klode) will review your patch and will forward them to -Michael Vogt, for inclusion in his branch. On release, this will be merged into -the debian-sid branch. - - -Example patch session ----------------------- -In the following example, we edit a file, create a merge directive (an enhanced -patch), and report a wishlist bug with this patch against the python-apt -package:: - - user@pc:~$ bzr clone http://bzr.debian.org/apt/python-apt/debian-sid/ - user@pc:~$ cd debian-sid - user@pc:~/debian-sid$ editor FILES - user@pc:~/debian-sid$ pep8.py FILES # PEP 8 check, see above. - user@pc:~/debian-sid$ pylint -e FILES # Check with pylint - user@pc:~/debian-sid$ pyflakes FILES # Check with pyflakes - user@pc:~/debian-sid$ pychecker FILES # Check with pychecker - user@pc:~/debian-sid$ bzr commit - user@pc:~/debian-sid$ bzr send -o my-patch - user@pc:~/debian-sid$ reportbug --severity=wishlist --tag=patch --attach=my-patch python-apt - user@pc:~/debian-sid$ # Add --list-cc=jak@debian.org if you change docs. diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst new file mode 100644 index 00000000..04933b73 --- /dev/null +++ b/doc/source/contributing.rst @@ -0,0 +1,160 @@ +Contributing to python-apt +========================== +Let's say you need a new feature, you can develop it, and you want to get it +included in python-apt. Then be sure to follow the following guidelines. + +Available branches +------------------- +First of all, let's talk a bit about the bzr branches of python-apt. In the +following parts, we will assume that you use bzr to create your changes and +submit them. + +**mvo:** http://people.ubuntu.com/~mvo/bzr/python-apt/mvo + This is Michael Vogt's branch. Most of the development of apt happens here, + as he is the lead maintainer of python-apt. + + This branch is also available from Launchpads super mirror, via + ``lp:python-apt``. Checkouts from Launchpad are generally faster and can + use the bzr protocoll. + + VCS-Browser: https://code.launchpad.net/~mvo/python-apt/python-apt--mvo + +**debian-sid:** http://bzr.debian.org/apt/python-apt/debian-sid + This is the official Debian branch of python-apt. All code which will be + uploaded to Debian is here. It is not as up-to-date as the mvo branch, + because this branch often gets updated just right before the release + happens. + + VCS-Browser: http://bzr.debian.org/loggerhead/apt/python-apt/debian-sid/changes + +**jak:** http://bzr.debian.org/users/jak/python-apt/jak + This is Julian Andres Klode's (the documentation author's) branch. This + is the place where cleanup and documentation updates happen. It is based + off debian-sid or mvo. + + VCS-Browser: http://bzr.debian.org/loggerhead/users/jak/python-apt/jak/changes + +**ubuntu:** ``lp:~ubuntu-core-dev/python-apt/ubuntu`` + This is the official Ubuntu development branch. The same notes apply as + for the debian-sid branch above. + + VCS-Browser: https://code.launchpad.net/~ubuntu-core-dev/python-apt/ubuntu + + +C++ Coding style +---------------- +When you work on the C++ code in the python/ directory, you should follow some +basic rules. + +The indentation of the code is a bit non-standard. We currently use 3 spaces +indentation for the C++ code. + +When you create new functions, you should follow some naming conventions. All +C++ functions are named according to the ``CamelCase`` convention. + +The resulting Python functions should be ``CamelCase`` as well in apt_pkg, or +``mixedCase`` in apt_inst. The same applies for variables, parameters, +attributes, etc. + +.. note:: + + This coding style guidelines are incomplete. If you have any questions + send an email to deity@lists.debian.org. + + +Python Coding Style +------------------- +The coding style for all code written in python is :PEP:`8`. For modules and +classes added from version 0.7.9 on, there are no exceptions. + +Classes introduced prior to 0.7.9 use mixedCase names for methods, functions +and variables. These names will be replaced by names conforming to :PEP:`8` +in a future release of python-apt. + +Therefore, try to reduce the introduction of the mixedName code to the absolute +minimum (sometimes you can also use shorter names). + +In order to make the automatic generation of Python 3 code using 2to possible, +code written in Python may not utilize any functionality unsupported by 2to3 or +deprecated as of Python 2.6. + +.. note:: + + You can use the tool pep8.py from http://svn.browsershots.org/trunk/devtools/pep8/ + to validate your code. Please also run pylint, pychecker, and pyflakes and + fix all new **errors** they report (undefined names, etc.). + +Submitting your patch +--------------------- +First of all, the patch you create should be based against the debian-sid +branch of python-apt. + +Once you have made your change, check that it: + + * conforms to :PEP:`8` (checked with pep8.py). It should, at least not + introduce new errors. (and never have whitespace at end of line) + * produces no new errors in pychecker, pyflakes and pylint (unless you + can't fix them, but please tell so when requesting the merge, so it can + be fixed before hitting one of the main branches). + * does not change the behaviour of existing code in a non-compatible way. + +If your change follows all points of the checklist, you can commit it to your +repository. (You could commit it first, and check later, and then commit the +fixes, but commits should be logical and it makes no sense to have to commits +for one logical unit). + +Once you have made all your changes, you can run ``bzr send -o patch-name`` +to create a so called *merge-directive*, which contains your changes and +allows us to preserve the history of your changes. (But please replace patch-name +with something useful). + +Now report a bug against the python-apt package, attach the merge directive +you created in the previous step, and tag it with 'patch'. It might also be +a good idea to prefix the bug report with '[PATCH]'. + +If your patch introduces new functions, parameters, etc. , but does not update +the content of this documentation, please CC. jak@debian.org, and add a short +notice to the bug report. Also see `Documentation updates` + +Once your patch got merged, you can *pull* the branch into which it has been +merged into your local one. If you have made changes since you submitted your +patch, you may need to *merge* the branch instead. + +.. note:: + + If you plan to work on python-apt for a longer time, it may be a good + idea to publish your branch somewhere. Alioth (http://alioth.debian.org) + and Launchpad (https://launchpad.net) provide bzr hosting. You can also + use any webspace with ftp or sftp connection (for the upload). Then you do + not need to send *merge directives*, but you can point to your branch + instead. + + +Documentation updates +--------------------- +If you want to update the documentation, please follow the procedure as written +above. But please CC: jak@debian.org in the bug report. + +You can send your content in plain text, but reStructuredText is the preferred +format. I (Julian Andres Klode) will review your patch and will forward them to +Michael Vogt, for inclusion in his branch. On release, this will be merged into +the debian-sid branch. + + +Example patch session +---------------------- +In the following example, we edit a file, create a merge directive (an enhanced +patch), and report a wishlist bug with this patch against the python-apt +package:: + + user@pc:~$ bzr clone http://bzr.debian.org/apt/python-apt/debian-sid/ + user@pc:~$ cd debian-sid + user@pc:~/debian-sid$ editor FILES + user@pc:~/debian-sid$ pep8.py FILES # PEP 8 check, see above. + user@pc:~/debian-sid$ pylint -e FILES # Check with pylint + user@pc:~/debian-sid$ pyflakes FILES # Check with pyflakes + user@pc:~/debian-sid$ pychecker FILES # Check with pychecker + user@pc:~/debian-sid$ bzr commit + user@pc:~/debian-sid$ bzr send -o my-patch + user@pc:~/debian-sid$ reportbug --severity=wishlist --tag=patch --attach=my-patch python-apt + user@pc:~/debian-sid$ # Add --list-cc=jak@debian.org if you change docs. diff --git a/doc/source/index.rst b/doc/source/index.rst index 23ea4cca..930ff55c 100644 --- a/doc/source/index.rst +++ b/doc/source/index.rst @@ -24,7 +24,7 @@ Contents: apt_pkg/index apt_inst aptsources/index - coding + contributing -- cgit v1.2.3 From 8413810c46f802490280b0be1beebaaadf1aa9f2 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 14 Apr 2009 00:47:23 +0200 Subject: * Remove any trailing whitespace --- apt/package.py | 3 +-- doc/source/apt_pkg/index.rst | 2 +- python/apt_pkgmodule.cc | 2 +- python/cache.cc | 2 +- python/cdrom.cc | 6 +++--- python/configuration.cc | 18 +++++++++--------- python/depcache.cc | 12 ++++++------ python/progress.cc | 2 +- python/tag.cc | 12 ++++++------ python/tar.cc | 2 +- tests/getcache_mem_corruption.py | 6 +++--- 11 files changed, 33 insertions(+), 34 deletions(-) (limited to 'doc/source') diff --git a/apt/package.py b/apt/package.py index 5adef15c..3ea1105d 100644 --- a/apt/package.py +++ b/apt/package.py @@ -639,7 +639,6 @@ class Package(object): def installedPriority(self): """Return the priority (of the installed version). - .. deprecated:: 0.7.9 """ return getattr(self.installed, 'priority', None) @@ -800,7 +799,7 @@ class Package(object): contain multiple named variables which will be substitued. These variables are (src_section, prefix, src_pkg, src_ver). An example is the Ubuntu changelog:: - + "http://changelogs.ubuntu.com/changelogs/pool" \\ "/%(src_section)s/%(prefix)s/%(src_pkg)s" \\ "/%(src_pkg)s_%(src_ver)s/changelog" diff --git a/doc/source/apt_pkg/index.rst b/doc/source/apt_pkg/index.rst index 38310bb5..60c3ba9b 100644 --- a/doc/source/apt_pkg/index.rst +++ b/doc/source/apt_pkg/index.rst @@ -252,7 +252,7 @@ Dependencies >>> apt_pkg.ParseDepends("PkgA (>= VerA) | PkgB (>= VerB)") [[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]] - + Furthemore, this function also supports to limit the architectures, as used in e.g. Build-Depends:: diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 5d0b2c0a..145a2bab 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -481,7 +481,7 @@ extern "C" void initapt_pkg() if (PyType_Ready(&PkgCdromType) == -1) return; if (PyType_Ready(&PkgProblemResolverType) == -1) return; if (PyType_Ready(&PkgActionGroupType) == -1) return; - + // Initialize the module PyObject *Module = Py_InitModule("apt_pkg",methods); diff --git a/python/cache.cc b/python/cache.cc index 4db097c7..31d8c45d 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -951,7 +951,7 @@ PyObject *TmpGetCache(PyObject *Self,PyObject *Args) progress.setCallbackInst(pyCallbackInst); if (Cache->Open(progress,false) == false) return HandleErrors(); - } + } else { OpTextProgress Prog; if (Cache->Open(Prog,false) == false) diff --git a/python/cdrom.cc b/python/cdrom.cc index 1278d6b7..0816d93e 100644 --- a/python/cdrom.cc +++ b/python/cdrom.cc @@ -84,16 +84,16 @@ PyTypeObject PkgCdromType = 0, // tp_hash 0, // tp_call 0, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "Cdrom Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext PkgCdromMethods, // tp_methods }; diff --git a/python/configuration.cc b/python/configuration.cc index a95ac029..b4adf357 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -498,16 +498,16 @@ PyTypeObject ConfigurationType = 0, // tp_hash 0, // tp_call 0, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "Configuration Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext CnfMethods, // tp_methods }; @@ -532,16 +532,16 @@ PyTypeObject ConfigurationPtrType = 0, // tp_hash 0, // tp_call 0, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "ConfigurationPtr Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext CnfMethods, // tp_methods }; @@ -566,16 +566,16 @@ PyTypeObject ConfigurationSubType = 0, // tp_hash 0, // tp_call 0, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "ConfigurationSub Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext CnfMethods, // tp_methods }; diff --git a/python/depcache.cc b/python/depcache.cc index b23eecd9..2c73a1a9 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -769,16 +769,16 @@ PyTypeObject PkgProblemResolverType = 0, // tp_hash 0, // tp_call 0, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "ProblemResolver Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext PkgProblemResolverMethods, // tp_methods }; @@ -825,16 +825,16 @@ PyTypeObject PkgActionGroupType = 0, // tp_hash 0, // tp_call 0, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "ActionGroup Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext PkgActionGroupMethods, // tp_methods }; diff --git a/python/progress.cc b/python/progress.cc index c5a1c138..bec40ce9 100644 --- a/python/progress.cc +++ b/python/progress.cc @@ -185,7 +185,7 @@ bool PyFetchProgress::Pulse(pkgAcquire * Owner) bool res = true; if(!PyArg_Parse(result, "b", &res)) { - // most of the time the user who subclasses the pulse() + // most of the time the user who subclasses the pulse() // method forgot to add a return {True,False} so we just // assume he wants a True return true; diff --git a/python/tag.cc b/python/tag.cc index baf97b59..cdea3e03 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -401,16 +401,16 @@ PyTypeObject TagSecType = 0, // tp_hash 0, // tp_call TagSecStr, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "TagSection Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext TagSecMethods // tp_methods }; @@ -459,16 +459,16 @@ PyTypeObject TagFileType = 0, // tp_hash 0, // tp_call 0, // tp_str - 0, // tp_getattro + 0, // tp_getattro 0, // tp_setattro - 0, // tp_as_buffer + 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "TagFile Object", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter + 0, // tp_iter 0, // tp_iternext TagFileMethods, // tp_methods 0, // tp_members diff --git a/python/tar.cc b/python/tar.cc index f0d57823..217554c2 100644 --- a/python/tar.cc +++ b/python/tar.cc @@ -111,7 +111,7 @@ PyObject *tarExtract(PyObject *Self,PyObject *Args) int fileno = PyObject_AsFileDescriptor(File); if (fileno == -1) return 0; - + FileFd Fd(fileno,false); ExtractTar Tar(Fd,0xFFFFFFFF,Comp); if (_error->PendingError() == true) diff --git a/tests/getcache_mem_corruption.py b/tests/getcache_mem_corruption.py index 42e9af00..c3f6eff3 100644 --- a/tests/getcache_mem_corruption.py +++ b/tests/getcache_mem_corruption.py @@ -6,16 +6,16 @@ import re import unittest class TestGetCache(unittest.TestCase): - + def setUp(self): apt_pkg.InitConfig() apt_pkg.InitSystem() - + def testWrongInvocation(self): # wrongly invoke GetCache() rather than GetDepCache() apt_cache = apt_pkg.GetCache() self.assertRaises(ValueError, apt_pkg.GetCache, apt_cache) - + def testProperInvocation(self): apt_cache = apt_pkg.GetCache(apt.progress.OpTextProgress()) apt_depcache = apt_pkg.GetDepCache(apt_cache) -- cgit v1.2.3 From abc7c861e85265b0725aa82a51fe41f9183bc506 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 15 Apr 2009 20:23:04 +0200 Subject: * Upload as 0.7.90 to experimental This is the first pre-release of python-apt 0.8. It is completely backward compatible (even on Python 3), API changes will appear in 0.7.91. --- debian/changelog | 2 +- doc/source/apt_inst.rst | 10 +++++----- doc/source/apt_pkg/cache.rst | 8 ++++---- doc/source/apt_pkg/index.rst | 8 ++++---- 4 files changed, 14 insertions(+), 14 deletions(-) (limited to 'doc/source') diff --git a/debian/changelog b/debian/changelog index d356c3cf..b2f2b965 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,4 +1,4 @@ -python-apt (0.7.11) UNRELEASED; urgency=low +python-apt (0.7.90) experimental; urgency=low * Introduce support for Python 3 (Closes: #523645) diff --git a/doc/source/apt_inst.rst b/doc/source/apt_inst.rst index 999d074e..cd371e36 100644 --- a/doc/source/apt_inst.rst +++ b/doc/source/apt_inst.rst @@ -15,7 +15,7 @@ Checking packages :class:`file()` object, a file descriptor, or anything implementing a :meth:`fileno` method. - .. versionchanged:: 0.7.11 + .. versionchanged:: 0.8.0 Added support for file descriptors and objects implementing a :meth:`fileno` method. @@ -34,7 +34,7 @@ Listing contents See :ref:`emulating-dpkg-contents` for a more detailed example. - .. versionchanged:: 0.7.11 + .. versionchanged:: 0.8.0 Added support for file descriptors and objects implementing a :meth:`fileno` method. .. function:: tarExtract(file,func,comp) @@ -47,7 +47,7 @@ Listing contents The parameter *file* may be a :class:`file()` object, a file descriptor, or anything implementing a :meth:`fileno` method. - .. versionchanged:: 0.7.11 + .. versionchanged:: 0.8.0 Added support for file descriptors and objects implementing a :meth:`fileno` method. @@ -81,7 +81,7 @@ Extracting contents If the directory given by *rootdir* does not exist, the package is extracted into the current directory. - .. versionchanged:: 0.7.11 + .. versionchanged:: 0.8.0 Added support for file descriptors and objects implementing a :meth:`fileno` method. .. function:: debExtractControl(file[, member='control']) @@ -97,7 +97,7 @@ Extracting contents print debExtractControl(open("package.deb")) - .. versionchanged:: 0.7.11 + .. versionchanged:: 0.8.0 Added support for file descriptors and objects implementing a :meth:`fileno` method. diff --git a/doc/source/apt_pkg/cache.rst b/doc/source/apt_pkg/cache.rst index 86515569..a58f1356 100644 --- a/doc/source/apt_pkg/cache.rst +++ b/doc/source/apt_pkg/cache.rst @@ -121,7 +121,7 @@ Classes in apt_pkg Return ``True`` if *conf* has a key *key*, else ``False``. - .. versionadded:: 0.7.11 + .. versionadded:: 0.8.0 .. describe:: conf[key] @@ -207,7 +207,7 @@ Classes in apt_pkg Return whether the configuration contains the key *key*. - .. deprecated:: 0.7.11 + .. deprecated:: 0.8.0 .. method:: get(key[, default='']) @@ -1211,7 +1211,7 @@ broken dependencies: Return ``True`` if *section* has a key *key*, else ``False``. - .. versionadded:: 0.7.11 + .. versionadded:: 0.8.0 .. method:: Bytes @@ -1236,7 +1236,7 @@ broken dependencies: Check whether the field with named by *key* exists. - .. deprecated:: 0.7.11 + .. deprecated:: 0.8.0 .. method:: keys() diff --git a/doc/source/apt_pkg/index.rst b/doc/source/apt_pkg/index.rst index 60c3ba9b..47923c23 100644 --- a/doc/source/apt_pkg/index.rst +++ b/doc/source/apt_pkg/index.rst @@ -166,7 +166,7 @@ of the ones provides in Python's :mod:`hashlib` module. object (or a file descriptor), in which case the md5sum of its contents is returned. - .. versionchanged:: 0.7.11 + .. versionchanged:: 0.8.0 Added support for using file descriptors. .. function:: sha1sum(object) @@ -176,7 +176,7 @@ of the ones provides in Python's :mod:`hashlib` module. object (or a file descriptor), in which case the sha1sum of its contents is returned. - .. versionchanged:: 0.7.11 + .. versionchanged:: 0.8.0 Added support for using file descriptors. .. function:: sha256sum(object) @@ -186,7 +186,7 @@ of the ones provides in Python's :mod:`hashlib` module. object (or a file descriptor), in which case the sha256sum of its contents is returned. - .. versionchanged:: 0.7.11 + .. versionchanged:: 0.8.0 Added support for using file descriptors. Debian control files @@ -202,7 +202,7 @@ Debian control files be a :class:`file()` object, a file descriptor, or anything providing a :meth:`fileno()` method. - .. versionchanged:: 0.7.11 + .. versionchanged:: 0.8.0 Added support for using file descriptors. .. autofunction:: RewriteSection(section, order, rewrite_list) -- cgit v1.2.3 From 4bab1d0fb960a10f73cd6b313f7942d7258c8d72 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 17 Apr 2009 18:13:46 +0200 Subject: * doc: Update the documentation to use the new names. --- doc/source/apt/cache.rst | 4 ++-- doc/source/apt/package.rst | 6 +++--- doc/source/examples/apt-gtk.py | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) (limited to 'doc/source') diff --git a/doc/source/apt/cache.rst b/doc/source/apt/cache.rst index d96cba97..ddb2dc64 100644 --- a/doc/source/apt/cache.rst +++ b/doc/source/apt/cache.rst @@ -66,8 +66,8 @@ packages whose state has been changed, eg. packages marked for installation:: >>> from apt.cache import FilteredCache, Cache, MarkedChangesFilter >>> cache = apt.Cache() >>> changed = apt.FilteredCache(cache) - >>> changed.setFilter(MarkedChangesFilter()) - >>> print len(changed) == len(cache.GetChanges()) # Both need to have same length + >>> changed.set_filter(MarkedChangesFilter()) + >>> print len(changed) == len(cache.get_changes()) # Both need to have same length True diff --git a/doc/source/apt/package.rst b/doc/source/apt/package.rst index bb74915e..4b143b8a 100644 --- a/doc/source/apt/package.rst +++ b/doc/source/apt/package.rst @@ -40,7 +40,7 @@ Dependency Information The version or None. - .. attribute:: preDepend + .. attribute:: pre_depend Boolean value whether this is a pre-dependency. @@ -101,9 +101,9 @@ Examples print 'python-apt is trusted:', pkg.candidate.origins[0].trusted # Mark python-apt for install - pkg.markInstall() + pkg.mark_install() - print 'python-apt is marked for install:', pkg.markedInstall + print 'python-apt is marked for install:', pkg.marked_install print 'python-apt is (summary):', pkg.candidate.summary diff --git a/doc/source/examples/apt-gtk.py b/doc/source/examples/apt-gtk.py index 835ea4ee..ad46454e 100644 --- a/doc/source/examples/apt-gtk.py +++ b/doc/source/examples/apt-gtk.py @@ -17,10 +17,10 @@ def main(): progress.show() win.show() cache = apt.cache.Cache(progress.open) - if cache["xterm"].isInstalled: - cache["xterm"].markDelete() + if cache["xterm"].is_installed: + cache["xterm"].mark_delete() else: - cache["xterm"].markInstall() + cache["xterm"].mark_install() progress.show_terminal(expanded=True) cache.commit(progress.fetch, progress.install) gtk.main() -- cgit v1.2.3 From d19943ea8489e06a1f5cd0bd545e0a0aeb4b8551 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 19 Apr 2009 17:30:57 +0200 Subject: * Update the code to use the new classes. --- apt/cache.py | 22 +++++++++++----------- apt/cdrom.py | 2 +- apt/debfile.py | 6 +++--- apt/package.py | 22 +++++++++++----------- doc/examples/acquire.py | 26 +++++++++++++------------- doc/examples/action.py | 4 ++-- doc/examples/build-deps.py | 8 ++++---- doc/examples/cdrom.py | 2 +- doc/examples/checkstate.py | 2 +- doc/examples/config.py | 2 +- doc/examples/configisc.py | 2 +- doc/examples/deb_inspect.py | 2 +- doc/examples/depcache.py | 4 ++-- doc/examples/desc.py | 6 +++--- doc/examples/indexfile.py | 6 +++--- doc/examples/metaindex.py | 2 +- doc/examples/print_uris.py | 2 +- doc/examples/recommends.py | 2 +- doc/examples/sources.py | 6 +++--- doc/examples/tagfile.py | 2 +- doc/source/examples/cache-packages.py | 2 +- doc/source/examples/cache-pkgfile.py | 2 +- doc/source/examples/missing-deps.py | 2 +- tests/cache.py | 4 ++-- tests/depcache.py | 4 ++-- tests/getcache_mem_corruption.py | 8 ++++---- tests/memleak.py | 8 ++++---- tests/pkgproblemresolver.py | 6 +++--- tests/pkgrecords.py | 6 +++--- tests/pkgsrcrecords.py | 4 ++-- 30 files changed, 88 insertions(+), 88 deletions(-) (limited to 'doc/source') diff --git a/apt/cache.py b/apt/cache.py index 05d8d1a9..60fd6553 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -78,10 +78,10 @@ class Cache(object): if progress is None: progress = apt.progress.OpProgress() self._run_callbacks("cache_pre_open") - self._cache = apt_pkg.GetCache(progress) - self._depcache = apt_pkg.GetDepCache(self._cache) - self._records = apt_pkg.GetPkgRecords(self._cache) - self._list = apt_pkg.GetPkgSourceList() + self._cache = apt_pkg.Cache(progress) + self._depcache = apt_pkg.DepCache(self._cache) + self._records = apt_pkg.PackageRecords(self._cache) + self._list = apt_pkg.SourceList() self._list.ReadMainList() self._set = set() self._weakref = weakref.WeakValueDictionary() @@ -154,8 +154,8 @@ class Cache(object): @property def required_download(self): """Get the size of the packages that are required to download.""" - pm = apt_pkg.GetPackageManager(self._depcache) - fetcher = apt_pkg.GetAcquire() + pm = apt_pkg.PackageManager(self._depcache) + fetcher = apt_pkg.Acquire() pm.GetArchives(fetcher, self._list, self._records) return fetcher.FetchNeeded @@ -270,7 +270,7 @@ class Cache(object): def install_archives(self, pm, install_progress): """ The first parameter *pm* refers to an object returned by - apt_pkg.GetPackageManager(). + apt_pkg.PackageManager(). The second parameter *install_progress* refers to an InstallProgress() object of the module apt.progress. @@ -309,8 +309,8 @@ class Cache(object): if install_progress is None: install_progress = apt.progress.InstallProgress() - pm = apt_pkg.GetPackageManager(self._depcache) - fetcher = apt_pkg.GetAcquire(fetch_progress) + pm = apt_pkg.PackageManager(self._depcache) + fetcher = apt_pkg.Acquire(fetch_progress) while True: # fetch archives first res = self._fetch_archives(fetcher, pm) @@ -494,8 +494,8 @@ def _test(): if not os.path.exists(dir): os.mkdir(dir) apt_pkg.Config.Set("Dir::Cache::Archives", "/tmp/pytest") - pm = apt_pkg.GetPackageManager(cache._depcache) - fetcher = apt_pkg.GetAcquire(apt.progress.TextFetchProgress()) + pm = apt_pkg.PackageManager(cache._depcache) + fetcher = apt_pkg.Acquire(apt.progress.TextFetchProgress()) cache._fetch_archives(fetcher, pm) #sys.exit(1) diff --git a/apt/cdrom.py b/apt/cdrom.py index 907ac622..b9625ebf 100644 --- a/apt/cdrom.py +++ b/apt/cdrom.py @@ -45,7 +45,7 @@ class Cdrom(object): """ def __init__(self, progress=None, mountpoint=None, nomount=True): - self._cdrom = apt_pkg.GetCdrom() + self._cdrom = apt_pkg.Cdrom() if progress is None: self._progress = CdromProgress() else: diff --git a/apt/debfile.py b/apt/debfile.py index c60fc92d..6e4adb39 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -57,7 +57,7 @@ class DebPackage(object): "missing '%s' member" % "debian-binary")) control = apt_inst.debExtractControl(open(self.filename)) - self._sections = apt_pkg.ParseSection(control) + self._sections = apt_pkg.TagSection(control) self.pkgname = self._sections["Package"] def __getitem__(self, key): @@ -357,7 +357,7 @@ class DebPackage(object): """Satisfy the dependencies.""" # turn off MarkAndSweep via a action group (if available) try: - _actiongroup = apt_pkg.GetPkgActionGroup(self._cache._depcache) + _actiongroup = apt_pkg.ActionGroup(self._cache._depcache) except AttributeError: pass # check depends @@ -458,7 +458,7 @@ class DscSrcPackage(DebPackage): conflicts_tags = ["Build-Conflicts", "Build-Conflicts-Indep"] fobj = open(file) - tagfile = apt_pkg.ParseTagFile(fobj) + tagfile = apt_pkg.TagFile(fobj) sec = tagfile.Section try: while tagfile.Step() == 1: diff --git a/apt/package.py b/apt/package.py index 411f9635..3dbdf058 100644 --- a/apt/package.py +++ b/apt/package.py @@ -158,7 +158,7 @@ class Record(Mapping): """ def __init__(self, record_str): - self._rec = apt_pkg.ParseSection(record_str) + self._rec = apt_pkg.TagSection(record_str) def __hash__(self): return hash(self._rec) @@ -448,9 +448,9 @@ class Version(object): if _file_is_same(destfile, self.size, self._records.MD5Hash): print 'Ignoring already existing file:', destfile return - acq = apt_pkg.GetAcquire(progress or apt.progress.TextFetchProgress()) - apt_pkg.GetPkgAcqFile(acq, self.uri, self._records.MD5Hash, self.size, - base, destFile=destfile) + acq = apt_pkg.Acquire(progress or apt.progress.TextFetchProgress()) + apt_pkg.AcquireFile(acq, self.uri, self._records.MD5Hash, self.size, + base, destfile=destfile) acq.Run() for item in acq.Items: if item.Status != item.StatDone: @@ -474,8 +474,8 @@ class Version(object): If *unpack* is ``True``, the path to the extracted directory is returned. Otherwise, the path to the .dsc file is returned. """ - src = apt_pkg.GetPkgSrcRecords() - acq = apt_pkg.GetAcquire(progress or apt.progress.TextFetchProgress()) + src = apt_pkg.SourceRecords() + acq = apt_pkg.Acquire(progress or apt.progress.TextFetchProgress()) dsc = None src.Lookup(self.package.name) @@ -497,8 +497,8 @@ class Version(object): continue finally: fobj.close() - apt_pkg.GetPkgAcqFile(acq, src.Index.ArchiveURI(path), md5, size, - base, destFile=destfile) + apt_pkg.AcquireFile(acq, src.Index.ArchiveURI(path), md5, size, + base, destfile=destfile) acq.Run() for item in acq.Items: @@ -879,7 +879,7 @@ class Package(object): # this feature only works if the correct deb-src are in the # sources.list # otherwise we fall back to the binary version number - src_records = apt_pkg.GetPkgSrcRecords() + src_records = apt_pkg.SourceRecords() src_rec = src_records.Lookup(src_pkg) if src_rec: src_ver = src_records.Version @@ -1016,7 +1016,7 @@ class Package(object): self._pcache._depcache.MarkDelete(self._pkg, purge) # try to fix broken stuffsta if auto_fix and self._pcache._depcache.BrokenCount > 0: - fix = apt_pkg.GetPkgProblemResolver(self._pcache._depcache) + fix = apt_pkg.ProblemResolver(self._pcache._depcache) fix.Clear(self._pkg) fix.Protect(self._pkg) fix.Remove(self._pkg) @@ -1043,7 +1043,7 @@ class Package(object): self._pcache._depcache.MarkInstall(self._pkg, auto_inst, from_user) # try to fix broken stuff if auto_fix and self._pcache._depcache.BrokenCount > 0: - fixer = apt_pkg.GetPkgProblemResolver(self._pcache._depcache) + fixer = apt_pkg.ProblemResolver(self._pcache._depcache) fixer.Clear(self._pkg) fixer.Protect(self._pkg) fixer.Resolve(True) diff --git a/doc/examples/acquire.py b/doc/examples/acquire.py index 41a38588..96426a32 100644 --- a/doc/examples/acquire.py +++ b/doc/examples/acquire.py @@ -4,10 +4,10 @@ import apt_pkg import os -def get_file(fetcher, uri, destFile): +def get_file(fetcher, uri, destfile): # get the file - af = apt_pkg.GetPkgAcqFile(fetcher, uri=uri, descr="sample descr", - destFile=destFile) + af = apt_pkg.AcquireFile(fetcher, uri=uri, descr="sample descr", + destfile=destfile) res = fetcher.Run() if res != fetcher.ResultContinue: return False @@ -19,21 +19,21 @@ apt_pkg.init() #apt_pkg.Config.Set("Debug::pkgPackageManager","1"); #apt_pkg.Config.Set("Debug::pkgDPkgProgressReporting","1"); -cache = apt_pkg.GetCache() -depcache = apt_pkg.GetDepCache(cache) +cache = apt_pkg.Cache() +depcache = apt_pkg.DepCache(cache) -recs = apt_pkg.GetPkgRecords(cache) -list = apt_pkg.GetPkgSourceList() +recs = apt_pkg.PackageRecords(cache) +list = apt_pkg.SourceList() list.ReadMainList() # show the amount fetch needed for a dist-upgrade depcache.Upgrade(True) progress = apt.progress.TextFetchProgress() -fetcher = apt_pkg.GetAcquire(progress) -pm = apt_pkg.GetPackageManager(depcache) +fetcher = apt_pkg.Acquire(progress) +pm = apt_pkg.PackageManager(depcache) pm.GetArchives(fetcher, list, recs) print "%s (%s)" % (apt_pkg.SizeToStr(fetcher.FetchNeeded), fetcher.FetchNeeded) -actiongroup = apt_pkg.GetPkgActionGroup(depcache) +actiongroup = apt_pkg.ActionGroup(depcache) for pkg in cache.Packages: depcache.MarkKeep(pkg) @@ -48,9 +48,9 @@ pkg = cache["3ddesktop"] depcache.MarkInstall(pkg) progress = apt.progress.TextFetchProgress() -fetcher = apt_pkg.GetAcquire(progress) -#fetcher = apt_pkg.GetAcquire() -pm = apt_pkg.GetPackageManager(depcache) +fetcher = apt_pkg.Acquire(progress) +#fetcher = apt_pkg.Acquire() +pm = apt_pkg.PackageManager(depcache) print pm print fetcher diff --git a/doc/examples/action.py b/doc/examples/action.py index 8ee86eb7..512945df 100644 --- a/doc/examples/action.py +++ b/doc/examples/action.py @@ -10,7 +10,7 @@ from progress import TextFetchProgress apt_pkg.init() progress = OpTextProgress() -cache = apt_pkg.GetCache(progress) +cache = apt_pkg.Cache(progress) print "Available packages: %s " % cache.PackageCount print "Fetching" @@ -25,7 +25,7 @@ print "example package iter: %s" % iter # get depcache print "\n\n depcache" -depcache = apt_pkg.GetDepCache(cache, progress) +depcache = apt_pkg.DepCache(cache, progress) depcache.ReadPinFile() print "got a depcache: %s " % depcache print "Marked for install: %s " % depcache.InstCount diff --git a/doc/examples/build-deps.py b/doc/examples/build-deps.py index b5ac88a2..656f1361 100755 --- a/doc/examples/build-deps.py +++ b/doc/examples/build-deps.py @@ -21,11 +21,11 @@ def get_source_pkg(pkg, records, depcache): # main apt_pkg.init() -cache = apt_pkg.GetCache() -depcache = apt_pkg.GetDepCache(cache) +cache = apt_pkg.Cache() +depcache = apt_pkg.DepCache(cache) depcache.Init() -records = apt_pkg.GetPkgRecords(cache) -srcrecords = apt_pkg.GetPkgSrcRecords() +records = apt_pkg.PackageRecords(cache) +srcrecords = apt_pkg.SourceRecords() # base package that we use for build-depends calculation if len(sys.argv) < 2: diff --git a/doc/examples/cdrom.py b/doc/examples/cdrom.py index 408bd720..78f2a8af 100644 --- a/doc/examples/cdrom.py +++ b/doc/examples/cdrom.py @@ -10,7 +10,7 @@ from progress import TextCdromProgress # init apt_pkg.init() -cdrom = apt_pkg.GetCdrom() +cdrom = apt_pkg.Cdrom() print cdrom progress = TextCdromProgress() diff --git a/doc/examples/checkstate.py b/doc/examples/checkstate.py index 3368d500..41040b6c 100755 --- a/doc/examples/checkstate.py +++ b/doc/examples/checkstate.py @@ -8,7 +8,7 @@ import apt_pkg apt_pkg.init() -cache = apt_pkg.GetCache() +cache = apt_pkg.Cache() packages = cache.Packages uninstalled, updated, upgradable = {}, {}, {} diff --git a/doc/examples/config.py b/doc/examples/config.py index 9d4e51fc..0dff4cac 100755 --- a/doc/examples/config.py +++ b/doc/examples/config.py @@ -21,7 +21,7 @@ import posixpath # configuration object apt_pkg.Config which is used interally by apt-pkg # routines to control unusual situations. I recommend using the sytem global # whenever possible.. -Cnf = apt_pkg.newConfiguration() +Cnf = apt_pkg.Configuration() print "Command line is", sys.argv diff --git a/doc/examples/configisc.py b/doc/examples/configisc.py index 8da1ad0a..fe3d161b 100755 --- a/doc/examples/configisc.py +++ b/doc/examples/configisc.py @@ -17,7 +17,7 @@ if len(ConfigFile) != 1: print "Must have exactly 1 file name" sys.exit(0) -Cnf = apt_pkg.newConfiguration() +Cnf = apt_pkg.Configuration() apt_pkg.ReadConfigFileISC(Cnf, ConfigFile[0]) # Print the configuration space diff --git a/doc/examples/deb_inspect.py b/doc/examples/deb_inspect.py index cc0d04be..54c52b7b 100755 --- a/doc/examples/deb_inspect.py +++ b/doc/examples/deb_inspect.py @@ -25,7 +25,7 @@ if __name__ == "__main__": print "Now extracting the control file:" control = apt_inst.debExtractControl(open(file)) - sections = apt_pkg.ParseSection(control) + sections = apt_pkg.TagSection(control) print "Maintainer is: " print sections["Maintainer"] diff --git a/doc/examples/depcache.py b/doc/examples/depcache.py index de038fe8..858e45a4 100644 --- a/doc/examples/depcache.py +++ b/doc/examples/depcache.py @@ -9,7 +9,7 @@ from progress import TextProgress apt_pkg.init() progress = TextProgress() -cache = apt_pkg.GetCache(progress) +cache = apt_pkg.Cache(progress) print "Available packages: %s " % cache.PackageCount iter = cache["base-config"] @@ -17,7 +17,7 @@ print "example package iter: %s" % iter # get depcache print "\n\n depcache" -depcache = apt_pkg.GetDepCache(cache) +depcache = apt_pkg.DepCache(cache) depcache.ReadPinFile() # init is needed after the creation/pin file reading depcache.Init(progress) diff --git a/doc/examples/desc.py b/doc/examples/desc.py index 2febf348..d50aa0ce 100644 --- a/doc/examples/desc.py +++ b/doc/examples/desc.py @@ -6,8 +6,8 @@ apt_pkg.init() apt_pkg.Config.Set("APT::Acquire::Translation", "de") -cache = apt_pkg.GetCache() -depcache = apt_pkg.GetDepCache(cache) +cache = apt_pkg.Cache() +depcache = apt_pkg.DepCache(cache) pkg = cache["gcc"] cand = depcache.GetCandidateVer(pkg) @@ -18,7 +18,7 @@ print desc print desc.FileList (f, index) = desc.FileList.pop(0) -records = apt_pkg.GetPkgRecords(cache) +records = apt_pkg.PackageRecords(cache) records.Lookup((f, index)) desc = records.LongDesc print len(desc) diff --git a/doc/examples/indexfile.py b/doc/examples/indexfile.py index 2f1f27f8..cc5070aa 100644 --- a/doc/examples/indexfile.py +++ b/doc/examples/indexfile.py @@ -4,11 +4,11 @@ import apt_pkg apt_pkg.init() -sources = apt_pkg.GetPkgSourceList() +sources = apt_pkg.SourceList() sources.ReadMainList() -cache = apt_pkg.GetCache() -depcache = apt_pkg.GetDepCache(cache) +cache = apt_pkg.Cache() +depcache = apt_pkg.DepCache(cache) pkg = cache["libimlib2"] cand = depcache.GetCandidateVer(pkg) for (f, i) in cand.FileList: diff --git a/doc/examples/metaindex.py b/doc/examples/metaindex.py index 816a3fd7..bbb4ac47 100644 --- a/doc/examples/metaindex.py +++ b/doc/examples/metaindex.py @@ -4,7 +4,7 @@ import apt_pkg apt_pkg.init() -sources = apt_pkg.GetPkgSourceList() +sources = apt_pkg.SourceList() sources.ReadMainList() diff --git a/doc/examples/print_uris.py b/doc/examples/print_uris.py index 3b678e83..c64a4b54 100755 --- a/doc/examples/print_uris.py +++ b/doc/examples/print_uris.py @@ -13,7 +13,7 @@ upgradable = filter(lambda p: p.isUpgradable, cache) for pkg in upgradable: pkg._lookupRecord(True) - path = apt_pkg.ParseSection(pkg._records.Record)["Filename"] + path = apt_pkg.TagSection(pkg._records.Record)["Filename"] cand = pkg._depcache.GetCandidateVer(pkg._pkg) for (packagefile, i) in cand.FileList: indexfile = cache._list.FindIndex(packagefile) diff --git a/doc/examples/recommends.py b/doc/examples/recommends.py index f0b3b1be..0ecd5882 100755 --- a/doc/examples/recommends.py +++ b/doc/examples/recommends.py @@ -3,7 +3,7 @@ import apt_pkg apt_pkg.init() -cache = apt_pkg.GetCache() +cache = apt_pkg.Cache() class Wanted: diff --git a/doc/examples/sources.py b/doc/examples/sources.py index 49652982..bc08ad69 100644 --- a/doc/examples/sources.py +++ b/doc/examples/sources.py @@ -4,10 +4,10 @@ import apt_pkg apt_pkg.init() -#cache = apt_pkg.GetCache() -#sources = apt_pkg.GetPkgSrcRecords(cache) +#cache = apt_pkg.Cache() +#sources = apt_pkg.SourceRecords(cache) -sources = apt_pkg.GetPkgSrcRecords() +sources = apt_pkg.SourceRecords() sources.Restart() while sources.Lookup('hello'): print sources.Package, sources.Version, sources.Maintainer, \ diff --git a/doc/examples/tagfile.py b/doc/examples/tagfile.py index 4faf08ac..770e40de 100755 --- a/doc/examples/tagfile.py +++ b/doc/examples/tagfile.py @@ -1,7 +1,7 @@ #!/usr/bin/env python import apt_pkg -Parse = apt_pkg.ParseTagFile(open("/var/lib/dpkg/status", "r")) +Parse = apt_pkg.TagFile(open("/var/lib/dpkg/status", "r")) while Parse.Step() == 1: print Parse.Section.get("Package") diff --git a/doc/source/examples/cache-packages.py b/doc/source/examples/cache-packages.py index 1abe7cf2..0af96f7d 100644 --- a/doc/source/examples/cache-packages.py +++ b/doc/source/examples/cache-packages.py @@ -8,7 +8,7 @@ def main(): """Main.""" apt_pkg.InitConfig() apt_pkg.InitSystem() - cache = apt_pkg.GetCache() + cache = apt_pkg.Cache() print "Essential packages:" for pkg in cache.Packages: if pkg.Essential: diff --git a/doc/source/examples/cache-pkgfile.py b/doc/source/examples/cache-pkgfile.py index f25975d3..a7c22c97 100644 --- a/doc/source/examples/cache-pkgfile.py +++ b/doc/source/examples/cache-pkgfile.py @@ -5,7 +5,7 @@ import apt_pkg def main(): """Example for PackageFile()""" apt_pkg.init() - cache = apt_pkg.GetCache() + cache = apt_pkg.Cache() for pkgfile in cache.FileList: print 'Package-File:', pkgfile.FileName print 'Index-Type:', pkgfile.IndexType # 'Debian Package Index' diff --git a/doc/source/examples/missing-deps.py b/doc/source/examples/missing-deps.py index 3ca16e45..dd5eeb8a 100644 --- a/doc/source/examples/missing-deps.py +++ b/doc/source/examples/missing-deps.py @@ -35,7 +35,7 @@ def main(): apt_pkg.InitConfig() apt_pkg.InitSystem() - cache = apt_pkg.GetCache() + cache = apt_pkg.Cache() for pkg in sorted(cache.Packages, key=lambda pkg: pkg.Name): # pkg is from a list of packages, sorted by name. diff --git a/tests/cache.py b/tests/cache.py index 87a544e8..f0bf6761 100644 --- a/tests/cache.py +++ b/tests/cache.py @@ -9,8 +9,8 @@ import sys def main(): apt_pkg.init() - cache = apt_pkg.GetCache() - depcache = apt_pkg.GetDepCache(cache) + cache = apt_pkg.Cache() + depcache = apt_pkg.DepCache(cache) depcache.Init() i=0 all=cache.PackageCount diff --git a/tests/depcache.py b/tests/depcache.py index 19aba680..0d59648e 100644 --- a/tests/depcache.py +++ b/tests/depcache.py @@ -9,8 +9,8 @@ import sys def main(): apt_pkg.init() - cache = apt_pkg.GetCache() - depcache = apt_pkg.GetDepCache(cache) + cache = apt_pkg.Cache() + depcache = apt_pkg.DepCache(cache) depcache.Init() i=0 all=cache.PackageCount diff --git a/tests/getcache_mem_corruption.py b/tests/getcache_mem_corruption.py index c3f6eff3..c6e5ff80 100644 --- a/tests/getcache_mem_corruption.py +++ b/tests/getcache_mem_corruption.py @@ -13,12 +13,12 @@ class TestGetCache(unittest.TestCase): def testWrongInvocation(self): # wrongly invoke GetCache() rather than GetDepCache() - apt_cache = apt_pkg.GetCache() - self.assertRaises(ValueError, apt_pkg.GetCache, apt_cache) + apt_cache = apt_pkg.Cache() + self.assertRaises(ValueError, apt_pkg.Cache, apt_cache) def testProperInvocation(self): - apt_cache = apt_pkg.GetCache(apt.progress.OpTextProgress()) - apt_depcache = apt_pkg.GetDepCache(apt_cache) + apt_cache = apt_pkg.Cache(apt.progress.OpTextProgress()) + apt_depcache = apt_pkg.DepCache(apt_cache) if __name__ == "__main__": unittest.main() diff --git a/tests/memleak.py b/tests/memleak.py index 659091fc..5299f35f 100755 --- a/tests/memleak.py +++ b/tests/memleak.py @@ -29,10 +29,10 @@ for i in range(100): # no memleak, but more or less the apt.Cache.open() code for i in range(100): - cache = apt_pkg.GetCache() - depcache = apt_pkg.GetDepCache(cache) - records = apt_pkg.GetPkgRecords(cache) - list = apt_pkg.GetPkgSourceList() + cache = apt_pkg.Cache() + depcache = apt_pkg.DepCache(cache) + records = apt_pkg.PackageRecords(cache) + list = apt_pkg.SourceList() list.ReadMainList() dict = {} for pkg in cache.Packages: diff --git a/tests/pkgproblemresolver.py b/tests/pkgproblemresolver.py index a21d8d9d..0d6d0611 100644 --- a/tests/pkgproblemresolver.py +++ b/tests/pkgproblemresolver.py @@ -9,8 +9,8 @@ import sys def main(): apt_pkg.init() - cache = apt_pkg.GetCache() - depcache = apt_pkg.GetDepCache(cache) + cache = apt_pkg.Cache() + depcache = apt_pkg.DepCache(cache) depcache.Init() i=0 all=cache.PackageCount @@ -25,7 +25,7 @@ def main(): if ver is not None: depcache.MarkInstall(pkg) if depcache.BrokenCount > 0: - fixer = apt_pkg.GetPkgProblemResolver(depcache) + fixer = apt_pkg.ProblemResolver(depcache) fixer.Clear(pkg) fixer.Protect(pkg) # we first try to resolve the problem diff --git a/tests/pkgrecords.py b/tests/pkgrecords.py index 5866847d..2fe6ad20 100644 --- a/tests/pkgrecords.py +++ b/tests/pkgrecords.py @@ -10,14 +10,14 @@ import sys def main(): apt_pkg.init() - cache = apt_pkg.GetCache() - depcache = apt_pkg.GetDepCache(cache) + cache = apt_pkg.Cache() + depcache = apt_pkg.DepCache(cache) depcache.Init() i=0 print "Running PkgRecords test on all packages:" for pkg in cache.Packages: i += 1 - records = apt_pkg.GetPkgRecords(cache) + records = apt_pkg.PackageRecords(cache) if len(pkg.VersionList) == 0: #print "no available version, cruft" continue diff --git a/tests/pkgsrcrecords.py b/tests/pkgsrcrecords.py index 77670540..2ea9dd3a 100644 --- a/tests/pkgsrcrecords.py +++ b/tests/pkgsrcrecords.py @@ -10,12 +10,12 @@ import sys def main(): apt_pkg.init() - cache = apt_pkg.GetCache() + cache = apt_pkg.Cache() i=0 print "Running PkgSrcRecords test on all packages:" for x in cache.Packages: i += 1 - src = apt_pkg.GetPkgSrcRecords() + src = apt_pkg.SourceRecords() if src.Lookup(x.Name): #print src.Package pass -- cgit v1.2.3 From 071b059f8ccb35eaeb6c9457244f783ad69ba957 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 19 Apr 2009 19:48:08 +0200 Subject: * doc: Update the documentation to the current state. --- doc/source/apt/index.rst | 2 - doc/source/apt_pkg.rst | 1740 +++++++++++++++++++++++++++++++++++++++++ doc/source/apt_pkg/cache.rst | 1243 ----------------------------- doc/source/apt_pkg/index.rst | 530 ------------- doc/source/index.rst | 22 +- doc/source/whatsnew/0.8.0.rst | 33 + doc/source/whatsnew/index.rst | 9 + 7 files changed, 1793 insertions(+), 1786 deletions(-) create mode 100644 doc/source/apt_pkg.rst delete mode 100644 doc/source/apt_pkg/cache.rst delete mode 100644 doc/source/apt_pkg/index.rst create mode 100644 doc/source/whatsnew/0.8.0.rst create mode 100644 doc/source/whatsnew/index.rst (limited to 'doc/source') diff --git a/doc/source/apt/index.rst b/doc/source/apt/index.rst index 5047a0fd..9cd6ef45 100644 --- a/doc/source/apt/index.rst +++ b/doc/source/apt/index.rst @@ -11,8 +11,6 @@ with an easy-to-use interface. functions provided as deprecated ones. .. automodule:: apt - :members: - diff --git a/doc/source/apt_pkg.rst b/doc/source/apt_pkg.rst new file mode 100644 index 00000000..8c602f37 --- /dev/null +++ b/doc/source/apt_pkg.rst @@ -0,0 +1,1740 @@ +:mod:`apt_pkg` --- The low-level bindings for apt-pkg +===================================================== +.. module:: apt_pkg + +The apt_pkg extensions provides a more low-level way to work with apt. It can +do everything apt can, and is written in C++. It has been in python-apt since +the beginning. + + +Module Initialization +--------------------- + +Initialization is needed for most functions, but not for all of them. Some can +be called without having run init*(), but will not return the expected value. + +.. function:: initConfig + + Initialize the configuration of apt. This is needed for most operations. + +.. function:: initSystem + + Initialize the system. + +.. function:: init + + Deprecated function. Use initConfig() and initSystem() instead. + +Working with the cache +---------------------- +.. class:: Cache([progress]) + + Return a :class:`Cache()` object. The optional parameter *progress* + specifies an instance of :class:`apt.progress.OpProgress()` which will + display the open progress. + + .. describe:: cache[pkgname] + + Return the :class:`Package()` object for the package name given by + *pkgname*. + + .. method:: Close() + + Close the package cache. + + .. method:: Open([progress]) + + Open the package cache again. The parameter *progress* may be set to + an :class:`apt.progress.OpProgress()` object or `None`. + + .. method:: Update(progress, list) + + Update the package cache. + + The parameter *progress* points to an :class:`apt.progress.FetchProgress()` + object. The parameter *list* refers to a :class:`SourceList()` object. + + .. attribute:: DependsCount + + The total number of dependencies. + + .. attribute:: PackageCount + + The total number of packages available in the cache. + + .. attribute:: ProvidesCount + + The number of provided packages. + + .. attribute:: VerFileCount + + .. todo:: Seems to be some mixture of versions and pkgFile. + + .. attribute:: VersionCount + + The total number of package versions available in the cache. + + .. attribute:: PackageFileCount + + The total number of Packages files available (the Packages files + listing the packages). This is the same as the length of the list in + the attribute :attr:`FileList`. + + .. attribute:: FileList + + A list of :class:`PackageFile` objects. + +.. class:: DepCache(cache) + + Return a :class:`DepCache` object. The parameter *cache* specifies an + instance of :class:`Cache`. + + The DepCache object contains various methods to manipulate the cache, + to install packages, to remove them, and much more. + + .. method:: Commit(fprogress, iprogress) + + Apply all the changes made. + + The parameter *fprogress* has to be set to an instance of + apt.progress.FetchProgress or one of its subclasses. + + The parameter *iprogress* has to be set to an instance of + apt.progress.InstallProgress or one of its subclasses. + + .. method:: FixBroken() + + Try to fix all broken packages in the cache. + + .. method:: GetCandidateVer(pkg) + + Return the candidate version of the package, ie. the version that + would be installed normally. + + The parameter *pkg* refers to an :class:`Package` object, + available using the :class:`pkgCache`. + + This method returns a :class:`Version` object. + + .. method:: SetCandidateVer(pkg, version) + + The opposite of :meth:`pkgDepCache.GetCandidateVer`. Set the candidate + version of the :class:`Package` *pkg* to the :class:`Version` + *version*. + + + .. method:: Upgrade([distUpgrade=False]) + + Perform an upgrade. More detailed, this marks all the upgradable + packages for upgrade. You still need to call + :meth:`pkgDepCache.Commit` for the changes to apply. + + To perform a dist-upgrade, the optional parameter *distUpgrade* has + to be set to True. + + .. method:: FixBroken() + + Fix broken packages. + + .. method:: ReadPinFile() + + Read the policy, eg. /etc/apt/preferences. + + .. method:: MinimizeUpgrade() + + Go over the entire set of packages and try to keep each package marked + for upgrade. If a conflict is generated then the package is restored. + + .. todo:: + Explain better.. + + .. method:: MarkKeep(pkg) + + Mark the :class:`Package` *pkg* for keep. + + .. method:: MarkDelete(pkg[, purge]) + + Mark the :class:`Package` *pkg* for delete. If *purge* is True, + the configuration files will be removed as well. + + .. method:: MarkInstall(pkg[, autoInst=True[, fromUser=True]]) + + Mark the :class:`Package` *pkg* for install. + + If *autoInst* is ``True``, the dependencies of the package will be + installed as well. This is the default. + + If *fromUser* is ``True``, the package will be marked as manually + installed. This is the default. + + .. method:: SetReinstall(pkg) + + Set if the :class:`Package` *pkg* should be reinstalled. + + .. method:: IsUpgradable(pkg) + + Return ``1`` if the package is upgradable. + + The package can be upgraded by calling :meth:`pkgDepCache.MarkInstall`. + + .. method:: IsNowBroken(pkg) + + Return `1` if the package is broken now (including changes made, but + not committed). + + .. method:: IsInstBroken(pkg) + + Return ``1`` if the package is broken on the current install. This + takes changes which have not been committed not into effect. + + .. method:: IsGarbage(pkg) + + Return ``1`` if the package is garbage, ie. if it is automatically + installed and no longer referenced by other packages. + + .. method:: IsAutoInstalled(pkg) + + Return ``1`` if the package is automatically installed (eg. as the + dependency of another package). + + .. method:: MarkedInstall(pkg) + + Return ``1`` if the package is marked for install. + + .. method:: MarkedUpgrade(pkg) + + Return ``1`` if the package is marked for upgrade. + + .. method:: MarkedDelete(pkg) + + Return ``1`` if the package is marked for delete. + + .. method:: MarkedKeep(pkg) + + Return ``1`` if the package is marked for keep. + + .. method:: MarkedReinstall(pkg) + + Return ``1`` if the package should be installed. + + .. method:: MarkedDowngrade(pkg) + + Return ``1`` if the package should be downgraded. + + .. attribute:: KeepCount + + Integer, number of packages marked as keep + + .. attribute:: InstCount + + Integer, number of packages marked for installation. + + .. attribute:: DelCount + + Number of packages which should be removed. + + .. attribute:: BrokenCount + + Number of packages which are broken. + + .. attribute:: UsrSize + + The size required for the changes on the filesystem. If you install + packages, this is positive, if you remove them its negative. + + .. attribute:: DebSize + + The size of the packages which are needed for the changes to be + applied. + + +.. class:: PackageManager(depcache) + + Return a new :class:`PackageManager` object. The parameter *depcache* + specifies a :class:`DepCache` object. + + :class:`PackageManager` objects provide several methods and attributes, + which will be listed here: + + .. method:: GetArchives(fetcher, list, records) + + Add all the selected packages to the :class:`Acquire()` object + *fetcher*. + + The parameter *list* refers to a :class:`SourceList()` object. + + The parameter *records* refers to a :class:`PackageRecords()` object. + + .. method:: DoInstall() + + Install the packages. + + .. method:: FixMissing + + Fix the installation if a package could not be downloaded. + + .. attribute:: ResultCompleted + + A constant for checking whether the the result is 'completed'. + + Compare it against the return value of :meth:`PkgManager.GetArchives` + or :meth:`PkgManager.DoInstall`. + + .. attribute:: ResultFailed + + A constant for checking whether the the result is 'failed'. + + Compare it against the return value of :meth:`PkgManager.GetArchives` + or :meth:`PkgManager.DoInstall`. + + .. attribute:: ResultIncomplete + + A constant for checking whether the the result is 'incomplete'. + + Compare it against the return value of :meth:`PkgManager.GetArchives` + or :meth:`PkgManager.DoInstall`. + +Improve performance with :class:`ActionGroup` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +.. class:: ActionGroup(depcache) + + Create a new :class:`ActionGroup()` object for the :class:`DepCache` object + given by the parameter *depcache*. + + :class:`ActionGroup()` objects make operations on the cache faster by + delaying certain cleanup operations until the action group is released. + + ActionGroup is also a context manager and therefore supports the + :keyword:`with` statement. But because it becomes active as soon as it + is created, you should not create an ActionGroup() object before entering + the with statement. + + If you want to use ActionGroup as a with statement (which is recommended + because it makes it easier to see when an actiongroup is active), always + use the following form:: + + with apt_pkg.ActionGroup(depcache): + ... + + For code which has to run on Python versions prior to 2.5, you can also + use the traditional way:: + + actiongroup = apt_pkg.ActionGroup(depcache) + ... + actiongroup.release() + + :class:`ActionGroup` provides the following method: + + .. method:: release() + + Release the ActionGroup. This will reactive the collection of package + garbage. + +Resolving Dependencies +^^^^^^^^^^^^^^^^^^^^^^ + +.. class:: ProblemResolver(depcache) + + Return a new :class:`ProblemResolver` object. The parameter *depcache* + specifies a :class:`pkgDepCache` object as returned by :func:`GetDepCache`. + + The problem resolver helps when there are problems in the package + selection. An example is a package which conflicts with another, already + installed package. + + .. method:: Protect(pkg) + + Protect the :class:`Package()` object given by the parameter *pkg*. + + .. todo:: + + Really document it. + + .. method:: InstallProtect() + + Protect all installed packages from being removed. + + .. method:: Remove(pkg) + + Remove the :class:`Package()` object given by the parameter *pkg*. + + .. todo:: + + Really document it. + + .. method:: Clear(pkg) + + Reset the :class:`Package()` *pkg* to the default state. + + .. todo:: + + Really document it. + + .. method:: Resolve() + + Try to resolve problems by installing and removing packages. + + .. method:: ResolveByKeep() + + Try to resolve problems only by using keep. + + +:class:`PackageFile` +-------------------- +.. class:: PackageFile + + A :class:`PackageFile` represents a Packages file, eg. + /var/lib/dpkg/status. + + .. attribute:: Architecture + + The architecture of the package file. + + .. attribute:: Archive + + The archive (eg. unstable) + + .. attribute:: Component + + The component (eg. main) + + .. attribute:: FileName + + The name of the file. + + .. attribute:: ID + + The ID of the package. This is an integer which can be used to store + further information about the file [eg. as dictionary key]. + + .. attribute:: IndexType + + The sort of the index file. In normal cases, this is + 'Debian Package Index'. + + .. attribute:: Label + + The Label, as set in the Release file + + .. attribute:: NotAutomatic + + Whether packages from this list will be updated automatically. The + default for eg. example is 0 (aka false). + + .. attribute:: NotSource + + Whether the file has no source from which it can be updated. In such a + case, the value is 1; else 0. /var/lib/dpkg/status is 0 for example. + + Example:: + + for pkgfile in cache.FileList: + if pkgfile.NotSource: + print 'The file %s has no source.' % pkgfile.FileName + + .. attribute:: Origin + + The Origin, as set in the Release file + + .. attribute:: Site + + The hostname of the site. + + .. attribute:: Size + + The size of the file. + + .. attribute:: Version + + The version, as set in the release file (eg. "4.0" for "Etch") + + +Example +^^^^^^^ +.. literalinclude:: examples/cache-pkgfile.py + + +:class:`Package` +---------------- + +.. class:: Package + + The pkgCache::Package objects are an interface to package specific + features. + + + Attributes: + + .. attribute:: CurrentVer + + The version currently installed, or None. This returns a + :class:`Version` object. + + .. attribute:: ID + + The ID of the package. This can be used to store information about + the package. The ID is an int value. + + .. attribute:: Name + + This is the name of the package. + + .. attribute:: ProvidesList + + A list of packages providing this package. More detailed, this is a + list of tuples (str:pkgname, ????, :class:`Version`). + + If you want to check for check for virtual packages, the expression + ``pkg.ProvidesList and not pkg.VersionList`` helps you. It detects if + the package is provided by something else and is not available as a + real package. + + .. attribute:: RevDependsList + + An iterator of :class:`Dependency` objects for dependencies on this + package. + + .. attribute:: Section + + The section of the package, as specified in the record. The list of + possible sections is defined in the Policy. + + .. attribute:: VersionList + + A list of :class:`Version` objects for all versions available in the + cache. + + **States**: + + .. attribute:: SelectedState + + The state we want it to be, ie. if you mark a package for installation, + this is :attr:`apt_pkg.SelStateInstall`. + + See :ref:`SelStates` for a list of available states. + + .. attribute:: InstState + + The state the currently installed version is in. This is normally + :attr:`apt_pkg.InstStateOK`, unless the installation failed. + + See :ref:`InstStates` for a list of available states. + + .. attribute:: CurState + + The current state of the package (not installed, unpacked, installed, + etc). See :ref:`CurStates` for a list of available states. + + **Flags**: + + .. attribute:: Auto + + Whether the package was installed automatically as a dependency of + another package. (or marked otherwise as automatically installed) + + .. attribute:: Essential + + Whether the package is essential. + + .. attribute:: Important + + Whether the package is important. + +Example: +^^^^^^^^^ +.. literalinclude:: examples/cache-packages.py + + + +:class:`Version` +---------------- +.. class:: Version + + The version object contains all information related to a specific package + version. + + .. attribute:: VerStr + + The version, as a string. + + .. attribute:: Section + + The usual sections (eg. admin, net, etc.). Prefixed with the component + name for packages not in main (eg. non-free/admin). + + .. attribute:: Arch + + The architecture of the package, eg. amd64 or all. + + .. attribute:: FileList + + A list of (:class:`PackageFile`, int: index) tuples for all Package + files containing this version of the package. + + .. attribute:: DependsListStr + + A dictionary of dependencies. The key specifies the type of the + dependency ('Depends', 'Recommends', etc.). + + + The value is a list, containing items which refer to the or-groups of + dependencies. Each of these or-groups is itself a list, containing + tuples like ('pkgname', 'version', 'relation') for each or-choice. + + An example return value for a package with a 'Depends: python (>= 2.4)' + would be:: + + {'Depends': [ + [ + ('python', '2.4', '>=') + ] + ] + } + + The same for a dependency on A (>= 1) | B (>= 2):: + + {'Depends': [ + [ + ('A', '1', '>='), + ('B', '2', '>='), + ] + ] + } + + .. attribute:: DependsList + + This is basically the same as :attr:`Version.DependsListStr`, + but instead of the ('pkgname', 'version', 'relation') tuples, + it returns :class:`Dependency` objects, which can assist you with + useful functions. + + .. attribute:: ParentPkg + + The :class:`Package` object this version belongs to. + + .. attribute:: ProvidesList + + This returns a list of all packages provided by this version. Like + :attr:`Package.ProvidesList`, it returns a list of tuples + of the form ('virtualpkgname', ???, :class:`Version`), where as the + last item is the same as the object itself. + + .. attribute:: Size + + The size of the .deb file, in bytes. + + .. attribute:: InstalledSize + + The size of the package (in kilobytes), when unpacked on the disk. + + .. attribute:: Hash + + An integer hash value. + + .. attribute:: ID + + An integer id. + + .. attribute:: Priority + + The integer representation of the priority. This can be used to speed + up comparisons a lot, compared to :attr:`Version.PriorityStr`. + + The values are defined in the :mod:`apt_pkg` extension, see + :ref:`Priorities` for more information. + + .. attribute:: PriorityStr + + Return the priority of the package version, as a string, eg. + "optional". + + .. attribute:: Downloadable + + Whether this package can be downloaded from a remote site. + + .. attribute:: TranslatedDescription + + Return a :class:`Description` object. + + +:class:`Dependency` +------------------- +.. class:: Dependency + + Represent a dependency from one package to another one. + + .. method:: AllTargets + + A list of :class:`Version` objects which satisfy the dependency, + and do not conflict with already installed ones. + + From my experience, if you use this method to select the target + version, it is the best to select the last item unless any of the + other candidates is already installed. This leads to results being + very close to the normal package installation. + + .. method:: SmartTargetPkg + + Return a :class:`Version` object of a package which satisfies the + dependency and does not conflict with installed packages + (the 'natural target'). + + .. attribute:: TargetVer + + The target version of the dependency, as string. Empty string if the + dependency is not versioned. + + .. attribute:: TargetPkg + + The :class:`Package` object of the target package. + + .. attribute:: ParentVer + + The :class:`Version` object of the parent version, ie. the package + which declares the dependency. + + .. attribute:: ParentPkg + + The :class:`Package` object of the package which declares the + dependency. This is the same as using ParentVer.ParentPkg. + + .. attribute:: CompType + + The type of comparison (>=, ==, >>, <=), as string. + + .. attribute:: DepType + + The type of the dependency, as string, eg. "Depends". + + .. attribute:: ID + + The ID of the package, as integer. + +Example: Find all missing dependencies +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +With the help of Dependency.AllTargets(), you can easily find all packages with +broken dependencies: + +.. literalinclude:: examples/missing-deps.py + + +:class:`Description` +-------------------- +.. class:: Description + + Represent the description of the package. + + .. attribute:: LanguageCode + + The language code of the description + + .. attribute:: md5 + + The md5 hashsum of the description + + .. attribute:: FileList + + A list of tuples (:class:`PackageFile`, int: index). + + + +:class:`MetaIndex` +------------------ + +.. todo:: + + Complete them + +.. class:: MetaIndex + + .. attribute:: URI + .. attribute:: Dist + .. attribute:: IsTrusted + .. attribute:: IndexFiles + + +:class:`PackageIndexFile` +------------------------- + +.. class:: PackageIndexFile + + .. method:: ArchiveURI(path) + + Return the full url to path in the archive. + + .. attribute:: Label + + Return the Label. + + .. attribute:: Exists + + Return whether the file exists. + + .. attribute:: HasPackages + + Return whether the file has packages. + + .. attribute:: Size + + Size of the file + + .. attribute:: IsTrusted + + Whether we can trust the file. + + +Records +-------- + +.. class:: PackageRecords(cache) + + Create a new :class:`PackageRecords` object, for the packages in the cache + specified by the parameter *cache*. + + Provide access to the packages records. This provides very useful + attributes for fast (convient) access to some fields of the record. + + .. method:: Lookup(verfile_iter) + + Change the actual package to the package given by the verfile_iter. + + The parameter *verfile_iter* refers to a tuple consisting + of (:class:`PackageFile()`, int: index), as returned by various + attributes, including :attr:`Version.FileList`. + + Example (shortened):: + + cand = depcache.GetCandidateVer(cache['python-apt']) + records.Lookup(cand.FileList[0]) + # Now you can access the record + print records.SourcePkg # == python-apt + + .. attribute:: FileName + + Return the field 'Filename' of the record. This is the path to the + package, relative to the base path of the archive. + + .. attribute:: MD5Hash + + Return the MD5 hashsum of the package This refers to the field + 'MD5Sum' in the raw record. + + .. attribute:: SHA1Hash + + Return the SHA1 hashsum of the package. This refers to the field 'SHA1' + in the raw record. + + .. attribute:: SHA256Hash + + Return the SHA256 hashsum of the package. This refers to the field + 'SHA256' in the raw record. + + .. versionadded:: 0.7.9 + + .. attribute:: SourcePkg + + Return the source package. + + .. attribute:: SourceVer + + Return the source version. + + .. attribute:: Maintainer + + Return the maintainer of the package. + + .. attribute:: ShortDesc + + Return the short description. This is the summary on the first line of + the 'Description' field. + + .. attribute:: LongDesc + + Return the long description. These are lines 2-END from the + 'Description' field. + + .. attribute:: Name + + Return the name of the package. This is the 'Package' field. + + .. attribute:: Homepage + + Return the Homepage. This is the 'Homepage' field. + + .. attribute:: Record + + Return the whole record as a string. If you want to access fields of + the record not available as an attribute, you can use + :func:`apt_pkg.ParseSection` to parse the record and access the field + name. + + Example:: + + section = apt_pkg.ParseSection(records.Record) + print section['SHA256'] + + +.. class:: SourceRecords + + This represents the entries in the Sources files, ie. the dsc files of + the source packages. + + .. note:: + + If the Lookup failed, because no package could be found, no error is + raised. Instead, the attributes listed below are simply not existing + anymore (same applies when no Lookup has been made, or when it has + been restarted). + + .. method:: Lookup(pkgname) + + Lookup the record for the package named *pkgname*. To access all + available records, you need to call it multiple times. + + Imagine a package P with two versions X, Y. The first ``Lookup(P)`` + would set the record to version X and the second ``Lookup(P)`` to + version Y. + + .. method:: Restart() + + Restart the lookup. + + Imagine a package P with two versions X, Y. The first ``Lookup(P)`` + would set the record to version X and the second ``Lookup(P)`` to + version Y. + + If you now call ``Restart()``, the internal position will be cleared. + Now you can call ``Lookup(P)`` again to move to X. + + .. attribute:: Package + + The name of the source package. + + .. attribute:: Version + + A string describing the version of the source package. + + .. attribute:: Maintainer + + A string describing the name of the maintainer. + + .. attribute:: Section + + A string describing the section. + + .. attribute:: Record + + The whole record, as a string. You can use :func:`apt_pkg.ParseSection` + if you need to parse it. + + You need to parse the record if you want to access fields not available + via the attributes, eg. 'Standards-Version' + + .. attribute:: Binaries + + Return a list of strings describing the package names of the binaries + created by the source package. This matches the 'Binary' field in the + raw record. + + .. attribute:: Index + + The index in the Sources files. + + .. attribute:: Files + + The list of files. This returns a list of tuples with the contents + ``(str: md5, int: size, str: path, str:type)``. + + .. attribute:: BuildDepends + + Return the list of Build dependencies, as + ``(str: package, str: version, int: op, int: type)``. + + .. table:: Values of *op* + + ===== ============================================= + Value Meaning + ===== ============================================= + 0x0 No Operation (no versioned build dependency) + 0x10 | (or) - this will be added to the other values + 0x1 <= (less than or equal) + 0x2 >= (greater than or equal) + 0x3 << (less than) + 0x4 >> (greater than) + 0x5 == (equal) + 0x6 != (not equal) + ===== ============================================= + + .. table:: Values of *type* + + ===== =================== + Value Meaning + ===== =================== + 0 Build-Depends + 1 Build-Depends-Indep + 2 Build-Conflicts + 3 Build-Conflicts-Indep + ===== =================== + + **Example**: In the following content, we will imagine a + build-dependency:: + + Build-Depends: A (>= 1) | B (>= 1), C + + This results in:: + + [('A', '1', 18, 0), # 18 = 16 + 2 = 0x10 + 0x2 + ('B', '1', 2, 0), + ('C', '', 0, 0)] + + This is **not** the same as returned by + :func:`apt_pkg.ParseSrcDepends`. + + + +The Acquire interface +---------------------- +The Acquire Interface is responsible for all sorts of downloading in apt. All +packages, index files, etc. downloading is done using the Acquire functionality. + +The :mod:`apt_pkg` module provides a subset of this functionality which allows +you to implement file downloading in your applications. Together with the +:class:`PackageManager` class you can also fetch all the packages marked for +installation. + + +.. class:: Acquire([progress]) + + Return an :class:`Acquire` object. The parameter *progress* refers to + an :class:`apt.progress.FetchProgress()` object. + + Acquire objects maintaing a list of items which will be fetched or have + been fetched already during the lifetime of this object. To add new items + to this list, you can create new :class:`AcquireFile` objects which allow + you to add single files. + + Acquire items have multiple methods: + + .. method:: Acquire.Run() + + Fetch all the items which have been added by :func:`GetPkgAcqFile`. + + .. method:: Acquire.Shutdown() + + Shut the fetcher down. + + .. attribute:: Acquire.TotalNeeded + + The total amount of bytes needed (including those of files which are + already present) + + .. attribute:: Acquire.FetchNeeded + + The total amount of bytes which need to be fetched. + + .. attribute:: Acquire.PartialPresent + + Whether some files have been acquired already. (???) + +.. class:: AcquireItem + + The :class:`AcquireItem()` objects represent the items of a + :class:`Acquire` object. :class:`AcquireItem()` objects can not be created + by the user, they are solely available through the :attr:`Acquire.Items` + list of an :class:`Acquire` object. + + .. attribute:: ID + + The ID of the item. + + .. attribute:: Complete + + Is the item completely acquired? + + .. attribute:: Local + + Is the item a local file? + + .. attribute:: IsTrusted + + Can the file be trusted? + + .. attribute:: FileSize + + The size of the file, in bytes. + + .. attribute:: ErrorText + + The error message. For example, when a file does not exist on a http + server, this will contain a 404 error message. + + .. attribute:: DestFile + + The location the file is saved as. + + .. attribute:: DescURI + + The source location. + + **Status**: + + .. attribute:: Status + + Integer, representing the status of the item. + + .. attribute:: StatIdle + + Constant for comparing :attr:`AcquireItem.Status`. + + .. attribute:: StatFetching + + Constant for comparing :attr:`AcquireItem.Status` + + .. attribute:: StatDone + + Constant for comparing :attr:`AcquireItem.Status` + + .. attribute:: StatError + + Constant for comparing :attr:`AcquireItem.Status` + + .. attribute:: StatAuthError + + Constant for comparing :attr:`AcquireItem.Status` + + +.. class:: AcquireFile(owner, uri[, md5, size, descr, shortdescr, destdir, destfile]) + + Create a new :class:`AcquireFile()` object and register it with *acquire*, + so it will be fetched. AcquireFile objects provide no methods or attributes + and are completely useless at the moment. + + The parameter *owner* refers to an :class:`Acquire()` object as returned + by :func:`GetAcquire`. The file will be added to the Acquire queue + automatically. + + The parameter *uri* refers to the location of the file, any protocol + of apt is supported. + + The parameter *md5* refers to the md5sum of the file. This can be used + for checking the file. + + The parameter *size* can be used to specify the size of the package, + which can then be used to calculate the progress and validate the download. + + The parameter *descr* is a descripition of the download. It may be + used to describe the item in the progress class. *shortDescr* is the + short form of it. + + You can use *destdir* to manipulate the directory where the file will + be saved in. Instead of *destdir*, you can also specify the full path to + the file using the parameter *destfile*. You can not combine both. + + + + + + +Hash functions +-------------- +The apt_pkg module also provides several hash functions. If you develop +applications with python-apt it is often easier to use these functions instead +of the ones provides in Python's :mod:`hashlib` module. + +.. function:: md5sum(object) + + Return the md5sum of the object. *object* may either be a string, in + which case the md5sum of the string is returned, or a :class:`file()` + object (or a file descriptor), in which case the md5sum of its contents is + returned. + + .. versionchanged:: 0.8.0 + Added support for using file descriptors. + +.. function:: sha1sum(object) + + Return the sha1sum of the object. *object* may either be a string, in + which case the sha1sum of the string is returned, or a :class:`file()` + object (or a file descriptor), in which case the sha1sum of its contents + is returned. + + .. versionchanged:: 0.8.0 + Added support for using file descriptors. + +.. function:: sha256sum(object) + + Return the sha256sum of the object. *object* may either be a string, in + which case the sha256sum of the string is returned, or a :class:`file()` + object (or a file descriptor), in which case the sha256sum of its contents + is returned. + + .. versionchanged:: 0.8.0 + Added support for using file descriptors. + +Debian control files +-------------------- +Debian control files are files containing multiple stanzas of :RFC:`822`-style +header sections. They are widely used in the Debian community, and can represent +many kinds of information. One example for such a file is the +:file:`/var/lib/dpkg/status` file which contains a list of the currently +installed packages. + +The :mod:`apt_pkg` module provides two classes to read those files and parts +thereof and provides a function :func:`RewriteSection` which takes a +:class:`TagSection()` object and sorting information and outputs a sorted +section as a string. + +.. class:: TagFile(file) + + An object which represents a typical debian control file. Can be used for + Packages, Sources, control, Release, etc. + + An example for working with a TagFile could look like:: + + tagf = apt_pkg.TagFile(open('/var/lib/dpkg/status')) + tagf.Step() + print tagf.Section['Package'] + + .. method:: Step + + Step forward to the next section. This simply returns ``1`` if OK, and + ``0`` if there is no section + + .. method:: Offset + + Return the current offset (in bytes) from the beginning of the file. + + .. method:: Jump(offset) + + Jump back/forward to *offset*. Use ``Jump(0)`` to jump to the + beginning of the file again. + + .. attribute:: Section + + This is the current :class:`TagSection()` instance. + +.. class:: TagSection(text) + + Represent a single section of a debian control file. + + .. describe:: section[key] + + Return the value of the field at *key*. If *key* is not available, + raise :exc:`KeyError`. + + .. describe:: key in section + + Return ``True`` if *section* has a key *key*, else ``False``. + + .. versionadded:: 0.8.0 + + .. method:: Bytes + + The number of bytes in the section. + + .. method:: Find(key, default='') + + Return the value of the field at the key *key* if available, + else return *default*. + + .. method:: FindFlag(key) + + Find a yes/no value for the key *key*. An example for such a + field is 'Essential'. + + .. method:: get(key, default='') + + Return the value of the field at the key *key* if available, else + return *default*. + + .. method:: has_key(key) + + Check whether the field with named by *key* exists. + + .. deprecated:: 0.8.0 + + .. method:: keys() + + Return a list of keys in the section. + +.. autofunction:: RewriteSection(section, order, rewrite_list) + +.. data:: RewritePackageOrder + + The order in which the information for binary packages should be rewritten, + i.e. the order in which the fields should appear. + +.. data:: RewriteSourceOrder + + The order in which the information for source packages should be rewritten, + i.e. the order in which the fields should appear. + +Dependencies +------------ +.. function:: CheckDep(pkgver, op, depver) + + Check that the dependency requirements consisting of op and depver can be + satisfied by the version pkgver. + + Example:: + + >>> bool(apt_pkg.CheckDep("1.0", ">=", "1")) + True + +.. function:: ParseDepends(depends) + + Parse the string *depends* which contains dependency information as + specified in Debian Policy, Section 7.1. + + Returns a list. The members of this list are lists themselves and contain + one or more tuples in the format ``(package,version,operation)`` for every + 'or'-option given, e.g.:: + + >>> apt_pkg.ParseDepends("PkgA (>= VerA) | PkgB (>= VerB)") + [[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]] + +.. function:: ParseSrcDepends(depends) + + Parse the string *depends* which contains dependency information as + specified in Debian Policy, Section 7.1. + + Returns a list. The members of this list are lists themselves and contain + one or more tuples in the format ``(package,version,operation)`` for every + 'or'-option given, e.g.:: + + >>> apt_pkg.ParseDepends("PkgA (>= VerA) | PkgB (>= VerB)") + [[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]] + + + Furthemore, this function also supports to limit the architectures, as + used in e.g. Build-Depends:: + + >>> apt_pkg.ParseSrcDepends("a (>= 01) [i386 amd64]") + [[('a', '01', '>=')]] + + +Configuration +------------- + +.. class:: Configuration() + + Configuration() objects store the configuration of apt, mostly created from + the contents of :file:`/etc/apt.conf` and the files in + :file:`/etc/apt.conf.d`. + + .. describe:: key in conf + + Return ``True`` if *conf* has a key *key*, else ``False``. + + .. versionadded:: 0.8.0 + + .. describe:: conf[key] + + Return the value of the option given key *key*. If it does not + exist, raise :exc:`KeyError`. + + .. describe:: conf[key] = value + + Set the option at *key* to *value*. + + .. method:: Find(key[, default='']) + + Return the value for the given key *key*. This is the same as + :meth:`Configuration.get`. + + If *key* does not exist, return *default*. + + .. method:: FindFile(key[, default='']) + + Return the filename hold by the configuration at *key*. This formats the + filename correctly and supports the Dir:: stuff in the configuration. + + If *key* does not exist, return *default*. + + .. method:: FindDir(key[, default='/']) + + Return the absolute path to the directory specified in *key*. A + trailing slash is appended. + + If *key* does not exist, return *default*. + + .. method:: FindI(key[, default=0]) + + Return the integer value stored at *key*. + + If *key* does not exist, return *default*. + + .. method:: FindB(key[, default=0]) + + Return the boolean value stored at *key*. This returns an integer, but + it should be treated like True/False. + + If *key* does not exist, return *default*. + + .. method:: Set(key, value) + + Set the value of *key* to *value*. + + .. method:: Exists(key) + + Check whether the key *key* exists in the configuration. + + .. method:: SubTree(key) + + Return a sub tree starting at *key*. The resulting object can be used + like this one. + + .. method:: List([key]) + + List all items at *key*. Normally, return the keys at the top level, + eg. APT, Dir, etc. + + Use *key* to specify a key of which the childs will be returned. + + .. method:: ValueList([key]) + + Same as :meth:`Configuration.List`, but this time for the values. + + .. method:: MyTag() + + Return the tag name of the current tree. Normally this is an empty + string, but for subtrees it is the key of the subtree. + + .. method:: Clear(key) + + Clear the configuration. Remove all values and keys at *key*. + + .. method:: keys([key]) + + Return all the keys, recursive. If *key* is specified, ... (FIXME) + + .. method:: has_key(key) + + Return whether the configuration contains the key *key*. + + .. deprecated:: 0.8.0 + + .. method:: get(key[, default='']) + + This behaves just like :meth:`dict.get` and :meth:`Configuration.Find`, + it returns the value of key or if it does not exist, *default*. + +.. class:: ConfigurationPtr + + Behaves like a :class:`Configuration()` objects, but uses a pointer to the + underlying C++ object. This is used for the default configuration in the + :data:`Config` attribute of the module. + +.. class:: ConfigurationSub + + Behaves like a :class:`Configuration()` objects, but provides access to + a subsection of another Configuration-like object. This type of object is + returned by the :meth:`Configuration.SubTree()` method. + +.. data:: Config + + A :class:`ConfigurationPtr()` object with the default configuration. This + object is initialized by calling :func:`InitConfig`. + + +Modifying +^^^^^^^^^ + + +.. function:: ReadConfigFile(configuration, filename) + + Read the configuration file specified by the parameter *filename* and add + the settings therein to the :class:`Configuration()` object specified by + the parameter *configuration* + +.. function:: ReadConfigDir(configuration, dirname) + + Read configuration files in the directory specified by the parameter + *dirname* and add the settings therein to the :class:`Configuration()` + object specified by the parameter *configuration*. + +.. function:: ReadConfigFileISC(configuration, filename) + + Read the configuration file specified by the parameter *filename* and add + the settings therein to the :class:`Configuration()` object specified by + the parameter *configuration* + +.. function:: ParseCommandLine(configuration,options,argv) + + This function is like getopt except it manipulates a configuration space. + output is a list of non-option arguments (filenames, etc). *options* is a + list of tuples of the form ``(‘c’,”long-opt or None”, + ”Configuration::Variable”,”optional type”)``. + + Where ``type`` may be one of HasArg, IntLevel, Boolean, InvBoolean, + ConfigFile, or ArbItem. The default is Boolean. + +Locking +-------- + +.. function:: GetLock(filename) + + Create an empty file at the path specified by the parameter *filename* and + lock it. + + While the file is locked by a process, calling this function in another + process returns ``-1``. + + When the lock is not required anymore, the file descriptor should be closed + using :func:`os.close`. + +.. function:: PkgSystemLock() + + Lock the global pkgsystem. + +.. function:: PkgSystemUnLock() + + Unlock the global pkgsystem. + +Other classes +-------------- +.. class:: Cdrom() + + Return a Cdrom object with the following methods: + + .. method:: Ident(progress) + + Identify the cdrom. The parameter *progress* refers to an + :class:`apt.progress.CdromProgress()` object. + + .. method:: Add(progress) + + Add the cdrom to the sources.list file. The parameter *progress* + refers to an :class:`apt.progress.CdromProgress()` object. + +.. class:: SourceList + + This is for :file:`/etc/apt/sources.list`. + + .. method:: FindIndex(pkgfile) + + Return a :class:`PackageIndexFile` object for the :class:`PackageFile` + *pkgfile*. + + .. method:: ReadMainList + + Read the main list. + + .. method:: GetIndexes(acq[, all]) + + Add the index files to the :class:`Acquire()` object *acq*. If *all* is + given and ``True``, all files are fetched. + +String functions +---------------- +.. function:: Base64Encode(string) + + Encode the given string using base64, e.g:: + + >>> apt_pkg.Base64Encode(u"A") + 'QQ==' + + +.. function:: CheckDomainList(host, list) + + See if Host is in a ',' seperated list, e.g.:: + + apt_pkg.CheckDomainList("alioth.debian.org","debian.net,debian.org") + +.. function:: DeQuoteString(string) + + Dequote the string specified by the parameter *string*, e.g.:: + + >>> apt_pkg.DeQuoteString("%61%70%74%20is%20cool") + 'apt is cool' + +.. function:: QuoteString(string, repl) + + For every character listed in the string *repl*, replace all occurences in + the string *string* with the correct HTTP encoded value: + + >>> apt_pkg.QuoteString("apt is cool","apt") + '%61%70%74%20is%20cool' + +.. function:: SizeToStr(size) + + Return a string presenting the human-readable version of the integer + *size*. When calculating the units (k,M,G,etc.) the size is divided by the + factor 1000. + + Example:: + + >>> apt_pkg.SizeToStr(10000) + '10.0k' + +.. function:: StringToBool(input) + + Parse the string *input* and return one of **-1**, **0**, **1**. + + .. table:: Return values + + ===== ============================================= + Value Meaning + ===== ============================================= + -1 The string *input* is not recognized. + 0 The string *input* evaluates to **False**. + +1 The string *input* evaluates to **True**. + ===== ============================================= + + Example:: + + >>> apt_pkg.StringToBool("yes") + 1 + >>> apt_pkg.StringToBool("no") + 0 + >>> apt_pkg.StringToBool("not-recognized") + -1 + +.. function:: StrToTime(rfc_time) + + Convert the :rfc:`1123` conforming string *rfc_time* to the unix time, and + return the integer. This is the opposite of :func:`TimeRFC1123`. + + Example:: + + >> apt_pkg.StrToTime('Thu, 01 Jan 1970 00:00:00 GMT') + 0 + +.. function:: TimeRFC1123(seconds) + + Format the unix time specified by the integer *seconds*, according to the + requirements of :rfc:`1123`. + + Example:: + + >>> apt_pkg.TimeRFC1123(0) + 'Thu, 01 Jan 1970 00:00:00 GMT' + + +.. function:: TimeToStr(seconds) + + Format a given duration in a human-readable manner. The parameter *seconds* + refers to a number of seconds, given as an integer. The return value is a + string with a unit like 's' for seconds. + + Example:: + + >>> apt_pkg.TimeToStr(3601) + '1h0min1s' + +.. function:: UpstreamVersion(version) + + Return the string *version*, eliminating everything following the last + '-'. Thus, this should be equivalent to ``version.rsplit('-', 1)[0]``. + +.. function:: URItoFileName(uri) + + Take a string *uri* as parameter and return a filename which can be used to + store the file, based on the URI. + + Example:: + + >>> apt_pkg.URItoFileName('http://debian.org/index.html') + 'debian.org_index.html' + + +.. function:: VersionCompare(a, b) + + Compare two versions, *a* and *b*, and return an integer value which has + the same characteristic as the built-in :func:`cmp` function. + + .. table:: Return values + + ===== ============================================= + Value Meaning + ===== ============================================= + > 0 The version *a* is greater than version *b*. + = 0 Both versions are equal. + < 0 The version *a* is less than version *b*. + ===== ============================================= + + + + +Module Constants +---------------- +.. _CurStates: + +Package States +^^^^^^^^^^^^^^^ +.. data:: CurStateConfigFiles +.. data:: CurStateHalfConfigured +.. data:: CurStateHalfInstalled +.. data:: CurStateInstalled +.. data:: CurStateNotInstalled +.. data:: CurStateUnPacked + + + + +Dependency types +^^^^^^^^^^^^^^^^ +.. data:: DepConflicts +.. data:: DepDepends +.. data:: DepObsoletes +.. data:: DepPreDepends +.. data:: DepRecommends +.. data:: DepReplaces +.. data:: DepSuggests + +.. _InstStates: + +Installed states +^^^^^^^^^^^^^^^^ +.. data:: InstStateHold +.. data:: InstStateHoldReInstReq +.. data:: InstStateOk +.. data:: InstStateReInstReq + +.. _Priorities: + +Priorities +^^^^^^^^^^^ +.. data:: PriExtra +.. data:: PriImportant +.. data:: PriOptional +.. data:: PriRequired +.. data:: PriStandard + + +.. _SelStates: + +Select states +^^^^^^^^^^^^^ +.. data:: SelStateDeInstall +.. data:: SelStateHold +.. data:: SelStateInstall +.. data:: SelStatePurge +.. data:: SelStateUnknown + + +Build information +^^^^^^^^^^^^^^^^^ +.. data:: Date + + The date on which this extension has been compiled. + +.. data:: LibVersion + + The version of the apt_pkg library. This is **not** the version of apt, + nor the version of python-apt. + +.. data:: Time + + The time this extension has been built. + +.. data:: Version + + The version of apt (not of python-apt). + +.. data:: _COMPAT_0_7 + + A more or less internal variable defining whether this build provides an + API which is compatible to the one of python-apt 0.7. This is used in the + apt and aptsources packages to decide whether compatibility should be + enabled or not. diff --git a/doc/source/apt_pkg/cache.rst b/doc/source/apt_pkg/cache.rst deleted file mode 100644 index a58f1356..00000000 --- a/doc/source/apt_pkg/cache.rst +++ /dev/null @@ -1,1243 +0,0 @@ -Classes in apt_pkg -================== - -.. todo:: - - This should be split and cleaned up a bit. - -:class:`Acquire` ----------------- -.. class:: Acquire - - .. method:: Run() - - Fetch all the items which have been added by - :func:`apt_pkg.GetPkgAcqFile`. - - .. method:: Shutdown - - Shut the fetcher down. - -:class:`PkgAcqFile` -------------------- -.. class:: PkgAcqFile - - This class provides no methods or attributes - -:class:`AcquireItem` ---------------------- - -.. class:: AcquireItem - - .. attribute:: ID - - The ID of the item. - - .. attribute:: Complete - - Is the item completely acquired? - - .. attribute:: Local - - Is the item a local file? - - .. attribute:: IsTrusted - - Can the file be trusted? - - .. attribute:: FileSize - - The size of the file, in bytes. - - .. attribute:: ErrorText - - The error message. For example, when a file does not exist on a http - server, this will contain a 404 error message. - - .. attribute:: DestFile - - The location the file is saved as. - - .. attribute:: DescURI - - The source location. - - **Status**: - - .. attribute:: Status - - Integer, representing the status of the item. - - .. attribute:: StatIdle - - Constant for comparing :attr:`AcquireItem.Status`. - - .. attribute:: StatFetching - - Constant for comparing :attr:`AcquireItem.Status` - - .. attribute:: StatDone - - Constant for comparing :attr:`AcquireItem.Status` - - .. attribute:: StatError - - Constant for comparing :attr:`AcquireItem.Status` - - .. attribute:: StatAuthError - - Constant for comparing :attr:`AcquireItem.Status` - -:class:`ActionGroup` --------------------- - -.. class:: ActionGroup - - Normally, apt checkes the package cache after every modification for - packages which are automatically installed but on which no package depends - anymore (it collects the package garbage). - - Using ActionGroups you can turn this off and therefore make your code - much faster. - - Initialize it using :func:`apt_pkg.GetPkgActionGroup`, eg:: - - apt_pkg.GetPkgActionGroup(depcache) - - .. method:: release - - Release the ActionGroup. This will reactive the collection of package - garbage. - - -:class:`Configuration` ----------------------- - -.. class:: Configuration - - The Configuration objects store the configuration of apt. - - .. describe:: key in conf - - Return ``True`` if *conf* has a key *key*, else ``False``. - - .. versionadded:: 0.8.0 - - .. describe:: conf[key] - - Return the value of the option given key *key*. If it does not - exist, raise :exc:`KeyError`. - - .. describe:: conf[key] = value - - Set the option at *key* to *value*. - - .. method:: Find(key[, default='']) - - Return the value for the given key *key*. This is the same as - :meth:`Configuration.get`. - - If *key* does not exist, return *default*. - - .. method:: FindFile(key[, default='']) - - Return the filename hold by the configuration at *key*. This formats the - filename correctly and supports the Dir:: stuff in the configuration. - - If *key* does not exist, return *default*. - - .. method:: FindDir(key[, default='/']) - - Return the absolute path to the directory specified in *key*. A - trailing slash is appended. - - If *key* does not exist, return *default*. - - .. method:: FindI(key[, default=0]) - - Return the integer value stored at *key*. - - If *key* does not exist, return *default*. - - .. method:: FindB(key[, default=0]) - - Return the boolean value stored at *key*. This returns an integer, but - it should be treated like True/False. - - If *key* does not exist, return *default*. - - .. method:: Set(key, value) - - Set the value of *key* to *value*. - - .. method:: Exists(key) - - Check whether the key *key* exists in the configuration. - - .. method:: SubTree(key) - - Return a sub tree starting at *key*. The resulting object can be used - like this one. - - .. method:: List([key]) - - List all items at *key*. Normally, return the keys at the top level, - eg. APT, Dir, etc. - - Use *key* to specify a key of which the childs will be returned. - - .. method:: ValueList([key]) - - Same as :meth:`Configuration.List`, but this time for the values. - - .. method:: MyTag() - - Return the tag name of the current tree. Normally this is an empty - string, but for subtrees it is the key of the subtree. - - .. method:: Clear(key) - - Clear the configuration. Remove all values and keys at *key*. - - .. method:: keys([key]) - - Return all the keys, recursive. If *key* is specified, ... (FIXME) - - .. method:: has_key(key) - - Return whether the configuration contains the key *key*. - - .. deprecated:: 0.8.0 - - .. method:: get(key[, default='']) - - This behaves just like :meth:`dict.get` and :meth:`Configuration.Find`, - it returns the value of key or if it does not exist, *default*. - - -:class:`pkgCache` ------------------ -.. class:: pkgCache - - The :class:`pkgCache` class prov - - .. describe:: cache[pkgname] - - Return the :class:`Package()` object for the package name given by - *pkgname*. - - .. method:: Close() - - Close the package cache. - - .. method:: Open([progress]) - - Open the package cache again. The parameter *progress* may be set to - an :class:`apt.progress.OpProgress()` object or `None`. - - .. method:: Update(progress, list) - - Update the package cache. - - The parameter *progress* points to an :class:`apt.progress.FetchProgress()` - object. - - The parameter *list* refers to an object as returned by - :func:`apt_pkg.GetPkgSourceList`. - - .. attribute:: DependsCount - - The total number of dependencies. - - .. attribute:: PackageCount - - The total number of packages available in the cache. - - .. attribute:: ProvidesCount - - The number of provided packages. - - .. attribute:: VerFileCount - - .. todo:: Seems to be some mixture of versions and pkgFile. - - .. attribute:: VersionCount - - The total number of package versions available in the cache. - - .. attribute:: PackageFileCount - - The total number of Packages files available (the Packages files - listing the packages). This is the same as the length of the list in - the attribute :attr:`FileList`. - - .. attribute:: FileList - - A list of :class:`PackageFile` objects. - - -:class:`PackageFile` --------------------- -.. class:: PackageFile - - A :class:`PackageFile` represents a Packages file, eg. - /var/lib/dpkg/status. - - .. attribute:: Architecture - - The architecture of the package file. - - .. attribute:: Archive - - The archive (eg. unstable) - - .. attribute:: Component - - The component (eg. main) - - .. attribute:: FileName - - The name of the file. - - .. attribute:: ID - - The ID of the package. This is an integer which can be used to store - further information about the file [eg. as dictionary key]. - - .. attribute:: IndexType - - The sort of the index file. In normal cases, this is - 'Debian Package Index'. - - .. attribute:: Label - - The Label, as set in the Release file - - .. attribute:: NotAutomatic - - Whether packages from this list will be updated automatically. The - default for eg. example is 0 (aka false). - - .. attribute:: NotSource - - Whether the file has no source from which it can be updated. In such a - case, the value is 1; else 0. /var/lib/dpkg/status is 0 for example. - - Example:: - - for pkgfile in cache.FileList: - if pkgfile.NotSource: - print 'The file %s has no source.' % pkgfile.FileName - - .. attribute:: Origin - - The Origin, as set in the Release file - - .. attribute:: Site - - The hostname of the site. - - .. attribute:: Size - - The size of the file. - - .. attribute:: Version - - The version, as set in the release file (eg. "4.0" for "Etch") - - -Example -^^^^^^^ -.. literalinclude:: ../examples/cache-pkgfile.py - - -:class:`Package` ----------------- - -.. class:: Package - - The pkgCache::Package objects are an interface to package specific - features. - - - Attributes: - - .. attribute:: CurrentVer - - The version currently installed, or None. This returns a - :class:`Version` object. - - .. attribute:: ID - - The ID of the package. This can be used to store information about - the package. The ID is an int value. - - .. attribute:: Name - - This is the name of the package. - - .. attribute:: ProvidesList - - A list of packages providing this package. More detailed, this is a - list of tuples (str:pkgname, ????, :class:`Version`). - - If you want to check for check for virtual packages, the expression - ``pkg.ProvidesList and not pkg.VersionList`` helps you. It detects if - the package is provided by something else and is not available as a - real package. - - .. attribute:: RevDependsList - - An iterator of :class:`Dependency` objects for dependencies on this - package. - - .. attribute:: Section - - The section of the package, as specified in the record. The list of - possible sections is defined in the Policy. - - .. attribute:: VersionList - - A list of :class:`Version` objects for all versions available in the - cache. - - **States**: - - .. attribute:: SelectedState - - The state we want it to be, ie. if you mark a package for installation, - this is :attr:`apt_pkg.SelStateInstall`. - - See :ref:`SelStates` for a list of available states. - - .. attribute:: InstState - - The state the currently installed version is in. This is normally - :attr:`apt_pkg.InstStateOK`, unless the installation failed. - - See :ref:`InstStates` for a list of available states. - - .. attribute:: CurState - - The current state of the package (not installed, unpacked, installed, - etc). See :ref:`CurStates` for a list of available states. - - **Flags**: - - .. attribute:: Auto - - Whether the package was installed automatically as a dependency of - another package. (or marked otherwise as automatically installed) - - .. attribute:: Essential - - Whether the package is essential. - - .. attribute:: Important - - Whether the package is important. - -Example: -^^^^^^^^^ -.. literalinclude:: ../examples/cache-packages.py - - - -:class:`Version` ----------------- -.. class:: Version - - The version object contains all information related to a specific package - version. - - .. attribute:: VerStr - - The version, as a string. - - .. attribute:: Section - - The usual sections (eg. admin, net, etc.). Prefixed with the component - name for packages not in main (eg. non-free/admin). - - .. attribute:: Arch - - The architecture of the package, eg. amd64 or all. - - .. attribute:: FileList - - A list of (:class:`PackageFile`, int: index) tuples for all Package - files containing this version of the package. - - .. attribute:: DependsListStr - - A dictionary of dependencies. The key specifies the type of the - dependency ('Depends', 'Recommends', etc.). - - - The value is a list, containing items which refer to the or-groups of - dependencies. Each of these or-groups is itself a list, containing - tuples like ('pkgname', 'version', 'relation') for each or-choice. - - An example return value for a package with a 'Depends: python (>= 2.4)' - would be:: - - {'Depends': [ - [ - ('python', '2.4', '>=') - ] - ] - } - - The same for a dependency on A (>= 1) | B (>= 2):: - - {'Depends': [ - [ - ('A', '1', '>='), - ('B', '2', '>='), - ] - ] - } - - .. attribute:: DependsList - - This is basically the same as :attr:`Version.DependsListStr`, - but instead of the ('pkgname', 'version', 'relation') tuples, - it returns :class:`Dependency` objects, which can assist you with - useful functions. - - .. attribute:: ParentPkg - - The :class:`Package` object this version belongs to. - - .. attribute:: ProvidesList - - This returns a list of all packages provided by this version. Like - :attr:`Package.ProvidesList`, it returns a list of tuples - of the form ('virtualpkgname', ???, :class:`Version`), where as the - last item is the same as the object itself. - - .. attribute:: Size - - The size of the .deb file, in bytes. - - .. attribute:: InstalledSize - - The size of the package (in kilobytes), when unpacked on the disk. - - .. attribute:: Hash - - An integer hash value. - - .. attribute:: ID - - An integer id. - - .. attribute:: Priority - - The integer representation of the priority. This can be used to speed - up comparisons a lot, compared to :attr:`Version.PriorityStr`. - - The values are defined in the :mod:`apt_pkg` extension, see - :ref:`Priorities` for more information. - - .. attribute:: PriorityStr - - Return the priority of the package version, as a string, eg. - "optional". - - .. attribute:: Downloadable - - Whether this package can be downloaded from a remote site. - - .. attribute:: TranslatedDescription - - Return a :class:`Description` object. - - -:class:`Dependency` -------------------- -.. class:: Dependency - - Represent a dependency from one package to another one. - - .. method:: AllTargets - - A list of :class:`Version` objects which satisfy the dependency, - and do not conflict with already installed ones. - - From my experience, if you use this method to select the target - version, it is the best to select the last item unless any of the - other candidates is already installed. This leads to results being - very close to the normal package installation. - - .. method:: SmartTargetPkg - - Return a :class:`Version` object of a package which satisfies the - dependency and does not conflict with installed packages - (the 'natural target'). - - .. attribute:: TargetVer - - The target version of the dependency, as string. Empty string if the - dependency is not versioned. - - .. attribute:: TargetPkg - - The :class:`Package` object of the target package. - - .. attribute:: ParentVer - - The :class:`Version` object of the parent version, ie. the package - which declares the dependency. - - .. attribute:: ParentPkg - - The :class:`Package` object of the package which declares the - dependency. This is the same as using ParentVer.ParentPkg. - - .. attribute:: CompType - - The type of comparison (>=, ==, >>, <=), as string. - - .. attribute:: DepType - - The type of the dependency, as string, eg. "Depends". - - .. attribute:: ID - - The ID of the package, as integer. - -Example: Find all missing dependencies -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -With the help of Dependency.AllTargets(), you can easily find all packages with -broken dependencies: - -.. literalinclude:: ../examples/missing-deps.py - - -:class:`Description` --------------------- -.. class:: Description - - Represent the description of the package. - - .. attribute:: LanguageCode - - The language code of the description - - .. attribute:: md5 - - The md5 hashsum of the description - - .. attribute:: FileList - - A list of tuples (:class:`PackageFile`, int: index). - - - -:class:`pkgDepCache` --------------------- -.. class:: pkgDepCache - - The pkgDepCache object contains various methods to manipulate the cache, - to install packages, to remove them, and much more. - - .. method:: Commit(fprogress, iprogress) - - Apply all the changes made. - - The parameter *fprogress* has to be set to an instance of - apt.progress.FetchProgress or one of its subclasses. - - The parameter *iprogress* has to be set to an instance of - apt.progress.InstallProgress or one of its subclasses. - - .. method:: FixBroken() - - Try to fix all broken packages in the cache. - - .. method:: GetCandidateVer(pkg) - - Return the candidate version of the package, ie. the version that - would be installed normally. - - The parameter *pkg* refers to an :class:`Package` object, - available using the :class:`pkgCache`. - - This method returns a :class:`Version` object. - - .. method:: SetCandidateVer(pkg, version) - - The opposite of :meth:`pkgDepCache.GetCandidateVer`. Set the candidate - version of the :class:`Package` *pkg* to the :class:`Version` - *version*. - - - .. method:: Upgrade([distUpgrade=False]) - - Perform an upgrade. More detailed, this marks all the upgradable - packages for upgrade. You still need to call - :meth:`pkgDepCache.Commit` for the changes to apply. - - To perform a dist-upgrade, the optional parameter *distUpgrade* has - to be set to True. - - .. method:: FixBroken() - - Fix broken packages. - - .. method:: ReadPinFile() - - Read the policy, eg. /etc/apt/preferences. - - .. method:: MinimizeUpgrade() - - Go over the entire set of packages and try to keep each package marked - for upgrade. If a conflict is generated then the package is restored. - - .. todo:: - Explain better.. - - .. method:: MarkKeep(pkg) - - Mark the :class:`Package` *pkg* for keep. - - .. method:: MarkDelete(pkg[, purge]) - - Mark the :class:`Package` *pkg* for delete. If *purge* is True, - the configuration files will be removed as well. - - .. method:: MarkInstall(pkg[, autoInst=True[, fromUser=True]]) - - Mark the :class:`Package` *pkg* for install. - - If *autoInst* is ``True``, the dependencies of the package will be - installed as well. This is the default. - - If *fromUser* is ``True``, the package will be marked as manually - installed. This is the default. - - .. method:: SetReinstall(pkg) - - Set if the :class:`Package` *pkg* should be reinstalled. - - .. method:: IsUpgradable(pkg) - - Return ``1`` if the package is upgradable. - - The package can be upgraded by calling :meth:`pkgDepCache.MarkInstall`. - - .. method:: IsNowBroken(pkg) - - Return `1` if the package is broken now (including changes made, but - not committed). - - .. method:: IsInstBroken(pkg) - - Return ``1`` if the package is broken on the current install. This - takes changes which have not been committed not into effect. - - .. method:: IsGarbage(pkg) - - Return ``1`` if the package is garbage, ie. if it is automatically - installed and no longer referenced by other packages. - - .. method:: IsAutoInstalled(pkg) - - Return ``1`` if the package is automatically installed (eg. as the - dependency of another package). - - .. method:: MarkedInstall(pkg) - - Return ``1`` if the package is marked for install. - - .. method:: MarkedUpgrade(pkg) - - Return ``1`` if the package is marked for upgrade. - - .. method:: MarkedDelete(pkg) - - Return ``1`` if the package is marked for delete. - - .. method:: MarkedKeep(pkg) - - Return ``1`` if the package is marked for keep. - - .. method:: MarkedReinstall(pkg) - - Return ``1`` if the package should be installed. - - .. method:: MarkedDowngrade(pkg) - - Return ``1`` if the package should be downgraded. - - .. attribute:: KeepCount - - Integer, number of packages marked as keep - - .. attribute:: InstCount - - Integer, number of packages marked for installation. - - .. attribute:: DelCount - - Number of packages which should be removed. - - .. attribute:: BrokenCount - - Number of packages which are broken. - - .. attribute:: UsrSize - - The size required for the changes on the filesystem. If you install - packages, this is positive, if you remove them its negative. - - .. attribute:: DebSize - - The size of the packages which are needed for the changes to be - applied. - - -:class:`MetaIndex` ------------------- - -.. todo:: - - Complete them - -.. class:: MetaIndex - - .. attribute:: URI - .. attribute:: Dist - .. attribute:: IsTrusted - .. attribute:: IndexFiles - - -:class:`PackageIndexFile` -------------------------- - -.. class:: PackageIndexFile - - .. method:: ArchiveURI(path) - - Return the full url to path in the archive. - - .. attribute:: Label - - Return the Label. - - .. attribute:: Exists - - Return whether the file exists. - - .. attribute:: HasPackages - - Return whether the file has packages. - - .. attribute:: Size - - Size of the file - - .. attribute:: IsTrusted - - Whether we can trust the file. - - -:class:`PkgManager` -------------------- - -.. class:: PkgManager - - Class, as returned by :func:`apt_pkg.GetPackageManager`. - - .. method:: GetArchives(fetcher, list, records) - - Add all the selected packages to the :class:`Acquire()` object - *fetcher*. - - The parameter *list* refers to a :class:`PkgSourceList()` object, as - returned by :func:`apt_pkg.GetPkgSourceList`. - - The parameter *records* refers to a :class:`pkgRecords()` object, as - returned by :func:`apt_pkg.GetPkgRecords`. - - .. method:: DoInstall() - - Install the packages. - - .. method:: FixMissing - - Fix the installation if a package could not be downloaded. - - .. attribute:: ResultCompleted - - A constant for checking whether the the result is 'completed'. - - Compare it against the return value of :meth:`PkgManager.GetArchives` - or :meth:`PkgManager.DoInstall`. - - .. attribute:: ResultFailed - - A constant for checking whether the the result is 'failed'. - - Compare it against the return value of :meth:`PkgManager.GetArchives` - or :meth:`PkgManager.DoInstall`. - - .. attribute:: ResultIncomplete - - A constant for checking whether the the result is 'incomplete'. - - Compare it against the return value of :meth:`PkgManager.GetArchives` - or :meth:`PkgManager.DoInstall`. - -:class:`pkgRecords` --------------------- - -.. class:: PkgRecords - - Provide access to the packages records. This provides very useful - attributes for fast (convient) access to some fields of the record. - - See :func:`apt_pkg.GetPkgRecords` for initialization. - - - .. method:: Lookup(verfile_iter) - - Change the actual package to the package given by the verfile_iter. - - The parameter *verfile_iter* refers to a tuple consisting - of (:class:`PackageFile()`, int: index), as returned by various - attributes, including :attr:`Version.FileList`. - - Example (shortened):: - - cand = depcache.GetCandidateVer(cache['python-apt']) - records.Lookup(cand.FileList[0]) - # Now you can access the record - print records.SourcePkg # == python-apt - - .. attribute:: FileName - - Return the field 'Filename' of the record. This is the path to the - package, relative to the base path of the archive. - - .. attribute:: MD5Hash - - Return the MD5 hashsum of the package This refers to the field - 'MD5Sum' in the raw record. - - .. attribute:: SHA1Hash - - Return the SHA1 hashsum of the package. This refers to the field 'SHA1' - in the raw record. - - .. attribute:: SHA256Hash - - Return the SHA256 hashsum of the package. This refers to the field - 'SHA256' in the raw record. - - .. versionadded:: 0.7.9 - - .. attribute:: SourcePkg - - Return the source package. - - .. attribute:: SourceVer - - Return the source version. - - .. attribute:: Maintainer - - Return the maintainer of the package. - - .. attribute:: ShortDesc - - Return the short description. This is the summary on the first line of - the 'Description' field. - - .. attribute:: LongDesc - - Return the long description. These are lines 2-END from the - 'Description' field. - - .. attribute:: Name - - Return the name of the package. This is the 'Package' field. - - .. attribute:: Homepage - - Return the Homepage. This is the 'Homepage' field. - - .. attribute:: Record - - Return the whole record as a string. If you want to access fields of - the record not available as an attribute, you can use - :func:`apt_pkg.ParseSection` to parse the record and access the field - name. - - Example:: - - section = apt_pkg.ParseSection(records.Record) - print section['SHA256'] - -:class:`PkgSrcRecords` ----------------------- - -.. class:: PkgSrcRecords - - This represents the entries in the Sources files, ie. the dsc files of - the source packages. - - .. note:: - - If the Lookup failed, because no package could be found, no error is - raised. Instead, the attributes listed below are simply not existing - anymore (same applies when no Lookup has been made, or when it has - been restarted). - - .. method:: Lookup(pkgname) - - Lookup the record for the package named *pkgname*. To access all - available records, you need to call it multiple times. - - Imagine a package P with two versions X, Y. The first ``Lookup(P)`` - would set the record to version X and the second ``Lookup(P)`` to - version Y. - - .. method:: Restart() - - Restart the lookup. - - Imagine a package P with two versions X, Y. The first ``Lookup(P)`` - would set the record to version X and the second ``Lookup(P)`` to - version Y. - - If you now call ``Restart()``, the internal position will be cleared. - Now you can call ``Lookup(P)`` again to move to X. - - .. attribute:: Package - - The name of the source package. - - .. attribute:: Version - - A string describing the version of the source package. - - .. attribute:: Maintainer - - A string describing the name of the maintainer. - - .. attribute:: Section - - A string describing the section. - - .. attribute:: Record - - The whole record, as a string. You can use :func:`apt_pkg.ParseSection` - if you need to parse it. - - You need to parse the record if you want to access fields not available - via the attributes, eg. 'Standards-Version' - - .. attribute:: Binaries - - Return a list of strings describing the package names of the binaries - created by the source package. This matches the 'Binary' field in the - raw record. - - .. attribute:: Index - - The index in the Sources files. - - .. attribute:: Files - - The list of files. This returns a list of tuples with the contents - ``(str: md5, int: size, str: path, str:type)``. - - .. attribute:: BuildDepends - - Return the list of Build dependencies, as - ``(str: package, str: version, int: op, int: type)``. - - .. table:: Values of *op* - - ===== ============================================= - Value Meaning - ===== ============================================= - 0x0 No Operation (no versioned build dependency) - 0x10 | (or) - this will be added to the other values - 0x1 <= (less than or equal) - 0x2 >= (greater than or equal) - 0x3 << (less than) - 0x4 >> (greater than) - 0x5 == (equal) - 0x6 != (not equal) - ===== ============================================= - - .. table:: Values of *type* - - ===== =================== - Value Meaning - ===== =================== - 0 Build-Depends - 1 Build-Depends-Indep - 2 Build-Conflicts - 3 Build-Conflicts-Indep - ===== =================== - - **Example**: In the following content, we will imagine a - build-dependency:: - - Build-Depends: A (>= 1) | B (>= 1), C - - This results in:: - - [('A', '1', 18, 0), # 18 = 16 + 2 = 0x10 + 0x2 - ('B', '1', 2, 0), - ('C', '', 0, 0)] - - This is **not** the same as returned by - :func:`apt_pkg.ParseSrcDepends`. - - -:class:`PkgSourceList` ------------------------ - -.. class:: PkgSourceList - - This is for :file:`/etc/apt/sources.list`. - - .. method:: FindIndex(pkgfile) - - Return a :class:`PackageIndexFile` object for the :class:`PackageFile` - *pkgfile*. - - .. method:: ReadMainList - - Read the main list. - - .. method:: GetIndexes(acq[, all]) - - Add the index files to the :class:`Acquire()` object *acq*. If *all* is - given and ``True``, all files are fetched. - - -:class:`ProblemResolver` ------------------------- -.. class:: ProblemResolver - - The problem resolver helps when there are problems in the package - selection. An example is a package which conflicts with another, already - installed package. - - .. method:: Protect(pkg) - - Protect the :class:`Package()` object given by the parameter *pkg*. - - .. todo:: - - Really document it. - - .. method:: InstallProtect() - - Protect all installed packages from being removed. - - .. method:: Remove(pkg) - - Remove the :class:`Package()` object given by the parameter *pkg*. - - .. todo:: - - Really document it. - - .. method:: Clear(pkg) - - Reset the :class:`Package()` *pkg* to the default state. - - .. todo:: - - Really document it. - - .. method:: Resolve() - - Try to resolve problems by installing and removing packages. - - .. method:: ResolveByKeep() - - Try to resolve problems only by using keep. - - -:class:`TagFile` ----------------- - -.. class:: TagFile - - An object which represents a typical debian control file. Can be used for - Packages, Sources, control, Release, etc. - - Use :func:`apt_pkg.ParseTagFile` to parse a file. - - .. method:: Step - - Step forward to the next section. This simply returns ``1`` if OK, and - ``0`` if there is no section - - .. method:: Offset - - Return the current offset (in bytes) from the beginning of the file. - - .. method:: Jump(offset) - - Jump back/forward to *offset*. Use ``Jump(0)`` to jump to the - beginning of the file again. - - .. attribute:: Section - - This is the current :class:`TagSection()` instance. - -:class:`TagSection` -------------------- - -.. class:: TagSection - - Represent a single section of a debian control file. - - .. describe:: section[key] - - Return the value of the field at *key*. If *key* is not available, - raise :exc:`KeyError`. - - .. describe:: key in section - - Return ``True`` if *section* has a key *key*, else ``False``. - - .. versionadded:: 0.8.0 - - .. method:: Bytes - - The number of bytes in the section. - - .. method:: Find(key, default='') - - Return the value of the field at the key *key* if available, - else return *default*. - - .. method:: FindFlag(key) - - Find a yes/no value for the key *key*. An example for such a - field is 'Essential'. - - .. method:: get(key, default='') - - Return the value of the field at the key *key* if available, else - return *default*. - - .. method:: has_key(key) - - Check whether the field with named by *key* exists. - - .. deprecated:: 0.8.0 - - .. method:: keys() - - Return a list of keys in the section. diff --git a/doc/source/apt_pkg/index.rst b/doc/source/apt_pkg/index.rst deleted file mode 100644 index 47923c23..00000000 --- a/doc/source/apt_pkg/index.rst +++ /dev/null @@ -1,530 +0,0 @@ -:mod:`apt_pkg` --- The low-level bindings for apt-pkg -===================================================== -.. module:: apt_pkg - -The apt_pkg extensions provides a more low-level way to work with apt. It can -do everything apt can, and is written in C++. It has been in python-apt since -the beginning. - - -.. toctree:: - :maxdepth: 2 - :glob: - - * - - -Module Initialization ---------------------- - -Initialization is needed for most functions, but not for all of them. Some can -be called without having run init*(), but will not return the expected value. - -.. function:: initConfig - - Initialize the configuration of apt. This is needed for most operations. - -.. function:: initSystem - - Initialize the system. - -.. function:: init - - Deprecated function. Use initConfig() and initSystem() instead. - -Object initialization ----------------------- -.. function:: GetCache([progress]) - - Return a :class:`pkgCache` object. The optional parameter *progress* - specifies an instance of :class:`apt.progress.OpProgress()` which will - display the open progress. - -.. function:: GetCdrom() - - Return a Cdrom object with the following methods: - - .. method:: Cdrom.Ident(progress) - - Identify the cdrom. The parameter *progress* refers to an - :class:`apt.progress.CdromProgress()` object. - - .. method:: Cdrom.Add(progress) - - Add the cdrom to the sources.list file. The parameter *progress* - refers to an :class:`apt.progress.CdromProgress()` object. - - -.. function:: GetDepCache(cache) - - Return a :class:`pkgDepCache` object. The parameter *cache* specifies an - instance of :class:`pkgCache` (see :func:`GetCache()`). - - -.. function:: GetPkgSourceList() - - Return a :class:`PkgSourceList` object. - -.. function:: GetPackageManager(depcache) - - Return a new :class:`PkgManager` object. The parameter *depcache* specifies - a :class:`pkgDepCache` object as returned by :func:`GetDepCache`. - -.. function:: GetPkgActionGroup(depcache) - - Return a new :class:`ActionGroup` object. The parameter *depcache* - specifies a :class:`pkgDepCache` object as returned by :func:`GetDepCache`. - -.. function:: GetPkgProblemResolver(depcache) - - Return a new :class:`ProblemResolver` object. The parameter *depcache* - specifies a :class:`pkgDepCache` object as returned by :func:`GetDepCache`. - -.. function:: GetPkgRecords(cache) - - Return a new :class:`PkgRecords` object. - - The parameter *cache* refers to an :class:`pkgCache` object, as returned - by :func:`GetCache`. - -.. function:: GetPkgSrcRecords() - - Return a new :class:`PkgSrcRecords` object. - - - -The Acquire interface ----------------------- -.. function:: GetAcquire([progress]) - - Return an :class:`Acquire` object. This is a class which allows you - to fetch files, or archive contents. The parameter *progress* refers to - an :class:`apt.progress.FetchProgress()` object. - - Acquire items have multiple methods: - - .. method:: Acquire.Run() - - Fetch all the items which have been added by :func:`GetPkgAcqFile`. - - .. method:: Acquire.Shutdown() - - Shut the fetcher down. - - .. attribute:: Acquire.TotalNeeded - - The total amount of bytes needed (including those of files which are - already present) - - .. attribute:: Acquire.FetchNeeded - - The total amount of bytes which need to be fetched. - - .. attribute:: Acquire.PartialPresent - - Whether some files have been acquired already. (???) - - -.. function:: GetPkgAcqFile(aquire, uri[, md5, size, descr, shortDescr, destDir, destFile]) - - Create a new :class:`PkgAcqFile()` object and register it with *acquire*, - so it will be fetched. - - The parameter *acquire* refers to an :class:`Acquire()` object as returned - by :func:`GetAcquire`. The file will be added to the Acquire queue - automatically. - - The parameter *uri* refers to the location of the file, any protocol - of apt is supported. - - The parameter *md5* refers to the md5sum of the file. This can be used - for checking the file. - - The parameter *size* can be used to specify the size of the package, - which can then be used to calculate the progress and validate the download. - - The parameter *descr* is a descripition of the download. It may be - used to describe the item in the progress class. *shortDescr* is the - short form of it. - - You can use *destDir* to manipulate the directory where the file will - be saved in. Instead of *destDir*, you can also specify the full path to - the file using the parameter *destFile*. You can not combine both. - - - -Hash functions --------------- -The apt_pkg module also provides several hash functions. If you develop -applications with python-apt it is often easier to use these functions instead -of the ones provides in Python's :mod:`hashlib` module. - -.. function:: md5sum(object) - - Return the md5sum of the object. *object* may either be a string, in - which case the md5sum of the string is returned, or a :class:`file()` - object (or a file descriptor), in which case the md5sum of its contents is - returned. - - .. versionchanged:: 0.8.0 - Added support for using file descriptors. - -.. function:: sha1sum(object) - - Return the sha1sum of the object. *object* may either be a string, in - which case the sha1sum of the string is returned, or a :class:`file()` - object (or a file descriptor), in which case the sha1sum of its contents - is returned. - - .. versionchanged:: 0.8.0 - Added support for using file descriptors. - -.. function:: sha256sum(object) - - Return the sha256sum of the object. *object* may either be a string, in - which case the sha256sum of the string is returned, or a :class:`file()` - object (or a file descriptor), in which case the sha256sum of its contents - is returned. - - .. versionchanged:: 0.8.0 - Added support for using file descriptors. - -Debian control files --------------------- -.. function:: ParseSection(text) - - Parse the string given in the parameter *text* and return a - :class:`TagSection` object. - -.. function:: ParseTagFile(file) - - Parse the given *file* and return a :class:`TagFile()` object. *file* may - be a :class:`file()` object, a file descriptor, or anything providing a - :meth:`fileno()` method. - - .. versionchanged:: 0.8.0 - Added support for using file descriptors. - -.. autofunction:: RewriteSection(section, order, rewrite_list) - -.. data:: RewritePackageOrder - - The order in which the information for binary packages should be rewritten, - i.e. the order in which the fields should appear. - -.. data:: RewriteSourceOrder - - The order in which the information for source packages should be rewritten, - i.e. the order in which the fields should appear. - -Dependencies ------------- -.. function:: CheckDep(pkgver, op, depver) - - Check that the dependency requirements consisting of op and depver can be - satisfied by the version pkgver. - - Example:: - - >>> bool(apt_pkg.CheckDep("1.0", ">=", "1")) - True - -.. function:: ParseDepends(depends) - - Parse the string *depends* which contains dependency information as - specified in Debian Policy, Section 7.1. - - Returns a list. The members of this list are lists themselves and contain - one or more tuples in the format ``(package,version,operation)`` for every - 'or'-option given, e.g.:: - - >>> apt_pkg.ParseDepends("PkgA (>= VerA) | PkgB (>= VerB)") - [[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]] - -.. function:: ParseSrcDepends(depends) - - Parse the string *depends* which contains dependency information as - specified in Debian Policy, Section 7.1. - - Returns a list. The members of this list are lists themselves and contain - one or more tuples in the format ``(package,version,operation)`` for every - 'or'-option given, e.g.:: - - >>> apt_pkg.ParseDepends("PkgA (>= VerA) | PkgB (>= VerB)") - [[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]] - - - Furthemore, this function also supports to limit the architectures, as - used in e.g. Build-Depends:: - - >>> apt_pkg.ParseSrcDepends("a (>= 01) [i386 amd64]") - [[('a', '01', '>=')]] - - -Configuration -------------- - -.. data:: Config - - A :class:`Configuration()`-like object with the default configuration. This - is implemented in the :class:`ConfigurationPtr` class, which has the same - API like the :class:`Configuration` class. - -.. function:: newConfiguration() - - Return a new :class:`Configuration` object. - -.. function:: ReadConfigFile(configuration, filename) - - Read the configuration file specified by the parameter *filename* and add - the settings therein to the :class:`Configuration()` object specified by - the parameter *configuration* - -.. function:: ReadConfigDir(configuration, dirname) - - Read configuration files in the directory specified by the parameter - *dirname* and add the settings therein to the :class:`Configuration()` - object specified by the parameter *configuration*. - -.. function:: ReadConfigFileISC(configuration, filename) - - Read the configuration file specified by the parameter *filename* and add - the settings therein to the :class:`Configuration()` object specified by - the parameter *configuration* - -.. function:: ParseCommandLine(configuration,options,argv) - - This function is like getopt except it manipulates a configuration space. - output is a list of non-option arguments (filenames, etc). *options* is a - list of tuples of the form ``(‘c’,”long-opt or None”, - ”Configuration::Variable”,”optional type”)``. - - Where ``type`` may be one of HasArg, IntLevel, Boolean, InvBoolean, - ConfigFile, or ArbItem. The default is Boolean. - -Locking --------- - -.. function:: GetLock(filename) - - Create an empty file at the path specified by the parameter *filename* and - lock it. - - While the file is locked by a process, calling this function in another - process returns ``-1``. - - When the lock is not required anymore, the file descriptor should be closed - using :func:`os.close`. - -.. function:: PkgSystemLock() - - Lock the global pkgsystem. - -.. function:: PkgSystemUnLock() - - Unlock the global pkgsystem. - -Other functions ----------------- -.. function:: Base64Encode(string) - - Encode the given string using base64, e.g:: - - >>> apt_pkg.Base64Encode(u"A") - 'QQ==' - - -.. function:: CheckDomainList(host, list) - - See if Host is in a ',' seperated list, e.g.:: - - apt_pkg.CheckDomainList("alioth.debian.org","debian.net,debian.org") - -.. function:: DeQuoteString(string) - - Dequote the string specified by the parameter *string*, e.g.:: - - >>> apt_pkg.DeQuoteString("%61%70%74%20is%20cool") - 'apt is cool' - -.. function:: QuoteString(string, repl) - - For every character listed in the string *repl*, replace all occurences in - the string *string* with the correct HTTP encoded value: - - >>> apt_pkg.QuoteString("apt is cool","apt") - '%61%70%74%20is%20cool' - -.. function:: SizeToStr(size) - - Return a string presenting the human-readable version of the integer - *size*. When calculating the units (k,M,G,etc.) the size is divided by the - factor 1000. - - Example:: - - >>> apt_pkg.SizeToStr(10000) - '10.0k' - -.. function:: StringToBool(input) - - Parse the string *input* and return one of **-1**, **0**, **1**. - - .. table:: Return values - - ===== ============================================= - Value Meaning - ===== ============================================= - -1 The string *input* is not recognized. - 0 The string *input* evaluates to **False**. - +1 The string *input* evaluates to **True**. - ===== ============================================= - - Example:: - - >>> apt_pkg.StringToBool("yes") - 1 - >>> apt_pkg.StringToBool("no") - 0 - >>> apt_pkg.StringToBool("not-recognized") - -1 - -.. function:: StrToTime(rfc_time) - - Convert the :rfc:`1123` conforming string *rfc_time* to the unix time, and - return the integer. This is the opposite of :func:`TimeRFC1123`. - - Example:: - - >> apt_pkg.StrToTime('Thu, 01 Jan 1970 00:00:00 GMT') - 0 - -.. function:: TimeRFC1123(seconds) - - Format the unix time specified by the integer *seconds*, according to the - requirements of :rfc:`1123`. - - Example:: - - >>> apt_pkg.TimeRFC1123(0) - 'Thu, 01 Jan 1970 00:00:00 GMT' - - -.. function:: TimeToStr(seconds) - - Format a given duration in a human-readable manner. The parameter *seconds* - refers to a number of seconds, given as an integer. The return value is a - string with a unit like 's' for seconds. - - Example:: - - >>> apt_pkg.TimeToStr(3601) - '1h0min1s' - -.. function:: UpstreamVersion(version) - - Return the string *version*, eliminating everything following the last - '-'. Thus, this should be equivalent to ``version.rsplit('-', 1)[0]``. - -.. function:: URItoFileName(uri) - - Take a string *uri* as parameter and return a filename which can be used to - store the file, based on the URI. - - Example:: - - >>> apt_pkg.URItoFileName('http://debian.org/index.html') - 'debian.org_index.html' - - -.. function:: VersionCompare(a, b) - - Compare two versions, *a* and *b*, and return an integer value which has - the same characteristic as the built-in :func:`cmp` function. - - .. table:: Return values - - ===== ============================================= - Value Meaning - ===== ============================================= - > 0 The version *a* is greater than version *b*. - = 0 Both versions are equal. - < 0 The version *a* is less than version *b*. - ===== ============================================= - - - - -.. _CurStates: - -Package States ---------------- -.. data:: CurStateConfigFiles -.. data:: CurStateHalfConfigured -.. data:: CurStateHalfInstalled -.. data:: CurStateInstalled -.. data:: CurStateNotInstalled -.. data:: CurStateUnPacked - - - - -Dependency types ----------------- -.. data:: DepConflicts -.. data:: DepDepends -.. data:: DepObsoletes -.. data:: DepPreDepends -.. data:: DepRecommends -.. data:: DepReplaces -.. data:: DepSuggests - -.. _InstStates: - -Installed states ------------------ -.. data:: InstStateHold -.. data:: InstStateHoldReInstReq -.. data:: InstStateOk -.. data:: InstStateReInstReq - -.. _Priorities: - -Priorities ----------- -.. data:: PriExtra -.. data:: PriImportant -.. data:: PriOptional -.. data:: PriRequired -.. data:: PriStandard - - -.. _SelStates: - -Select states --------------- -.. data:: SelStateDeInstall -.. data:: SelStateHold -.. data:: SelStateInstall -.. data:: SelStatePurge -.. data:: SelStateUnknown - - -Build information ------------------ -.. data:: Date - - The date on which this extension has been compiled. - -.. data:: LibVersion - - The version of the apt_pkg library. This is **not** the version of apt, - nor the version of python-apt. - -.. data:: Time - - The time this extension has been built. - -.. data:: Version - - The version of apt (not of python-apt). diff --git a/doc/source/index.rst b/doc/source/index.rst index 930ff55c..2e05061a 100644 --- a/doc/source/index.rst +++ b/doc/source/index.rst @@ -1,27 +1,27 @@ Welcome to python-apt's documentation! ====================================== -.. note:: +This is the official documentation for version |version| of the Python bindings +for Debian's famous APT package management. - This documentation can not be considered complete at the moment. But it - provides better documentation than the documentation available through - pydoc. +This documentation has been created by Sphinx, using reStructuredText files +written by Julian Andres Klode , and in case of the apt +package, from the documentation shipped in the modules. -.. note:: +Contents: - This documentation has been created by Sphinx, using reStructuredText files - written by Julian Andres Klode , and in case of the apt - package, from the documentation shipped in the modules. - +.. toctree:: + :hidden: -Contents: + whatsnew/index .. toctree:: :maxdepth: 2 + whatsnew/0.8.0 apt/index - apt_pkg/index + apt_pkg apt_inst aptsources/index contributing diff --git a/doc/source/whatsnew/0.8.0.rst b/doc/source/whatsnew/0.8.0.rst new file mode 100644 index 00000000..d1ac3ac5 --- /dev/null +++ b/doc/source/whatsnew/0.8.0.rst @@ -0,0 +1,33 @@ +What's New In python-apt 0.8 +============================ +Python-apt 0.8 is a new major release of the python bindings for the APT +package management libraries. It provides support for Python 3, new language +features and an API conforming to :PEP:`8`. + +Despite the many changes made in python-apt 0.8, the release still provides +backwards compatibility to the 0.7 series. This makes it possible to run your +old applications. Applications using the old API should be updated to the new +API, because the old one will be removed after some time. + +Support for Python 3 +-------------------- +Python-apt is the first Debian package to support the third major release of +Python. The port is straight forward and integrates as nicely in Python 3 as +the Python 2 builds integrate in Python 2. + +Real classes in :mod:`apt_pkg` +------------------------------ + +Complete rename of functions, methods and attributes +----------------------------------------------------- + +Supporting new language features like the :keyword:`with` statement +------------------------------------------------------------------- + +Other changes +------------- +This release of python-apt also features several other, smaller changes: + + * Reduced memory usage by creating Package() objects in apt.Cache() only + when needed. + * Support to set the candidate version in :class:`apt.package.Package` diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst new file mode 100644 index 00000000..cc270a16 --- /dev/null +++ b/doc/source/whatsnew/index.rst @@ -0,0 +1,9 @@ +What's new in python-apt +======================== + +.. toctree:: + :maxdepth: 2 + :glob: + + * + -- cgit v1.2.3 From cdabff6d329baba8024224b362f79d822ddd943e Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 4 Jun 2009 18:54:50 +0200 Subject: apt, aptsources, doc: Update to use the new names. --- apt/__init__.py | 4 +- apt/cache.py | 78 ++--- apt/cdrom.py | 14 +- apt/debfile.py | 50 +-- apt/package.py | 208 ++++++------ apt/progress/__init__.py | 8 +- apt/progress/gtk2.py | 2 +- aptsources/distinfo.py | 2 +- aptsources/sourceslist.py | 16 +- doc/source/apt_pkg.rst | 608 +++++++++++++++++----------------- doc/source/examples/cache-packages.py | 16 +- doc/source/examples/cache-pkgfile.py | 14 +- doc/source/examples/dpkg-contents.py | 4 +- doc/source/examples/dpkg-extract.py | 2 +- doc/source/examples/dpkg-info.py | 4 +- doc/source/examples/missing-deps.py | 30 +- 16 files changed, 531 insertions(+), 529 deletions(-) (limited to 'doc/source') diff --git a/apt/__init__.py b/apt/__init__.py index 734b3240..41c0a30f 100644 --- a/apt/__init__.py +++ b/apt/__init__.py @@ -31,7 +31,9 @@ if apt_pkg._COMPAT_0_7: if apt_pkg._COMPAT_0_7: - from apt_pkg import SizeToStr, TimeToStr, VersionCompare + from apt_pkg import (size_to_str as SizeToStr, + time_to_str as TimeToStr, + version_compare as VersionCompare) # init the package system apt_pkg.init() diff --git a/apt/cache.py b/apt/cache.py index 60fd6553..56b32d45 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -52,16 +52,16 @@ class Cache(object): self._callbacks = {} if memonly: # force apt to build its caches in memory - apt_pkg.Config.Set("Dir::Cache::pkgcache", "") + apt_pkg.config.set("Dir::Cache::pkgcache", "") if rootdir: if os.path.exists(rootdir+"/etc/apt/apt.conf"): - apt_pkg.ReadConfigFile(apt_pkg.Config, + apt_pkg.read_config_file(apt_pkg.config, rootdir + "/etc/apt/apt.conf") if os.path.isdir(rootdir+"/etc/apt/apt.conf.d"): - apt_pkg.ReadConfigDir(apt_pkg.Config, + apt_pkg.read_config_dir(apt_pkg.config, rootdir + "/etc/apt/apt.conf.d") - apt_pkg.Config.Set("Dir", rootdir) - apt_pkg.Config.Set("Dir::State::status", + apt_pkg.config.set("Dir", rootdir) + apt_pkg.config.set("Dir::State::status", rootdir + "/var/lib/dpkg/status") self.open(progress) @@ -82,20 +82,20 @@ class Cache(object): self._depcache = apt_pkg.DepCache(self._cache) self._records = apt_pkg.PackageRecords(self._cache) self._list = apt_pkg.SourceList() - self._list.ReadMainList() + self._list.read_main_list() self._set = set() self._weakref = weakref.WeakValueDictionary() progress.Op = "Building data structures" i=last=0 - size=len(self._cache.Packages) - for pkg in self._cache.Packages: + size=len(self._cache.packages) + for pkg in self._cache.packages: if progress is not None and last+100 < i: progress.update(i/float(size)*100) last=i # drop stuff with no versions (cruft) - if len(pkg.VersionList) > 0: - self._set.add(pkg.Name) + if len(pkg.version_list) > 0: + self._set.add(pkg.name) i += 1 @@ -148,7 +148,7 @@ class Cache(object): default value is False. """ self.cache_pre_change() - self._depcache.Upgrade(dist_upgrade) + self._depcache.upgrade(dist_upgrade) self.cache_post_change() @property @@ -156,13 +156,13 @@ class Cache(object): """Get the size of the packages that are required to download.""" pm = apt_pkg.PackageManager(self._depcache) fetcher = apt_pkg.Acquire() - pm.GetArchives(fetcher, self._list, self._records) - return fetcher.FetchNeeded + pm.get_archives(fetcher, self._list, self._records) + return fetcher.fetch_needed @property def required_space(self): """Get the size of the additional required space on the fs.""" - return self._depcache.UsrSize + return self._depcache.usr_size @property def req_reinstall_pkgs(self): @@ -170,31 +170,31 @@ class Cache(object): reqreinst = set() for pkg in self: if (not pkg.candidate.downloadable and - (pkg._pkg.InstState == apt_pkg.InstStateReInstReq or - pkg._pkg.InstState == apt_pkg.InstStateHoldReInstReq)): + (pkg._pkg.inst_state == apt_pkg.INSTSTATE_RE_INST_REQ or + pkg._pkg.inst_state == apt_pkg.INSTSTATE_HOLD_RE_INST_REQ)): reqreinst.add(pkg.name) return reqreinst def _run_fetcher(self, fetcher): # do the actual fetching - res = fetcher.Run() + res = fetcher.run() # now check the result (this is the code from apt-get.cc) failed = False transient = False err_msg = "" - for item in fetcher.Items: - if item.Status == item.StatDone: + for item in fetcher.items: + if item.status == item.stat_done: continue - if item.StatIdle: + if item.stat_idle: transient = True continue - err_msg += "Failed to fetch %s %s\n" % (item.DescURI, - item.ErrorText) + err_msg += "Failed to fetch %s %s\n" % (item.desc_uri, + item.error_text) failed = True # we raise a exception if the download failed or it was cancelt - if res == fetcher.ResultCancelled: + if res == fetcher.result_cancelled: raise FetchCancelledException(err_msg) elif failed: raise FetchFailedException(err_msg) @@ -204,14 +204,14 @@ class Cache(object): """ fetch the needed archives """ # get lock - lockfile = apt_pkg.Config.FindDir("Dir::Cache::Archives") + "lock" - lock = apt_pkg.GetLock(lockfile) + lockfile = apt_pkg.config.find_dir("Dir::Cache::Archives") + "lock" + lock = apt_pkg.get_lock(lockfile) if lock < 0: raise LockFailedException("Failed to lock %s" % lockfile) try: # this may as well throw a SystemError exception - if not pm.GetArchives(fetcher, self._list, self._records): + if not pm.get_archives(fetcher, self._list, self._records): return False # now run the fetcher, throw exception if something fails to be # fetched @@ -222,7 +222,7 @@ class Cache(object): def is_virtual_package(self, pkgname): """Return whether the package is a virtual package.""" pkg = self._cache[pkgname] - return bool(pkg.ProvidesList and not pkg.VersionList) + return bool(pkg.provides_list and not pkg.version_list) def get_providing_packages(self, virtual): """ @@ -232,15 +232,15 @@ class Cache(object): providers = [] try: vp = self._cache[virtual] - if len(vp.VersionList) != 0: + if len(vp.version_list) != 0: return providers except KeyError: return providers for pkg in self: - v = self._depcache.GetCandidateVer(pkg._pkg) + v = self._depcache.get_candidate_ver(pkg._pkg) if v is None: continue - for p in v.ProvidesList: + for p in v.provides_list: if virtual == p[0]: # we found a pkg that provides this virtual pkg providers.append(pkg) @@ -254,15 +254,15 @@ class Cache(object): apt.progress.FetchProgress, the default is apt.progress.FetchProgress() . """ - lockfile = apt_pkg.Config.FindDir("Dir::State::Lists") + "lock" - lock = apt_pkg.GetLock(lockfile) + lockfile = apt_pkg.config.find_dir("Dir::State::Lists") + "lock" + lock = apt_pkg.get_lock(lockfile) if lock < 0: raise LockFailedException("Failed to lock %s" % lockfile) try: if fetch_progress is None: fetch_progress = apt.progress.FetchProgress() - return self._cache.Update(fetch_progress, self._list) + return self._cache.update(fetch_progress, self._list) finally: os.close(lock) @@ -317,17 +317,17 @@ class Cache(object): # then install res = self.install_archives(pm, install_progress) - if res == pm.ResultCompleted: + if res == pm.result_completed: break - if res == pm.ResultFailed: + if res == pm.result_failed: raise SystemError("installArchives() failed") # reload the fetcher for media swaping - fetcher.Shutdown() - return (res == pm.ResultCompleted) + fetcher.shutdown() + return (res == pm.result_completed) def clear(self): """ Unmark all changes """ - self._depcache.Init() + self._depcache.init() # cache changes @@ -493,7 +493,7 @@ def _test(): for dir in ["/tmp/pytest", "/tmp/pytest/partial"]: if not os.path.exists(dir): os.mkdir(dir) - apt_pkg.Config.Set("Dir::Cache::Archives", "/tmp/pytest") + apt_pkg.config.set("Dir::Cache::Archives", "/tmp/pytest") pm = apt_pkg.PackageManager(cache._depcache) fetcher = apt_pkg.Acquire(apt.progress.TextFetchProgress()) cache._fetch_archives(fetcher, pm) diff --git a/apt/cdrom.py b/apt/cdrom.py index b9625ebf..a98b5d99 100644 --- a/apt/cdrom.py +++ b/apt/cdrom.py @@ -52,20 +52,20 @@ class Cdrom(object): self._progress = progress # see if we have a alternative mountpoint if mountpoint is not None: - apt_pkg.Config.Set("Acquire::cdrom::mount", mountpoint) + apt_pkg.config.set("Acquire::cdrom::mount", mountpoint) # do not mess with mount points by default if nomount: - apt_pkg.Config.Set("APT::CDROM::NoMount", "true") + apt_pkg.config.set("APT::CDROM::NoMount", "true") else: - apt_pkg.Config.Set("APT::CDROM::NoMount", "false") + apt_pkg.config.set("APT::CDROM::NoMount", "false") def add(self): """Add cdrom to the sources.list.""" - return self._cdrom.Add(self._progress) + return self._cdrom.add(self._progress) def ident(self): """Identify the cdrom.""" - (res, ident) = self._cdrom.Ident(self._progress) + (res, ident) = self._cdrom.ident(self._progress) if res: return ident @@ -77,8 +77,8 @@ class Cdrom(object): # FIXME: throw exception instead return False # Get a list of files - src = glob.glob(apt_pkg.Config.FindDir("Dir::Etc::sourceparts") + '*') - src.append(apt_pkg.Config.FindFile("Dir::Etc::sourcelist")) + src = glob.glob(apt_pkg.config.find_dir("Dir::Etc::sourceparts") + '*') + src.append(apt_pkg.config.find_file("Dir::Etc::sourcelist")) # Check each file for fname in src: for line in open(fname): diff --git a/apt/debfile.py b/apt/debfile.py index 6e4adb39..84bbe3ab 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -52,11 +52,11 @@ class DebPackage(object): def open(self, filename): " open given debfile " self.filename = filename - if not apt_inst.arCheckMember(open(self.filename), "debian-binary"): + if not apt_inst.ar_check_member(open(self.filename), "debian-binary"): raise NoDebArchiveException(_("This is not a valid DEB archive, " "missing '%s' member" % "debian-binary")) - control = apt_inst.debExtractControl(open(self.filename)) + control = apt_inst.deb_extract_control(open(self.filename)) self._sections = apt_pkg.TagSection(control) self.pkgname = self._sections["Package"] @@ -72,9 +72,9 @@ class DebPackage(object): files.append(name) for member in self._supported_data_members: - if apt_inst.arCheckMember(open(self.filename), member): + if apt_inst.ar_check_member(open(self.filename), member): try: - apt_inst.debExtract(open(self.filename), extract_cb, + apt_inst.deb_extract(open(self.filename), extract_cb, member) break except SystemError: @@ -106,7 +106,7 @@ class DebPackage(object): continue inst = self._cache[depname].installed - if inst is not None and apt_pkg.CheckDep(inst.version, oper, ver): + if inst is not None and apt_pkg.check_dep(inst.version, oper, ver): return True return False @@ -129,10 +129,10 @@ class DebPackage(object): # now check if we can satisfy the deps with the candidate(s) # in the cache pkg = self._cache[depname] - cand = self._cache._depcache.GetCandidateVer(pkg._pkg) + cand = self._cache._depcache.get_candidate_ver(pkg._pkg) if not cand: continue - if not apt_pkg.CheckDep(cand.VerStr, oper, ver): + if not apt_pkg.check_dep(cand.ver_str, oper, ver): continue # check if we need to install it @@ -168,7 +168,7 @@ class DebPackage(object): #print "ver: %s" % ver #print "pkgver: %s " % pkgver #print "oper: %s " % oper - if (apt_pkg.CheckDep(pkgver, oper, ver) and not + if (apt_pkg.check_dep(pkgver, oper, ver) and not self.replaces_real_pkg(pkgname, oper, ver)): self._failure_string += _("Conflicts with the installed package " "'%s'" % pkg.name) @@ -211,7 +211,7 @@ class DebPackage(object): """List of package names conflicting with this package.""" key = "Conflicts" try: - return apt_pkg.ParseDepends(self._sections[key]) + return apt_pkg.parse_depends(self._sections[key]) except KeyError: return [] @@ -222,7 +222,7 @@ class DebPackage(object): # find depends for key in "Depends", "PreDepends": try: - depends.extend(apt_pkg.ParseDepends(self._sections[key])) + depends.extend(apt_pkg.parse_depends(self._sections[key])) except KeyError: pass return depends @@ -232,7 +232,7 @@ class DebPackage(object): """List of virtual packages which are provided by this package.""" key = "Provides" try: - return apt_pkg.ParseDepends(self._sections[key]) + return apt_pkg.parse_depends(self._sections[key]) except KeyError: return [] @@ -241,7 +241,7 @@ class DebPackage(object): """List of packages which are replaced by this package.""" key = "Replaces" try: - return apt_pkg.ParseDepends(self._sections[key]) + return apt_pkg.parse_depends(self._sections[key]) except KeyError: return [] @@ -261,7 +261,7 @@ class DebPackage(object): pkgver = None for or_group in self.replaces: for (name, ver, oper) in or_group: - if (name == pkgname and apt_pkg.CheckDep(pkgver, oper, ver)): + if (name == pkgname and apt_pkg.check_dep(pkgver, oper, ver)): self._dbg(3, "we have a replaces in our package for the " "conflict against '%s'" % (pkgname)) return True @@ -298,7 +298,7 @@ class DebPackage(object): else: cachever = self._cache[pkgname].candidate.version if cachever is not None: - cmp = apt_pkg.VersionCompare(cachever, debver) + cmp = apt_pkg.version_compare(cachever, debver) self._dbg(1, "CompareVersion(debver,instver): %s" % cmp) if cmp == 0: return VERSION_SAME @@ -310,11 +310,11 @@ class DebPackage(object): def check(self): """Check if the package is installable.""" - self._dbg(3, "checkDepends") + self._dbg(3, "check_depends") # check arch arch = self._sections["Architecture"] - if arch != "all" and arch != apt_pkg.Config.Find("APT::Architecture"): + if arch != "all" and arch != apt_pkg.config.find("APT::Architecture"): self._dbg(1, "ERROR: Wrong architecture dude!") self._failure_string = _("Wrong architecture '%s'" % arch) return False @@ -341,7 +341,7 @@ class DebPackage(object): if not self.check_conflicts(): return False - if self._cache._depcache.BrokenCount > 0: + if self._cache._depcache.broken_count > 0: self._failure_string = _("Failed to satisfy all dependencies " "(broken cache)") # clean the cache again @@ -351,7 +351,7 @@ class DebPackage(object): def satisfy_depends_str(self, dependsstr): """Satisfy the dependencies in the given string.""" - return self._satisfy_depends(apt_pkg.ParseDepends(dependsstr)) + return self._satisfy_depends(apt_pkg.parse_depends(dependsstr)) def _satisfy_depends(self, depends): """Satisfy the dependencies.""" @@ -459,17 +459,17 @@ class DscSrcPackage(DebPackage): fobj = open(file) tagfile = apt_pkg.TagFile(fobj) - sec = tagfile.Section + sec = tagfile.section try: - while tagfile.Step() == 1: + while tagfile.step() == 1: for tag in depends_tags: if not tag in sec: continue - self._depends.extend(apt_pkg.ParseSrcDepends(sec[tag])) + self._depends.extend(apt_pkg.parse_src_depends(sec[tag])) for tag in conflicts_tags: if not tag in sec: continue - self._conflicts.extend(apt_pkg.ParseSrcDepends(sec[tag])) + self._conflicts.extend(apt_pkg.parse_src_depends(sec[tag])) if 'Source' in sec: self.pkgname = sec['Source'] if 'Binary' in sec: @@ -490,7 +490,7 @@ class DscSrcPackage(DebPackage): """Check if the package is installable..""" if not self.check_conflicts(): for pkgname in self._installed_conflicts: - if self._cache[pkgname]._pkg.Essential: + if self._cache[pkgname]._pkg.essential: raise Exception(_("An essential package would be removed")) self._cache[pkgname].mark_delete() # FIXME: a additional run of the checkConflicts() @@ -525,13 +525,13 @@ def _test(): print ret #s = DscSrcPackage(cache, "../tests/3ddesktop_0.2.9-6.dsc") - #s.checkDep() + #s.check_dep() #print "Missing deps: ",s.missingDeps #print "Print required changes: ", s.requiredChanges s = DscSrcPackage(cache=cache) d = "libc6 (>= 2.3.2), libaio (>= 0.3.96) | libaio1 (>= 0.3.96)" - print s._satisfy_depends(apt_pkg.ParseDepends(d)) + print s._satisfy_depends(apt_pkg.parse_depends(d)) if __name__ == "__main__": _test() diff --git a/apt/package.py b/apt/package.py index 3dbdf058..a24486e1 100644 --- a/apt/package.py +++ b/apt/package.py @@ -130,15 +130,15 @@ class Origin(object): """ def __init__(self, pkg, packagefile): - self.archive = packagefile.Archive - self.component = packagefile.Component - self.label = packagefile.Label - self.origin = packagefile.Origin - self.site = packagefile.Site - self.not_automatic = packagefile.NotAutomatic + self.archive = packagefile.archive + self.component = packagefile.component + self.label = packagefile.label + self.origin = packagefile.origin + self.site = packagefile.site + self.not_automatic = packagefile.not_automatic # check the trust - indexfile = pkg._pcache._list.FindIndex(packagefile) - if indexfile and indexfile.IsTrusted: + indexfile = pkg._pcache._list.find_index(packagefile) + if indexfile and indexfile.is_trusted: self.trusted = True else: self.trusted = False @@ -206,19 +206,19 @@ class Version(object): self._cand = cand def __eq__(self, other): - return self._cand.ID == other._cand.ID + return self._cand.id == other._cand.id def __gt__(self, other): - return apt_pkg.VersionCompare(self.version, other.version) > 0 + return apt_pkg.version_compare(self.version, other.version) > 0 def __lt__(self, other): - return apt_pkg.VersionCompare(self.version, other.version) < 0 + return apt_pkg.version_compare(self.version, other.version) < 0 def __ne__(self, other): return not self.__eq__(other) def __hash__(self): - return self._cand.Hash + return self._cand.hash def __repr__(self): return '' % (self.package.name, @@ -227,60 +227,60 @@ class Version(object): @property def _records(self): """Internal helper that moves the Records to the right position.""" - if self.package._pcache._records.Lookup(self._cand.FileList[0]): + if self.package._pcache._records.lookup(self._cand.file_list[0]): return self.package._pcache._records @property def _translated_records(self): """Internal helper to get the translated description.""" - desc_iter = self._cand.TranslatedDescription - self.package._pcache._records.Lookup(desc_iter.FileList.pop(0)) + desc_iter = self._cand.translated_description + self.package._pcache._records.lookup(desc_iter.file_list.pop(0)) return self.package._pcache._records @property def installed_size(self): """Return the size of the package when installed.""" - return self._cand.InstalledSize + return self._cand.installed_size @property def homepage(self): """Return the homepage for the package.""" - return self._records.Homepage + return self._records.homepage @property def size(self): """Return the size of the package.""" - return self._cand.Size + return self._cand.size @property def architecture(self): """Return the architecture of the package version.""" - return self._cand.Arch + return self._cand.arch @property def downloadable(self): """Return whether the version of the package is downloadable.""" - return bool(self._cand.Downloadable) + return bool(self._cand.downloadable) @property def version(self): """Return the version as a string.""" - return self._cand.VerStr + return self._cand.ver_str @property def summary(self): """Return the short description (one line summary).""" - return self._translated_records.ShortDesc + return self._translated_records.short_desc @property def raw_description(self): """return the long description (raw).""" - return self._records.LongDesc + return self._records.long_desc @property def section(self): """Return the section of the package.""" - return self._cand.Section + return self._cand.section @property def description(self): @@ -292,7 +292,7 @@ class Version(object): for more information. """ desc = '' - dsc = self._translated_records.LongDesc + dsc = self._translated_records.long_desc try: if not isinstance(dsc, unicode): # Only convert where needed (i.e. Python 2.X) @@ -333,32 +333,32 @@ class Version(object): def source_name(self): """Return the name of the source package.""" try: - return self._records.SourcePkg or self.package.name + return self._records.source_pkg or self.package.name except IndexError: return self.package.name @property def priority(self): """Return the priority of the package, as string.""" - return self._cand.PriorityStr + return self._cand.priority_str @property def record(self): """Return a Record() object for this version.""" - return Record(self._records.Record) + return Record(self._records.record) @property def dependencies(self): """Return the dependencies of the package version.""" depends_list = [] - depends = self._cand.DependsList + depends = self._cand.depends_list for t in ["PreDepends", "Depends"]: try: for dep_ver_list in depends[t]: base_deps = [] for dep_or in dep_ver_list: - base_deps.append(BaseDependency(dep_or.TargetPkg.Name, - dep_or.CompType, dep_or.TargetVer, + base_deps.append(BaseDependency(dep_or.target_pkg.name, + dep_or.comp_type, dep_or.target_ver, (t == "PreDepends"))) depends_list.append(Dependency(base_deps)) except KeyError: @@ -369,7 +369,7 @@ class Version(object): def origins(self): """Return a list of origins for the package version.""" origins = [] - for (packagefile, index) in self._cand.FileList: + for (packagefile, index) in self._cand.file_list: origins.append(Origin(self.package, packagefile)) return origins @@ -379,7 +379,7 @@ class Version(object): .. versionadded:: 0.7.10 """ - return self._records.FileName + return self._records.file_name @property def md5(self): @@ -387,7 +387,7 @@ class Version(object): .. versionadded:: 0.7.10 """ - return self._records.MD5Hash + return self._records.md5_hash @property def sha1(self): @@ -395,7 +395,7 @@ class Version(object): .. versionadded:: 0.7.10 """ - return self._records.SHA1Hash + return self._records.sha1_hash @property def sha256(self): @@ -403,17 +403,17 @@ class Version(object): .. versionadded:: 0.7.10 """ - return self._records.SHA256Hash + return self._records.sha256_hash def _uris(self): """Return an iterator over all available urls. .. versionadded:: 0.7.10 """ - for (packagefile, index) in self._cand.FileList: - indexfile = self.package._pcache._list.FindIndex(packagefile) + for (packagefile, index) in self._cand.file_list: + indexfile = self.package._pcache._list.find_index(packagefile) if indexfile: - yield indexfile.ArchiveURI(self._records.FileName) + yield indexfile.archive_uri(self._records.file_name) @property def uris(self): @@ -443,19 +443,19 @@ class Version(object): .. versionadded:: 0.7.10 """ - base = os.path.basename(self._records.FileName) + base = os.path.basename(self._records.file_name) destfile = os.path.join(destdir, base) - if _file_is_same(destfile, self.size, self._records.MD5Hash): + if _file_is_same(destfile, self.size, self._records.md5_hash): print 'Ignoring already existing file:', destfile return acq = apt_pkg.Acquire(progress or apt.progress.TextFetchProgress()) - apt_pkg.AcquireFile(acq, self.uri, self._records.MD5Hash, self.size, - base, destfile=destfile) - acq.Run() - for item in acq.Items: - if item.Status != item.StatDone: + apt_pkg.AcquireFile(acq, self.uri, self._records.md5_hash, self.size, + base, dest_file=destfile) + acq.run() + for item in acq.items: + if item.status != item.stat_done: raise FetchError("The item %r could not be fetched: %s" % - (item.DestFile, item.ErrorText)) + (item.dest_file, item.error_text)) return os.path.abspath(destfile) def fetch_source(self, destdir="", progress=None, unpack=True): @@ -478,13 +478,13 @@ class Version(object): acq = apt_pkg.Acquire(progress or apt.progress.TextFetchProgress()) dsc = None - src.Lookup(self.package.name) + src.lookup(self.package.name) try: - while self.version != src.Version: - src.Lookup(self.package.name) + while self.version != src.version: + src.lookup(self.package.name) except AttributeError: raise ValueError("No source for %r" % self) - for md5, size, path, type in src.Files: + for md5, size, path, type in src.files: base = os.path.basename(path) destfile = os.path.join(destdir, base) if type == 'dsc': @@ -497,17 +497,17 @@ class Version(object): continue finally: fobj.close() - apt_pkg.AcquireFile(acq, src.Index.ArchiveURI(path), md5, size, - base, destfile=destfile) - acq.Run() + apt_pkg.AcquireFile(acq, src.index.archive_uri(path), md5, size, + base, dest_file=destfile) + acq.run() - for item in acq.Items: - if item.Status != item.StatDone: + for item in acq.items: + if item.status != item.stat_done: raise FetchError("The item %r could not be fetched: %s" % - (item.DestFile, item.ErrorText)) + (item.dest_file, item.error_text)) if unpack: - outdir = src.Package + '-' + apt_pkg.UpstreamVersion(src.Version) + outdir = src.package + '-' + apt_pkg.upstream_version(src.version) outdir = os.path.join(destdir, outdir) subprocess.check_call(["dpkg-source", "-x", dsc, outdir]) return os.path.abspath(outdir) @@ -530,7 +530,7 @@ class Package(object): self._changelog = "" # Cached changelog def __repr__(self): - return '' % (self._pkg.Name, self._pkg.ID) + return '' % (self._pkg.name, self._pkg.id) def candidate(self): """Return the candidate version of the package. @@ -541,14 +541,14 @@ class Package(object): .. versionadded:: 0.7.9 """ - cand = self._pcache._depcache.GetCandidateVer(self._pkg) + cand = self._pcache._depcache.get_candidate_ver(self._pkg) if cand is not None: return Version(self, cand) def __set_candidate(self, version): """Set the candidate version of the package.""" self._pcache.cache_pre_change() - self._pcache._depcache.SetCandidateVer(self._pkg, version._cand) + self._pcache._depcache.set_candidate_ver(self._pkg, version._cand) self._pcache.cache_post_change() candidate = property(candidate, __set_candidate) @@ -559,26 +559,26 @@ class Package(object): .. versionadded:: 0.7.9 """ - if self._pkg.CurrentVer is not None: - return Version(self, self._pkg.CurrentVer) + if self._pkg.current_ver is not None: + return Version(self, self._pkg.current_ver) @property def name(self): """Return the name of the package.""" - return self._pkg.Name + return self._pkg.name @property def id(self): """Return a uniq ID for the package. This can be used eg. to store additional information about the pkg.""" - return self._pkg.ID + return self._pkg.id def __hash__(self): """Return the hash of the object. This returns the same value as ID, which is unique.""" - return self._pkg.ID + return self._pkg.id @DeprecatedProperty def installedVersion(self): #pylint: disable-msg=C0103 @@ -641,12 +641,12 @@ class Package(object): .. deprecated:: 0.7.9 """ try: - return self.candidate._records.SourcePkg or self._pkg.Name + return self.candidate._records.source_pkg or self._pkg.name except AttributeError: try: - return self.installed._records.SourcePkg or self._pkg.Name + return self.installed._records.source_pkg or self._pkg.name except AttributeError: - return self._pkg.Name + return self._pkg.name @DeprecatedProperty def homepage(self): @@ -659,7 +659,7 @@ class Package(object): @property def section(self): """Return the section of the package.""" - return self._pkg.Section + return self._pkg.section @DeprecatedProperty def priority(self): @@ -724,43 +724,43 @@ class Package(object): @property def marked_install(self): """Return ``True`` if the package is marked for install.""" - return self._pcache._depcache.MarkedInstall(self._pkg) + return self._pcache._depcache.marked_install(self._pkg) @property def marked_upgrade(self): """Return ``True`` if the package is marked for upgrade.""" - return self._pcache._depcache.MarkedUpgrade(self._pkg) + return self._pcache._depcache.marked_upgrade(self._pkg) @property def marked_delete(self): """Return ``True`` if the package is marked for delete.""" - return self._pcache._depcache.MarkedDelete(self._pkg) + return self._pcache._depcache.marked_delete(self._pkg) @property def marked_keep(self): """Return ``True`` if the package is marked for keep.""" - return self._pcache._depcache.MarkedKeep(self._pkg) + return self._pcache._depcache.marked_keep(self._pkg) @property def marked_downgrade(self): """ Package is marked for downgrade """ - return self._pcache._depcache.MarkedDowngrade(self._pkg) + return self._pcache._depcache.marked_downgrade(self._pkg) @property def marked_reinstall(self): """Return ``True`` if the package is marked for reinstall.""" - return self._pcache._depcache.MarkedReinstall(self._pkg) + return self._pcache._depcache.marked_reinstall(self._pkg) @property def is_installed(self): """Return ``True`` if the package is installed.""" - return (self._pkg.CurrentVer is not None) + return (self._pkg.current_ver is not None) @property def is_upgradable(self): """Return ``True`` if the package is upgradable.""" return (self.is_installed and - self._pcache._depcache.IsUpgradable(self._pkg)) + self._pcache._depcache.is_upgradable(self._pkg)) @property def is_auto_removable(self): @@ -771,7 +771,7 @@ class Package(object): is no longer required. """ return self.is_installed and \ - self._pcache._depcache.IsGarbage(self._pkg) + self._pcache._depcache.is_garbage(self._pkg) # sizes @@ -880,15 +880,15 @@ class Package(object): # sources.list # otherwise we fall back to the binary version number src_records = apt_pkg.SourceRecords() - src_rec = src_records.Lookup(src_pkg) + src_rec = src_records.lookup(src_pkg) if src_rec: - src_ver = src_records.Version + src_ver = src_records.version #if apt_pkg.VersionCompare(binver, srcver) > 0: # srcver = binver if not src_ver: src_ver = bin_ver #print "srcver: %s" % src_ver - section = src_records.Section + section = src_records.section #print "srcsect: %s" % section else: # fail into the error handler @@ -954,8 +954,8 @@ class Package(object): changelog_ver = match.group(1) if changelog_ver and ":" in changelog_ver: changelog_ver = changelog_ver.split(":", 1)[1] - if (installed and apt_pkg.VersionCompare(changelog_ver, - installed) <= 0): + if (installed and apt_pkg.version_compare( + changelog_ver, installed) <= 0): break # EOF (shouldn't really happen) changelog += line @@ -992,14 +992,14 @@ class Package(object): .. versionadded:: 0.7.9 """ - return [Version(self, ver) for ver in self._pkg.VersionList] + return [Version(self, ver) for ver in self._pkg.version_list] # depcache actions def mark_keep(self): """Mark a package for keep.""" self._pcache.cache_pre_change() - self._pcache._depcache.MarkKeep(self._pkg) + self._pcache._depcache.mark_keep(self._pkg) self._pcache.cache_post_change() @deprecated_args @@ -1013,15 +1013,15 @@ class Package(object): as well. The default is to keep the configuration. """ self._pcache.cache_pre_change() - self._pcache._depcache.MarkDelete(self._pkg, purge) + self._pcache._depcache.mark_delete(self._pkg, purge) # try to fix broken stuffsta - if auto_fix and self._pcache._depcache.BrokenCount > 0: + if auto_fix and self._pcache._depcache.broken_count > 0: fix = apt_pkg.ProblemResolver(self._pcache._depcache) - fix.Clear(self._pkg) - fix.Protect(self._pkg) - fix.Remove(self._pkg) - fix.InstallProtect() - fix.Resolve() + fix.clear(self._pkg) + fix.protect(self._pkg) + fix.remove(self._pkg) + fix.install_protect() + fix.resolve() self._pcache.cache_post_change() @deprecated_args @@ -1040,13 +1040,13 @@ class Package(object): when no other package depends on it. """ self._pcache.cache_pre_change() - self._pcache._depcache.MarkInstall(self._pkg, auto_inst, from_user) + self._pcache._depcache.mark_install(self._pkg, auto_inst, from_user) # try to fix broken stuff - if auto_fix and self._pcache._depcache.BrokenCount > 0: + if auto_fix and self._pcache._depcache.broken_count > 0: fixer = apt_pkg.ProblemResolver(self._pcache._depcache) - fixer.Clear(self._pkg) - fixer.Protect(self._pkg) - fixer.Resolve(True) + fixer.clear(self._pkg) + fixer.protect(self._pkg) + fixer.resolve(True) self._pcache.cache_post_change() def mark_upgrade(self): @@ -1056,7 +1056,7 @@ class Package(object): else: # FIXME: we may want to throw a exception here sys.stderr.write(("MarkUpgrade() called on a non-upgrable pkg: " - "'%s'\n") % self._pkg.Name) + "'%s'\n") % self._pkg.name) def commit(self, fprogress, iprogress): """Commit the changes. @@ -1067,7 +1067,7 @@ class Package(object): The parameter *iprogress* refers to an InstallProgress() object, as found in apt.progress. """ - self._pcache._depcache.Commit(fprogress, iprogress) + self._pcache._depcache.commit(fprogress, iprogress) if not apt_pkg._COMPAT_0_7: @@ -1149,8 +1149,8 @@ def _test(): if pkg.is_upgradable: if random.randint(0, 1) == 1: pkg.mark_install(i) - print "Broken: %s " % cache._depcache.BrokenCount - print "InstCount: %s " % cache._depcache.InstCount + print "Broken: %s " % cache._depcache.broken_count + print "InstCount: %s " % cache._depcache.inst_count print # get a new cache @@ -1163,8 +1163,8 @@ def _test(): cache[name].mark_delete(i) except SystemError: print "Error trying to remove: %s " % name - print "Broken: %s " % cache._depcache.BrokenCount - print "DelCount: %s " % cache._depcache.DelCount + print "Broken: %s " % cache._depcache.broken_count + print "DelCount: %s " % cache._depcache.del_count # self-test if __name__ == "__main__": diff --git a/apt/progress/__init__.py b/apt/progress/__init__.py index 769942ce..d2a9d497 100644 --- a/apt/progress/__init__.py +++ b/apt/progress/__init__.py @@ -153,8 +153,8 @@ class TextFetchProgress(FetchProgress): FetchProgress.pulse(self) if self.currentCPS > 0: s = "[%2.f%%] %sB/s %s" % (self.percent, - apt_pkg.SizeToStr(int(self.currentCPS)), - apt_pkg.TimeToStr(int(self.eta))) + apt_pkg.size_to_str(int(self.currentCPS)), + apt_pkg.time_to_str(int(self.eta))) else: s = "%2.f%% [Working]" % (self.percent) print "\r%s" % (s), @@ -184,7 +184,7 @@ class DumbInstallProgress(object): def run(self, pm): """Start installation.""" - return pm.DoInstall() + return pm.do_install() def finishUpdate(self): """Called when update has finished.""" @@ -278,7 +278,7 @@ class InstallProgress(DumbInstallProgress): pid = self.fork() if pid == 0: # child - res = pm.DoInstall(self.writefd) + res = pm.do_install(self.writefd) os._exit(res) self.child_pid = pid res = self.waitChild() diff --git a/apt/progress/gtk2.py b/apt/progress/gtk2.py index 36d459bc..06ece2d5 100644 --- a/apt/progress/gtk2.py +++ b/apt/progress/gtk2.py @@ -247,7 +247,7 @@ class GFetchProgress(gobject.GObject, apt.progress.FetchProgress): "%(speed)s/s") % \ {"current": currentItem, "total": self.totalItems, - "speed": apt_pkg.SizeToStr(self.currentCPS)}) + "speed": apt_pkg.size_to_str(self.currentCPS)}) else: text = (_("Downloading file %(current)li of %(total)li") % \ {"current": currentItem, diff --git a/aptsources/distinfo.py b/aptsources/distinfo.py index ce44e48b..268d9b9f 100644 --- a/aptsources/distinfo.py +++ b/aptsources/distinfo.py @@ -148,7 +148,7 @@ class DistInfo: base_dir = "/usr/share/python-apt/templates"): self.metarelease_uri = '' self.templates = [] - self.arch = apt_pkg.Config.Find("APT::Architecture") + self.arch = apt_pkg.config.find("APT::Architecture") location = None match_loc = re.compile(r"^#LOC:(.+)$") diff --git a/aptsources/sourceslist.py b/aptsources/sourceslist.py index fdc0f029..710bfe15 100644 --- a/aptsources/sourceslist.py +++ b/aptsources/sourceslist.py @@ -88,8 +88,8 @@ class SourceEntry: self.comment = "" # (optional) comment self.line = line # the original sources.list line if file is None: - file = apt_pkg.Config.FindDir( - "Dir::Etc")+apt_pkg.Config.Find("Dir::Etc::sourcelist") + file = apt_pkg.config.find_dir( + "Dir::Etc")+apt_pkg.config.find("Dir::Etc::sourcelist") self.file = file # the file that the entry is located in self.parse(line) self.template = None # type DistInfo.Suite @@ -237,10 +237,10 @@ class SourcesList(object): """ update the list of known entries """ self.list = [] # read sources.list - file = apt_pkg.Config.FindFile("Dir::Etc::sourcelist") + file = apt_pkg.config.find_file("Dir::Etc::sourcelist") self.load(file) # read sources.list.d - partsdir = apt_pkg.Config.FindDir("Dir::Etc::sourceparts") + partsdir = apt_pkg.config.find_dir("Dir::Etc::sourceparts") for file in glob.glob("%s/*.list" % partsdir): self.load(file) # check if the source item fits a predefined template @@ -312,12 +312,12 @@ class SourcesList(object): def restore_backup(self, backup_ext): " restore sources.list files based on the backup extension " - file = apt_pkg.Config.FindFile("Dir::Etc::sourcelist") + file = apt_pkg.config.find_file("Dir::Etc::sourcelist") if os.path.exists(file+backup_ext) and \ os.path.exists(file): shutil.copy(file+backup_ext, file) # now sources.list.d - partsdir = apt_pkg.Config.FindDir("Dir::Etc::sourceparts") + partsdir = apt_pkg.config.find_dir("Dir::Etc::sourceparts") for file in glob.glob("%s/*.list" % partsdir): if os.path.exists(file+backup_ext): shutil.copy(file+backup_ext, file) @@ -355,7 +355,7 @@ class SourcesList(object): files = {} # write an empty default config file if there aren't any sources if len(self.list) == 0: - path = apt_pkg.Config.FindFile("Dir::Etc::sourcelist") + path = apt_pkg.config.find_file("Dir::Etc::sourcelist") header = ( "## See sources.list(5) for more information, especialy\n" "# Remember that you can only use http, ftp or file URIs\n" @@ -433,7 +433,7 @@ class SourceEntryMatcher: # some simple tests if __name__ == "__main__": - apt_pkg.InitConfig() + apt_pkg.init_config() sources = SourcesList() for entry in sources: diff --git a/doc/source/apt_pkg.rst b/doc/source/apt_pkg.rst index 8c602f37..39b48c35 100644 --- a/doc/source/apt_pkg.rst +++ b/doc/source/apt_pkg.rst @@ -13,17 +13,17 @@ Module Initialization Initialization is needed for most functions, but not for all of them. Some can be called without having run init*(), but will not return the expected value. -.. function:: initConfig +.. function:: init_config Initialize the configuration of apt. This is needed for most operations. -.. function:: initSystem +.. function:: init_system Initialize the system. .. function:: init - Deprecated function. Use initConfig() and initSystem() instead. + Deprecated function. Use init_config() and init_system() instead. Working with the cache ---------------------- @@ -38,49 +38,49 @@ Working with the cache Return the :class:`Package()` object for the package name given by *pkgname*. - .. method:: Close() + .. method:: close() Close the package cache. - .. method:: Open([progress]) + .. method:: open([progress]) Open the package cache again. The parameter *progress* may be set to an :class:`apt.progress.OpProgress()` object or `None`. - .. method:: Update(progress, list) + .. method:: update(progress, list) Update the package cache. The parameter *progress* points to an :class:`apt.progress.FetchProgress()` object. The parameter *list* refers to a :class:`SourceList()` object. - .. attribute:: DependsCount + .. attribute:: depends_count The total number of dependencies. - .. attribute:: PackageCount + .. attribute:: package_count The total number of packages available in the cache. - .. attribute:: ProvidesCount + .. attribute:: provides_count The number of provided packages. - .. attribute:: VerFileCount + .. attribute:: ver_file_count .. todo:: Seems to be some mixture of versions and pkgFile. - .. attribute:: VersionCount + .. attribute:: version_count The total number of package versions available in the cache. - .. attribute:: PackageFileCount + .. attribute:: package_file_count The total number of Packages files available (the Packages files listing the packages). This is the same as the length of the list in - the attribute :attr:`FileList`. + the attribute :attr:`file_list`. - .. attribute:: FileList + .. attribute:: file_list A list of :class:`PackageFile` objects. @@ -92,7 +92,7 @@ Working with the cache The DepCache object contains various methods to manipulate the cache, to install packages, to remove them, and much more. - .. method:: Commit(fprogress, iprogress) + .. method:: commit(fprogress, iprogress) Apply all the changes made. @@ -102,11 +102,11 @@ Working with the cache The parameter *iprogress* has to be set to an instance of apt.progress.InstallProgress or one of its subclasses. - .. method:: FixBroken() + .. method:: fix_broken() Try to fix all broken packages in the cache. - .. method:: GetCandidateVer(pkg) + .. method:: get_candidate_ver(pkg) Return the candidate version of the package, ie. the version that would be installed normally. @@ -116,31 +116,31 @@ Working with the cache This method returns a :class:`Version` object. - .. method:: SetCandidateVer(pkg, version) + .. method:: set_candidate_ver(pkg, version) - The opposite of :meth:`pkgDepCache.GetCandidateVer`. Set the candidate + The opposite of :meth:`pkgDepCache.get_candidate_ver`. Set the candidate version of the :class:`Package` *pkg* to the :class:`Version` *version*. - .. method:: Upgrade([distUpgrade=False]) + .. method:: upgrade([dist_upgrade=False]) Perform an upgrade. More detailed, this marks all the upgradable packages for upgrade. You still need to call - :meth:`pkgDepCache.Commit` for the changes to apply. + :meth:`pkgDepCache.commit` for the changes to apply. - To perform a dist-upgrade, the optional parameter *distUpgrade* has + To perform a dist-upgrade, the optional parameter *dist_upgrade* has to be set to True. - .. method:: FixBroken() + .. method:: fix_broken() Fix broken packages. - .. method:: ReadPinFile() + .. method:: read_pin_file() Read the policy, eg. /etc/apt/preferences. - .. method:: MinimizeUpgrade() + .. method:: minimize_upgrade() Go over the entire set of packages and try to keep each package marked for upgrade. If a conflict is generated then the package is restored. @@ -148,101 +148,101 @@ Working with the cache .. todo:: Explain better.. - .. method:: MarkKeep(pkg) + .. method:: mark_keep(pkg) Mark the :class:`Package` *pkg* for keep. - .. method:: MarkDelete(pkg[, purge]) + .. method:: mark_delete(pkg[, purge]) Mark the :class:`Package` *pkg* for delete. If *purge* is True, the configuration files will be removed as well. - .. method:: MarkInstall(pkg[, autoInst=True[, fromUser=True]]) + .. method:: mark_install(pkg[, auto_inst=True[, from_user=True]]) Mark the :class:`Package` *pkg* for install. - If *autoInst* is ``True``, the dependencies of the package will be + If *auto_inst* is ``True``, the dependencies of the package will be installed as well. This is the default. - If *fromUser* is ``True``, the package will be marked as manually + If *from_user* is ``True``, the package will be marked as manually installed. This is the default. - .. method:: SetReinstall(pkg) + .. method:: set_re_install(pkg) Set if the :class:`Package` *pkg* should be reinstalled. - .. method:: IsUpgradable(pkg) + .. method:: is_upgradable(pkg) Return ``1`` if the package is upgradable. The package can be upgraded by calling :meth:`pkgDepCache.MarkInstall`. - .. method:: IsNowBroken(pkg) + .. method:: is_now_broken(pkg) Return `1` if the package is broken now (including changes made, but not committed). - .. method:: IsInstBroken(pkg) + .. method:: is_inst_broken(pkg) Return ``1`` if the package is broken on the current install. This takes changes which have not been committed not into effect. - .. method:: IsGarbage(pkg) + .. method:: is_garbage(pkg) Return ``1`` if the package is garbage, ie. if it is automatically installed and no longer referenced by other packages. - .. method:: IsAutoInstalled(pkg) + .. method:: is_auto_installed(pkg) Return ``1`` if the package is automatically installed (eg. as the dependency of another package). - .. method:: MarkedInstall(pkg) + .. method:: marked_install(pkg) Return ``1`` if the package is marked for install. - .. method:: MarkedUpgrade(pkg) + .. method:: marked_upgrade(pkg) Return ``1`` if the package is marked for upgrade. - .. method:: MarkedDelete(pkg) + .. method:: marked_delete(pkg) Return ``1`` if the package is marked for delete. - .. method:: MarkedKeep(pkg) + .. method:: marked_keep(pkg) Return ``1`` if the package is marked for keep. - .. method:: MarkedReinstall(pkg) + .. method:: marked_reinstall(pkg) Return ``1`` if the package should be installed. - .. method:: MarkedDowngrade(pkg) + .. method:: marked_downgrade(pkg) Return ``1`` if the package should be downgraded. - .. attribute:: KeepCount + .. attribute:: keep_count Integer, number of packages marked as keep - .. attribute:: InstCount + .. attribute:: inst_count Integer, number of packages marked for installation. - .. attribute:: DelCount + .. attribute:: del_count Number of packages which should be removed. - .. attribute:: BrokenCount + .. attribute:: broken_count Number of packages which are broken. - .. attribute:: UsrSize + .. attribute:: usr_size The size required for the changes on the filesystem. If you install packages, this is positive, if you remove them its negative. - .. attribute:: DebSize + .. attribute:: deb_size The size of the packages which are needed for the changes to be applied. @@ -256,7 +256,7 @@ Working with the cache :class:`PackageManager` objects provide several methods and attributes, which will be listed here: - .. method:: GetArchives(fetcher, list, records) + .. method:: get_archives(fetcher, list, records) Add all the selected packages to the :class:`Acquire()` object *fetcher*. @@ -265,34 +265,34 @@ Working with the cache The parameter *records* refers to a :class:`PackageRecords()` object. - .. method:: DoInstall() + .. method:: do_install() Install the packages. - .. method:: FixMissing + .. method:: fix_missing Fix the installation if a package could not be downloaded. - .. attribute:: ResultCompleted + .. attribute:: result_completed A constant for checking whether the the result is 'completed'. - Compare it against the return value of :meth:`PkgManager.GetArchives` - or :meth:`PkgManager.DoInstall`. + Compare it against the return value of :meth:`PackageManager.get_archives` + or :meth:`PackageManager.do_install`. - .. attribute:: ResultFailed + .. attribute:: result_failed A constant for checking whether the the result is 'failed'. - Compare it against the return value of :meth:`PkgManager.GetArchives` - or :meth:`PkgManager.DoInstall`. + Compare it against the return value of :meth:`PackageManager.get_archives` + or :meth:`PackageManager.do_install`. - .. attribute:: ResultIncomplete + .. attribute:: result_incomplete A constant for checking whether the the result is 'incomplete'. - Compare it against the return value of :meth:`PkgManager.GetArchives` - or :meth:`PkgManager.DoInstall`. + Compare it against the return value of :meth:`PackageManager.get_archives` + or :meth:`PackageManager.do_install`. Improve performance with :class:`ActionGroup` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -336,13 +336,13 @@ Resolving Dependencies .. class:: ProblemResolver(depcache) Return a new :class:`ProblemResolver` object. The parameter *depcache* - specifies a :class:`pkgDepCache` object as returned by :func:`GetDepCache`. + specifies a :class:`pDepCache` object. The problem resolver helps when there are problems in the package selection. An example is a package which conflicts with another, already installed package. - .. method:: Protect(pkg) + .. method:: protect(pkg) Protect the :class:`Package()` object given by the parameter *pkg*. @@ -350,11 +350,11 @@ Resolving Dependencies Really document it. - .. method:: InstallProtect() + .. method:: install_protect() Protect all installed packages from being removed. - .. method:: Remove(pkg) + .. method:: remove(pkg) Remove the :class:`Package()` object given by the parameter *pkg*. @@ -362,7 +362,7 @@ Resolving Dependencies Really document it. - .. method:: Clear(pkg) + .. method:: clear(pkg) Reset the :class:`Package()` *pkg* to the default state. @@ -370,11 +370,11 @@ Resolving Dependencies Really document it. - .. method:: Resolve() + .. method:: resolve() Try to resolve problems by installing and removing packages. - .. method:: ResolveByKeep() + .. method:: resolve_by_keep() Try to resolve problems only by using keep. @@ -386,65 +386,65 @@ Resolving Dependencies A :class:`PackageFile` represents a Packages file, eg. /var/lib/dpkg/status. - .. attribute:: Architecture + .. attribute:: architecture The architecture of the package file. - .. attribute:: Archive + .. attribute:: archive The archive (eg. unstable) - .. attribute:: Component + .. attribute:: component The component (eg. main) - .. attribute:: FileName + .. attribute:: file_name The name of the file. - .. attribute:: ID + .. attribute:: id The ID of the package. This is an integer which can be used to store further information about the file [eg. as dictionary key]. - .. attribute:: IndexType + .. attribute:: index_type The sort of the index file. In normal cases, this is 'Debian Package Index'. - .. attribute:: Label + .. attribute:: label The Label, as set in the Release file - .. attribute:: NotAutomatic + .. attribute:: not_automatic Whether packages from this list will be updated automatically. The default for eg. example is 0 (aka false). - .. attribute:: NotSource + .. attribute:: not_source Whether the file has no source from which it can be updated. In such a case, the value is 1; else 0. /var/lib/dpkg/status is 0 for example. Example:: - for pkgfile in cache.FileList: - if pkgfile.NotSource: - print 'The file %s has no source.' % pkgfile.FileName + for pkgfile in cache.file_list: + if pkgfile.not_source: + print 'The file %s has no source.' % pkgfile.file_name - .. attribute:: Origin + .. attribute:: origin The Origin, as set in the Release file - .. attribute:: Site + .. attribute:: site The hostname of the site. - .. attribute:: Size + .. attribute:: size The size of the file. - .. attribute:: Version + .. attribute:: version The version, as set in the release file (eg. "4.0" for "Etch") @@ -465,78 +465,78 @@ Example Attributes: - .. attribute:: CurrentVer + .. attribute:: current_ver The version currently installed, or None. This returns a :class:`Version` object. - .. attribute:: ID + .. attribute:: id The ID of the package. This can be used to store information about the package. The ID is an int value. - .. attribute:: Name + .. attribute:: name This is the name of the package. - .. attribute:: ProvidesList + .. attribute:: provides_list A list of packages providing this package. More detailed, this is a list of tuples (str:pkgname, ????, :class:`Version`). If you want to check for check for virtual packages, the expression - ``pkg.ProvidesList and not pkg.VersionList`` helps you. It detects if + ``pkg.provides_list and not pkg._version_list`` helps you. It detects if the package is provided by something else and is not available as a real package. - .. attribute:: RevDependsList + .. attribute:: rev_depends_list An iterator of :class:`Dependency` objects for dependencies on this package. - .. attribute:: Section + .. attribute:: section The section of the package, as specified in the record. The list of possible sections is defined in the Policy. - .. attribute:: VersionList + .. attribute:: version_list A list of :class:`Version` objects for all versions available in the cache. **States**: - .. attribute:: SelectedState + .. attribute:: selected_state The state we want it to be, ie. if you mark a package for installation, - this is :attr:`apt_pkg.SelStateInstall`. + this is :attr:`apt_pkg.SELSTATE_INSTALL`. See :ref:`SelStates` for a list of available states. - .. attribute:: InstState + .. attribute:: inst_state The state the currently installed version is in. This is normally - :attr:`apt_pkg.InstStateOK`, unless the installation failed. + :attr:`apt_pkg.INSTSTATE_OK`, unless the installation failed. See :ref:`InstStates` for a list of available states. - .. attribute:: CurState + .. attribute:: cur_state The current state of the package (not installed, unpacked, installed, etc). See :ref:`CurStates` for a list of available states. **Flags**: - .. attribute:: Auto + .. attribute:: auto Whether the package was installed automatically as a dependency of another package. (or marked otherwise as automatically installed) - .. attribute:: Essential + .. attribute:: essential Whether the package is essential. - .. attribute:: Important + .. attribute:: important Whether the package is important. @@ -553,25 +553,25 @@ Example: The version object contains all information related to a specific package version. - .. attribute:: VerStr + .. attribute:: ver_str The version, as a string. - .. attribute:: Section + .. attribute:: section The usual sections (eg. admin, net, etc.). Prefixed with the component name for packages not in main (eg. non-free/admin). - .. attribute:: Arch + .. attribute:: arch The architecture of the package, eg. amd64 or all. - .. attribute:: FileList + .. attribute:: file_list A list of (:class:`PackageFile`, int: index) tuples for all Package files containing this version of the package. - .. attribute:: DependsListStr + .. attribute:: depends_list_str A dictionary of dependencies. The key specifies the type of the dependency ('Depends', 'Recommends', etc.). @@ -601,58 +601,58 @@ Example: ] } - .. attribute:: DependsList + .. attribute:: depends_list This is basically the same as :attr:`Version.DependsListStr`, but instead of the ('pkgname', 'version', 'relation') tuples, it returns :class:`Dependency` objects, which can assist you with useful functions. - .. attribute:: ParentPkg + .. attribute:: parent_pkg The :class:`Package` object this version belongs to. - .. attribute:: ProvidesList + .. attribute:: provides_list This returns a list of all packages provided by this version. Like - :attr:`Package.ProvidesList`, it returns a list of tuples + :attr:`Package.provides_list`, it returns a list of tuples of the form ('virtualpkgname', ???, :class:`Version`), where as the last item is the same as the object itself. - .. attribute:: Size + .. attribute:: size The size of the .deb file, in bytes. - .. attribute:: InstalledSize + .. attribute:: installed_size The size of the package (in kilobytes), when unpacked on the disk. - .. attribute:: Hash + .. attribute:: hash An integer hash value. - .. attribute:: ID + .. attribute:: id An integer id. - .. attribute:: Priority + .. attribute:: priority The integer representation of the priority. This can be used to speed - up comparisons a lot, compared to :attr:`Version.PriorityStr`. + up comparisons a lot, compared to :attr:`Version.priority_str`. The values are defined in the :mod:`apt_pkg` extension, see :ref:`Priorities` for more information. - .. attribute:: PriorityStr + .. attribute:: priority_str Return the priority of the package version, as a string, eg. "optional". - .. attribute:: Downloadable + .. attribute:: downloadable Whether this package can be downloaded from a remote site. - .. attribute:: TranslatedDescription + .. attribute:: translated_description Return a :class:`Description` object. @@ -663,7 +663,7 @@ Example: Represent a dependency from one package to another one. - .. method:: AllTargets + .. method:: all_targets A list of :class:`Version` objects which satisfy the dependency, and do not conflict with already installed ones. @@ -673,40 +673,40 @@ Example: other candidates is already installed. This leads to results being very close to the normal package installation. - .. method:: SmartTargetPkg + .. method:: smart_target_pkg Return a :class:`Version` object of a package which satisfies the dependency and does not conflict with installed packages (the 'natural target'). - .. attribute:: TargetVer + .. attribute:: target_ver The target version of the dependency, as string. Empty string if the dependency is not versioned. - .. attribute:: TargetPkg + .. attribute:: target_pkg The :class:`Package` object of the target package. - .. attribute:: ParentVer + .. attribute:: parent_ver The :class:`Version` object of the parent version, ie. the package which declares the dependency. - .. attribute:: ParentPkg + .. attribute:: parent_pkg The :class:`Package` object of the package which declares the dependency. This is the same as using ParentVer.ParentPkg. - .. attribute:: CompType + .. attribute:: comp_type The type of comparison (>=, ==, >>, <=), as string. - .. attribute:: DepType + .. attribute:: dep_type The type of the dependency, as string, eg. "Depends". - .. attribute:: ID + .. attribute:: id The ID of the package, as integer. @@ -724,7 +724,7 @@ broken dependencies: Represent the description of the package. - .. attribute:: LanguageCode + .. attribute:: language_code The language code of the description @@ -732,7 +732,7 @@ broken dependencies: The md5 hashsum of the description - .. attribute:: FileList + .. attribute:: file_list A list of tuples (:class:`PackageFile`, int: index). @@ -747,10 +747,10 @@ broken dependencies: .. class:: MetaIndex - .. attribute:: URI - .. attribute:: Dist - .. attribute:: IsTrusted - .. attribute:: IndexFiles + .. attribute:: uri + .. attribute:: dist + .. attribute:: is_trusted + .. attribute:: index_files :class:`PackageIndexFile` @@ -758,27 +758,27 @@ broken dependencies: .. class:: PackageIndexFile - .. method:: ArchiveURI(path) + .. method:: archive_uri(path) Return the full url to path in the archive. - .. attribute:: Label + .. attribute:: label Return the Label. - .. attribute:: Exists + .. attribute:: exists Return whether the file exists. - .. attribute:: HasPackages + .. attribute:: has_packages Return whether the file has packages. - .. attribute:: Size + .. attribute:: size Size of the file - .. attribute:: IsTrusted + .. attribute:: is_trusted Whether we can trust the file. @@ -794,13 +794,13 @@ Records Provide access to the packages records. This provides very useful attributes for fast (convient) access to some fields of the record. - .. method:: Lookup(verfile_iter) + .. method:: lookup(verfile_iter) Change the actual package to the package given by the verfile_iter. The parameter *verfile_iter* refers to a tuple consisting of (:class:`PackageFile()`, int: index), as returned by various - attributes, including :attr:`Version.FileList`. + attributes, including :attr:`Version.file_list`. Example (shortened):: @@ -809,69 +809,69 @@ Records # Now you can access the record print records.SourcePkg # == python-apt - .. attribute:: FileName + .. attribute:: file_name Return the field 'Filename' of the record. This is the path to the package, relative to the base path of the archive. - .. attribute:: MD5Hash + .. attribute:: md5_hash Return the MD5 hashsum of the package This refers to the field 'MD5Sum' in the raw record. - .. attribute:: SHA1Hash + .. attribute:: sha1_hash Return the SHA1 hashsum of the package. This refers to the field 'SHA1' in the raw record. - .. attribute:: SHA256Hash + .. attribute:: sha256_hash Return the SHA256 hashsum of the package. This refers to the field 'SHA256' in the raw record. .. versionadded:: 0.7.9 - .. attribute:: SourcePkg + .. attribute:: source_pkg Return the source package. - .. attribute:: SourceVer + .. attribute:: source_ver Return the source version. - .. attribute:: Maintainer + .. attribute:: maintainer Return the maintainer of the package. - .. attribute:: ShortDesc + .. attribute:: short_desc Return the short description. This is the summary on the first line of the 'Description' field. - .. attribute:: LongDesc + .. attribute:: long_desc Return the long description. These are lines 2-END from the 'Description' field. - .. attribute:: Name + .. attribute:: name Return the name of the package. This is the 'Package' field. - .. attribute:: Homepage + .. attribute:: homepage Return the Homepage. This is the 'Homepage' field. - .. attribute:: Record + .. attribute:: record Return the whole record as a string. If you want to access fields of the record not available as an attribute, you can use - :func:`apt_pkg.ParseSection` to parse the record and access the field + :class:`apt_pkg.TagSection` to parse the record and access the field name. Example:: - section = apt_pkg.ParseSection(records.Record) - print section['SHA256'] + section = apt_pkg.TagSection(records.record) + print section['SHA256'] # Use records.sha256_hash instead .. class:: SourceRecords @@ -886,16 +886,16 @@ Records anymore (same applies when no Lookup has been made, or when it has been restarted). - .. method:: Lookup(pkgname) + .. method:: lookup(pkgname) Lookup the record for the package named *pkgname*. To access all available records, you need to call it multiple times. - Imagine a package P with two versions X, Y. The first ``Lookup(P)`` - would set the record to version X and the second ``Lookup(P)`` to + Imagine a package P with two versions X, Y. The first ``lookup(P)`` + would set the record to version X and the second ``lookup(P)`` to version Y. - .. method:: Restart() + .. method:: restart() Restart the lookup. @@ -903,26 +903,26 @@ Records would set the record to version X and the second ``Lookup(P)`` to version Y. - If you now call ``Restart()``, the internal position will be cleared. - Now you can call ``Lookup(P)`` again to move to X. + If you now call ``restart()``, the internal position will be cleared. + Now you can call ``lookup(P)`` again to move to X. - .. attribute:: Package + .. attribute:: package The name of the source package. - .. attribute:: Version + .. attribute:: version A string describing the version of the source package. - .. attribute:: Maintainer + .. attribute:: maintainer A string describing the name of the maintainer. - .. attribute:: Section + .. attribute:: section A string describing the section. - .. attribute:: Record + .. attribute:: record The whole record, as a string. You can use :func:`apt_pkg.ParseSection` if you need to parse it. @@ -930,22 +930,22 @@ Records You need to parse the record if you want to access fields not available via the attributes, eg. 'Standards-Version' - .. attribute:: Binaries + .. attribute:: binaries Return a list of strings describing the package names of the binaries created by the source package. This matches the 'Binary' field in the raw record. - .. attribute:: Index + .. attribute:: index The index in the Sources files. - .. attribute:: Files + .. attribute:: files The list of files. This returns a list of tuples with the contents ``(str: md5, int: size, str: path, str:type)``. - .. attribute:: BuildDepends + .. attribute:: build_depends Return the list of Build dependencies, as ``(str: package, str: version, int: op, int: type)``. @@ -1015,24 +1015,24 @@ installation. Acquire items have multiple methods: - .. method:: Acquire.Run() + .. method:: run() - Fetch all the items which have been added by :func:`GetPkgAcqFile`. + Fetch all the items which have been added by :class:`AcquireFile`. - .. method:: Acquire.Shutdown() + .. method:: shutdown() Shut the fetcher down. - .. attribute:: Acquire.TotalNeeded + .. attribute:: total_needed The total amount of bytes needed (including those of files which are already present) - .. attribute:: Acquire.FetchNeeded + .. attribute:: fetch_needed The total amount of bytes which need to be fetched. - .. attribute:: Acquire.PartialPresent + .. attribute:: partial_present Whether some files have been acquired already. (???) @@ -1040,70 +1040,70 @@ installation. The :class:`AcquireItem()` objects represent the items of a :class:`Acquire` object. :class:`AcquireItem()` objects can not be created - by the user, they are solely available through the :attr:`Acquire.Items` + by the user, they are solely available through the :attr:`Acquire.items` list of an :class:`Acquire` object. - .. attribute:: ID + .. attribute:: id The ID of the item. - .. attribute:: Complete + .. attribute:: complete Is the item completely acquired? - .. attribute:: Local + .. attribute:: local Is the item a local file? - .. attribute:: IsTrusted + .. attribute:: is_trusted Can the file be trusted? - .. attribute:: FileSize + .. attribute:: file_size The size of the file, in bytes. - .. attribute:: ErrorText + .. attribute:: error_text The error message. For example, when a file does not exist on a http server, this will contain a 404 error message. - .. attribute:: DestFile + .. attribute:: dest_file The location the file is saved as. - .. attribute:: DescURI + .. attribute:: desc_uri The source location. **Status**: - .. attribute:: Status + .. attribute:: status Integer, representing the status of the item. - .. attribute:: StatIdle + .. attribute:: stat_idle - Constant for comparing :attr:`AcquireItem.Status`. + Constant for comparing :attr:`AcquireItem.status`. - .. attribute:: StatFetching + .. attribute:: stat_fetching - Constant for comparing :attr:`AcquireItem.Status` + Constant for comparing :attr:`AcquireItem.status` - .. attribute:: StatDone + .. attribute:: stat_done - Constant for comparing :attr:`AcquireItem.Status` + Constant for comparing :attr:`AcquireItem.status` - .. attribute:: StatError + .. attribute:: stat_error - Constant for comparing :attr:`AcquireItem.Status` + Constant for comparing :attr:`AcquireItem.status` - .. attribute:: StatAuthError + .. attribute:: stat_auth_error - Constant for comparing :attr:`AcquireItem.Status` + Constant for comparing :attr:`AcquireItem.status` -.. class:: AcquireFile(owner, uri[, md5, size, descr, shortdescr, destdir, destfile]) +.. class:: AcquireFile(owner, uri[, md5, size, descr, short_descr, dest_dir, dest_file]) Create a new :class:`AcquireFile()` object and register it with *acquire*, so it will be fetched. AcquireFile objects provide no methods or attributes @@ -1123,12 +1123,12 @@ installation. which can then be used to calculate the progress and validate the download. The parameter *descr* is a descripition of the download. It may be - used to describe the item in the progress class. *shortDescr* is the + used to describe the item in the progress class. *short_descr* is the short form of it. - You can use *destdir* to manipulate the directory where the file will - be saved in. Instead of *destdir*, you can also specify the full path to - the file using the parameter *destfile*. You can not combine both. + You can use *dest_dir* to manipulate the directory where the file will + be saved in. Instead of *dest_dir*, you can also specify the full path to + the file using the parameter *dest_file*. You can not combine both. @@ -1192,24 +1192,24 @@ section as a string. An example for working with a TagFile could look like:: tagf = apt_pkg.TagFile(open('/var/lib/dpkg/status')) - tagf.Step() - print tagf.Section['Package'] + tagf.step() + print tagf.section['Package'] - .. method:: Step + .. method:: step Step forward to the next section. This simply returns ``1`` if OK, and ``0`` if there is no section - .. method:: Offset + .. method:: offset Return the current offset (in bytes) from the beginning of the file. - .. method:: Jump(offset) + .. method:: jump(offset) - Jump back/forward to *offset*. Use ``Jump(0)`` to jump to the + Jump back/forward to *offset*. Use ``jump(0)`` to jump to the beginning of the file again. - .. attribute:: Section + .. attribute:: section This is the current :class:`TagSection()` instance. @@ -1228,16 +1228,16 @@ section as a string. .. versionadded:: 0.8.0 - .. method:: Bytes + .. method:: bytes The number of bytes in the section. - .. method:: Find(key, default='') + .. method:: find(key, default='') Return the value of the field at the key *key* if available, else return *default*. - .. method:: FindFlag(key) + .. method:: find_flag(key) Find a yes/no value for the key *key*. An example for such a field is 'Essential'. @@ -1257,31 +1257,31 @@ section as a string. Return a list of keys in the section. -.. autofunction:: RewriteSection(section, order, rewrite_list) +.. autofunction:: rewrite_section(section, order, rewrite_list) -.. data:: RewritePackageOrder +.. data:: REWRITE_PACKAGE_ORDER The order in which the information for binary packages should be rewritten, i.e. the order in which the fields should appear. -.. data:: RewriteSourceOrder +.. data:: REWRITE_SOURCE_ORDER The order in which the information for source packages should be rewritten, i.e. the order in which the fields should appear. Dependencies ------------ -.. function:: CheckDep(pkgver, op, depver) +.. function:: check_dep(pkgver, op, depver) Check that the dependency requirements consisting of op and depver can be satisfied by the version pkgver. Example:: - >>> bool(apt_pkg.CheckDep("1.0", ">=", "1")) + >>> bool(apt_pkg.check_dep("1.0", ">=", "1")) True -.. function:: ParseDepends(depends) +.. function:: parse_depends(depends) Parse the string *depends* which contains dependency information as specified in Debian Policy, Section 7.1. @@ -1290,10 +1290,10 @@ Dependencies one or more tuples in the format ``(package,version,operation)`` for every 'or'-option given, e.g.:: - >>> apt_pkg.ParseDepends("PkgA (>= VerA) | PkgB (>= VerB)") + >>> apt_pkg.parse_depends("PkgA (>= VerA) | PkgB (>= VerB)") [[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]] -.. function:: ParseSrcDepends(depends) +.. function:: parse_src_depends(depends) Parse the string *depends* which contains dependency information as specified in Debian Policy, Section 7.1. @@ -1302,14 +1302,14 @@ Dependencies one or more tuples in the format ``(package,version,operation)`` for every 'or'-option given, e.g.:: - >>> apt_pkg.ParseDepends("PkgA (>= VerA) | PkgB (>= VerB)") + >>> apt_pkg.parse_depends("PkgA (>= VerA) | PkgB (>= VerB)") [[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]] Furthemore, this function also supports to limit the architectures, as used in e.g. Build-Depends:: - >>> apt_pkg.ParseSrcDepends("a (>= 01) [i386 amd64]") + >>> apt_pkg.parse_src_depends("a (>= 01) [i386 amd64]") [[('a', '01', '>=')]] @@ -1337,70 +1337,70 @@ Configuration Set the option at *key* to *value*. - .. method:: Find(key[, default='']) + .. method:: find(key[, default='']) Return the value for the given key *key*. This is the same as :meth:`Configuration.get`. If *key* does not exist, return *default*. - .. method:: FindFile(key[, default='']) + .. method:: find_file(key[, default='']) Return the filename hold by the configuration at *key*. This formats the filename correctly and supports the Dir:: stuff in the configuration. If *key* does not exist, return *default*. - .. method:: FindDir(key[, default='/']) + .. method:: find_dir(key[, default='/']) Return the absolute path to the directory specified in *key*. A trailing slash is appended. If *key* does not exist, return *default*. - .. method:: FindI(key[, default=0]) + .. method:: find_i(key[, default=0]) Return the integer value stored at *key*. If *key* does not exist, return *default*. - .. method:: FindB(key[, default=0]) + .. method:: find_b(key[, default=0]) Return the boolean value stored at *key*. This returns an integer, but it should be treated like True/False. If *key* does not exist, return *default*. - .. method:: Set(key, value) + .. method:: set(key, value) Set the value of *key* to *value*. - .. method:: Exists(key) + .. method:: exists(key) Check whether the key *key* exists in the configuration. - .. method:: SubTree(key) + .. method:: sub_tree(key) Return a sub tree starting at *key*. The resulting object can be used like this one. - .. method:: List([key]) + .. method:: list([key]) List all items at *key*. Normally, return the keys at the top level, eg. APT, Dir, etc. Use *key* to specify a key of which the childs will be returned. - .. method:: ValueList([key]) + .. method:: value_list([key]) - Same as :meth:`Configuration.List`, but this time for the values. + Same as :meth:`Configuration.list`, but this time for the values. - .. method:: MyTag() + .. method:: my_tag() Return the tag name of the current tree. Normally this is an empty string, but for subtrees it is the key of the subtree. - .. method:: Clear(key) + .. method:: clear(key) Clear the configuration. Remove all values and keys at *key*. @@ -1416,7 +1416,7 @@ Configuration .. method:: get(key[, default='']) - This behaves just like :meth:`dict.get` and :meth:`Configuration.Find`, + This behaves just like :meth:`dict.get` and :meth:`Configuration.find`, it returns the value of key or if it does not exist, *default*. .. class:: ConfigurationPtr @@ -1429,37 +1429,37 @@ Configuration Behaves like a :class:`Configuration()` objects, but provides access to a subsection of another Configuration-like object. This type of object is - returned by the :meth:`Configuration.SubTree()` method. + returned by the :meth:`Configuration.sub_tree()` method. -.. data:: Config +.. data:: config A :class:`ConfigurationPtr()` object with the default configuration. This - object is initialized by calling :func:`InitConfig`. + object is initialized by calling :func:`init_config`. Modifying ^^^^^^^^^ -.. function:: ReadConfigFile(configuration, filename) +.. function:: read_config_file(configuration, filename) Read the configuration file specified by the parameter *filename* and add the settings therein to the :class:`Configuration()` object specified by the parameter *configuration* -.. function:: ReadConfigDir(configuration, dirname) +.. function:: read_config_dir(configuration, dirname) Read configuration files in the directory specified by the parameter *dirname* and add the settings therein to the :class:`Configuration()` object specified by the parameter *configuration*. -.. function:: ReadConfigFileISC(configuration, filename) +.. function:: read_config_file_isc(configuration, filename) Read the configuration file specified by the parameter *filename* and add the settings therein to the :class:`Configuration()` object specified by the parameter *configuration* -.. function:: ParseCommandLine(configuration,options,argv) +.. function:: parse_command_line(configuration, options, argv) This function is like getopt except it manipulates a configuration space. output is a list of non-option arguments (filenames, etc). *options* is a @@ -1472,7 +1472,7 @@ Modifying Locking -------- -.. function:: GetLock(filename) +.. function:: get_lock(filename) Create an empty file at the path specified by the parameter *filename* and lock it. @@ -1483,11 +1483,11 @@ Locking When the lock is not required anymore, the file descriptor should be closed using :func:`os.close`. -.. function:: PkgSystemLock() +.. function:: pkg_system_lock() Lock the global pkgsystem. -.. function:: PkgSystemUnLock() +.. function:: pkg_system_un_lock() Unlock the global pkgsystem. @@ -1497,12 +1497,12 @@ Other classes Return a Cdrom object with the following methods: - .. method:: Ident(progress) + .. method:: ident(progress) Identify the cdrom. The parameter *progress* refers to an :class:`apt.progress.CdromProgress()` object. - .. method:: Add(progress) + .. method:: add(progress) Add the cdrom to the sources.list file. The parameter *progress* refers to an :class:`apt.progress.CdromProgress()` object. @@ -1511,52 +1511,52 @@ Other classes This is for :file:`/etc/apt/sources.list`. - .. method:: FindIndex(pkgfile) + .. method:: find_index(pkgfile) Return a :class:`PackageIndexFile` object for the :class:`PackageFile` *pkgfile*. - .. method:: ReadMainList + .. method:: read_main_list Read the main list. - .. method:: GetIndexes(acq[, all]) + .. method:: get_indexes(acq[, all]) Add the index files to the :class:`Acquire()` object *acq*. If *all* is given and ``True``, all files are fetched. String functions ---------------- -.. function:: Base64Encode(string) +.. function:: base64_encode(string) Encode the given string using base64, e.g:: - >>> apt_pkg.Base64Encode(u"A") + >>> apt_pkg.base64_encode(u"A") 'QQ==' -.. function:: CheckDomainList(host, list) +.. function:: check_domain_list(host, list) See if Host is in a ',' seperated list, e.g.:: - apt_pkg.CheckDomainList("alioth.debian.org","debian.net,debian.org") + apt_pkg.check_domain_list("alioth.debian.org","debian.net,debian.org") -.. function:: DeQuoteString(string) +.. function:: de_quote_string(string) Dequote the string specified by the parameter *string*, e.g.:: >>> apt_pkg.DeQuoteString("%61%70%74%20is%20cool") 'apt is cool' -.. function:: QuoteString(string, repl) +.. function:: quote_string(string, repl) For every character listed in the string *repl*, replace all occurences in the string *string* with the correct HTTP encoded value: - >>> apt_pkg.QuoteString("apt is cool","apt") + >>> apt_pkg.quote_string("apt is cool","apt") '%61%70%74%20is%20cool' -.. function:: SizeToStr(size) +.. function:: size_to_str(size) Return a string presenting the human-readable version of the integer *size*. When calculating the units (k,M,G,etc.) the size is divided by the @@ -1564,10 +1564,10 @@ String functions Example:: - >>> apt_pkg.SizeToStr(10000) + >>> apt_pkg.size_to_str(10000) '10.0k' -.. function:: StringToBool(input) +.. function:: string_to_bool(input) Parse the string *input* and return one of **-1**, **0**, **1**. @@ -1583,35 +1583,35 @@ String functions Example:: - >>> apt_pkg.StringToBool("yes") + >>> apt_pkg.string_to_bool("yes") 1 - >>> apt_pkg.StringToBool("no") + >>> apt_pkg.string_to_bool("no") 0 - >>> apt_pkg.StringToBool("not-recognized") + >>> apt_pkg.string_to_bool("not-recognized") -1 -.. function:: StrToTime(rfc_time) +.. function:: str_to_time(rfc_time) Convert the :rfc:`1123` conforming string *rfc_time* to the unix time, and return the integer. This is the opposite of :func:`TimeRFC1123`. Example:: - >> apt_pkg.StrToTime('Thu, 01 Jan 1970 00:00:00 GMT') + >> apt_pkg.str_to_time('Thu, 01 Jan 1970 00:00:00 GMT') 0 -.. function:: TimeRFC1123(seconds) +.. function:: time_rfc1123(seconds) Format the unix time specified by the integer *seconds*, according to the requirements of :rfc:`1123`. Example:: - >>> apt_pkg.TimeRFC1123(0) + >>> apt_pkg.time_rfc1123(0) 'Thu, 01 Jan 1970 00:00:00 GMT' -.. function:: TimeToStr(seconds) +.. function:: time_to_str(seconds) Format a given duration in a human-readable manner. The parameter *seconds* refers to a number of seconds, given as an integer. The return value is a @@ -1619,26 +1619,26 @@ String functions Example:: - >>> apt_pkg.TimeToStr(3601) + >>> apt_pkg.time_to_str(3601) '1h0min1s' -.. function:: UpstreamVersion(version) +.. function:: upstream_version(version) Return the string *version*, eliminating everything following the last '-'. Thus, this should be equivalent to ``version.rsplit('-', 1)[0]``. -.. function:: URItoFileName(uri) +.. function:: uri_to_file_name(uri) Take a string *uri* as parameter and return a filename which can be used to store the file, based on the URI. Example:: - >>> apt_pkg.URItoFileName('http://debian.org/index.html') + >>> apt_pkg.uri_to_file_name('http://debian.org/index.html') 'debian.org_index.html' -.. function:: VersionCompare(a, b) +.. function:: version_compare(a, b) Compare two versions, *a* and *b*, and return an integer value which has the same characteristic as the built-in :func:`cmp` function. @@ -1662,73 +1662,73 @@ Module Constants Package States ^^^^^^^^^^^^^^^ -.. data:: CurStateConfigFiles -.. data:: CurStateHalfConfigured -.. data:: CurStateHalfInstalled -.. data:: CurStateInstalled -.. data:: CurStateNotInstalled -.. data:: CurStateUnPacked +.. data:: CURSTATE_CONFIG_FILES +.. data:: CURSTATE_HALF_CONFIGURED +.. data:: CURSTATE_HALF_INSTALLED +.. data:: CURSTATE_INSTALLED +.. data:: CURSTATE_NOT_INSTALLED +.. data:: CURSTATE_UN_PACKED Dependency types ^^^^^^^^^^^^^^^^ -.. data:: DepConflicts -.. data:: DepDepends -.. data:: DepObsoletes -.. data:: DepPreDepends -.. data:: DepRecommends -.. data:: DepReplaces -.. data:: DepSuggests +.. data:: DEP_CONFLICTS +.. data:: DEP_DEPENDS +.. data:: DEP_OBSOLETES +.. data:: DEP_PRE_DEPENDS +.. data:: DEP_RECOMMENDS +.. data:: DEP_REPLACES +.. data:: DEP_SUGGESTS .. _InstStates: Installed states ^^^^^^^^^^^^^^^^ -.. data:: InstStateHold -.. data:: InstStateHoldReInstReq -.. data:: InstStateOk -.. data:: InstStateReInstReq +.. data:: INSTSTATE_HOLD +.. data:: INSTSTATE_HOLD_RE_INST_REQ +.. data:: INSTSTATE_OK +.. data:: INSTSTATE_RE_INST_REQ .. _Priorities: Priorities ^^^^^^^^^^^ -.. data:: PriExtra -.. data:: PriImportant -.. data:: PriOptional -.. data:: PriRequired -.. data:: PriStandard +.. data:: PRI_EXTRA +.. data:: PRI_IMPORTANT +.. data:: PRI_OPTIONAL +.. data:: PRI_REQUIRED +.. data:: PRI_STANDARD .. _SelStates: Select states ^^^^^^^^^^^^^ -.. data:: SelStateDeInstall -.. data:: SelStateHold -.. data:: SelStateInstall -.. data:: SelStatePurge -.. data:: SelStateUnknown +.. data:: SELSTATE_DE_INSTALL +.. data:: SELSTATE_HOLD +.. data:: SELSTATE_INSTALL +.. data:: SELSTATE_PURGE +.. data:: SELSTATE_UNKNOWN Build information ^^^^^^^^^^^^^^^^^ -.. data:: Date +.. data:: DATE The date on which this extension has been compiled. -.. data:: LibVersion +.. data:: LIB_VERSION The version of the apt_pkg library. This is **not** the version of apt, nor the version of python-apt. -.. data:: Time +.. data:: TIME The time this extension has been built. -.. data:: Version +.. data:: VERSION The version of apt (not of python-apt). diff --git a/doc/source/examples/cache-packages.py b/doc/source/examples/cache-packages.py index 0af96f7d..72534303 100644 --- a/doc/source/examples/cache-packages.py +++ b/doc/source/examples/cache-packages.py @@ -6,17 +6,17 @@ import apt_pkg def main(): """Main.""" - apt_pkg.InitConfig() - apt_pkg.InitSystem() + apt_pkg.init_config() + apt_pkg.init_system() cache = apt_pkg.Cache() print "Essential packages:" - for pkg in cache.Packages: - if pkg.Essential: - print " ", pkg.Name + for pkg in cache.packages: + if pkg.essential: + print " ", pkg.name print "Important packages:" - for pkg in cache.Packages: - if pkg.Important: - print " ", pkg.Name + for pkg in cache.packages: + if pkg.important: + print " ", pkg.name if __name__ == "__main__": main() diff --git a/doc/source/examples/cache-pkgfile.py b/doc/source/examples/cache-pkgfile.py index a7c22c97..1300a55c 100644 --- a/doc/source/examples/cache-pkgfile.py +++ b/doc/source/examples/cache-pkgfile.py @@ -6,19 +6,19 @@ def main(): """Example for PackageFile()""" apt_pkg.init() cache = apt_pkg.Cache() - for pkgfile in cache.FileList: - print 'Package-File:', pkgfile.FileName - print 'Index-Type:', pkgfile.IndexType # 'Debian Package Index' - if pkgfile.NotSource: + for pkgfile in cache.file_list: + print 'Package-File:', pkgfile.file_name + print 'Index-Type:', pkgfile.index_type # 'Debian Package Index' + if pkgfile.not_source: print 'Source: None' else: - if pkgfile.Site: + if pkgfile.site: # There is a source, and a site, print the site - print 'Source:', pkgfile.Site + print 'Source:', pkgfile.site else: # It seems to be a local repository print 'Source: Local package file' - if pkgfile.NotAutomatic: + if pkgfile.not_automatic: # The system won't be updated automatically (eg. experimental) print 'Automatic: No' else: diff --git a/doc/source/examples/dpkg-contents.py b/doc/source/examples/dpkg-contents.py index 99d1596f..24d7ce98 100644 --- a/doc/source/examples/dpkg-contents.py +++ b/doc/source/examples/dpkg-contents.py @@ -28,7 +28,7 @@ def format_mode(what, mode): def callback(what, name, link, mode, uid, gid, size, mtime, major, minor): - """callback for debExtract""" + """callback for deb_extract""" s_mode = format_mode(what, mode) s_owner = "%s/%s" % (pwd.getpwuid(uid)[0], grp.getgrgid(gid)[0]) s_size = "%9d" % size @@ -47,7 +47,7 @@ def main(): fobj = open(sys.argv[1]) try: - apt_inst.debExtract(fobj, callback, "data.tar.gz") + apt_inst.deb_extract(fobj, callback, "data.tar.gz") finally: fobj.close() diff --git a/doc/source/examples/dpkg-extract.py b/doc/source/examples/dpkg-extract.py index ced8652f..8d144029 100644 --- a/doc/source/examples/dpkg-extract.py +++ b/doc/source/examples/dpkg-extract.py @@ -17,7 +17,7 @@ def main(): fobj = open(sys.argv[1]) try: - apt_inst.debExtractArchive(fobj, sys.argv[2]) + apt_inst.deb_extract_archive(fobj, sys.argv[2]) finally: fobj.close() diff --git a/doc/source/examples/dpkg-info.py b/doc/source/examples/dpkg-info.py index ff98d8b1..6be8595c 100644 --- a/doc/source/examples/dpkg-info.py +++ b/doc/source/examples/dpkg-info.py @@ -2,7 +2,7 @@ """Emulate dpkg --info package.deb control-file""" import sys -from apt_inst import debExtractControl +from apt_inst import deb_extract_control def main(): @@ -12,7 +12,7 @@ def main(): sys.exit(0) fobj = open(sys.argv[1]) try: - print debExtractControl(fobj, sys.argv[2]) + print deb_extract_control(fobj, sys.argv[2]) finally: fobj.close() diff --git a/doc/source/examples/missing-deps.py b/doc/source/examples/missing-deps.py index dd5eeb8a..7af18128 100644 --- a/doc/source/examples/missing-deps.py +++ b/doc/source/examples/missing-deps.py @@ -5,9 +5,9 @@ import apt_pkg def fmt_dep(dep): """Format a Dependency object [of apt_pkg] as a string.""" - ret = dep.TargetPkg.Name - if dep.TargetVer: - ret += " (%s %s)" % (dep.CompType, dep.TargetVer) + ret = dep.target_pkg.name + if dep.target_ver: + ret += " (%s %s)" % (dep.comp_type, dep.target_ver) return ret @@ -15,15 +15,15 @@ def check_version(pkgver): """Check the version of the package""" missing = [] - for or_group in pkgver.DependsList.get("Pre-Depends", []) + \ - pkgver.DependsList.get("Depends", []): - if not any(dep.AllTargets() for dep in or_group): + for or_group in pkgver.depends_list.get("Pre-Depends", []) + \ + pkgver.depends_list.get("Depends", []): + if not any(dep.all_targets() for dep in or_group): # If none of the or-choices can be satisfied, add it to missing missing.append(or_group) if missing: - print "Package:", pkgver.ParentPkg.Name - print "Version:", pkgver.VerStr + print "Package:", pkgver.parent_pkg.name + print "Version:", pkgver.ver_str print "Missing:", print ", ".join(" | ".join(fmt_dep(dep) for dep in or_group) for or_group in missing) @@ -32,18 +32,18 @@ def check_version(pkgver): def main(): """The main function.""" - apt_pkg.InitConfig() - apt_pkg.InitSystem() + apt_pkg.init_config() + apt_pkg.init_system() cache = apt_pkg.Cache() - for pkg in sorted(cache.Packages, key=lambda pkg: pkg.Name): + for pkg in sorted(cache.packages, key=lambda pkg: pkg.name): # pkg is from a list of packages, sorted by name. - for version in pkg.VersionList: + for version in pkg.version_list: # Check every version - for pfile, _ in version.FileList: - if (pfile.Origin == "Debian" and pfile.Component == "main" and - pfile.Archive == "unstable"): + for pfile, _ in version.file_list: + if (pfile.origin == "Debian" and pfile.component == "main" and + pfile.archive == "unstable"): # We only want packages from Debian unstable main. check_version(version) break -- cgit v1.2.3 From 14dfadc054e9bdafd2507dbca70dbec925471ae0 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 5 Jun 2009 15:00:15 +0200 Subject: Introduce the rename rules formally, and add some exceptions. --- apt/cache.py | 4 +- apt/package.py | 10 ++--- doc/source/apt_pkg.rst | 36 ++++++++-------- doc/source/examples/cache-pkgfile.py | 2 +- doc/source/whatsnew/0.8.0.rst | 82 +++++++++++++++++++++++++++++++++++- python/acquire.cc | 10 ++--- python/apt_pkgmodule.cc | 16 +++---- python/cache.cc | 2 +- python/configuration.cc | 2 +- python/depcache.cc | 4 +- python/pkgrecords.cc | 2 +- 11 files changed, 124 insertions(+), 46 deletions(-) (limited to 'doc/source') diff --git a/apt/cache.py b/apt/cache.py index 56b32d45..8590510c 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -170,8 +170,8 @@ class Cache(object): reqreinst = set() for pkg in self: if (not pkg.candidate.downloadable and - (pkg._pkg.inst_state == apt_pkg.INSTSTATE_RE_INST_REQ or - pkg._pkg.inst_state == apt_pkg.INSTSTATE_HOLD_RE_INST_REQ)): + (pkg._pkg.inst_state == apt_pkg.INSTSTATE_REINSTREQ or + pkg._pkg.inst_state == apt_pkg.INSTSTATE_HOLD_REINSTREQ)): reqreinst.add(pkg.name) return reqreinst diff --git a/apt/package.py b/apt/package.py index a24486e1..48d14595 100644 --- a/apt/package.py +++ b/apt/package.py @@ -379,7 +379,7 @@ class Version(object): .. versionadded:: 0.7.10 """ - return self._records.file_name + return self._records.filename @property def md5(self): @@ -413,7 +413,7 @@ class Version(object): for (packagefile, index) in self._cand.file_list: indexfile = self.package._pcache._list.find_index(packagefile) if indexfile: - yield indexfile.archive_uri(self._records.file_name) + yield indexfile.archive_uri(self._records.filename) @property def uris(self): @@ -443,19 +443,19 @@ class Version(object): .. versionadded:: 0.7.10 """ - base = os.path.basename(self._records.file_name) + base = os.path.basename(self._records.filename) destfile = os.path.join(destdir, base) if _file_is_same(destfile, self.size, self._records.md5_hash): print 'Ignoring already existing file:', destfile return acq = apt_pkg.Acquire(progress or apt.progress.TextFetchProgress()) apt_pkg.AcquireFile(acq, self.uri, self._records.md5_hash, self.size, - base, dest_file=destfile) + base, destfile=destfile) acq.run() for item in acq.items: if item.status != item.stat_done: raise FetchError("The item %r could not be fetched: %s" % - (item.dest_file, item.error_text)) + (item.destfile, item.error_text)) return os.path.abspath(destfile) def fetch_source(self, destdir="", progress=None, unpack=True): diff --git a/doc/source/apt_pkg.rst b/doc/source/apt_pkg.rst index 39b48c35..c814615c 100644 --- a/doc/source/apt_pkg.rst +++ b/doc/source/apt_pkg.rst @@ -167,7 +167,7 @@ Working with the cache If *from_user* is ``True``, the package will be marked as manually installed. This is the default. - .. method:: set_re_install(pkg) + .. method:: set_reinstall(pkg) Set if the :class:`Package` *pkg* should be reinstalled. @@ -398,7 +398,7 @@ Resolving Dependencies The component (eg. main) - .. attribute:: file_name + .. attribute:: filename The name of the file. @@ -430,7 +430,7 @@ Resolving Dependencies for pkgfile in cache.file_list: if pkgfile.not_source: - print 'The file %s has no source.' % pkgfile.file_name + print 'The file %s has no source.' % pkgfile.filename .. attribute:: origin @@ -809,7 +809,7 @@ Records # Now you can access the record print records.SourcePkg # == python-apt - .. attribute:: file_name + .. attribute:: filename Return the field 'Filename' of the record. This is the path to the package, relative to the base path of the archive. @@ -1103,7 +1103,7 @@ installation. Constant for comparing :attr:`AcquireItem.status` -.. class:: AcquireFile(owner, uri[, md5, size, descr, short_descr, dest_dir, dest_file]) +.. class:: AcquireFile(owner, uri[, md5, size, descr, short_descr, destdir, destfile]) Create a new :class:`AcquireFile()` object and register it with *acquire*, so it will be fetched. AcquireFile objects provide no methods or attributes @@ -1126,9 +1126,9 @@ installation. used to describe the item in the progress class. *short_descr* is the short form of it. - You can use *dest_dir* to manipulate the directory where the file will - be saved in. Instead of *dest_dir*, you can also specify the full path to - the file using the parameter *dest_file*. You can not combine both. + You can use *destdir* to manipulate the directory where the file will + be saved in. Instead of *destdir*, you can also specify the full path to + the file using the parameter *destfile*. You can not combine both. @@ -1379,7 +1379,7 @@ Configuration Check whether the key *key* exists in the configuration. - .. method:: sub_tree(key) + .. method:: subtree(key) Return a sub tree starting at *key*. The resulting object can be used like this one. @@ -1429,7 +1429,7 @@ Configuration Behaves like a :class:`Configuration()` objects, but provides access to a subsection of another Configuration-like object. This type of object is - returned by the :meth:`Configuration.sub_tree()` method. + returned by the :meth:`Configuration.subtree()` method. .. data:: config @@ -1459,7 +1459,7 @@ Modifying the settings therein to the :class:`Configuration()` object specified by the parameter *configuration* -.. function:: parse_command_line(configuration, options, argv) +.. function:: parse_commandline(configuration, options, argv) This function is like getopt except it manipulates a configuration space. output is a list of non-option arguments (filenames, etc). *options* is a @@ -1541,11 +1541,11 @@ String functions apt_pkg.check_domain_list("alioth.debian.org","debian.net,debian.org") -.. function:: de_quote_string(string) +.. function:: dequote_string(string) Dequote the string specified by the parameter *string*, e.g.:: - >>> apt_pkg.DeQuoteString("%61%70%74%20is%20cool") + >>> apt_pkg.dequote_string("%61%70%74%20is%20cool") 'apt is cool' .. function:: quote_string(string, repl) @@ -1627,14 +1627,14 @@ String functions Return the string *version*, eliminating everything following the last '-'. Thus, this should be equivalent to ``version.rsplit('-', 1)[0]``. -.. function:: uri_to_file_name(uri) +.. function:: uri_to_filename(uri) Take a string *uri* as parameter and return a filename which can be used to store the file, based on the URI. Example:: - >>> apt_pkg.uri_to_file_name('http://debian.org/index.html') + >>> apt_pkg.uri_to_filename('http://debian.org/index.html') 'debian.org_index.html' @@ -1667,7 +1667,7 @@ Package States .. data:: CURSTATE_HALF_INSTALLED .. data:: CURSTATE_INSTALLED .. data:: CURSTATE_NOT_INSTALLED -.. data:: CURSTATE_UN_PACKED +.. data:: CURSTATE_UNPACKED @@ -1687,9 +1687,9 @@ Dependency types Installed states ^^^^^^^^^^^^^^^^ .. data:: INSTSTATE_HOLD -.. data:: INSTSTATE_HOLD_RE_INST_REQ +.. data:: INSTSTATE_HOLD_REINSTREQ .. data:: INSTSTATE_OK -.. data:: INSTSTATE_RE_INST_REQ +.. data:: INSTSTATE_REINSTREQ .. _Priorities: diff --git a/doc/source/examples/cache-pkgfile.py b/doc/source/examples/cache-pkgfile.py index 1300a55c..f4cc2e66 100644 --- a/doc/source/examples/cache-pkgfile.py +++ b/doc/source/examples/cache-pkgfile.py @@ -7,7 +7,7 @@ def main(): apt_pkg.init() cache = apt_pkg.Cache() for pkgfile in cache.file_list: - print 'Package-File:', pkgfile.file_name + print 'Package-File:', pkgfile.filename print 'Index-Type:', pkgfile.index_type # 'Debian Package Index' if pkgfile.not_source: print 'Source: None' diff --git a/doc/source/whatsnew/0.8.0.rst b/doc/source/whatsnew/0.8.0.rst index d1ac3ac5..d507e82a 100644 --- a/doc/source/whatsnew/0.8.0.rst +++ b/doc/source/whatsnew/0.8.0.rst @@ -15,19 +15,97 @@ Python-apt is the first Debian package to support the third major release of Python. The port is straight forward and integrates as nicely in Python 3 as the Python 2 builds integrate in Python 2. +Please be aware that python-apt builds for Python 3 are built without the +compatibility options enabled for Python 2 builds. They also do not provide +methods like :meth:`has_key` on mapping objects, because it has been removed +in Python 3. + Real classes in :mod:`apt_pkg` ------------------------------ +The 0.8 release introduces real classes in the :mod:`apt_pkg` extension. This +is an important step forward and makes writing code much easier, because you +can see the classes without having to create an object first. It also makes +it easier to talk about those classes, because they have a real name now. + +The 0.7 series shipped many functions for creating new objects, because the +classes were not exported. In 0.8, the classes themselves replace those +functions, as you can see in the following table. + +.. table:: + + ===================================== ================================= + Function Replacing class + ===================================== ================================= + :func:`apt_pkg.GetAcquire` :class:`apt_pkg.Acquire` + :func:`apt_pkg.GetCache()` :class:`apt_pkg.Cache` + :func:`apt_pkg.GetCdrom()` :class:`apt_pkg.Cdrom` + :func:`apt_pkg.GetDepCache()` :class:`apt_pkg.DepCache` + :func:`apt_pkg.GetPackageManager` :class:`apt_pkg.PackageManager` + :func:`apt_pkg.GetPkgAcqFile` :class:`apt_pkg.AcquireFile` + :func:`apt_pkg.GetPkgActionGroup` :class:`apt_pkg.ActionGroup` + :func:`apt_pkg.GetPkgProblemResolver` :class:`apt_pkg.ProblemResolver` + :func:`apt_pkg.GetPkgRecords` :class:`apt_pkg.PackageRecords` + :func:`apt_pkg.GetPkgSourceList` :class:`apt_pkg.SourceList` + :func:`apt_pkg.GetPkgSrcRecords` :class:`apt_pkg.SourceRecords` + :func:`apt_pkg.ParseSection` :class:`apt_pkg.TagSection` + :func:`apt_pkg.ParseTagFile` :class:`apt_pkg.TagFile` + ===================================== ================================= Complete rename of functions, methods and attributes ----------------------------------------------------- +In May 2008, Ben Finney reported bug 481061 against the python-apt package, +asking for PEP8 conformant names. With the release of python-apt 0.8, this +is finally happening. Supporting new language features like the :keyword:`with` statement ------------------------------------------------------------------- +This is not a real big change, but it's good to have it: +:class:`apt_pkg.ActionGroup` can now be used as a context manager for the +:keyword:`with` statement. This makes it more obvious that you are using an +action group, and is just cooler:: + + with apt_pkg.ActionGroup(depcache): + for package in my_selected_packages: + depcache.mark_install(package) + +This also works for :class:`apt.Cache`:: + + with cache.action_group(): # cache is an Instance of apt.Cache + for package in my_selected_packages: + package.mark_install() # Instance of apt.Package + Other changes ------------- This release of python-apt also features several other, smaller changes: - * Reduced memory usage by creating Package() objects in apt.Cache() only - when needed. + * Reduced memory usage by making :class:`apt.Cache` create + :class:`apt.Package()` object dynamically, instead of creating all of + them during the cache initialization. * Support to set the candidate version in :class:`apt.package.Package` + +Porting your applications to python-apt 0.8 +------------------------------------------- +Porting your application to python-apt 0.8 may be trivial. You should download +the source tarball of python-apt and run the tool utils/migrate-0.8 using +Python 2.6 over your code:: + + python2.6 utils/migrate-0.8.py -c myapp.py mypackage/ + +This will search your code for places where possibly deprecated names are +used. Using the argument ``-c``, you can turn colorized output on. + +Now that you know which parts of your code have to be changed, you have to know +how to do this. For classes, please look at the table. For all attributes, +methods, functions, and their parameters the following rules apply: + + 1. Replace leading [A-Z] with [a-z] (e.g DescURI => descURI) + 2. Replace multiple [A-Z] with [A-Z][a-z] (e.g. descURI => descUri) + 3. Replace every [A-Z] with the corresponding [a-z] (descUri => desc_uri) + +As an exception, refixes such as 'de' (e.g. 'dequote') or 'un' (e.g. 'unlock') +are normally not seperated by underscores from the next word. There are also +some other exceptions which are listed here, and apply to any name containing +this word: **filename**, **filesize**, **destdir**, **destfile**, **dequote**, +**unlock**, **reinstall**, **pinfile**, **REINSTREQ**, **UNPACKED**, +**parse_commandline**. diff --git a/python/acquire.cc b/python/acquire.cc index 1b1c5dd8..5f38f7bd 100644 --- a/python/acquire.cc +++ b/python/acquire.cc @@ -40,9 +40,9 @@ MkGet(AcquireItemGetStatAuthError,Py_BuildValue("i", pkgAcquire::Item::StatAuthE static PyGetSetDef AcquireItemGetSet[] = { {"complete",AcquireItemGetComplete}, {"desc_uri",AcquireItemGetDescURI}, - {"dest_file",AcquireItemGetDestFile}, + {"destfile",AcquireItemGetDestFile}, {"error_text",AcquireItemGetErrorText}, - {"file_size",AcquireItemGetFileSize}, + {"filesize",AcquireItemGetFileSize}, {"is",AcquireItemGetID}, {"is_trusted",AcquireItemGetIsTrusted}, {"local",AcquireItemGetLocal}, @@ -310,7 +310,7 @@ static PyObject *PkgAcquireFileNew(PyTypeObject *type, PyObject *Args, PyObject int size = 0; uri = md5 = descr = shortDescr = destDir = destFile = ""; - char * kwlist[] = {"owner","uri", "md5", "size", "descr", "shortdescr", + char * kwlist[] = {"owner","uri", "md5", "size", "descr", "short_descr", "destdir", "destfile", NULL}; if (PyArg_ParseTupleAndKeywords(Args, kwds, "O!s|sissss", kwlist, @@ -335,8 +335,8 @@ static PyObject *PkgAcquireFileNew(PyTypeObject *type, PyObject *Args, PyObject static char *doc_PkgAcquireFile = - "AcquireFile(owner, uri[, md5, size, descr, short_descr, dest_dir," - "dest_file]) -> New AcquireFile() object\n\n" + "AcquireFile(owner, uri[, md5, size, descr, short_descr, destdir," + "destfile]) -> New AcquireFile() object\n\n" "The parameter *owner* refers to an apt_pkg.Acquire() object. You can use\n" "*destdir* OR *destfile* to specify the destination directory/file."; diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index bfabc652..403e0ebf 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -407,7 +407,7 @@ static PyMethodDef methods[] = // Locking {"get_lock",GetLock,METH_VARARGS,doc_GetLock}, {"pkgsystem_lock",PkgSystemLock,METH_VARARGS,doc_PkgSystemLock}, - {"pkgsystem_un_lock",PkgSystemUnLock,METH_VARARGS,doc_PkgSystemUnLock}, + {"pkgsystem_unlock",PkgSystemUnLock,METH_VARARGS,doc_PkgSystemUnLock}, #ifdef COMPAT_0_7 {"GetLock",GetLock,METH_VARARGS,doc_GetLock}, {"PkgSystemLock",PkgSystemLock,METH_VARARGS,doc_PkgSystemLock}, @@ -418,7 +418,7 @@ static PyMethodDef methods[] = {"read_config_file",LoadConfig,METH_VARARGS,doc_LoadConfig}, {"read_config_dir",LoadConfigDir,METH_VARARGS,doc_LoadConfigDir}, {"read_config_file_isc",LoadConfigISC,METH_VARARGS,doc_LoadConfig}, - {"parse_command_line",ParseCommandLine,METH_VARARGS,doc_ParseCommandLine}, + {"parse_commandline",ParseCommandLine,METH_VARARGS,doc_ParseCommandLine}, #ifdef COMPAT_0_7 {"ReadConfigFile",LoadConfig,METH_VARARGS,doc_LoadConfig}, {"ReadConfigDir",LoadConfigDir,METH_VARARGS,doc_LoadConfigDir}, @@ -452,10 +452,10 @@ static PyMethodDef methods[] = // Strings {"check_domain_list",StrCheckDomainList,METH_VARARGS,"CheckDomainList(String,String) -> Bool"}, {"quote_string",StrQuoteString,METH_VARARGS,"QuoteString(String,String) -> String"}, - {"de_quote_string",StrDeQuote,METH_VARARGS,"DeQuoteString(String) -> String"}, + {"dequote_string",StrDeQuote,METH_VARARGS,"DeQuoteString(String) -> String"}, {"size_to_str",StrSizeToStr,METH_VARARGS,"SizeToStr(int) -> String"}, {"time_to_str",StrTimeToStr,METH_VARARGS,"TimeToStr(int) -> String"}, - {"uri_to_file_name",StrURItoFileName,METH_VARARGS,"URItoFileName(String) -> String"}, + {"uri_to_filename",StrURItoFileName,METH_VARARGS,"URItoFileName(String) -> String"}, {"base64_encode",StrBase64Encode,METH_VARARGS,"Base64Encode(String) -> String"}, {"string_to_bool",StrStringToBool,METH_VARARGS,"StringToBool(String) -> int"}, {"time_rfc1123",StrTimeRFC1123,METH_VARARGS,"TimeRFC1123(int) -> String"}, @@ -657,7 +657,7 @@ extern "C" void initapt_pkg() #endif // CurState PyModule_AddIntConstant(Module,"CURSTATE_NOT_INSTALLED",pkgCache::State::NotInstalled); - PyModule_AddIntConstant(Module,"CURSTATE_UN_PACKED",pkgCache::State::UnPacked); + PyModule_AddIntConstant(Module,"CURSTATE_UNPACKED",pkgCache::State::UnPacked); PyModule_AddIntConstant(Module,"CURSTATE_HALF_CONFIGURED",pkgCache::State::HalfConfigured); PyModule_AddIntConstant(Module,"CURSTATE_HALF_INSTALLED",pkgCache::State::HalfInstalled); PyModule_AddIntConstant(Module,"CURSTATE_CONFIG_FILES",pkgCache::State::ConfigFiles); @@ -666,13 +666,13 @@ extern "C" void initapt_pkg() PyModule_AddIntConstant(Module,"SELSTATE_UNKNOWN",pkgCache::State::Unknown); PyModule_AddIntConstant(Module,"SELSTATE_INSTALL",pkgCache::State::Install); PyModule_AddIntConstant(Module,"SELSTATE_HOLD",pkgCache::State::Hold); - PyModule_AddIntConstant(Module,"SELSTATE_DE_INSTALL",pkgCache::State::DeInstall); + PyModule_AddIntConstant(Module,"SELSTATE_DEINSTALL",pkgCache::State::DeInstall); PyModule_AddIntConstant(Module,"SELSTATE_PURGE",pkgCache::State::Purge); // InstState PyModule_AddIntConstant(Module,"INSTSTATE_OK",pkgCache::State::Ok); - PyModule_AddIntConstant(Module,"INSTSTATE_RE_INST_REQ",pkgCache::State::ReInstReq); + PyModule_AddIntConstant(Module,"INSTSTATE_REINSTREQ",pkgCache::State::ReInstReq); PyModule_AddIntConstant(Module,"INSTSTATE_HOLD",pkgCache::State::Hold); - PyModule_AddIntConstant(Module,"INSTSTATE_HOLD_RE_INST_REQ",pkgCache::State::HoldReInstReq); + PyModule_AddIntConstant(Module,"INSTSTATE_HOLD_REINSTREQ",pkgCache::State::HoldReInstReq); #ifdef COMPAT_0_7 PyModule_AddIntConstant(Module,"CurStateNotInstalled",pkgCache::State::NotInstalled); diff --git a/python/cache.cc b/python/cache.cc index 21a6a872..d09e22f3 100644 --- a/python/cache.cc +++ b/python/cache.cc @@ -1030,7 +1030,7 @@ static PyGetSetDef PackageFileGetSet[] = { {(char*)"architecture",PackageFile_GetArchitecture}, {(char*)"archive",PackageFile_GetArchive}, {(char*)"component",PackageFile_GetComponent}, - {(char*)"file_name",PackageFile_GetFileName}, + {(char*)"filename",PackageFile_GetFileName}, {(char*)"id",PackageFile_GetID}, {(char*)"index_type",PackageFile_GetIndexType}, {(char*)"label",PackageFile_GetLabel}, diff --git a/python/configuration.cc b/python/configuration.cc index 7b08d90e..81dd78ac 100644 --- a/python/configuration.cc +++ b/python/configuration.cc @@ -462,7 +462,7 @@ static PyMethodDef CnfMethods[] = // Others {"set",CnfSet,METH_VARARGS,doc_Set}, {"exists",CnfExists,METH_VARARGS,doc_Exists}, - {"sub_tree",CnfSubTree,METH_VARARGS,doc_SubTree}, + {"subtree",CnfSubTree,METH_VARARGS,doc_SubTree}, {"list",CnfList,METH_VARARGS,doc_List}, {"value_list",CnfValueList,METH_VARARGS,doc_ValueList}, {"my_tag",CnfMyTag,METH_VARARGS,doc_MyTag}, diff --git a/python/depcache.cc b/python/depcache.cc index 650dcb23..f69802f8 100644 --- a/python/depcache.cc +++ b/python/depcache.cc @@ -535,13 +535,13 @@ static PyMethodDef PkgDepCacheMethods[] = // global cache operations {"upgrade",PkgDepCacheUpgrade,METH_VARARGS,"Perform Upgrade (optional boolean argument if dist-upgrade should be performed)"}, {"fix_broken",PkgDepCacheFixBroken,METH_VARARGS,"Fix broken packages"}, - {"read_pin_file",PkgDepCacheReadPinFile,METH_VARARGS,"Read the pin policy"}, + {"read_pinfile",PkgDepCacheReadPinFile,METH_VARARGS,"Read the pin policy"}, {"minimize_upgrade",PkgDepCacheMinimizeUpgrade, METH_VARARGS,"Go over the entire set of packages and try to keep each package marked for upgrade. If a conflict is generated then the package is restored."}, // Manipulators {"mark_keep",PkgDepCacheMarkKeep,METH_VARARGS,"Mark package for keep"}, {"mark_delete",PkgDepCacheMarkDelete,METH_VARARGS,"Mark package for delete (optional boolean argument if it should be purged)"}, {"mark_install",PkgDepCacheMarkInstall,METH_VARARGS,"Mark package for Install"}, - {"set_re_install",PkgDepCacheSetReInstall,METH_VARARGS,"Set if the package should be reinstalled"}, + {"set_reinstall",PkgDepCacheSetReInstall,METH_VARARGS,"Set if the package should be reinstalled"}, // state information {"is_upgradable",PkgDepCacheIsUpgradable,METH_VARARGS,"Is pkg upgradable"}, {"is_now_broken",PkgDepCacheIsNowBroken,METH_VARARGS,"Is pkg is now broken"}, diff --git a/python/pkgrecords.cc b/python/pkgrecords.cc index 48440387..212e4ab0 100644 --- a/python/pkgrecords.cc +++ b/python/pkgrecords.cc @@ -120,7 +120,7 @@ static PyObject *PkgRecordsGetRecord(PyObject *Self,void*) { return PyString_FromStringAndSize(start,stop-start); } static PyGetSetDef PkgRecordsGetSet[] = { - {"file_name",PkgRecordsGetFileName}, + {"filename",PkgRecordsGetFileName}, {"homepage",PkgRecordsGetHomepage}, {"long_desc",PkgRecordsGetLongDesc}, {"md5_hash",PkgRecordsGetMD5Hash}, -- cgit v1.2.3 From 5160ad8b3f71cb256e62bab5fc532d3d73b2f7b4 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 5 Jun 2009 15:24:39 +0200 Subject: doc/source/conf.py: Force compatibility to be off when creating documentation. --- doc/source/conf.py | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'doc/source') diff --git a/doc/source/conf.py b/doc/source/conf.py index 52c8a21b..5a289f32 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -31,6 +31,10 @@ if os.path.exists("../../build"): if version in dirname: sys.path.insert(0, os.path.abspath('../../build/' + dirname)) +# Hack: Disable compatibility mode +import apt_pkg +apt_pkg._COMPAT_0_7 = 0 + # General configuration # --------------------- -- cgit v1.2.3 From cef966b55a04ad09f38857aa1a3bff3e49b8f6a4 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 5 Jun 2009 19:29:17 +0200 Subject: apt/cache.py: Introduce Cache.actiongroup() This is a short function which creates an actiongroup on the current depcache. --- apt/cache.py | 21 +++++++++++++++++++++ doc/source/whatsnew/0.8.0.rst | 2 +- 2 files changed, 22 insertions(+), 1 deletion(-) (limited to 'doc/source') diff --git a/apt/cache.py b/apt/cache.py index 8590510c..16dfc011 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -347,6 +347,27 @@ class Cache(object): self._callbacks[name] = [] self._callbacks[name].append(callback) + def actiongroup(self): + """Return an ActionGroup() object for the current cache. + + Action groups can be used to speedup actions. The action group is + active as soon as it is created, and disabled when the object is + deleted or when release() is called. + + You can use the action group as a context manager, this is the + recommended way:: + + with cache.actiongroup(): + for package in my_selected_packages: + package.mark_install() + + This way, the ActionGroup is automatically released as soon as the + with statement block is left. It also has the benefit of making it + clear which parts of the code run with a action group and which + don't. + """ + return apt_pkg.ActionGroup(self._depcache) + if apt_pkg._COMPAT_0_7: _runCallbacks = function_deprecated_by(_run_callbacks) getChanges = function_deprecated_by(get_changes) diff --git a/doc/source/whatsnew/0.8.0.rst b/doc/source/whatsnew/0.8.0.rst index d507e82a..b2236e44 100644 --- a/doc/source/whatsnew/0.8.0.rst +++ b/doc/source/whatsnew/0.8.0.rst @@ -70,7 +70,7 @@ action group, and is just cooler:: This also works for :class:`apt.Cache`:: - with cache.action_group(): # cache is an Instance of apt.Cache + with cache.actiongroup(): # cache is an Instance of apt.Cache for package in my_selected_packages: package.mark_install() # Instance of apt.Package -- cgit v1.2.3 From 3461ce22ec52b896f97aeb6d925f214098826c59 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 8 Jul 2009 20:43:12 +0200 Subject: doc/source/whatsnew/0.8.0.rst: Document the changes to the dependency handling. --- doc/source/whatsnew/0.8.0.rst | 61 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) (limited to 'doc/source') diff --git a/doc/source/whatsnew/0.8.0.rst b/doc/source/whatsnew/0.8.0.rst index b2236e44..e1acb5db 100644 --- a/doc/source/whatsnew/0.8.0.rst +++ b/doc/source/whatsnew/0.8.0.rst @@ -74,6 +74,67 @@ This also works for :class:`apt.Cache`:: for package in my_selected_packages: package.mark_install() # Instance of apt.Package +Unification of dependency handling +---------------------------------- +In apt 0.7, there were three different return types of functions parsing +dependencies. + +First of all, there were :func:`apt_pkg.ParseDepends()` and +:func:`apt_pkg.ParseSrcDepends()` which returned a list of or groups (which +are lists themselves) which contain tuples in the format ``(package,ver,op)``, +whereas op is one of "<=",">=","<<",">>","=","!=". + +Secondly, there was Package.DependsListStr which returned a dictionary mapping +the type of the dependency (e.g. 'Depends', 'Recommends') to a list similar to +those of :func:`apt_pkg.ParseDepends()`. The only difference was that the +values ">>", "<<" of op are ">", "<" instead. + +Thirdly, there was SourceRecords.BuildDepends, which returned a simple list +of tuples in the format ``(package, version, op, type)``, whereas ``op`` was +the integer representation of those ">>", "<<" actions and ``type`` an integer +representing the type of the dependency (e.g. 'Build-Depends'). The whole +format was almost useless from the Python perspective because the string +representations or constants for checking the values were not exported. + +python-apt 0.8 puts an end to this confusion and uses one basic format, which +is the format known from Package.DependsListStr. The format change only applies +to the new functions and attributes, i.e. :attr:`SourceRecords.build_depends` +will now return a dict, whereas :attr:`SourceRecords.BuildDepends` will still +return the classic format. The functions :func:`apt_pkg.parse_depends` and +:func:`apt_pkg.parse_src_depends` now use the same values for ``op`` as +:attr:`Package.DependsListStr` does. + +Example:: + + >>> s = apt_pkg.SourceRecords() + >>> s.lookup("apt") + 1 + >>> s.build_depends + {'Build-Depends': [[('debhelper', '5.0', '>=')], + [('libdb-dev', '', '')], + [('gettext', '0.12', '>=')], + [('libcurl4-gnutls-dev', '', ''), + ('libcurl3-gnutls-dev', '7.15.5', '>=')], + [('debiandoc-sgml', '', '')], + [('docbook-utils', '0.6.12', '>=')], + [('xsltproc', '', '')], + [('docbook-xsl', '', '')], + [('xmlto', '', '')]]} + >>> s.BuildDepends + [('debhelper', '5.0', 2, 0), + ('libdb-dev', '', 0, 0), + ('gettext', '0.12', 2, 0), + ('libcurl4-gnutls-dev', '', 16, 0), + ('libcurl3-gnutls-dev', '7.15.5', 2, 0), + ('debiandoc-sgml', '', 0, 0), + ('docbook-utils', '0.6.12', 2, 0), + ('xsltproc', '', 0, 0), + ('docbook-xsl', '', 0, 0), + ('xmlto', '', 0, 0)] + + + + Other changes ------------- -- cgit v1.2.3 From 7d12f1ce6bc839f27604782bc712a0ccb481f2b2 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 8 Jul 2009 20:59:15 +0200 Subject: doc/source/apt_pkg.rst: Update the documentation to reflect the latest changes. --- apt/package.py | 2 +- doc/source/apt_pkg.rst | 44 ++++++++++++++++++++++++++++++++++---------- 2 files changed, 35 insertions(+), 11 deletions(-) (limited to 'doc/source') diff --git a/apt/package.py b/apt/package.py index 6d451eca..072e86ca 100644 --- a/apt/package.py +++ b/apt/package.py @@ -64,7 +64,7 @@ class BaseDependency(object): Attributes defined here: name - The name of the dependency - relation - The relation (>>,>=,==,<<,<=,) + relation - The relation (>,>=,==,<,<=,) version - The version depended on pre_depend - Boolean value whether this is a pre-dependency. """ diff --git a/doc/source/apt_pkg.rst b/doc/source/apt_pkg.rst index c814615c..2af934a0 100644 --- a/doc/source/apt_pkg.rst +++ b/doc/source/apt_pkg.rst @@ -947,22 +947,30 @@ Records .. attribute:: build_depends + Return a dictionary representing the build-time dependencies of the + package. The format is the same as for :attr:`Version.depends_list_str` + and possible keys being ``"Build-Depends"``, ``"Build-Depends-Indep"``, + ``"Build-Conflicts"`` or ``"Build-Conflicts-Indep"``. + + .. attribute:: BuildDepends + Return the list of Build dependencies, as - ``(str: package, str: version, int: op, int: type)``. + ``(str: package, str: version, int: op, int: type)``. This is a + completely deprecated format .. table:: Values of *op* ===== ============================================= Value Meaning ===== ============================================= - 0x0 No Operation (no versioned build dependency) + 0x00 No Operation (no versioned build dependency) 0x10 | (or) - this will be added to the other values - 0x1 <= (less than or equal) - 0x2 >= (greater than or equal) - 0x3 << (less than) - 0x4 >> (greater than) - 0x5 == (equal) - 0x6 != (not equal) + 0x01 <= (less than or equal) + 0x02 >= (greater than or equal) + 0x03 << (less than) + 0x04 >> (greater than) + 0x05 = (equal) + 0x06 != (not equal) ===== ============================================= .. table:: Values of *type* @@ -983,7 +991,7 @@ Records This results in:: - [('A', '1', 18, 0), # 18 = 16 + 2 = 0x10 + 0x2 + [('A', '1', 18, 0), # 18 = (16 | 2) = (0x10 | 0x2) ('B', '1', 2, 0), ('C', '', 0, 0)] @@ -1293,10 +1301,19 @@ Dependencies >>> apt_pkg.parse_depends("PkgA (>= VerA) | PkgB (>= VerB)") [[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]] + + .. note:: + + The behavior of this function is different than the behavior of the + old function :func:`ParseDepends()`, because the third field + ``operation`` uses `>` instead of `>>` and `<` instead of `<<` which + is specified in control files. + + .. function:: parse_src_depends(depends) Parse the string *depends* which contains dependency information as - specified in Debian Policy, Section 7.1. + specified in Debian Policy, Section 7.1. Returns a list. The members of this list are lists themselves and contain one or more tuples in the format ``(package,version,operation)`` for every @@ -1312,6 +1329,13 @@ Dependencies >>> apt_pkg.parse_src_depends("a (>= 01) [i386 amd64]") [[('a', '01', '>=')]] + .. note:: + + The behavior of this function is different than the behavior of the + old function :func:`ParseDepends()`, because the third field + ``operation`` uses `>` instead of `>>` and `<` instead of `<<` which + is specified in control files. + Configuration ------------- -- cgit v1.2.3 From 5b489a994d009771d7f4d5beec45bbbb5468cd58 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 12 Jul 2009 19:07:55 +0200 Subject: python/hashes.cc: Introduce the Hashes class. The Hashes class is a function which calculates all supported hashes for one input. DebImg will use this for calculating the hashes of files. --- debian/changelog | 3 +- doc/source/apt_pkg.rst | 26 +++++++-- python/apt_pkgmodule.cc | 1 + python/apt_pkgmodule.h | 1 + python/hashes.cc | 136 ++++++++++++++++++++++++++++++++++++++++++++++++ python/makefile | 5 +- 6 files changed, 164 insertions(+), 8 deletions(-) create mode 100644 python/hashes.cc (limited to 'doc/source') diff --git a/debian/changelog b/debian/changelog index 8bc3e320..1f43cc8c 100644 --- a/debian/changelog +++ b/debian/changelog @@ -30,6 +30,7 @@ python-apt (0.7.92) UNRELEASED; urgency=low + Closes: #468123 - there is no need anymore for binding CompType or CompTypeDeb, because we don't return integer values for CompType anymore. + * Introduce apt_pkg.Hashes class. [ Sebastian Heinlein ] * apt/progress.py: Extract the package name from the status message @@ -45,7 +46,7 @@ python-apt (0.7.92) UNRELEASED; urgency=low * python/progress.cc: - low level code for update_status_full and pulse_items() - -- Julian Andres Klode Tue, 07 Jul 2009 16:56:44 +0200 + -- Julian Andres Klode Sun, 12 Jul 2009 18:51:57 +0200 python-apt (0.7.91) experimental; urgency=low diff --git a/doc/source/apt_pkg.rst b/doc/source/apt_pkg.rst index 2af934a0..9a14266e 100644 --- a/doc/source/apt_pkg.rst +++ b/doc/source/apt_pkg.rst @@ -1139,15 +1139,31 @@ installation. the file using the parameter *destfile*. You can not combine both. +Hashes +------ +The apt_pkg module also provides several hash functions. If you develop +applications with python-apt it is often easier to use these functions instead +of the ones provides in Python's :mod:`hashlib` module. +.. class:: Hashes(object) + Calculate all supported hashes of the object. *object* may either be a + string, in which cases the hashes of the string are calculated, or a + :class:`file()` object or file descriptor, in which case the hashes of + its contents is calculated. The calculated hashes are then available via + attributes: + .. attribute:: md5 -Hash functions --------------- -The apt_pkg module also provides several hash functions. If you develop -applications with python-apt it is often easier to use these functions instead -of the ones provides in Python's :mod:`hashlib` module. + The MD5 hash of the data, as string. + + .. attribute:: sha1 + + The SHA1 hash of the data, as string. + + .. attribute:: sha256 + + The SHA256 hash of the data, as string. .. function:: md5sum(object) diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 3f4aae37..4c0fd5ed 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -618,6 +618,7 @@ extern "C" void initapt_pkg() ADDTYPE(Module,"IndexRecords",&PyIndexRecords_Type); ADDTYPE(Module,"HashString",&PyHashString_Type); ADDTYPE(Module,"Policy",&PyPolicy_Type); + ADDTYPE(Module,"Hashes",&PyHashes_Type); // Tag file constants PyModule_AddObject(Module,"REWRITE_PACKAGE_ORDER", CharCharToList(TFRewritePackageOrder)); diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index 21355072..1a2f1a1a 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -116,5 +116,6 @@ extern PyTypeObject PyIndexRecords_Type; // Policy extern PyTypeObject PyPolicy_Type; +extern PyTypeObject PyHashes_Type; #endif diff --git a/python/hashes.cc b/python/hashes.cc new file mode 100644 index 00000000..a1ace6fc --- /dev/null +++ b/python/hashes.cc @@ -0,0 +1,136 @@ +/* hashes.cc - Wrapper around apt-pkg's Hashes. + * + * Copyright 2009 Julian Andres Klode + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +#include +#include "generic.h" +#include "apt_pkgmodule.h" +#include + +static PyObject *hashes_new(PyTypeObject *type,PyObject *args, + PyObject *kwds) +{ + return CppPyObject_NEW(type); +} + +static int hashes_init(PyObject *self, PyObject *args, PyObject *kwds) +{ + PyObject *object = 0; + int Fd; + char *kwlist[] = {"object", NULL}; + + if (PyArg_ParseTupleAndKeywords(args, kwds, "|O:__init__", kwlist, + &object) == 0) + return -1; + if (object == 0) + return 0; + Hashes &hashes = GetCpp(self); + + if (PyBytes_Check(object) != 0) { + char *s; + Py_ssize_t len; + PyBytes_AsStringAndSize(object, &s, &len); + hashes.Add((const unsigned char*)s, len); + } + else if ((Fd = PyObject_AsFileDescriptor(object)) != -1) { + struct stat St; + if (fstat(Fd, &St) != 0 || hashes.AddFD(Fd, St.st_size) == false) { + PyErr_SetFromErrno(PyExc_SystemError); + return -1; + } + } + else { + PyErr_SetString(PyExc_TypeError, "__init__() only understand strings" + " and files"); + return -1; + } + return 0; +} + +static PyObject *hashes_get_md5(PyObject *self, void*) +{ + return CppPyString(GetCpp(self).MD5.Result().Value()); +} + +static PyObject *hashes_get_sha1(PyObject *self, void*) +{ + return CppPyString(GetCpp(self).SHA1.Result().Value()); +} + +static PyObject *hashes_get_sha256(PyObject *self, void*) +{ + return CppPyString(GetCpp(self).SHA256.Result().Value()); +} + +static PyGetSetDef hashes_getset[] = { + {"md5",hashes_get_md5,0,"The MD5Sum of the file as a string."}, + {"sha1",hashes_get_sha1,0,"The SHA1Sum of the file as a string."}, + {"sha256",hashes_get_sha256,0,"The SHA256Sum of the file as a string."}, + {} +}; + +static char *hashes_doc = + "Hashes([object: (bytes, file)])\n\n" + "Calculate hashes for the given object. It can be used to create all\n" + "supported hashes for a file.\n\n" + "The parameter *object* can be a bytes (3.X) / str (2.X) object, or an\n" + "object providing the fileno() method or an integer describing a file\n" + "descriptor."; + +PyTypeObject PyHashes_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.Hashes", // tp_name + sizeof(CppPyObject), // tp_basicsize + 0, // tp_itemsize + // Methods + CppDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE, + hashes_doc, // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + hashes_getset, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + hashes_init, // tp_init + 0, // tp_alloc + hashes_new, // tp_new +}; diff --git a/python/makefile b/python/makefile index 6799d749..fff3a2e8 100644 --- a/python/makefile +++ b/python/makefile @@ -11,8 +11,9 @@ SLIBS = -lapt-pkg LIB_MAKES = apt-pkg/makefile APT_PKG_SRC = apt_pkgmodule.cc configuration.cc generic.cc tag.cc string.cc \ cache.cc pkgrecords.cc pkgsrcrecords.cc sourcelist.cc \ - depcache.cc progress.cc cdrom.cc acquire.cc pkgmanager.cc \ - indexfile.cc metaindex.cc hashstring.cc indexrecords.cc policy.cc + depcache.cc progress.cc cdrom.cc acquire.cc pkgmanager.cc \ + indexfile.cc metaindex.cc hashstring.cc indexrecords.cc \ + policy.cc hashes.cc SOURCE := $(APT_PKG_SRC) include $(PYTHON_H) progress.h -- cgit v1.2.3 From 4bea536827ad8f0d294bdac5268a893c6ac22a8a Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Jul 2009 18:49:01 +0200 Subject: doc/source/contributing.rst: Add C++ Coding style guidelines. These are the new C++ coding style guidelines, which are derived from PEP 7. --- doc/source/contributing.rst | 190 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 164 insertions(+), 26 deletions(-) (limited to 'doc/source') diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst index 04933b73..eafc2a2e 100644 --- a/doc/source/contributing.rst +++ b/doc/source/contributing.rst @@ -43,47 +43,185 @@ submit them. C++ Coding style ---------------- -When you work on the C++ code in the python/ directory, you should follow some -basic rules. +This document gives coding conventions for the C++ code comprising +the C++ extensions of Python APT. Please see the companion +informational PEP describing style guidelines for Python code (:PEP:`8`). -The indentation of the code is a bit non-standard. We currently use 3 spaces -indentation for the C++ code. +Note, rules are there to be broken. Two good reasons to break a +particular rule: -When you create new functions, you should follow some naming conventions. All -C++ functions are named according to the ``CamelCase`` convention. + (1) When applying the rule would make the code less readable, even + for someone who is used to reading code that follows the rules. -The resulting Python functions should be ``CamelCase`` as well in apt_pkg, or -``mixedCase`` in apt_inst. The same applies for variables, parameters, -attributes, etc. + (2) To be consistent with surrounding code that also breaks it + (maybe for historic reasons) -- although this is also an + opportunity to clean up someone else's mess (in true XP style). -.. note:: +This part of the document is derived from :PEP:`7` which was written by +Guido van Rossum. + + +C++ dialect +^^^^^^^^^^^ + +- Use ISO standard C++ (the 1998 version of the standard). + +- All function declarations and definitions must use full + prototypes (i.e. specify the types of all arguments). + +- Use C++ style // one-line comments where useful. + +- No compiler warnings with ``gcc -std=c++98 -Wall -Wno-write-strings``. There + should also be no errors with ``-pedantic`` added. + + +Code lay-out +^^^^^^^^^^^^ + +- Use 3-space indents, in files that already use them. In new source files, + that were created after this rule was introduced, use 4-space indents. + + At some point, the whole codebase may be converted to use only + 4-space indents. + +- No line should be longer than 79 characters. If this and the + previous rule together don't give you enough room to code, your + code is too complicated -- consider using subroutines. + +- No line should end in whitespace. If you think you need + significant trailing whitespace, think again -- somebody's + editor might delete it as a matter of routine. + +- Function definition style: function name in column 2, outermost + curly braces in column 1, blank line after local variable + declarations:: + + static int extra_ivars(PyTypeObject *type, PyTypeObject *base) + { + int t_size = PyType_BASICSIZE(type); + int b_size = PyType_BASICSIZE(base); + + assert(t_size >= b_size); /* type smaller than base! */ + ... + return 1; + } + +- Code structure: one space between keywords like 'if', 'for' and + the following left paren; no spaces inside the paren; braces as + shown:: + + if (mro != NULL) { + ... + } + else { + ... + } + +- The return statement should *not* get redundant parentheses:: + + return Py_None; /* correct */ + return(Py_None); /* incorrect */ + +- Function and macro call style: ``foo(a, b, c)`` -- no space before + the open paren, no spaces inside the parens, no spaces before + commas, one space after each comma. + +- Always put spaces around assignment, Boolean and comparison + operators. In expressions using a lot of operators, add spaces + around the outermost (lowest-priority) operators. + +- Breaking long lines: if you can, break after commas in the + outermost argument list. Always indent continuation lines + appropriately, e.g.:: + + PyErr_Format(PyExc_TypeError, + "cannot create '%.100s' instances", + type->tp_name); - This coding style guidelines are incomplete. If you have any questions - send an email to deity@lists.debian.org. +- When you break a long expression at a binary operator, the + operator goes at the end of the previous line, e.g.:: + + if (type->tp_dictoffset != 0 && base->tp_dictoffset == 0 && + type->tp_dictoffset == b_size && + (size_t)t_size == b_size + sizeof(PyObject *)) + return 0; /* "Forgive" adding a __dict__ only */ + +- Put blank lines around functions, structure definitions, and + major sections inside functions. + +- Comments go before the code they describe. + +- All functions and global variables should be declared static + unless they are to be part of a published interface + + +Naming conventions +^^^^^^^^^^^^^^^^^^ + +- Use a ``Py`` prefix for public functions; never for static + functions. The ``Py_`` prefix is reserved for global service + routines like ``Py_FatalError``; specific groups of routines + (e.g. specific object type APIs) use a longer prefix, + e.g. ``PyString_`` for string functions. + +- Public functions and variables use MixedCase with underscores, + like this: ``PyObject_GetAttr``, ``Py_BuildValue``, ``PyExc_TypeError``. + +- Internal functions and variables use lowercase with underscores, like + this: ``hashes_get_sha1.`` + +- Occasionally an "internal" function has to be visible to the + loader; we use the _Py prefix for this, e.g.: ``_PyObject_Dump``. + +- Macros should have a MixedCase prefix and then use upper case, + for example: ``PyString_AS_STRING``, ``Py_PRINT_RAW``. + + +Documentation Strings +^^^^^^^^^^^^^^^^^^^^^ +- The first line of each function docstring should be a "signature + line" that gives a brief synopsis of the arguments and return + value. For example:: + + PyDoc_STRVAR(myfunction__doc__, + "myfunction(name: str, value) -> bool\n\n" + Determine whether name and value make a valid pair."); + + The signature line should be formatted using the format for function + annotations described in :PEP:`3107`, whereas the annotations shall reflect + the name of the type (e.g. ``str``). The leading ``def`` and the trailing + ``:`` as used for function definitions must not be included. + + Always include a blank line between the signature line and the + text of the description. + + If the return value for the function is always ``None`` (because + there is no meaningful return value), do not include the + indication of the return type. + +- When writing multi-line docstrings, be sure to always use + string literal concatenation:: + + PyDoc_STRVAR(myfunction__doc__, + "myfunction(name, value) -> bool\n\n" + "Determine whether name and value make a valid pair."); Python Coding Style ------------------- -The coding style for all code written in python is :PEP:`8`. For modules and -classes added from version 0.7.9 on, there are no exceptions. - -Classes introduced prior to 0.7.9 use mixedCase names for methods, functions -and variables. These names will be replaced by names conforming to :PEP:`8` -in a future release of python-apt. +The coding style for all code written in python is :PEP:`8`. Exceptions from +this rule are the documentation, where code is sometimes formatted differently +to explain aspects, and functions provided for 0.7 compatibility purposes. -Therefore, try to reduce the introduction of the mixedName code to the absolute -minimum (sometimes you can also use shorter names). +When writing code, use tools like pylint, pyflakes, pychecker and pep8.py from +http://svn.browsershots.org/trunk/devtools/pep8/ to verify that your code is +OK. Fix all the problems which seem reasonable, and mention the unfixed issues +when asking for merge. In order to make the automatic generation of Python 3 code using 2to possible, code written in Python may not utilize any functionality unsupported by 2to3 or deprecated as of Python 2.6. -.. note:: - - You can use the tool pep8.py from http://svn.browsershots.org/trunk/devtools/pep8/ - to validate your code. Please also run pylint, pychecker, and pyflakes and - fix all new **errors** they report (undefined names, etc.). - Submitting your patch --------------------- First of all, the patch you create should be based against the debian-sid -- cgit v1.2.3 From 0f753709899127e0bbdc6bfcabfc84b0ba5cd3c2 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 13 Jul 2009 19:53:13 +0200 Subject: doc/source/contributing.rst: List debian-experimental, fix highlighting. --- doc/source/contributing.rst | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) (limited to 'doc/source') diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst index eafc2a2e..7c6b6e6d 100644 --- a/doc/source/contributing.rst +++ b/doc/source/contributing.rst @@ -27,6 +27,14 @@ submit them. VCS-Browser: http://bzr.debian.org/loggerhead/apt/python-apt/debian-sid/changes +**debian-experimental:** http://bzr.debian.org/apt/python-apt/debian-experimental + + This is another official Debian branch of python-apt, for releases + targetted at Debian experimental. This branch may contain unstable code + and may thus not work correctly. + + VCS-Browser: http://bzr.debian.org/loggerhead/apt/python-apt/debian-experimental/changes + **jak:** http://bzr.debian.org/users/jak/python-apt/jak This is Julian Andres Klode's (the documentation author's) branch. This is the place where cleanup and documentation updates happen. It is based @@ -41,6 +49,8 @@ submit them. VCS-Browser: https://code.launchpad.net/~ubuntu-core-dev/python-apt/ubuntu +.. highlightlang:: c + C++ Coding style ---------------- This document gives coding conventions for the C++ code comprising @@ -185,7 +195,7 @@ Documentation Strings PyDoc_STRVAR(myfunction__doc__, "myfunction(name: str, value) -> bool\n\n" - Determine whether name and value make a valid pair."); + "Determine whether name and value make a valid pair."); The signature line should be formatted using the format for function annotations described in :PEP:`3107`, whereas the annotations shall reflect @@ -224,8 +234,10 @@ deprecated as of Python 2.6. Submitting your patch --------------------- -First of all, the patch you create should be based against the debian-sid -branch of python-apt. +First of all, the patch you create should be based against the most current +branch of python-apt (debian-sid or debian-experimental). If it is a bugfix, +you should probably use debian-sid. If you choose the wrong branch, we will +ask you to rebase your patches against the correct one. Once you have made your change, check that it: @@ -271,13 +283,11 @@ patch, you may need to *merge* the branch instead. Documentation updates --------------------- If you want to update the documentation, please follow the procedure as written -above. But please CC: jak@debian.org in the bug report. - -You can send your content in plain text, but reStructuredText is the preferred -format. I (Julian Andres Klode) will review your patch and will forward them to -Michael Vogt, for inclusion in his branch. On release, this will be merged into -the debian-sid branch. +above. You can send your content in plain text, but reStructuredText is the +preferred format. I (Julian Andres Klode) will review your patch and include +it. +.. highlightlang:: sh Example patch session ---------------------- -- cgit v1.2.3 From b63d93492cba1ffd11454ab37e751ef6f938ff96 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 17 Jul 2009 14:10:21 +0200 Subject: doc/source/conf.py: Ignore failures to import apt_pkg. --- doc/source/conf.py | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) (limited to 'doc/source') diff --git a/doc/source/conf.py b/doc/source/conf.py index 5a289f32..86e6868c 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -16,6 +16,7 @@ # All configuration values have a default; values that are commented out # serve to show the default. import os +import glob import sys # If your extensions are in another directory, add it here. If the directory @@ -27,13 +28,21 @@ sys.path.insert(0, os.path.abspath('../..')) # Find the path to the built apt_pkg and apt_inst extensions if os.path.exists("../../build"): version = '.'.join(str(x) for x in sys.version_info[:2]) - for dirname in os.listdir('../../build'): - if version in dirname: - sys.path.insert(0, os.path.abspath('../../build/' + dirname)) + for apt_pkg_path in glob.glob('../../build/lib*%s/apt_pkg.so' % version): + sys.path.insert(0, os.path.dirname(apt_pkg_path)) + try: + import apt_pkg + except ImportError, exc: + # Not the correct version + sys.stderr.write('W: Ignoring error %s\n' % exc) + sys.path.pop(0) + else: + sys.stdout.write('I: Found apt_pkg.so in %s\n' % sys.path[0]) + # Hack: Disable compatibility mode + apt_pkg._COMPAT_0_7 = 0 + break + -# Hack: Disable compatibility mode -import apt_pkg -apt_pkg._COMPAT_0_7 = 0 # General configuration # --------------------- -- cgit v1.2.3 From 6f7b3df8f590467e76e99189f6ac9a78f8bec65d Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 20 Jul 2009 18:10:04 +0200 Subject: doc/source/whatsnew/0.8.0.rst: Document apt_pkg.SystemLock. --- doc/source/whatsnew/0.8.0.rst | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'doc/source') diff --git a/doc/source/whatsnew/0.8.0.rst b/doc/source/whatsnew/0.8.0.rst index e1acb5db..8889cbd9 100644 --- a/doc/source/whatsnew/0.8.0.rst +++ b/doc/source/whatsnew/0.8.0.rst @@ -57,8 +57,8 @@ In May 2008, Ben Finney reported bug 481061 against the python-apt package, asking for PEP8 conformant names. With the release of python-apt 0.8, this is finally happening. -Supporting new language features like the :keyword:`with` statement -------------------------------------------------------------------- +Context managers for the :keyword:`with` statement +-------------------------------------------------- This is not a real big change, but it's good to have it: :class:`apt_pkg.ActionGroup` can now be used as a context manager for the :keyword:`with` statement. This makes it more obvious that you are using an @@ -74,6 +74,11 @@ This also works for :class:`apt.Cache`:: for package in my_selected_packages: package.mark_install() # Instance of apt.Package +Yet another context manager is available for locking the package system:: + + with apt_pkg.SystemLock(): + # do your stuff here + Unification of dependency handling ---------------------------------- In apt 0.7, there were three different return types of functions parsing -- cgit v1.2.3 From 9d97c4ef07fe249ed2b5af7d52fe15655bbb9170 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 21 Jul 2009 17:51:43 +0200 Subject: python/lock.cc: Implement apt_pkg.FileLock(). This is yet another context manager, this time for locking files. It can be used multiple times and features an internal counter. --- doc/source/whatsnew/0.8.0.rst | 6 ++ python/apt_pkgmodule.cc | 1 + python/apt_pkgmodule.h | 1 + python/generic.h | 1 + python/lock.cc | 132 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 141 insertions(+) (limited to 'doc/source') diff --git a/doc/source/whatsnew/0.8.0.rst b/doc/source/whatsnew/0.8.0.rst index 8889cbd9..244da388 100644 --- a/doc/source/whatsnew/0.8.0.rst +++ b/doc/source/whatsnew/0.8.0.rst @@ -79,6 +79,12 @@ Yet another context manager is available for locking the package system:: with apt_pkg.SystemLock(): # do your stuff here +There is also one for file based locking: + + with apt_pkg.FileLock(filename): + # do your stuff here + + Unification of dependency handling ---------------------------------- In apt 0.7, there were three different return types of functions parsing diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index d4c23d2f..8b8e9c7f 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -652,6 +652,7 @@ extern "C" void initapt_pkg() ADDTYPE(Module,"AcquireItemDesc",&PyAcquireItemDesc_Type); ADDTYPE(Module,"CdromProgress",&PyCdromProgress_Type); ADDTYPE(Module,"SystemLock",&PySystemLock_Type); + ADDTYPE(Module,"FileLock",&PyFileLock_Type); // Tag file constants PyModule_AddObject(Module,"REWRITE_PACKAGE_ORDER", CharCharToList(TFRewritePackageOrder)); diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index de70c056..04bce2cc 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -118,6 +118,7 @@ extern PyTypeObject PyCdromProgress_Type; extern PyTypeObject PyAcquireItemDesc_Type; extern PyTypeObject PyAcquireWorker_Type; extern PyTypeObject PySystemLock_Type; +extern PyTypeObject PyFileLock_Type; #include "python-apt.h" #endif diff --git a/python/generic.h b/python/generic.h index 4a55e9bf..d7f121ce 100644 --- a/python/generic.h +++ b/python/generic.h @@ -54,6 +54,7 @@ typedef int Py_ssize_t; #define PyString_FromStringAndSize PyUnicode_FromStringAndSize #define PyString_AsString PyUnicode_AsString #define PyString_FromFormat PyUnicode_FromFormat +#define PyString_Type PyUnicode_Type #define PyInt_Check PyLong_Check #define PyInt_AsLong PyLong_AsLong // Force 0.7 compatibility to be off in Python 3 builds diff --git a/python/lock.cc b/python/lock.cc index 75665779..d4d45734 100644 --- a/python/lock.cc +++ b/python/lock.cc @@ -131,3 +131,135 @@ PyTypeObject PySystemLock_Type = { 0, // tp_alloc systemlock_new, // tp_new }; + + +/** + * File Based locking. + * + * The counter is increased by every call to filelock_enter() and decreased by + * every call to filelock_exit(). When the counter reaches 0, the underlying + * file descriptor is closed. + * + * Members: + * @member char* filename The name of the file + * @member int lock_count How many times we have locked it. + * @member int fd The filedescriptor returned by GetLock() or 0. + */ +struct filelock_object { + PyObject_HEAD + char *filename; + int lock_count; + int fd; +}; + +static PyObject *filelock_enter(filelock_object *self, PyObject *args) +{ + self->lock_count++; + // If we have no lock yet, get a lock. + if (self->lock_count == 1) { + self->fd = GetLock(self->filename, true); + if (self->fd == -1) { + self->lock_count--; + return HandleErrors(); + } + } + Py_INCREF(self); + return (PyObject *)self; +} + +static PyObject *filelock_exit(filelock_object *self, PyObject *args) +{ + // Count down the lock_count, if it is less than 0, reset it to 0. + self->lock_count--; + if (self->lock_count < 0) + self->lock_count = 0; + if (self->lock_count == 0 && self->fd != 0 && close(self->fd) == -1) { + return PyErr_SetFromErrno(PyExc_OSError); + } + Py_RETURN_FALSE; +} + +static PyObject *filelock_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + char *filename = 0; + char *kwlist[] = {"filename", NULL}; + if (PyArg_ParseTupleAndKeywords(args, kwds, "s:__init__", kwlist, + &filename) == 0) { + return NULL; + } + filelock_object *self = (filelock_object *)type->tp_alloc(type, 0); + // Copy the string into the object. + self->filename = new char[strlen(filename) + 1]; + strcpy(self->filename, filename); + return (PyObject *)self; +} + +static void filelock_dealloc(filelock_object *self) +{ + delete[] self->filename; + ((PyObject*)self)->ob_type->tp_free(self); +} + +static PyMethodDef filelock_methods[] = { + {"__enter__",(PyCFunction)filelock_enter,METH_VARARGS,"Lock the system."}, + {"__exit__",(PyCFunction)filelock_exit,METH_VARARGS,"Unlock the system."}, + {NULL} +}; + +static char *filelock_doc = "SystemLock(filename: str)\n\n" + "Context manager for locking using a file. The lock is established\n" + "as soon as the method __enter__() is called. It is released when\n" + "__exit__() is called.\n\n" + "This should be used via the 'with' statement, e.g.::\n\n" + " with apt_pkg.FileLock(filename):\n" + " ...\n\n" + "Once the block is left, the lock is released automatically. The object\n" + "can be used multiple times::\n\n" + " lock = apt_pkg.FileLock(filename)\n" + " with lock:\n" + " ...\n" + " with lock:\n" + " ...\n\n"; + +PyTypeObject PyFileLock_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "apt_pkg.FileLock", // tp_name + sizeof(filelock_object), // tp_basicsize + 0, // tp_itemsize + // Methods + destructor(filelock_dealloc), // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + (Py_TPFLAGS_DEFAULT | // tp_flags + Py_TPFLAGS_BASETYPE), + filelock_doc, // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + filelock_methods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + 0, // tp_alloc + filelock_new, // tp_new +}; -- cgit v1.2.3 From d8c0ca6ff164f79910b315c9525fa77417084edf Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Thu, 23 Jul 2009 21:42:17 +0200 Subject: doc/source: Big documentation reorganisation. Due to the new C++ API and because I wanted to include some tutorials, the documentation is now seperated into 4 sections: library => Documentation of modules. tutorials => Tutorials for using python-apt and contributing whatsnew => Release notes c++ => Documentation,Tutorials for the C++ API This commit also includes a new overview page, like the Python documentation. --- doc/source/apt/cache.rst | 78 -- doc/source/apt/cdrom.rst | 7 - doc/source/apt/debfile.rst | 39 - doc/source/apt/index.rst | 56 - doc/source/apt/package.rst | 111 -- doc/source/apt/progress.gtk2.rst | 29 - doc/source/apt/progress.rst | 37 - doc/source/apt_inst.rst | 122 -- doc/source/apt_pkg.rst | 1780 ------------------------ doc/source/aptsources/distinfo.rst | 10 - doc/source/aptsources/distro.rst | 10 - doc/source/aptsources/index.rst | 10 - doc/source/aptsources/sourceslist.rst | 10 - doc/source/conf.py | 31 +- doc/source/contents.rst | 20 + doc/source/contributing.rst | 308 ----- doc/source/examples/apt-cdrom.py | 70 + doc/source/index.rst | 41 - doc/source/library/apt.cache.rst | 78 ++ doc/source/library/apt.cdrom.rst | 7 + doc/source/library/apt.debfile.rst | 39 + doc/source/library/apt.package.rst | 111 ++ doc/source/library/apt.progress.gtk2.rst | 29 + doc/source/library/apt.progress.qt4.rst | 3 + doc/source/library/apt.progress.text.rst | 21 + doc/source/library/apt_inst.rst | 122 ++ doc/source/library/apt_pkg.rst | 1795 +++++++++++++++++++++++++ doc/source/library/aptsources.distinfo.rst | 11 + doc/source/library/aptsources.distro.rst | 11 + doc/source/library/aptsources.sourceslist.rst | 11 + doc/source/library/index.rst | 36 + doc/source/templates/indexcontent.html | 50 + doc/source/templates/layout.html | 10 + doc/source/tutorials/apt-cdrom.rst | 156 +++ doc/source/tutorials/contributing.rst | 312 +++++ doc/source/tutorials/index.rst | 8 + doc/source/whatsnew/0.8.0.rst | 4 +- 37 files changed, 2923 insertions(+), 2660 deletions(-) delete mode 100644 doc/source/apt/cache.rst delete mode 100644 doc/source/apt/cdrom.rst delete mode 100644 doc/source/apt/debfile.rst delete mode 100644 doc/source/apt/index.rst delete mode 100644 doc/source/apt/package.rst delete mode 100644 doc/source/apt/progress.gtk2.rst delete mode 100644 doc/source/apt/progress.rst delete mode 100644 doc/source/apt_inst.rst delete mode 100644 doc/source/apt_pkg.rst delete mode 100644 doc/source/aptsources/distinfo.rst delete mode 100644 doc/source/aptsources/distro.rst delete mode 100644 doc/source/aptsources/index.rst delete mode 100644 doc/source/aptsources/sourceslist.rst create mode 100644 doc/source/contents.rst delete mode 100644 doc/source/contributing.rst create mode 100644 doc/source/examples/apt-cdrom.py delete mode 100644 doc/source/index.rst create mode 100644 doc/source/library/apt.cache.rst create mode 100644 doc/source/library/apt.cdrom.rst create mode 100644 doc/source/library/apt.debfile.rst create mode 100644 doc/source/library/apt.package.rst create mode 100644 doc/source/library/apt.progress.gtk2.rst create mode 100644 doc/source/library/apt.progress.qt4.rst create mode 100644 doc/source/library/apt.progress.text.rst create mode 100644 doc/source/library/apt_inst.rst create mode 100644 doc/source/library/apt_pkg.rst create mode 100644 doc/source/library/aptsources.distinfo.rst create mode 100644 doc/source/library/aptsources.distro.rst create mode 100644 doc/source/library/aptsources.sourceslist.rst create mode 100644 doc/source/library/index.rst create mode 100644 doc/source/templates/indexcontent.html create mode 100644 doc/source/templates/layout.html create mode 100644 doc/source/tutorials/apt-cdrom.rst create mode 100644 doc/source/tutorials/contributing.rst create mode 100644 doc/source/tutorials/index.rst (limited to 'doc/source') diff --git a/doc/source/apt/cache.rst b/doc/source/apt/cache.rst deleted file mode 100644 index ddb2dc64..00000000 --- a/doc/source/apt/cache.rst +++ /dev/null @@ -1,78 +0,0 @@ -:mod:`apt.cache` --- The Cache class -===================================== -.. automodule:: apt.cache - -The Cache class ---------------- - -.. autoclass:: Cache - :members: - :undoc-members: - - .. describe:: cache[pkgname] - - Return a :class:`Package()` for the package with the name *pkgname*. - -Example -^^^^^^^ - -The following example shows how to load the cache, update it, and upgrade -all the packages on the system:: - - import apt - import apt.progress - - # First of all, open the cache - cache = apt.Cache() - # Now, lets update the package list - cache.update() - # We need to re-open the cache because it needs to read the package list - cache.open(None) - # Now we can do the same as 'apt-get upgrade' does - cache.upgrade() - # or we can play 'apt-get dist-upgrade' - cache.upgrade(True) - # Q: Why does nothing happen? - # A: You forgot to call commit()! - cache.commit(apt.progress.TextFetchProgress(), - apt.progress.InstallProgress()) - - - -Working with Filters --------------------- -.. autoclass:: Filter - :members: - :inherited-members: - :undoc-members: - -.. autoclass:: MarkedChangesFilter - :members: - :inherited-members: - :undoc-members: - -.. autoclass:: FilteredCache - :members: - :inherited-members: - :undoc-members: - - -Example -^^^^^^^ - -This is an example for a filtered cache, which only allows access to the -packages whose state has been changed, eg. packages marked for installation:: - - >>> from apt.cache import FilteredCache, Cache, MarkedChangesFilter - >>> cache = apt.Cache() - >>> changed = apt.FilteredCache(cache) - >>> changed.set_filter(MarkedChangesFilter()) - >>> print len(changed) == len(cache.get_changes()) # Both need to have same length - True - - -Exceptions ----------- -.. autoexception:: FetchCancelledException -.. autoexception:: FetchFailedException -.. autoexception:: LockFailedException diff --git a/doc/source/apt/cdrom.rst b/doc/source/apt/cdrom.rst deleted file mode 100644 index 56381f14..00000000 --- a/doc/source/apt/cdrom.rst +++ /dev/null @@ -1,7 +0,0 @@ -:mod:`apt.cdrom` - Functionality like in apt-cdrom -==================================================== -.. automodule:: apt.cdrom - :members: - - - diff --git a/doc/source/apt/debfile.rst b/doc/source/apt/debfile.rst deleted file mode 100644 index 7133b5a8..00000000 --- a/doc/source/apt/debfile.rst +++ /dev/null @@ -1,39 +0,0 @@ -:mod:`apt.debfile` --- Classes related to debian package files -============================================================== -The :mod:`apt.debfile` provides classes to work with locally available -debian packages, or source packages. - -.. module:: apt.debfile - -Binary packages ----------------- -.. autoclass:: DebPackage - :members: - :inherited-members: - :undoc-members: - - The :class:`DebPackage` class is a class for working with '.deb' files, - also known as Debian packages. - - It provides methods and attributes to get a list of the files in the - package, to install the package and much more. - - If you specify *cache* it has to point to an :class:`apt.cache.Cache()` - object. - - .. versionchanged:: 0.7.9 - Introduce all new methods (everything except for :meth:`open()` and - :attr:`filelist`) - - -Source packages ----------------- -.. autoclass:: DscSrcPackage - :members: - :inherited-members: - :undoc-members: - - Provide functionality to work with locally available source packages, - especially with their '.dsc' file. - - .. versionadded:: 0.7.9 diff --git a/doc/source/apt/index.rst b/doc/source/apt/index.rst deleted file mode 100644 index 9cd6ef45..00000000 --- a/doc/source/apt/index.rst +++ /dev/null @@ -1,56 +0,0 @@ -:mod:`apt` --- Highlevel apt package -===================================== -The highlevel apt package provides a lot of functionality, all -with an easy-to-use interface. - -.. warning:: - The API of this package is not considered stable. Evenmore, it is considered - to change the naming conventions in future to lowercase_with_underscores. - - In case this happens, the API will still be kept compatible, with the old - functions provided as deprecated ones. - -.. automodule:: apt - - - -.. toctree:: - :maxdepth: 2 - :glob: - - * - - -Classes exported in apt ------------------------- -These classes are defined in the submodules, but are also exported directly -in the package. - -.. class:: Cache - - Please see :class:`apt.cache.Cache` for documentation. - -.. class:: Cdrom - - Please see :class:`apt.cdrom.Cdrom` for documentation. - -.. class:: CdromProgress - - Please see :class:`apt.progress.CdromProgress` for documentation. - -.. class:: FetchProgress - - Please see :class:`apt.progress.FetchProgress` for documentation. - -.. class:: InstallProgress - - Please see :class:`apt.progress.InstallProgress` for documentation. - -.. class:: OpProgress - - Please see :class:`apt.progress.OpProgress` for documentation. - -.. class:: Package - - Please see :class:`apt.package.Package` for documentation. - diff --git a/doc/source/apt/package.rst b/doc/source/apt/package.rst deleted file mode 100644 index 4b143b8a..00000000 --- a/doc/source/apt/package.rst +++ /dev/null @@ -1,111 +0,0 @@ -:mod:`apt.package` --- Classes for package handling -==================================================== - - -.. automodule:: apt.package - - -The Package class ------------------ -.. autoclass:: Package - :members: - - .. note:: - - Several methods have been deprecated in version 0.7.9 of python-apt, - please see the :class:`Version` class for the new alternatives. - -The Version class ------------------ -.. autoclass:: Version - :members: - - -Dependency Information ----------------------- -.. class:: BaseDependency - - The :class:`BaseDependency` class defines various attributes for accessing - the parts of a dependency. The attributes are as follows: - - .. attribute:: name - - The name of the dependency - - .. attribute:: relation - - The relation (>>,>=,==,<<,<=,) - - .. attribute:: version - - The version or None. - - .. attribute:: pre_depend - - Boolean value whether this is a pre-dependency. - -.. class:: Dependency - - The dependency class represents a Or-Group of dependencies. It provides - an attribute to access the :class:`BaseDependency` object for the available - choices. - - .. attribute:: or_dependencies - - A list of :class:`BaseDependency` objects which could satisfy the - requirement of the Or-Group. - - -Origin Information -------------------- -.. class:: Origin - - The :class:`Origin` class provides access to the origin of the package. - It allows you to check the component, archive, the hostname, and even if - this package can be trusted. - - .. attribute:: archive - - The archive (eg. unstable) - - .. attribute:: component - - The component (eg. main) - - .. attribute:: label - - The Label, as set in the Release file - - .. attribute:: origin - - The Origin, as set in the Release file - - .. attribute:: site - - The hostname of the site. - - .. attribute:: trusted - - Boolean value whether this is trustworthy. An origin can be trusted, if - it provides a GPG-signed Release file and the GPG-key used is in the - keyring used by apt (see apt-key). - -Examples ---------- -.. code-block:: python - - import apt - - cache = apt.Cache() - pkg = cache['python-apt'] # Access the Package object for python-apt - print 'python-apt is trusted:', pkg.candidate.origins[0].trusted - - # Mark python-apt for install - pkg.mark_install() - - print 'python-apt is marked for install:', pkg.marked_install - - print 'python-apt is (summary):', pkg.candidate.summary - - # Now, really install it - cache.commit() diff --git a/doc/source/apt/progress.gtk2.rst b/doc/source/apt/progress.gtk2.rst deleted file mode 100644 index a83ab111..00000000 --- a/doc/source/apt/progress.gtk2.rst +++ /dev/null @@ -1,29 +0,0 @@ -:mod:`apt.progress.gtk2` --- GTK widgets -======================================== -.. automodule:: apt.progress.gtk2 - - -GObject progress classes -------------------------- - -.. autoclass:: GDpkgInstallProgress - :members: - -.. autoclass:: GFetchProgress - :members: - -.. autoclass:: GInstallProgress - :members: - -.. autoclass:: GOpProgress - :members: - -GTK+ Class ----------- -.. autoclass:: GtkAptProgress - :members: - - -Example -------- -.. literalinclude:: ../examples/apt-gtk.py diff --git a/doc/source/apt/progress.rst b/doc/source/apt/progress.rst deleted file mode 100644 index 8989aa27..00000000 --- a/doc/source/apt/progress.rst +++ /dev/null @@ -1,37 +0,0 @@ -:mod:`apt.progress` --- Classes for progress reporting -====================================================== -.. automodule:: apt.progress - -.. warning:: - - This class is currently under re-organisation. Therefore, the API may - change soon. The old names will still be kept until it is safe to remove - them. - - - -Classes without output ----------------------- -.. autoclass:: FetchProgress - :members: -.. autoclass:: OpProgress - :members: -.. autoclass:: CdromProgress - :members: -.. autoclass:: DumbInstallProgress - :members: - -Implementing classes for text output ------------------------------------- -.. autoclass:: TextFetchProgress - :members: -.. autoclass:: OpTextProgress - :members: -.. autoclass:: InstallProgress - :members: -.. autoclass:: DpkgInstallProgress - :members: - - - - diff --git a/doc/source/apt_inst.rst b/doc/source/apt_inst.rst deleted file mode 100644 index cd371e36..00000000 --- a/doc/source/apt_inst.rst +++ /dev/null @@ -1,122 +0,0 @@ -:mod:`apt_inst` - Working with local Debian packages -==================================================== -.. module:: apt_inst - -The :mod:`apt_inst` extension provides access to functions for working with -locally available Debian packages (.deb files) and tar files. - - -Checking packages ------------------- -.. function:: arCheckMember(file, membername) - - Check if the member specified by the parameter *membername* exists in - the AR file referenced by the parameter *file*, which may be a - :class:`file()` object, a file descriptor, or anything implementing a - :meth:`fileno` method. - - .. versionchanged:: 0.8.0 - Added support for file descriptors and objects implementing a :meth:`fileno` method. - - -Listing contents ------------------ -.. function:: debExtract(file, func, chunk) - - Call the function referenced by *func* for each member of the tar file - *chunk* which is contained in the AR file referenced by the parameter - *file*, which may be a :class:`file()` object, a file descriptor, or - anything implementing a :meth:`fileno` method. - - An example would be:: - - debExtract(open("package.deb"), my_callback, "data.tar.gz") - - See :ref:`emulating-dpkg-contents` for a more detailed example. - - .. versionchanged:: 0.8.0 - Added support for file descriptors and objects implementing a :meth:`fileno` method. - -.. function:: tarExtract(file,func,comp) - - Call the function *func* for each member of the tar file *file*. - - The parameter *comp* is a string determining the compressor used. Possible - options are "lzma", "bzip2" and "gzip". - - The parameter *file* may be a :class:`file()` object, a file descriptor, or - anything implementing a :meth:`fileno` method. - - .. versionchanged:: 0.8.0 - Added support for file descriptors and objects implementing a :meth:`fileno` method. - - -Callback -^^^^^^^^^ -Both of these functions expect a callback with the signature -``(what, name, link, mode, uid, gid, size, mtime, major, minor)``. - -The parameter *what* describes the type of the member. It can be 'FILE', -'DIR', or 'HARDLINK'. - -The parameter *name* refers to the name of the member. In case of links, -*link* refers to the target of the link. - - -Extracting contents -------------------- - -.. function:: debExtractArchive(file, rootdir) - - Extract the archive referenced by the :class:`file` object *file* - into the directory specified by *rootdir*. - - The parameter *file* may be a :class:`file()` object, a file descriptor, or - anything implementing a :meth:`fileno` method. - - See :ref:`emulating-dpkg-extract` for an example. - - .. warning:: - - If the directory given by *rootdir* does not exist, the package is - extracted into the current directory. - - .. versionchanged:: 0.8.0 - Added support for file descriptors and objects implementing a :meth:`fileno` method. - -.. function:: debExtractControl(file[, member='control']) - - Return the indicated file as a string from the control tar. The default - is 'control'. - - The parameter *file* may be a :class:`file()` object, a file descriptor, or - anything implementing a :meth:`fileno` method. - - If you want to print the control file of a given package, you could do - something like:: - - print debExtractControl(open("package.deb")) - - .. versionchanged:: 0.8.0 - Added support for file descriptors and objects implementing a :meth:`fileno` method. - - -.. _emulating-dpkg-extract: - -Example: Emulating :program:`dpkg` :option:`--extract` -------------------------------------------------------- -Here is a code snippet which emulates dpkg -x. It can be run as -:program:`tool` :option:`pkg.deb` :option:`outdir`. - -.. literalinclude:: examples/dpkg-extract.py - - -.. _emulating-dpkg-contents: - -Example: Emulating :program:`dpkg` :option:`--contents` -------------------------------------------------------- -.. literalinclude:: examples/dpkg-contents.py - -Example: Emulating :program:`dpkg` :option:`--info` ----------------------------------------------------- -.. literalinclude:: examples/dpkg-info.py diff --git a/doc/source/apt_pkg.rst b/doc/source/apt_pkg.rst deleted file mode 100644 index 9a14266e..00000000 --- a/doc/source/apt_pkg.rst +++ /dev/null @@ -1,1780 +0,0 @@ -:mod:`apt_pkg` --- The low-level bindings for apt-pkg -===================================================== -.. module:: apt_pkg - -The apt_pkg extensions provides a more low-level way to work with apt. It can -do everything apt can, and is written in C++. It has been in python-apt since -the beginning. - - -Module Initialization ---------------------- - -Initialization is needed for most functions, but not for all of them. Some can -be called without having run init*(), but will not return the expected value. - -.. function:: init_config - - Initialize the configuration of apt. This is needed for most operations. - -.. function:: init_system - - Initialize the system. - -.. function:: init - - Deprecated function. Use init_config() and init_system() instead. - -Working with the cache ----------------------- -.. class:: Cache([progress]) - - Return a :class:`Cache()` object. The optional parameter *progress* - specifies an instance of :class:`apt.progress.OpProgress()` which will - display the open progress. - - .. describe:: cache[pkgname] - - Return the :class:`Package()` object for the package name given by - *pkgname*. - - .. method:: close() - - Close the package cache. - - .. method:: open([progress]) - - Open the package cache again. The parameter *progress* may be set to - an :class:`apt.progress.OpProgress()` object or `None`. - - .. method:: update(progress, list) - - Update the package cache. - - The parameter *progress* points to an :class:`apt.progress.FetchProgress()` - object. The parameter *list* refers to a :class:`SourceList()` object. - - .. attribute:: depends_count - - The total number of dependencies. - - .. attribute:: package_count - - The total number of packages available in the cache. - - .. attribute:: provides_count - - The number of provided packages. - - .. attribute:: ver_file_count - - .. todo:: Seems to be some mixture of versions and pkgFile. - - .. attribute:: version_count - - The total number of package versions available in the cache. - - .. attribute:: package_file_count - - The total number of Packages files available (the Packages files - listing the packages). This is the same as the length of the list in - the attribute :attr:`file_list`. - - .. attribute:: file_list - - A list of :class:`PackageFile` objects. - -.. class:: DepCache(cache) - - Return a :class:`DepCache` object. The parameter *cache* specifies an - instance of :class:`Cache`. - - The DepCache object contains various methods to manipulate the cache, - to install packages, to remove them, and much more. - - .. method:: commit(fprogress, iprogress) - - Apply all the changes made. - - The parameter *fprogress* has to be set to an instance of - apt.progress.FetchProgress or one of its subclasses. - - The parameter *iprogress* has to be set to an instance of - apt.progress.InstallProgress or one of its subclasses. - - .. method:: fix_broken() - - Try to fix all broken packages in the cache. - - .. method:: get_candidate_ver(pkg) - - Return the candidate version of the package, ie. the version that - would be installed normally. - - The parameter *pkg* refers to an :class:`Package` object, - available using the :class:`pkgCache`. - - This method returns a :class:`Version` object. - - .. method:: set_candidate_ver(pkg, version) - - The opposite of :meth:`pkgDepCache.get_candidate_ver`. Set the candidate - version of the :class:`Package` *pkg* to the :class:`Version` - *version*. - - - .. method:: upgrade([dist_upgrade=False]) - - Perform an upgrade. More detailed, this marks all the upgradable - packages for upgrade. You still need to call - :meth:`pkgDepCache.commit` for the changes to apply. - - To perform a dist-upgrade, the optional parameter *dist_upgrade* has - to be set to True. - - .. method:: fix_broken() - - Fix broken packages. - - .. method:: read_pin_file() - - Read the policy, eg. /etc/apt/preferences. - - .. method:: minimize_upgrade() - - Go over the entire set of packages and try to keep each package marked - for upgrade. If a conflict is generated then the package is restored. - - .. todo:: - Explain better.. - - .. method:: mark_keep(pkg) - - Mark the :class:`Package` *pkg* for keep. - - .. method:: mark_delete(pkg[, purge]) - - Mark the :class:`Package` *pkg* for delete. If *purge* is True, - the configuration files will be removed as well. - - .. method:: mark_install(pkg[, auto_inst=True[, from_user=True]]) - - Mark the :class:`Package` *pkg* for install. - - If *auto_inst* is ``True``, the dependencies of the package will be - installed as well. This is the default. - - If *from_user* is ``True``, the package will be marked as manually - installed. This is the default. - - .. method:: set_reinstall(pkg) - - Set if the :class:`Package` *pkg* should be reinstalled. - - .. method:: is_upgradable(pkg) - - Return ``1`` if the package is upgradable. - - The package can be upgraded by calling :meth:`pkgDepCache.MarkInstall`. - - .. method:: is_now_broken(pkg) - - Return `1` if the package is broken now (including changes made, but - not committed). - - .. method:: is_inst_broken(pkg) - - Return ``1`` if the package is broken on the current install. This - takes changes which have not been committed not into effect. - - .. method:: is_garbage(pkg) - - Return ``1`` if the package is garbage, ie. if it is automatically - installed and no longer referenced by other packages. - - .. method:: is_auto_installed(pkg) - - Return ``1`` if the package is automatically installed (eg. as the - dependency of another package). - - .. method:: marked_install(pkg) - - Return ``1`` if the package is marked for install. - - .. method:: marked_upgrade(pkg) - - Return ``1`` if the package is marked for upgrade. - - .. method:: marked_delete(pkg) - - Return ``1`` if the package is marked for delete. - - .. method:: marked_keep(pkg) - - Return ``1`` if the package is marked for keep. - - .. method:: marked_reinstall(pkg) - - Return ``1`` if the package should be installed. - - .. method:: marked_downgrade(pkg) - - Return ``1`` if the package should be downgraded. - - .. attribute:: keep_count - - Integer, number of packages marked as keep - - .. attribute:: inst_count - - Integer, number of packages marked for installation. - - .. attribute:: del_count - - Number of packages which should be removed. - - .. attribute:: broken_count - - Number of packages which are broken. - - .. attribute:: usr_size - - The size required for the changes on the filesystem. If you install - packages, this is positive, if you remove them its negative. - - .. attribute:: deb_size - - The size of the packages which are needed for the changes to be - applied. - - -.. class:: PackageManager(depcache) - - Return a new :class:`PackageManager` object. The parameter *depcache* - specifies a :class:`DepCache` object. - - :class:`PackageManager` objects provide several methods and attributes, - which will be listed here: - - .. method:: get_archives(fetcher, list, records) - - Add all the selected packages to the :class:`Acquire()` object - *fetcher*. - - The parameter *list* refers to a :class:`SourceList()` object. - - The parameter *records* refers to a :class:`PackageRecords()` object. - - .. method:: do_install() - - Install the packages. - - .. method:: fix_missing - - Fix the installation if a package could not be downloaded. - - .. attribute:: result_completed - - A constant for checking whether the the result is 'completed'. - - Compare it against the return value of :meth:`PackageManager.get_archives` - or :meth:`PackageManager.do_install`. - - .. attribute:: result_failed - - A constant for checking whether the the result is 'failed'. - - Compare it against the return value of :meth:`PackageManager.get_archives` - or :meth:`PackageManager.do_install`. - - .. attribute:: result_incomplete - - A constant for checking whether the the result is 'incomplete'. - - Compare it against the return value of :meth:`PackageManager.get_archives` - or :meth:`PackageManager.do_install`. - -Improve performance with :class:`ActionGroup` -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -.. class:: ActionGroup(depcache) - - Create a new :class:`ActionGroup()` object for the :class:`DepCache` object - given by the parameter *depcache*. - - :class:`ActionGroup()` objects make operations on the cache faster by - delaying certain cleanup operations until the action group is released. - - ActionGroup is also a context manager and therefore supports the - :keyword:`with` statement. But because it becomes active as soon as it - is created, you should not create an ActionGroup() object before entering - the with statement. - - If you want to use ActionGroup as a with statement (which is recommended - because it makes it easier to see when an actiongroup is active), always - use the following form:: - - with apt_pkg.ActionGroup(depcache): - ... - - For code which has to run on Python versions prior to 2.5, you can also - use the traditional way:: - - actiongroup = apt_pkg.ActionGroup(depcache) - ... - actiongroup.release() - - :class:`ActionGroup` provides the following method: - - .. method:: release() - - Release the ActionGroup. This will reactive the collection of package - garbage. - -Resolving Dependencies -^^^^^^^^^^^^^^^^^^^^^^ - -.. class:: ProblemResolver(depcache) - - Return a new :class:`ProblemResolver` object. The parameter *depcache* - specifies a :class:`pDepCache` object. - - The problem resolver helps when there are problems in the package - selection. An example is a package which conflicts with another, already - installed package. - - .. method:: protect(pkg) - - Protect the :class:`Package()` object given by the parameter *pkg*. - - .. todo:: - - Really document it. - - .. method:: install_protect() - - Protect all installed packages from being removed. - - .. method:: remove(pkg) - - Remove the :class:`Package()` object given by the parameter *pkg*. - - .. todo:: - - Really document it. - - .. method:: clear(pkg) - - Reset the :class:`Package()` *pkg* to the default state. - - .. todo:: - - Really document it. - - .. method:: resolve() - - Try to resolve problems by installing and removing packages. - - .. method:: resolve_by_keep() - - Try to resolve problems only by using keep. - - -:class:`PackageFile` --------------------- -.. class:: PackageFile - - A :class:`PackageFile` represents a Packages file, eg. - /var/lib/dpkg/status. - - .. attribute:: architecture - - The architecture of the package file. - - .. attribute:: archive - - The archive (eg. unstable) - - .. attribute:: component - - The component (eg. main) - - .. attribute:: filename - - The name of the file. - - .. attribute:: id - - The ID of the package. This is an integer which can be used to store - further information about the file [eg. as dictionary key]. - - .. attribute:: index_type - - The sort of the index file. In normal cases, this is - 'Debian Package Index'. - - .. attribute:: label - - The Label, as set in the Release file - - .. attribute:: not_automatic - - Whether packages from this list will be updated automatically. The - default for eg. example is 0 (aka false). - - .. attribute:: not_source - - Whether the file has no source from which it can be updated. In such a - case, the value is 1; else 0. /var/lib/dpkg/status is 0 for example. - - Example:: - - for pkgfile in cache.file_list: - if pkgfile.not_source: - print 'The file %s has no source.' % pkgfile.filename - - .. attribute:: origin - - The Origin, as set in the Release file - - .. attribute:: site - - The hostname of the site. - - .. attribute:: size - - The size of the file. - - .. attribute:: version - - The version, as set in the release file (eg. "4.0" for "Etch") - - -Example -^^^^^^^ -.. literalinclude:: examples/cache-pkgfile.py - - -:class:`Package` ----------------- - -.. class:: Package - - The pkgCache::Package objects are an interface to package specific - features. - - - Attributes: - - .. attribute:: current_ver - - The version currently installed, or None. This returns a - :class:`Version` object. - - .. attribute:: id - - The ID of the package. This can be used to store information about - the package. The ID is an int value. - - .. attribute:: name - - This is the name of the package. - - .. attribute:: provides_list - - A list of packages providing this package. More detailed, this is a - list of tuples (str:pkgname, ????, :class:`Version`). - - If you want to check for check for virtual packages, the expression - ``pkg.provides_list and not pkg._version_list`` helps you. It detects if - the package is provided by something else and is not available as a - real package. - - .. attribute:: rev_depends_list - - An iterator of :class:`Dependency` objects for dependencies on this - package. - - .. attribute:: section - - The section of the package, as specified in the record. The list of - possible sections is defined in the Policy. - - .. attribute:: version_list - - A list of :class:`Version` objects for all versions available in the - cache. - - **States**: - - .. attribute:: selected_state - - The state we want it to be, ie. if you mark a package for installation, - this is :attr:`apt_pkg.SELSTATE_INSTALL`. - - See :ref:`SelStates` for a list of available states. - - .. attribute:: inst_state - - The state the currently installed version is in. This is normally - :attr:`apt_pkg.INSTSTATE_OK`, unless the installation failed. - - See :ref:`InstStates` for a list of available states. - - .. attribute:: cur_state - - The current state of the package (not installed, unpacked, installed, - etc). See :ref:`CurStates` for a list of available states. - - **Flags**: - - .. attribute:: auto - - Whether the package was installed automatically as a dependency of - another package. (or marked otherwise as automatically installed) - - .. attribute:: essential - - Whether the package is essential. - - .. attribute:: important - - Whether the package is important. - -Example: -^^^^^^^^^ -.. literalinclude:: examples/cache-packages.py - - - -:class:`Version` ----------------- -.. class:: Version - - The version object contains all information related to a specific package - version. - - .. attribute:: ver_str - - The version, as a string. - - .. attribute:: section - - The usual sections (eg. admin, net, etc.). Prefixed with the component - name for packages not in main (eg. non-free/admin). - - .. attribute:: arch - - The architecture of the package, eg. amd64 or all. - - .. attribute:: file_list - - A list of (:class:`PackageFile`, int: index) tuples for all Package - files containing this version of the package. - - .. attribute:: depends_list_str - - A dictionary of dependencies. The key specifies the type of the - dependency ('Depends', 'Recommends', etc.). - - - The value is a list, containing items which refer to the or-groups of - dependencies. Each of these or-groups is itself a list, containing - tuples like ('pkgname', 'version', 'relation') for each or-choice. - - An example return value for a package with a 'Depends: python (>= 2.4)' - would be:: - - {'Depends': [ - [ - ('python', '2.4', '>=') - ] - ] - } - - The same for a dependency on A (>= 1) | B (>= 2):: - - {'Depends': [ - [ - ('A', '1', '>='), - ('B', '2', '>='), - ] - ] - } - - .. attribute:: depends_list - - This is basically the same as :attr:`Version.DependsListStr`, - but instead of the ('pkgname', 'version', 'relation') tuples, - it returns :class:`Dependency` objects, which can assist you with - useful functions. - - .. attribute:: parent_pkg - - The :class:`Package` object this version belongs to. - - .. attribute:: provides_list - - This returns a list of all packages provided by this version. Like - :attr:`Package.provides_list`, it returns a list of tuples - of the form ('virtualpkgname', ???, :class:`Version`), where as the - last item is the same as the object itself. - - .. attribute:: size - - The size of the .deb file, in bytes. - - .. attribute:: installed_size - - The size of the package (in kilobytes), when unpacked on the disk. - - .. attribute:: hash - - An integer hash value. - - .. attribute:: id - - An integer id. - - .. attribute:: priority - - The integer representation of the priority. This can be used to speed - up comparisons a lot, compared to :attr:`Version.priority_str`. - - The values are defined in the :mod:`apt_pkg` extension, see - :ref:`Priorities` for more information. - - .. attribute:: priority_str - - Return the priority of the package version, as a string, eg. - "optional". - - .. attribute:: downloadable - - Whether this package can be downloaded from a remote site. - - .. attribute:: translated_description - - Return a :class:`Description` object. - - -:class:`Dependency` -------------------- -.. class:: Dependency - - Represent a dependency from one package to another one. - - .. method:: all_targets - - A list of :class:`Version` objects which satisfy the dependency, - and do not conflict with already installed ones. - - From my experience, if you use this method to select the target - version, it is the best to select the last item unless any of the - other candidates is already installed. This leads to results being - very close to the normal package installation. - - .. method:: smart_target_pkg - - Return a :class:`Version` object of a package which satisfies the - dependency and does not conflict with installed packages - (the 'natural target'). - - .. attribute:: target_ver - - The target version of the dependency, as string. Empty string if the - dependency is not versioned. - - .. attribute:: target_pkg - - The :class:`Package` object of the target package. - - .. attribute:: parent_ver - - The :class:`Version` object of the parent version, ie. the package - which declares the dependency. - - .. attribute:: parent_pkg - - The :class:`Package` object of the package which declares the - dependency. This is the same as using ParentVer.ParentPkg. - - .. attribute:: comp_type - - The type of comparison (>=, ==, >>, <=), as string. - - .. attribute:: dep_type - - The type of the dependency, as string, eg. "Depends". - - .. attribute:: id - - The ID of the package, as integer. - -Example: Find all missing dependencies -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -With the help of Dependency.AllTargets(), you can easily find all packages with -broken dependencies: - -.. literalinclude:: examples/missing-deps.py - - -:class:`Description` --------------------- -.. class:: Description - - Represent the description of the package. - - .. attribute:: language_code - - The language code of the description - - .. attribute:: md5 - - The md5 hashsum of the description - - .. attribute:: file_list - - A list of tuples (:class:`PackageFile`, int: index). - - - -:class:`MetaIndex` ------------------- - -.. todo:: - - Complete them - -.. class:: MetaIndex - - .. attribute:: uri - .. attribute:: dist - .. attribute:: is_trusted - .. attribute:: index_files - - -:class:`PackageIndexFile` -------------------------- - -.. class:: PackageIndexFile - - .. method:: archive_uri(path) - - Return the full url to path in the archive. - - .. attribute:: label - - Return the Label. - - .. attribute:: exists - - Return whether the file exists. - - .. attribute:: has_packages - - Return whether the file has packages. - - .. attribute:: size - - Size of the file - - .. attribute:: is_trusted - - Whether we can trust the file. - - -Records --------- - -.. class:: PackageRecords(cache) - - Create a new :class:`PackageRecords` object, for the packages in the cache - specified by the parameter *cache*. - - Provide access to the packages records. This provides very useful - attributes for fast (convient) access to some fields of the record. - - .. method:: lookup(verfile_iter) - - Change the actual package to the package given by the verfile_iter. - - The parameter *verfile_iter* refers to a tuple consisting - of (:class:`PackageFile()`, int: index), as returned by various - attributes, including :attr:`Version.file_list`. - - Example (shortened):: - - cand = depcache.GetCandidateVer(cache['python-apt']) - records.Lookup(cand.FileList[0]) - # Now you can access the record - print records.SourcePkg # == python-apt - - .. attribute:: filename - - Return the field 'Filename' of the record. This is the path to the - package, relative to the base path of the archive. - - .. attribute:: md5_hash - - Return the MD5 hashsum of the package This refers to the field - 'MD5Sum' in the raw record. - - .. attribute:: sha1_hash - - Return the SHA1 hashsum of the package. This refers to the field 'SHA1' - in the raw record. - - .. attribute:: sha256_hash - - Return the SHA256 hashsum of the package. This refers to the field - 'SHA256' in the raw record. - - .. versionadded:: 0.7.9 - - .. attribute:: source_pkg - - Return the source package. - - .. attribute:: source_ver - - Return the source version. - - .. attribute:: maintainer - - Return the maintainer of the package. - - .. attribute:: short_desc - - Return the short description. This is the summary on the first line of - the 'Description' field. - - .. attribute:: long_desc - - Return the long description. These are lines 2-END from the - 'Description' field. - - .. attribute:: name - - Return the name of the package. This is the 'Package' field. - - .. attribute:: homepage - - Return the Homepage. This is the 'Homepage' field. - - .. attribute:: record - - Return the whole record as a string. If you want to access fields of - the record not available as an attribute, you can use - :class:`apt_pkg.TagSection` to parse the record and access the field - name. - - Example:: - - section = apt_pkg.TagSection(records.record) - print section['SHA256'] # Use records.sha256_hash instead - - -.. class:: SourceRecords - - This represents the entries in the Sources files, ie. the dsc files of - the source packages. - - .. note:: - - If the Lookup failed, because no package could be found, no error is - raised. Instead, the attributes listed below are simply not existing - anymore (same applies when no Lookup has been made, or when it has - been restarted). - - .. method:: lookup(pkgname) - - Lookup the record for the package named *pkgname*. To access all - available records, you need to call it multiple times. - - Imagine a package P with two versions X, Y. The first ``lookup(P)`` - would set the record to version X and the second ``lookup(P)`` to - version Y. - - .. method:: restart() - - Restart the lookup. - - Imagine a package P with two versions X, Y. The first ``Lookup(P)`` - would set the record to version X and the second ``Lookup(P)`` to - version Y. - - If you now call ``restart()``, the internal position will be cleared. - Now you can call ``lookup(P)`` again to move to X. - - .. attribute:: package - - The name of the source package. - - .. attribute:: version - - A string describing the version of the source package. - - .. attribute:: maintainer - - A string describing the name of the maintainer. - - .. attribute:: section - - A string describing the section. - - .. attribute:: record - - The whole record, as a string. You can use :func:`apt_pkg.ParseSection` - if you need to parse it. - - You need to parse the record if you want to access fields not available - via the attributes, eg. 'Standards-Version' - - .. attribute:: binaries - - Return a list of strings describing the package names of the binaries - created by the source package. This matches the 'Binary' field in the - raw record. - - .. attribute:: index - - The index in the Sources files. - - .. attribute:: files - - The list of files. This returns a list of tuples with the contents - ``(str: md5, int: size, str: path, str:type)``. - - .. attribute:: build_depends - - Return a dictionary representing the build-time dependencies of the - package. The format is the same as for :attr:`Version.depends_list_str` - and possible keys being ``"Build-Depends"``, ``"Build-Depends-Indep"``, - ``"Build-Conflicts"`` or ``"Build-Conflicts-Indep"``. - - .. attribute:: BuildDepends - - Return the list of Build dependencies, as - ``(str: package, str: version, int: op, int: type)``. This is a - completely deprecated format - - .. table:: Values of *op* - - ===== ============================================= - Value Meaning - ===== ============================================= - 0x00 No Operation (no versioned build dependency) - 0x10 | (or) - this will be added to the other values - 0x01 <= (less than or equal) - 0x02 >= (greater than or equal) - 0x03 << (less than) - 0x04 >> (greater than) - 0x05 = (equal) - 0x06 != (not equal) - ===== ============================================= - - .. table:: Values of *type* - - ===== =================== - Value Meaning - ===== =================== - 0 Build-Depends - 1 Build-Depends-Indep - 2 Build-Conflicts - 3 Build-Conflicts-Indep - ===== =================== - - **Example**: In the following content, we will imagine a - build-dependency:: - - Build-Depends: A (>= 1) | B (>= 1), C - - This results in:: - - [('A', '1', 18, 0), # 18 = (16 | 2) = (0x10 | 0x2) - ('B', '1', 2, 0), - ('C', '', 0, 0)] - - This is **not** the same as returned by - :func:`apt_pkg.ParseSrcDepends`. - - - -The Acquire interface ----------------------- -The Acquire Interface is responsible for all sorts of downloading in apt. All -packages, index files, etc. downloading is done using the Acquire functionality. - -The :mod:`apt_pkg` module provides a subset of this functionality which allows -you to implement file downloading in your applications. Together with the -:class:`PackageManager` class you can also fetch all the packages marked for -installation. - - -.. class:: Acquire([progress]) - - Return an :class:`Acquire` object. The parameter *progress* refers to - an :class:`apt.progress.FetchProgress()` object. - - Acquire objects maintaing a list of items which will be fetched or have - been fetched already during the lifetime of this object. To add new items - to this list, you can create new :class:`AcquireFile` objects which allow - you to add single files. - - Acquire items have multiple methods: - - .. method:: run() - - Fetch all the items which have been added by :class:`AcquireFile`. - - .. method:: shutdown() - - Shut the fetcher down. - - .. attribute:: total_needed - - The total amount of bytes needed (including those of files which are - already present) - - .. attribute:: fetch_needed - - The total amount of bytes which need to be fetched. - - .. attribute:: partial_present - - Whether some files have been acquired already. (???) - -.. class:: AcquireItem - - The :class:`AcquireItem()` objects represent the items of a - :class:`Acquire` object. :class:`AcquireItem()` objects can not be created - by the user, they are solely available through the :attr:`Acquire.items` - list of an :class:`Acquire` object. - - .. attribute:: id - - The ID of the item. - - .. attribute:: complete - - Is the item completely acquired? - - .. attribute:: local - - Is the item a local file? - - .. attribute:: is_trusted - - Can the file be trusted? - - .. attribute:: file_size - - The size of the file, in bytes. - - .. attribute:: error_text - - The error message. For example, when a file does not exist on a http - server, this will contain a 404 error message. - - .. attribute:: dest_file - - The location the file is saved as. - - .. attribute:: desc_uri - - The source location. - - **Status**: - - .. attribute:: status - - Integer, representing the status of the item. - - .. attribute:: stat_idle - - Constant for comparing :attr:`AcquireItem.status`. - - .. attribute:: stat_fetching - - Constant for comparing :attr:`AcquireItem.status` - - .. attribute:: stat_done - - Constant for comparing :attr:`AcquireItem.status` - - .. attribute:: stat_error - - Constant for comparing :attr:`AcquireItem.status` - - .. attribute:: stat_auth_error - - Constant for comparing :attr:`AcquireItem.status` - - -.. class:: AcquireFile(owner, uri[, md5, size, descr, short_descr, destdir, destfile]) - - Create a new :class:`AcquireFile()` object and register it with *acquire*, - so it will be fetched. AcquireFile objects provide no methods or attributes - and are completely useless at the moment. - - The parameter *owner* refers to an :class:`Acquire()` object as returned - by :func:`GetAcquire`. The file will be added to the Acquire queue - automatically. - - The parameter *uri* refers to the location of the file, any protocol - of apt is supported. - - The parameter *md5* refers to the md5sum of the file. This can be used - for checking the file. - - The parameter *size* can be used to specify the size of the package, - which can then be used to calculate the progress and validate the download. - - The parameter *descr* is a descripition of the download. It may be - used to describe the item in the progress class. *short_descr* is the - short form of it. - - You can use *destdir* to manipulate the directory where the file will - be saved in. Instead of *destdir*, you can also specify the full path to - the file using the parameter *destfile*. You can not combine both. - - -Hashes ------- -The apt_pkg module also provides several hash functions. If you develop -applications with python-apt it is often easier to use these functions instead -of the ones provides in Python's :mod:`hashlib` module. - -.. class:: Hashes(object) - - Calculate all supported hashes of the object. *object* may either be a - string, in which cases the hashes of the string are calculated, or a - :class:`file()` object or file descriptor, in which case the hashes of - its contents is calculated. The calculated hashes are then available via - attributes: - - .. attribute:: md5 - - The MD5 hash of the data, as string. - - .. attribute:: sha1 - - The SHA1 hash of the data, as string. - - .. attribute:: sha256 - - The SHA256 hash of the data, as string. - -.. function:: md5sum(object) - - Return the md5sum of the object. *object* may either be a string, in - which case the md5sum of the string is returned, or a :class:`file()` - object (or a file descriptor), in which case the md5sum of its contents is - returned. - - .. versionchanged:: 0.8.0 - Added support for using file descriptors. - -.. function:: sha1sum(object) - - Return the sha1sum of the object. *object* may either be a string, in - which case the sha1sum of the string is returned, or a :class:`file()` - object (or a file descriptor), in which case the sha1sum of its contents - is returned. - - .. versionchanged:: 0.8.0 - Added support for using file descriptors. - -.. function:: sha256sum(object) - - Return the sha256sum of the object. *object* may either be a string, in - which case the sha256sum of the string is returned, or a :class:`file()` - object (or a file descriptor), in which case the sha256sum of its contents - is returned. - - .. versionchanged:: 0.8.0 - Added support for using file descriptors. - -Debian control files --------------------- -Debian control files are files containing multiple stanzas of :RFC:`822`-style -header sections. They are widely used in the Debian community, and can represent -many kinds of information. One example for such a file is the -:file:`/var/lib/dpkg/status` file which contains a list of the currently -installed packages. - -The :mod:`apt_pkg` module provides two classes to read those files and parts -thereof and provides a function :func:`RewriteSection` which takes a -:class:`TagSection()` object and sorting information and outputs a sorted -section as a string. - -.. class:: TagFile(file) - - An object which represents a typical debian control file. Can be used for - Packages, Sources, control, Release, etc. - - An example for working with a TagFile could look like:: - - tagf = apt_pkg.TagFile(open('/var/lib/dpkg/status')) - tagf.step() - print tagf.section['Package'] - - .. method:: step - - Step forward to the next section. This simply returns ``1`` if OK, and - ``0`` if there is no section - - .. method:: offset - - Return the current offset (in bytes) from the beginning of the file. - - .. method:: jump(offset) - - Jump back/forward to *offset*. Use ``jump(0)`` to jump to the - beginning of the file again. - - .. attribute:: section - - This is the current :class:`TagSection()` instance. - -.. class:: TagSection(text) - - Represent a single section of a debian control file. - - .. describe:: section[key] - - Return the value of the field at *key*. If *key* is not available, - raise :exc:`KeyError`. - - .. describe:: key in section - - Return ``True`` if *section* has a key *key*, else ``False``. - - .. versionadded:: 0.8.0 - - .. method:: bytes - - The number of bytes in the section. - - .. method:: find(key, default='') - - Return the value of the field at the key *key* if available, - else return *default*. - - .. method:: find_flag(key) - - Find a yes/no value for the key *key*. An example for such a - field is 'Essential'. - - .. method:: get(key, default='') - - Return the value of the field at the key *key* if available, else - return *default*. - - .. method:: has_key(key) - - Check whether the field with named by *key* exists. - - .. deprecated:: 0.8.0 - - .. method:: keys() - - Return a list of keys in the section. - -.. autofunction:: rewrite_section(section, order, rewrite_list) - -.. data:: REWRITE_PACKAGE_ORDER - - The order in which the information for binary packages should be rewritten, - i.e. the order in which the fields should appear. - -.. data:: REWRITE_SOURCE_ORDER - - The order in which the information for source packages should be rewritten, - i.e. the order in which the fields should appear. - -Dependencies ------------- -.. function:: check_dep(pkgver, op, depver) - - Check that the dependency requirements consisting of op and depver can be - satisfied by the version pkgver. - - Example:: - - >>> bool(apt_pkg.check_dep("1.0", ">=", "1")) - True - -.. function:: parse_depends(depends) - - Parse the string *depends* which contains dependency information as - specified in Debian Policy, Section 7.1. - - Returns a list. The members of this list are lists themselves and contain - one or more tuples in the format ``(package,version,operation)`` for every - 'or'-option given, e.g.:: - - >>> apt_pkg.parse_depends("PkgA (>= VerA) | PkgB (>= VerB)") - [[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]] - - - .. note:: - - The behavior of this function is different than the behavior of the - old function :func:`ParseDepends()`, because the third field - ``operation`` uses `>` instead of `>>` and `<` instead of `<<` which - is specified in control files. - - -.. function:: parse_src_depends(depends) - - Parse the string *depends* which contains dependency information as - specified in Debian Policy, Section 7.1. - - Returns a list. The members of this list are lists themselves and contain - one or more tuples in the format ``(package,version,operation)`` for every - 'or'-option given, e.g.:: - - >>> apt_pkg.parse_depends("PkgA (>= VerA) | PkgB (>= VerB)") - [[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]] - - - Furthemore, this function also supports to limit the architectures, as - used in e.g. Build-Depends:: - - >>> apt_pkg.parse_src_depends("a (>= 01) [i386 amd64]") - [[('a', '01', '>=')]] - - .. note:: - - The behavior of this function is different than the behavior of the - old function :func:`ParseDepends()`, because the third field - ``operation`` uses `>` instead of `>>` and `<` instead of `<<` which - is specified in control files. - - -Configuration -------------- - -.. class:: Configuration() - - Configuration() objects store the configuration of apt, mostly created from - the contents of :file:`/etc/apt.conf` and the files in - :file:`/etc/apt.conf.d`. - - .. describe:: key in conf - - Return ``True`` if *conf* has a key *key*, else ``False``. - - .. versionadded:: 0.8.0 - - .. describe:: conf[key] - - Return the value of the option given key *key*. If it does not - exist, raise :exc:`KeyError`. - - .. describe:: conf[key] = value - - Set the option at *key* to *value*. - - .. method:: find(key[, default='']) - - Return the value for the given key *key*. This is the same as - :meth:`Configuration.get`. - - If *key* does not exist, return *default*. - - .. method:: find_file(key[, default='']) - - Return the filename hold by the configuration at *key*. This formats the - filename correctly and supports the Dir:: stuff in the configuration. - - If *key* does not exist, return *default*. - - .. method:: find_dir(key[, default='/']) - - Return the absolute path to the directory specified in *key*. A - trailing slash is appended. - - If *key* does not exist, return *default*. - - .. method:: find_i(key[, default=0]) - - Return the integer value stored at *key*. - - If *key* does not exist, return *default*. - - .. method:: find_b(key[, default=0]) - - Return the boolean value stored at *key*. This returns an integer, but - it should be treated like True/False. - - If *key* does not exist, return *default*. - - .. method:: set(key, value) - - Set the value of *key* to *value*. - - .. method:: exists(key) - - Check whether the key *key* exists in the configuration. - - .. method:: subtree(key) - - Return a sub tree starting at *key*. The resulting object can be used - like this one. - - .. method:: list([key]) - - List all items at *key*. Normally, return the keys at the top level, - eg. APT, Dir, etc. - - Use *key* to specify a key of which the childs will be returned. - - .. method:: value_list([key]) - - Same as :meth:`Configuration.list`, but this time for the values. - - .. method:: my_tag() - - Return the tag name of the current tree. Normally this is an empty - string, but for subtrees it is the key of the subtree. - - .. method:: clear(key) - - Clear the configuration. Remove all values and keys at *key*. - - .. method:: keys([key]) - - Return all the keys, recursive. If *key* is specified, ... (FIXME) - - .. method:: has_key(key) - - Return whether the configuration contains the key *key*. - - .. deprecated:: 0.8.0 - - .. method:: get(key[, default='']) - - This behaves just like :meth:`dict.get` and :meth:`Configuration.find`, - it returns the value of key or if it does not exist, *default*. - -.. class:: ConfigurationPtr - - Behaves like a :class:`Configuration()` objects, but uses a pointer to the - underlying C++ object. This is used for the default configuration in the - :data:`Config` attribute of the module. - -.. class:: ConfigurationSub - - Behaves like a :class:`Configuration()` objects, but provides access to - a subsection of another Configuration-like object. This type of object is - returned by the :meth:`Configuration.subtree()` method. - -.. data:: config - - A :class:`ConfigurationPtr()` object with the default configuration. This - object is initialized by calling :func:`init_config`. - - -Modifying -^^^^^^^^^ - - -.. function:: read_config_file(configuration, filename) - - Read the configuration file specified by the parameter *filename* and add - the settings therein to the :class:`Configuration()` object specified by - the parameter *configuration* - -.. function:: read_config_dir(configuration, dirname) - - Read configuration files in the directory specified by the parameter - *dirname* and add the settings therein to the :class:`Configuration()` - object specified by the parameter *configuration*. - -.. function:: read_config_file_isc(configuration, filename) - - Read the configuration file specified by the parameter *filename* and add - the settings therein to the :class:`Configuration()` object specified by - the parameter *configuration* - -.. function:: parse_commandline(configuration, options, argv) - - This function is like getopt except it manipulates a configuration space. - output is a list of non-option arguments (filenames, etc). *options* is a - list of tuples of the form ``(‘c’,”long-opt or None”, - ”Configuration::Variable”,”optional type”)``. - - Where ``type`` may be one of HasArg, IntLevel, Boolean, InvBoolean, - ConfigFile, or ArbItem. The default is Boolean. - -Locking --------- - -.. function:: get_lock(filename) - - Create an empty file at the path specified by the parameter *filename* and - lock it. - - While the file is locked by a process, calling this function in another - process returns ``-1``. - - When the lock is not required anymore, the file descriptor should be closed - using :func:`os.close`. - -.. function:: pkg_system_lock() - - Lock the global pkgsystem. - -.. function:: pkg_system_un_lock() - - Unlock the global pkgsystem. - -Other classes --------------- -.. class:: Cdrom() - - Return a Cdrom object with the following methods: - - .. method:: ident(progress) - - Identify the cdrom. The parameter *progress* refers to an - :class:`apt.progress.CdromProgress()` object. - - .. method:: add(progress) - - Add the cdrom to the sources.list file. The parameter *progress* - refers to an :class:`apt.progress.CdromProgress()` object. - -.. class:: SourceList - - This is for :file:`/etc/apt/sources.list`. - - .. method:: find_index(pkgfile) - - Return a :class:`PackageIndexFile` object for the :class:`PackageFile` - *pkgfile*. - - .. method:: read_main_list - - Read the main list. - - .. method:: get_indexes(acq[, all]) - - Add the index files to the :class:`Acquire()` object *acq*. If *all* is - given and ``True``, all files are fetched. - -String functions ----------------- -.. function:: base64_encode(string) - - Encode the given string using base64, e.g:: - - >>> apt_pkg.base64_encode(u"A") - 'QQ==' - - -.. function:: check_domain_list(host, list) - - See if Host is in a ',' seperated list, e.g.:: - - apt_pkg.check_domain_list("alioth.debian.org","debian.net,debian.org") - -.. function:: dequote_string(string) - - Dequote the string specified by the parameter *string*, e.g.:: - - >>> apt_pkg.dequote_string("%61%70%74%20is%20cool") - 'apt is cool' - -.. function:: quote_string(string, repl) - - For every character listed in the string *repl*, replace all occurences in - the string *string* with the correct HTTP encoded value: - - >>> apt_pkg.quote_string("apt is cool","apt") - '%61%70%74%20is%20cool' - -.. function:: size_to_str(size) - - Return a string presenting the human-readable version of the integer - *size*. When calculating the units (k,M,G,etc.) the size is divided by the - factor 1000. - - Example:: - - >>> apt_pkg.size_to_str(10000) - '10.0k' - -.. function:: string_to_bool(input) - - Parse the string *input* and return one of **-1**, **0**, **1**. - - .. table:: Return values - - ===== ============================================= - Value Meaning - ===== ============================================= - -1 The string *input* is not recognized. - 0 The string *input* evaluates to **False**. - +1 The string *input* evaluates to **True**. - ===== ============================================= - - Example:: - - >>> apt_pkg.string_to_bool("yes") - 1 - >>> apt_pkg.string_to_bool("no") - 0 - >>> apt_pkg.string_to_bool("not-recognized") - -1 - -.. function:: str_to_time(rfc_time) - - Convert the :rfc:`1123` conforming string *rfc_time* to the unix time, and - return the integer. This is the opposite of :func:`TimeRFC1123`. - - Example:: - - >> apt_pkg.str_to_time('Thu, 01 Jan 1970 00:00:00 GMT') - 0 - -.. function:: time_rfc1123(seconds) - - Format the unix time specified by the integer *seconds*, according to the - requirements of :rfc:`1123`. - - Example:: - - >>> apt_pkg.time_rfc1123(0) - 'Thu, 01 Jan 1970 00:00:00 GMT' - - -.. function:: time_to_str(seconds) - - Format a given duration in a human-readable manner. The parameter *seconds* - refers to a number of seconds, given as an integer. The return value is a - string with a unit like 's' for seconds. - - Example:: - - >>> apt_pkg.time_to_str(3601) - '1h0min1s' - -.. function:: upstream_version(version) - - Return the string *version*, eliminating everything following the last - '-'. Thus, this should be equivalent to ``version.rsplit('-', 1)[0]``. - -.. function:: uri_to_filename(uri) - - Take a string *uri* as parameter and return a filename which can be used to - store the file, based on the URI. - - Example:: - - >>> apt_pkg.uri_to_filename('http://debian.org/index.html') - 'debian.org_index.html' - - -.. function:: version_compare(a, b) - - Compare two versions, *a* and *b*, and return an integer value which has - the same characteristic as the built-in :func:`cmp` function. - - .. table:: Return values - - ===== ============================================= - Value Meaning - ===== ============================================= - > 0 The version *a* is greater than version *b*. - = 0 Both versions are equal. - < 0 The version *a* is less than version *b*. - ===== ============================================= - - - - -Module Constants ----------------- -.. _CurStates: - -Package States -^^^^^^^^^^^^^^^ -.. data:: CURSTATE_CONFIG_FILES -.. data:: CURSTATE_HALF_CONFIGURED -.. data:: CURSTATE_HALF_INSTALLED -.. data:: CURSTATE_INSTALLED -.. data:: CURSTATE_NOT_INSTALLED -.. data:: CURSTATE_UNPACKED - - - - -Dependency types -^^^^^^^^^^^^^^^^ -.. data:: DEP_CONFLICTS -.. data:: DEP_DEPENDS -.. data:: DEP_OBSOLETES -.. data:: DEP_PRE_DEPENDS -.. data:: DEP_RECOMMENDS -.. data:: DEP_REPLACES -.. data:: DEP_SUGGESTS - -.. _InstStates: - -Installed states -^^^^^^^^^^^^^^^^ -.. data:: INSTSTATE_HOLD -.. data:: INSTSTATE_HOLD_REINSTREQ -.. data:: INSTSTATE_OK -.. data:: INSTSTATE_REINSTREQ - -.. _Priorities: - -Priorities -^^^^^^^^^^^ -.. data:: PRI_EXTRA -.. data:: PRI_IMPORTANT -.. data:: PRI_OPTIONAL -.. data:: PRI_REQUIRED -.. data:: PRI_STANDARD - - -.. _SelStates: - -Select states -^^^^^^^^^^^^^ -.. data:: SELSTATE_DE_INSTALL -.. data:: SELSTATE_HOLD -.. data:: SELSTATE_INSTALL -.. data:: SELSTATE_PURGE -.. data:: SELSTATE_UNKNOWN - - -Build information -^^^^^^^^^^^^^^^^^ -.. data:: DATE - - The date on which this extension has been compiled. - -.. data:: LIB_VERSION - - The version of the apt_pkg library. This is **not** the version of apt, - nor the version of python-apt. - -.. data:: TIME - - The time this extension has been built. - -.. data:: VERSION - - The version of apt (not of python-apt). - -.. data:: _COMPAT_0_7 - - A more or less internal variable defining whether this build provides an - API which is compatible to the one of python-apt 0.7. This is used in the - apt and aptsources packages to decide whether compatibility should be - enabled or not. diff --git a/doc/source/aptsources/distinfo.rst b/doc/source/aptsources/distinfo.rst deleted file mode 100644 index 96f9445d..00000000 --- a/doc/source/aptsources/distinfo.rst +++ /dev/null @@ -1,10 +0,0 @@ -:mod:`aptsources.distinfo` --- provide meta information for distro repositories -=============================================================================== - -.. automodule:: aptsources.distinfo - :members: - :undoc-members: - - .. note:: - - This part of the documentation is created automatically. diff --git a/doc/source/aptsources/distro.rst b/doc/source/aptsources/distro.rst deleted file mode 100644 index 06ca0fda..00000000 --- a/doc/source/aptsources/distro.rst +++ /dev/null @@ -1,10 +0,0 @@ -:mod:`aptsources.distro` --- Distribution abstraction of the sources.list -=============================================================================== - -.. automodule:: aptsources.distro - :members: - :undoc-members: - - .. note:: - - This part of the documentation is created automatically. diff --git a/doc/source/aptsources/index.rst b/doc/source/aptsources/index.rst deleted file mode 100644 index 898fbf74..00000000 --- a/doc/source/aptsources/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -:mod:`aptsources` --- Working with sources.list -===================================================== -.. automodule:: aptsources - -.. toctree:: - :maxdepth: 2 - :glob: - - * - diff --git a/doc/source/aptsources/sourceslist.rst b/doc/source/aptsources/sourceslist.rst deleted file mode 100644 index 509db3ce..00000000 --- a/doc/source/aptsources/sourceslist.rst +++ /dev/null @@ -1,10 +0,0 @@ -:mod:`aptsources.sourceslist` --- Provide an abstraction of the sources.list -============================================================================ - -.. automodule:: aptsources.sourceslist - :members: - :undoc-members: - - .. note:: - - This part of the documentation is created automatically. diff --git a/doc/source/conf.py b/doc/source/conf.py index 86e6868c..0a9d5ed5 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -54,7 +54,7 @@ extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', intersphinx_mapping = {'http://docs.python.org/': None} # Add any paths that contain templates here, relative to this directory. -templates_path = ['.templates'] +templates_path = ['templates'] # The suffix of source filenames. source_suffix = '.rst' @@ -63,7 +63,7 @@ source_suffix = '.rst' #source_encoding = 'utf-8' # The master toctree document. -master_doc = 'index' +#master_doc = 'contents' # General information about the project. project = u'python-apt' @@ -77,12 +77,21 @@ copyright = u'2009, Julian Andres Klode ' try: release=os.environ['DEBVER'] except KeyError: - from debian_bundle.changelog import Changelog - changes = Changelog(open('../../debian/changelog')) - # The full version, including alpha/beta/rc tags. - release = changes.full_version - -version = '.'.join(release.split('.')[:3]) + from subprocess import Popen, PIPE + p1 = Popen(["dpkg-parsechangelog", "-l../../debian/changelog"], + stdout=PIPE) + p2 = Popen(["sed", "-n", 's/^Version: //p'], stdin=p1.stdout, stdout=PIPE) + release = p2.communicate()[0] + +# Handle the alpha release scheme. +if int(release.split("~")[0].split(".")[2]) >= 90: + version_s = release.split("~")[0].split(".")[:3] + version_s[1] = str(int(version_s[1]) + 1) + version_s[2] = "0" + version = '.'.join(version_s) + del version_s +else: + version = '.'.join(release.split("~")[0].split('.')[:3]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -150,7 +159,7 @@ html_static_path = ['.static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' +html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. @@ -161,7 +170,7 @@ html_static_path = ['.static'] # Additional templates that should be rendered to pages, maps page names to # template names. -#html_additional_pages = {} +html_additional_pages = {"index": "indexcontent.html"} # If false, no module index is generated. #html_use_modindex = True @@ -199,7 +208,7 @@ htmlhelp_basename = 'python-aptdoc' # Grouping the document tree into LaTeX files. List of tuples # (source index, target name, title, author, document class [howto/manual]). latex_documents = [ - ('index', 'python-apt.tex', ur'python-apt Documentation', + ('contents', 'python-apt.tex', ur'python-apt Documentation', ur'Julian Andres Klode ', 'manual'), ] diff --git a/doc/source/contents.rst b/doc/source/contents.rst new file mode 100644 index 00000000..3c9fb511 --- /dev/null +++ b/doc/source/contents.rst @@ -0,0 +1,20 @@ +Python APT Documentation contents +====================================== + +Contents: + +.. toctree:: + + whatsnew/index + library/index + tutorials/index + c++/index + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst deleted file mode 100644 index 7c6b6e6d..00000000 --- a/doc/source/contributing.rst +++ /dev/null @@ -1,308 +0,0 @@ -Contributing to python-apt -========================== -Let's say you need a new feature, you can develop it, and you want to get it -included in python-apt. Then be sure to follow the following guidelines. - -Available branches -------------------- -First of all, let's talk a bit about the bzr branches of python-apt. In the -following parts, we will assume that you use bzr to create your changes and -submit them. - -**mvo:** http://people.ubuntu.com/~mvo/bzr/python-apt/mvo - This is Michael Vogt's branch. Most of the development of apt happens here, - as he is the lead maintainer of python-apt. - - This branch is also available from Launchpads super mirror, via - ``lp:python-apt``. Checkouts from Launchpad are generally faster and can - use the bzr protocoll. - - VCS-Browser: https://code.launchpad.net/~mvo/python-apt/python-apt--mvo - -**debian-sid:** http://bzr.debian.org/apt/python-apt/debian-sid - This is the official Debian branch of python-apt. All code which will be - uploaded to Debian is here. It is not as up-to-date as the mvo branch, - because this branch often gets updated just right before the release - happens. - - VCS-Browser: http://bzr.debian.org/loggerhead/apt/python-apt/debian-sid/changes - -**debian-experimental:** http://bzr.debian.org/apt/python-apt/debian-experimental - - This is another official Debian branch of python-apt, for releases - targetted at Debian experimental. This branch may contain unstable code - and may thus not work correctly. - - VCS-Browser: http://bzr.debian.org/loggerhead/apt/python-apt/debian-experimental/changes - -**jak:** http://bzr.debian.org/users/jak/python-apt/jak - This is Julian Andres Klode's (the documentation author's) branch. This - is the place where cleanup and documentation updates happen. It is based - off debian-sid or mvo. - - VCS-Browser: http://bzr.debian.org/loggerhead/users/jak/python-apt/jak/changes - -**ubuntu:** ``lp:~ubuntu-core-dev/python-apt/ubuntu`` - This is the official Ubuntu development branch. The same notes apply as - for the debian-sid branch above. - - VCS-Browser: https://code.launchpad.net/~ubuntu-core-dev/python-apt/ubuntu - - -.. highlightlang:: c - -C++ Coding style ----------------- -This document gives coding conventions for the C++ code comprising -the C++ extensions of Python APT. Please see the companion -informational PEP describing style guidelines for Python code (:PEP:`8`). - -Note, rules are there to be broken. Two good reasons to break a -particular rule: - - (1) When applying the rule would make the code less readable, even - for someone who is used to reading code that follows the rules. - - (2) To be consistent with surrounding code that also breaks it - (maybe for historic reasons) -- although this is also an - opportunity to clean up someone else's mess (in true XP style). - -This part of the document is derived from :PEP:`7` which was written by -Guido van Rossum. - - -C++ dialect -^^^^^^^^^^^ - -- Use ISO standard C++ (the 1998 version of the standard). - -- All function declarations and definitions must use full - prototypes (i.e. specify the types of all arguments). - -- Use C++ style // one-line comments where useful. - -- No compiler warnings with ``gcc -std=c++98 -Wall -Wno-write-strings``. There - should also be no errors with ``-pedantic`` added. - - -Code lay-out -^^^^^^^^^^^^ - -- Use 3-space indents, in files that already use them. In new source files, - that were created after this rule was introduced, use 4-space indents. - - At some point, the whole codebase may be converted to use only - 4-space indents. - -- No line should be longer than 79 characters. If this and the - previous rule together don't give you enough room to code, your - code is too complicated -- consider using subroutines. - -- No line should end in whitespace. If you think you need - significant trailing whitespace, think again -- somebody's - editor might delete it as a matter of routine. - -- Function definition style: function name in column 2, outermost - curly braces in column 1, blank line after local variable - declarations:: - - static int extra_ivars(PyTypeObject *type, PyTypeObject *base) - { - int t_size = PyType_BASICSIZE(type); - int b_size = PyType_BASICSIZE(base); - - assert(t_size >= b_size); /* type smaller than base! */ - ... - return 1; - } - -- Code structure: one space between keywords like 'if', 'for' and - the following left paren; no spaces inside the paren; braces as - shown:: - - if (mro != NULL) { - ... - } - else { - ... - } - -- The return statement should *not* get redundant parentheses:: - - return Py_None; /* correct */ - return(Py_None); /* incorrect */ - -- Function and macro call style: ``foo(a, b, c)`` -- no space before - the open paren, no spaces inside the parens, no spaces before - commas, one space after each comma. - -- Always put spaces around assignment, Boolean and comparison - operators. In expressions using a lot of operators, add spaces - around the outermost (lowest-priority) operators. - -- Breaking long lines: if you can, break after commas in the - outermost argument list. Always indent continuation lines - appropriately, e.g.:: - - PyErr_Format(PyExc_TypeError, - "cannot create '%.100s' instances", - type->tp_name); - -- When you break a long expression at a binary operator, the - operator goes at the end of the previous line, e.g.:: - - if (type->tp_dictoffset != 0 && base->tp_dictoffset == 0 && - type->tp_dictoffset == b_size && - (size_t)t_size == b_size + sizeof(PyObject *)) - return 0; /* "Forgive" adding a __dict__ only */ - -- Put blank lines around functions, structure definitions, and - major sections inside functions. - -- Comments go before the code they describe. - -- All functions and global variables should be declared static - unless they are to be part of a published interface - - -Naming conventions -^^^^^^^^^^^^^^^^^^ - -- Use a ``Py`` prefix for public functions; never for static - functions. The ``Py_`` prefix is reserved for global service - routines like ``Py_FatalError``; specific groups of routines - (e.g. specific object type APIs) use a longer prefix, - e.g. ``PyString_`` for string functions. - -- Public functions and variables use MixedCase with underscores, - like this: ``PyObject_GetAttr``, ``Py_BuildValue``, ``PyExc_TypeError``. - -- Internal functions and variables use lowercase with underscores, like - this: ``hashes_get_sha1.`` - -- Occasionally an "internal" function has to be visible to the - loader; we use the _Py prefix for this, e.g.: ``_PyObject_Dump``. - -- Macros should have a MixedCase prefix and then use upper case, - for example: ``PyString_AS_STRING``, ``Py_PRINT_RAW``. - - -Documentation Strings -^^^^^^^^^^^^^^^^^^^^^ -- The first line of each function docstring should be a "signature - line" that gives a brief synopsis of the arguments and return - value. For example:: - - PyDoc_STRVAR(myfunction__doc__, - "myfunction(name: str, value) -> bool\n\n" - "Determine whether name and value make a valid pair."); - - The signature line should be formatted using the format for function - annotations described in :PEP:`3107`, whereas the annotations shall reflect - the name of the type (e.g. ``str``). The leading ``def`` and the trailing - ``:`` as used for function definitions must not be included. - - Always include a blank line between the signature line and the - text of the description. - - If the return value for the function is always ``None`` (because - there is no meaningful return value), do not include the - indication of the return type. - -- When writing multi-line docstrings, be sure to always use - string literal concatenation:: - - PyDoc_STRVAR(myfunction__doc__, - "myfunction(name, value) -> bool\n\n" - "Determine whether name and value make a valid pair."); - - -Python Coding Style -------------------- -The coding style for all code written in python is :PEP:`8`. Exceptions from -this rule are the documentation, where code is sometimes formatted differently -to explain aspects, and functions provided for 0.7 compatibility purposes. - -When writing code, use tools like pylint, pyflakes, pychecker and pep8.py from -http://svn.browsershots.org/trunk/devtools/pep8/ to verify that your code is -OK. Fix all the problems which seem reasonable, and mention the unfixed issues -when asking for merge. - -In order to make the automatic generation of Python 3 code using 2to possible, -code written in Python may not utilize any functionality unsupported by 2to3 or -deprecated as of Python 2.6. - -Submitting your patch ---------------------- -First of all, the patch you create should be based against the most current -branch of python-apt (debian-sid or debian-experimental). If it is a bugfix, -you should probably use debian-sid. If you choose the wrong branch, we will -ask you to rebase your patches against the correct one. - -Once you have made your change, check that it: - - * conforms to :PEP:`8` (checked with pep8.py). It should, at least not - introduce new errors. (and never have whitespace at end of line) - * produces no new errors in pychecker, pyflakes and pylint (unless you - can't fix them, but please tell so when requesting the merge, so it can - be fixed before hitting one of the main branches). - * does not change the behaviour of existing code in a non-compatible way. - -If your change follows all points of the checklist, you can commit it to your -repository. (You could commit it first, and check later, and then commit the -fixes, but commits should be logical and it makes no sense to have to commits -for one logical unit). - -Once you have made all your changes, you can run ``bzr send -o patch-name`` -to create a so called *merge-directive*, which contains your changes and -allows us to preserve the history of your changes. (But please replace patch-name -with something useful). - -Now report a bug against the python-apt package, attach the merge directive -you created in the previous step, and tag it with 'patch'. It might also be -a good idea to prefix the bug report with '[PATCH]'. - -If your patch introduces new functions, parameters, etc. , but does not update -the content of this documentation, please CC. jak@debian.org, and add a short -notice to the bug report. Also see `Documentation updates` - -Once your patch got merged, you can *pull* the branch into which it has been -merged into your local one. If you have made changes since you submitted your -patch, you may need to *merge* the branch instead. - -.. note:: - - If you plan to work on python-apt for a longer time, it may be a good - idea to publish your branch somewhere. Alioth (http://alioth.debian.org) - and Launchpad (https://launchpad.net) provide bzr hosting. You can also - use any webspace with ftp or sftp connection (for the upload). Then you do - not need to send *merge directives*, but you can point to your branch - instead. - - -Documentation updates ---------------------- -If you want to update the documentation, please follow the procedure as written -above. You can send your content in plain text, but reStructuredText is the -preferred format. I (Julian Andres Klode) will review your patch and include -it. - -.. highlightlang:: sh - -Example patch session ----------------------- -In the following example, we edit a file, create a merge directive (an enhanced -patch), and report a wishlist bug with this patch against the python-apt -package:: - - user@pc:~$ bzr clone http://bzr.debian.org/apt/python-apt/debian-sid/ - user@pc:~$ cd debian-sid - user@pc:~/debian-sid$ editor FILES - user@pc:~/debian-sid$ pep8.py FILES # PEP 8 check, see above. - user@pc:~/debian-sid$ pylint -e FILES # Check with pylint - user@pc:~/debian-sid$ pyflakes FILES # Check with pyflakes - user@pc:~/debian-sid$ pychecker FILES # Check with pychecker - user@pc:~/debian-sid$ bzr commit - user@pc:~/debian-sid$ bzr send -o my-patch - user@pc:~/debian-sid$ reportbug --severity=wishlist --tag=patch --attach=my-patch python-apt - user@pc:~/debian-sid$ # Add --list-cc=jak@debian.org if you change docs. diff --git a/doc/source/examples/apt-cdrom.py b/doc/source/examples/apt-cdrom.py new file mode 100644 index 00000000..a20b0f12 --- /dev/null +++ b/doc/source/examples/apt-cdrom.py @@ -0,0 +1,70 @@ +#!/usr/bin/python +import sys + +import apt_pkg +import apt + + +def show_help(): + print ("apt %s compiled on %s %s" % (apt_pkg.VERSION, + apt_pkg.DATE, apt_pkg.TIME)) + if apt_pkg.config.find_b("version"): + return 0 + + # Copied from apt-cdrom + print ("Usage: apt-cdrom [options] command\n" + "\n" + "apt-cdrom is a tool to add CDROM's to APT's source list. The\n" + "CDROM mount point and device information is taken from apt.conf\n" + "and /etc/fstab.\n" + "\n" + "Commands:\n" + " add - Add a CDROM\n" + " ident - Report the identity of a CDROM\n" + "\n" + "Options:\n" + " -h This help text\n" + " -d CD-ROM mount point\n" + " -r Rename a recognized CD-ROM\n" + " -m No mounting\n" + " -f Fast mode, don't check package files\n" + " -a Thorough scan mode\n" + " -c=? Read this configuration file\n" + " -o=? Set an arbitrary configuration option, eg -o dir::cache=/tmp\n" + "See fstab(5)") + return 0 + + +def main(args): + arguments = apt_pkg.parse_commandline(apt_pkg.config, + [('h', "help", "help"), + ('v', "version", "version"), + ('d', "cdrom", "Acquire::cdrom::mount", "HasArg"), + ('r', "rename", "APT::CDROM::Rename"), + ('m', "no-mount", "APT::CDROM::NoMount"), + ('f', "fast", "APT::CDROM::Fast"), + ('n', "just-print", "APT::CDROM::NoAct"), + ('n', "recon", "APT::CDROM::NoAct"), + ('n', "no-act", "APT::CDROM::NoAct"), + ('a', "thorough", "APT::CDROM::Thorough"), + ('c', "config-file", "", "ConfigFile"), + ('o', "option", "", "ArbItem")], args) + + if apt_pkg.config.find_b("help") or apt_pkg.config.find_b("version"): + return show_help() + + progress = apt.progress.text.CdromProgress() + cdrom = apt_pkg.Cdrom() + + if not arguments: + return show_help() + elif arguments[0] == 'add': + cdrom.add(progress) + elif arguments[0] == 'ident': + cdrom.ident(progress) + else: + sys.stderr.write('E: Invalid operation %s\n' % arguments[0]) + return 1 + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/doc/source/index.rst b/doc/source/index.rst deleted file mode 100644 index 2e05061a..00000000 --- a/doc/source/index.rst +++ /dev/null @@ -1,41 +0,0 @@ -Welcome to python-apt's documentation! -====================================== - -This is the official documentation for version |version| of the Python bindings -for Debian's famous APT package management. - -This documentation has been created by Sphinx, using reStructuredText files -written by Julian Andres Klode , and in case of the apt -package, from the documentation shipped in the modules. - - -Contents: - -.. toctree:: - :hidden: - - whatsnew/index - -.. toctree:: - :maxdepth: 2 - - whatsnew/0.8.0 - apt/index - apt_pkg - apt_inst - aptsources/index - contributing - - - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` - - -TODO -====== -.. todolist:: diff --git a/doc/source/library/apt.cache.rst b/doc/source/library/apt.cache.rst new file mode 100644 index 00000000..ddb2dc64 --- /dev/null +++ b/doc/source/library/apt.cache.rst @@ -0,0 +1,78 @@ +:mod:`apt.cache` --- The Cache class +===================================== +.. automodule:: apt.cache + +The Cache class +--------------- + +.. autoclass:: Cache + :members: + :undoc-members: + + .. describe:: cache[pkgname] + + Return a :class:`Package()` for the package with the name *pkgname*. + +Example +^^^^^^^ + +The following example shows how to load the cache, update it, and upgrade +all the packages on the system:: + + import apt + import apt.progress + + # First of all, open the cache + cache = apt.Cache() + # Now, lets update the package list + cache.update() + # We need to re-open the cache because it needs to read the package list + cache.open(None) + # Now we can do the same as 'apt-get upgrade' does + cache.upgrade() + # or we can play 'apt-get dist-upgrade' + cache.upgrade(True) + # Q: Why does nothing happen? + # A: You forgot to call commit()! + cache.commit(apt.progress.TextFetchProgress(), + apt.progress.InstallProgress()) + + + +Working with Filters +-------------------- +.. autoclass:: Filter + :members: + :inherited-members: + :undoc-members: + +.. autoclass:: MarkedChangesFilter + :members: + :inherited-members: + :undoc-members: + +.. autoclass:: FilteredCache + :members: + :inherited-members: + :undoc-members: + + +Example +^^^^^^^ + +This is an example for a filtered cache, which only allows access to the +packages whose state has been changed, eg. packages marked for installation:: + + >>> from apt.cache import FilteredCache, Cache, MarkedChangesFilter + >>> cache = apt.Cache() + >>> changed = apt.FilteredCache(cache) + >>> changed.set_filter(MarkedChangesFilter()) + >>> print len(changed) == len(cache.get_changes()) # Both need to have same length + True + + +Exceptions +---------- +.. autoexception:: FetchCancelledException +.. autoexception:: FetchFailedException +.. autoexception:: LockFailedException diff --git a/doc/source/library/apt.cdrom.rst b/doc/source/library/apt.cdrom.rst new file mode 100644 index 00000000..56381f14 --- /dev/null +++ b/doc/source/library/apt.cdrom.rst @@ -0,0 +1,7 @@ +:mod:`apt.cdrom` - Functionality like in apt-cdrom +==================================================== +.. automodule:: apt.cdrom + :members: + + + diff --git a/doc/source/library/apt.debfile.rst b/doc/source/library/apt.debfile.rst new file mode 100644 index 00000000..7133b5a8 --- /dev/null +++ b/doc/source/library/apt.debfile.rst @@ -0,0 +1,39 @@ +:mod:`apt.debfile` --- Classes related to debian package files +============================================================== +The :mod:`apt.debfile` provides classes to work with locally available +debian packages, or source packages. + +.. module:: apt.debfile + +Binary packages +---------------- +.. autoclass:: DebPackage + :members: + :inherited-members: + :undoc-members: + + The :class:`DebPackage` class is a class for working with '.deb' files, + also known as Debian packages. + + It provides methods and attributes to get a list of the files in the + package, to install the package and much more. + + If you specify *cache* it has to point to an :class:`apt.cache.Cache()` + object. + + .. versionchanged:: 0.7.9 + Introduce all new methods (everything except for :meth:`open()` and + :attr:`filelist`) + + +Source packages +---------------- +.. autoclass:: DscSrcPackage + :members: + :inherited-members: + :undoc-members: + + Provide functionality to work with locally available source packages, + especially with their '.dsc' file. + + .. versionadded:: 0.7.9 diff --git a/doc/source/library/apt.package.rst b/doc/source/library/apt.package.rst new file mode 100644 index 00000000..4b143b8a --- /dev/null +++ b/doc/source/library/apt.package.rst @@ -0,0 +1,111 @@ +:mod:`apt.package` --- Classes for package handling +==================================================== + + +.. automodule:: apt.package + + +The Package class +----------------- +.. autoclass:: Package + :members: + + .. note:: + + Several methods have been deprecated in version 0.7.9 of python-apt, + please see the :class:`Version` class for the new alternatives. + +The Version class +----------------- +.. autoclass:: Version + :members: + + +Dependency Information +---------------------- +.. class:: BaseDependency + + The :class:`BaseDependency` class defines various attributes for accessing + the parts of a dependency. The attributes are as follows: + + .. attribute:: name + + The name of the dependency + + .. attribute:: relation + + The relation (>>,>=,==,<<,<=,) + + .. attribute:: version + + The version or None. + + .. attribute:: pre_depend + + Boolean value whether this is a pre-dependency. + +.. class:: Dependency + + The dependency class represents a Or-Group of dependencies. It provides + an attribute to access the :class:`BaseDependency` object for the available + choices. + + .. attribute:: or_dependencies + + A list of :class:`BaseDependency` objects which could satisfy the + requirement of the Or-Group. + + +Origin Information +------------------- +.. class:: Origin + + The :class:`Origin` class provides access to the origin of the package. + It allows you to check the component, archive, the hostname, and even if + this package can be trusted. + + .. attribute:: archive + + The archive (eg. unstable) + + .. attribute:: component + + The component (eg. main) + + .. attribute:: label + + The Label, as set in the Release file + + .. attribute:: origin + + The Origin, as set in the Release file + + .. attribute:: site + + The hostname of the site. + + .. attribute:: trusted + + Boolean value whether this is trustworthy. An origin can be trusted, if + it provides a GPG-signed Release file and the GPG-key used is in the + keyring used by apt (see apt-key). + +Examples +--------- +.. code-block:: python + + import apt + + cache = apt.Cache() + pkg = cache['python-apt'] # Access the Package object for python-apt + print 'python-apt is trusted:', pkg.candidate.origins[0].trusted + + # Mark python-apt for install + pkg.mark_install() + + print 'python-apt is marked for install:', pkg.marked_install + + print 'python-apt is (summary):', pkg.candidate.summary + + # Now, really install it + cache.commit() diff --git a/doc/source/library/apt.progress.gtk2.rst b/doc/source/library/apt.progress.gtk2.rst new file mode 100644 index 00000000..b16c903c --- /dev/null +++ b/doc/source/library/apt.progress.gtk2.rst @@ -0,0 +1,29 @@ +:mod:`apt.progress.gtk2` --- Progress reporting for GTK+ interfaces +=================================================================== +.. automodule:: apt.progress.gtk2 + + +GObject progress classes +------------------------- + +.. autoclass:: GDpkgInstallProgress + :members: + +.. autoclass:: GFetchProgress + :members: + +.. autoclass:: GInstallProgress + :members: + +.. autoclass:: GOpProgress + :members: + +GTK+ Class +---------- +.. autoclass:: GtkAptProgress + :members: + + +Example +------- +.. literalinclude:: ../examples/apt-gtk.py diff --git a/doc/source/library/apt.progress.qt4.rst b/doc/source/library/apt.progress.qt4.rst new file mode 100644 index 00000000..cd06a4e6 --- /dev/null +++ b/doc/source/library/apt.progress.qt4.rst @@ -0,0 +1,3 @@ +:mod:`apt.progress.qt4` --- Progress reporting for Qt4 interfaces +================================================================= +Not written yet. diff --git a/doc/source/library/apt.progress.text.rst b/doc/source/library/apt.progress.text.rst new file mode 100644 index 00000000..4e051e31 --- /dev/null +++ b/doc/source/library/apt.progress.text.rst @@ -0,0 +1,21 @@ +:mod:`apt.progress.text` --- Progress reporting for text interfaces +=================================================================== +.. automodule:: apt.progress.text + + +Acquire Progress Reporting +-------------------------- +.. autoclass:: AcquireProgress + :members: + + +CD-ROM Progress Reporting +-------------------------- +.. autoclass:: CdromProgress + :members: + +Operation Progress Reporting +----------------------------- +.. autoclass:: OpProgress + :members: + diff --git a/doc/source/library/apt_inst.rst b/doc/source/library/apt_inst.rst new file mode 100644 index 00000000..eef3db9f --- /dev/null +++ b/doc/source/library/apt_inst.rst @@ -0,0 +1,122 @@ +:mod:`apt_inst` - Working with local Debian packages +==================================================== +.. module:: apt_inst + +The :mod:`apt_inst` extension provides access to functions for working with +locally available Debian packages (.deb files) and tar files. + + +Checking packages +------------------ +.. function:: arCheckMember(file, membername) + + Check if the member specified by the parameter *membername* exists in + the AR file referenced by the parameter *file*, which may be a + :class:`file()` object, a file descriptor, or anything implementing a + :meth:`fileno` method. + + .. versionchanged:: 0.8.0 + Added support for file descriptors and objects implementing a :meth:`fileno` method. + + +Listing contents +----------------- +.. function:: debExtract(file, func, chunk) + + Call the function referenced by *func* for each member of the tar file + *chunk* which is contained in the AR file referenced by the parameter + *file*, which may be a :class:`file()` object, a file descriptor, or + anything implementing a :meth:`fileno` method. + + An example would be:: + + debExtract(open("package.deb"), my_callback, "data.tar.gz") + + See :ref:`emulating-dpkg-contents` for a more detailed example. + + .. versionchanged:: 0.8.0 + Added support for file descriptors and objects implementing a :meth:`fileno` method. + +.. function:: tarExtract(file,func,comp) + + Call the function *func* for each member of the tar file *file*. + + The parameter *comp* is a string determining the compressor used. Possible + options are "lzma", "bzip2" and "gzip". + + The parameter *file* may be a :class:`file()` object, a file descriptor, or + anything implementing a :meth:`fileno` method. + + .. versionchanged:: 0.8.0 + Added support for file descriptors and objects implementing a :meth:`fileno` method. + + +Callback +^^^^^^^^^ +Both of these functions expect a callback with the signature +``(what, name, link, mode, uid, gid, size, mtime, major, minor)``. + +The parameter *what* describes the type of the member. It can be 'FILE', +'DIR', or 'HARDLINK'. + +The parameter *name* refers to the name of the member. In case of links, +*link* refers to the target of the link. + + +Extracting contents +------------------- + +.. function:: debExtractArchive(file, rootdir) + + Extract the archive referenced by the :class:`file` object *file* + into the directory specified by *rootdir*. + + The parameter *file* may be a :class:`file()` object, a file descriptor, or + anything implementing a :meth:`fileno` method. + + See :ref:`emulating-dpkg-extract` for an example. + + .. warning:: + + If the directory given by *rootdir* does not exist, the package is + extracted into the current directory. + + .. versionchanged:: 0.8.0 + Added support for file descriptors and objects implementing a :meth:`fileno` method. + +.. function:: debExtractControl(file[, member='control']) + + Return the indicated file as a string from the control tar. The default + is 'control'. + + The parameter *file* may be a :class:`file()` object, a file descriptor, or + anything implementing a :meth:`fileno` method. + + If you want to print the control file of a given package, you could do + something like:: + + print debExtractControl(open("package.deb")) + + .. versionchanged:: 0.8.0 + Added support for file descriptors and objects implementing a :meth:`fileno` method. + + +.. _emulating-dpkg-extract: + +Example: Emulating :program:`dpkg` :option:`--extract` +------------------------------------------------------- +Here is a code snippet which emulates dpkg -x. It can be run as +:program:`tool` :option:`pkg.deb` :option:`outdir`. + +.. literalinclude:: ../examples/dpkg-extract.py + + +.. _emulating-dpkg-contents: + +Example: Emulating :program:`dpkg` :option:`--contents` +------------------------------------------------------- +.. literalinclude:: ../examples/dpkg-contents.py + +Example: Emulating :program:`dpkg` :option:`--info` +---------------------------------------------------- +.. literalinclude:: ../examples/dpkg-info.py diff --git a/doc/source/library/apt_pkg.rst b/doc/source/library/apt_pkg.rst new file mode 100644 index 00000000..6fccc207 --- /dev/null +++ b/doc/source/library/apt_pkg.rst @@ -0,0 +1,1795 @@ +:mod:`apt_pkg` --- The low-level bindings for apt-pkg +===================================================== +.. module:: apt_pkg + +The apt_pkg extensions provides a more low-level way to work with apt. It can +do everything apt can, and is written in C++. It has been in python-apt since +the beginning. + + +Module Initialization +--------------------- + +Initialization is needed for most functions, but not for all of them. Some can +be called without having run init*(), but will not return the expected value. + +.. function:: init_config + + Initialize the configuration of apt. This is needed for most operations. + +.. function:: init_system + + Initialize the system. + +.. function:: init + + Deprecated function. Use init_config() and init_system() instead. + +Working with the cache +---------------------- +.. class:: Cache([progress]) + + Return a :class:`Cache()` object. The optional parameter *progress* + specifies an instance of :class:`apt.progress.OpProgress()` which will + display the open progress. + + .. describe:: cache[pkgname] + + Return the :class:`Package()` object for the package name given by + *pkgname*. + + .. method:: close() + + Close the package cache. + + .. method:: open([progress]) + + Open the package cache again. The parameter *progress* may be set to + an :class:`apt.progress.OpProgress()` object or `None`. + + .. method:: update(progress, list) + + Update the package cache. + + The parameter *progress* points to an :class:`apt.progress.FetchProgress()` + object. The parameter *list* refers to a :class:`SourceList()` object. + + .. attribute:: depends_count + + The total number of dependencies. + + .. attribute:: package_count + + The total number of packages available in the cache. + + .. attribute:: provides_count + + The number of provided packages. + + .. attribute:: ver_file_count + + .. todo:: Seems to be some mixture of versions and pkgFile. + + .. attribute:: version_count + + The total number of package versions available in the cache. + + .. attribute:: package_file_count + + The total number of Packages files available (the Packages files + listing the packages). This is the same as the length of the list in + the attribute :attr:`file_list`. + + .. attribute:: file_list + + A list of :class:`PackageFile` objects. + +.. class:: DepCache(cache) + + Return a :class:`DepCache` object. The parameter *cache* specifies an + instance of :class:`Cache`. + + The DepCache object contains various methods to manipulate the cache, + to install packages, to remove them, and much more. + + .. method:: commit(fprogress, iprogress) + + Apply all the changes made. + + The parameter *fprogress* has to be set to an instance of + apt.progress.FetchProgress or one of its subclasses. + + The parameter *iprogress* has to be set to an instance of + apt.progress.InstallProgress or one of its subclasses. + + .. method:: fix_broken() + + Try to fix all broken packages in the cache. + + .. method:: get_candidate_ver(pkg) + + Return the candidate version of the package, ie. the version that + would be installed normally. + + The parameter *pkg* refers to an :class:`Package` object, + available using the :class:`pkgCache`. + + This method returns a :class:`Version` object. + + .. method:: set_candidate_ver(pkg, version) + + The opposite of :meth:`pkgDepCache.get_candidate_ver`. Set the candidate + version of the :class:`Package` *pkg* to the :class:`Version` + *version*. + + + .. method:: upgrade([dist_upgrade=False]) + + Perform an upgrade. More detailed, this marks all the upgradable + packages for upgrade. You still need to call + :meth:`pkgDepCache.commit` for the changes to apply. + + To perform a dist-upgrade, the optional parameter *dist_upgrade* has + to be set to True. + + .. method:: fix_broken() + + Fix broken packages. + + .. method:: read_pin_file() + + Read the policy, eg. /etc/apt/preferences. + + .. method:: minimize_upgrade() + + Go over the entire set of packages and try to keep each package marked + for upgrade. If a conflict is generated then the package is restored. + + .. todo:: + Explain better.. + + .. method:: mark_keep(pkg) + + Mark the :class:`Package` *pkg* for keep. + + .. method:: mark_delete(pkg[, purge]) + + Mark the :class:`Package` *pkg* for delete. If *purge* is True, + the configuration files will be removed as well. + + .. method:: mark_install(pkg[, auto_inst=True[, from_user=True]]) + + Mark the :class:`Package` *pkg* for install. + + If *auto_inst* is ``True``, the dependencies of the package will be + installed as well. This is the default. + + If *from_user* is ``True``, the package will be marked as manually + installed. This is the default. + + .. method:: set_reinstall(pkg) + + Set if the :class:`Package` *pkg* should be reinstalled. + + .. method:: is_upgradable(pkg) + + Return ``1`` if the package is upgradable. + + The package can be upgraded by calling :meth:`pkgDepCache.MarkInstall`. + + .. method:: is_now_broken(pkg) + + Return `1` if the package is broken now (including changes made, but + not committed). + + .. method:: is_inst_broken(pkg) + + Return ``1`` if the package is broken on the current install. This + takes changes which have not been committed not into effect. + + .. method:: is_garbage(pkg) + + Return ``1`` if the package is garbage, ie. if it is automatically + installed and no longer referenced by other packages. + + .. method:: is_auto_installed(pkg) + + Return ``1`` if the package is automatically installed (eg. as the + dependency of another package). + + .. method:: marked_install(pkg) + + Return ``1`` if the package is marked for install. + + .. method:: marked_upgrade(pkg) + + Return ``1`` if the package is marked for upgrade. + + .. method:: marked_delete(pkg) + + Return ``1`` if the package is marked for delete. + + .. method:: marked_keep(pkg) + + Return ``1`` if the package is marked for keep. + + .. method:: marked_reinstall(pkg) + + Return ``1`` if the package should be installed. + + .. method:: marked_downgrade(pkg) + + Return ``1`` if the package should be downgraded. + + .. attribute:: keep_count + + Integer, number of packages marked as keep + + .. attribute:: inst_count + + Integer, number of packages marked for installation. + + .. attribute:: del_count + + Number of packages which should be removed. + + .. attribute:: broken_count + + Number of packages which are broken. + + .. attribute:: usr_size + + The size required for the changes on the filesystem. If you install + packages, this is positive, if you remove them its negative. + + .. attribute:: deb_size + + The size of the packages which are needed for the changes to be + applied. + + +.. class:: PackageManager(depcache) + + Return a new :class:`PackageManager` object. The parameter *depcache* + specifies a :class:`DepCache` object. + + :class:`PackageManager` objects provide several methods and attributes, + which will be listed here: + + .. method:: get_archives(fetcher, list, records) + + Add all the selected packages to the :class:`Acquire()` object + *fetcher*. + + The parameter *list* refers to a :class:`SourceList()` object. + + The parameter *records* refers to a :class:`PackageRecords()` object. + + .. method:: do_install() + + Install the packages. + + .. method:: fix_missing + + Fix the installation if a package could not be downloaded. + + .. attribute:: result_completed + + A constant for checking whether the the result is 'completed'. + + Compare it against the return value of :meth:`PackageManager.get_archives` + or :meth:`PackageManager.do_install`. + + .. attribute:: result_failed + + A constant for checking whether the the result is 'failed'. + + Compare it against the return value of :meth:`PackageManager.get_archives` + or :meth:`PackageManager.do_install`. + + .. attribute:: result_incomplete + + A constant for checking whether the the result is 'incomplete'. + + Compare it against the return value of :meth:`PackageManager.get_archives` + or :meth:`PackageManager.do_install`. + +Improve performance with :class:`ActionGroup` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +.. class:: ActionGroup(depcache) + + Create a new :class:`ActionGroup()` object for the :class:`DepCache` object + given by the parameter *depcache*. + + :class:`ActionGroup()` objects make operations on the cache faster by + delaying certain cleanup operations until the action group is released. + + ActionGroup is also a context manager and therefore supports the + :keyword:`with` statement. But because it becomes active as soon as it + is created, you should not create an ActionGroup() object before entering + the with statement. + + If you want to use ActionGroup as a with statement (which is recommended + because it makes it easier to see when an actiongroup is active), always + use the following form:: + + with apt_pkg.ActionGroup(depcache): + ... + + For code which has to run on Python versions prior to 2.5, you can also + use the traditional way:: + + actiongroup = apt_pkg.ActionGroup(depcache) + ... + actiongroup.release() + + :class:`ActionGroup` provides the following method: + + .. method:: release() + + Release the ActionGroup. This will reactive the collection of package + garbage. + +Resolving Dependencies +^^^^^^^^^^^^^^^^^^^^^^ + +.. class:: ProblemResolver(depcache) + + Return a new :class:`ProblemResolver` object. The parameter *depcache* + specifies a :class:`pDepCache` object. + + The problem resolver helps when there are problems in the package + selection. An example is a package which conflicts with another, already + installed package. + + .. method:: protect(pkg) + + Protect the :class:`Package()` object given by the parameter *pkg*. + + .. todo:: + + Really document it. + + .. method:: install_protect() + + Protect all installed packages from being removed. + + .. method:: remove(pkg) + + Remove the :class:`Package()` object given by the parameter *pkg*. + + .. todo:: + + Really document it. + + .. method:: clear(pkg) + + Reset the :class:`Package()` *pkg* to the default state. + + .. todo:: + + Really document it. + + .. method:: resolve() + + Try to resolve problems by installing and removing packages. + + .. method:: resolve_by_keep() + + Try to resolve problems only by using keep. + + +:class:`PackageFile` +-------------------- +.. class:: PackageFile + + A :class:`PackageFile` represents a Packages file, eg. + /var/lib/dpkg/status. + + .. attribute:: architecture + + The architecture of the package file. + + .. attribute:: archive + + The archive (eg. unstable) + + .. attribute:: component + + The component (eg. main) + + .. attribute:: filename + + The name of the file. + + .. attribute:: id + + The ID of the package. This is an integer which can be used to store + further information about the file [eg. as dictionary key]. + + .. attribute:: index_type + + The sort of the index file. In normal cases, this is + 'Debian Package Index'. + + .. attribute:: label + + The Label, as set in the Release file + + .. attribute:: not_automatic + + Whether packages from this list will be updated automatically. The + default for eg. example is 0 (aka false). + + .. attribute:: not_source + + Whether the file has no source from which it can be updated. In such a + case, the value is 1; else 0. /var/lib/dpkg/status is 0 for example. + + Example:: + + for pkgfile in cache.file_list: + if pkgfile.not_source: + print 'The file %s has no source.' % pkgfile.filename + + .. attribute:: origin + + The Origin, as set in the Release file + + .. attribute:: site + + The hostname of the site. + + .. attribute:: size + + The size of the file. + + .. attribute:: version + + The version, as set in the release file (eg. "4.0" for "Etch") + + +Example +^^^^^^^ +.. literalinclude:: ../examples/cache-pkgfile.py + + +:class:`Package` +---------------- + +.. class:: Package + + The pkgCache::Package objects are an interface to package specific + features. + + + Attributes: + + .. attribute:: current_ver + + The version currently installed, or None. This returns a + :class:`Version` object. + + .. attribute:: id + + The ID of the package. This can be used to store information about + the package. The ID is an int value. + + .. attribute:: name + + This is the name of the package. + + .. attribute:: provides_list + + A list of packages providing this package. More detailed, this is a + list of tuples (str:pkgname, ????, :class:`Version`). + + If you want to check for check for virtual packages, the expression + ``pkg.provides_list and not pkg._version_list`` helps you. It detects if + the package is provided by something else and is not available as a + real package. + + .. attribute:: rev_depends_list + + An iterator of :class:`Dependency` objects for dependencies on this + package. + + .. attribute:: section + + The section of the package, as specified in the record. The list of + possible sections is defined in the Policy. + + .. attribute:: version_list + + A list of :class:`Version` objects for all versions available in the + cache. + + **States**: + + .. attribute:: selected_state + + The state we want it to be, ie. if you mark a package for installation, + this is :attr:`apt_pkg.SELSTATE_INSTALL`. + + See :ref:`SelStates` for a list of available states. + + .. attribute:: inst_state + + The state the currently installed version is in. This is normally + :attr:`apt_pkg.INSTSTATE_OK`, unless the installation failed. + + See :ref:`InstStates` for a list of available states. + + .. attribute:: cur_state + + The current state of the package (not installed, unpacked, installed, + etc). See :ref:`CurStates` for a list of available states. + + **Flags**: + + .. attribute:: auto + + Whether the package was installed automatically as a dependency of + another package. (or marked otherwise as automatically installed) + + .. attribute:: essential + + Whether the package is essential. + + .. attribute:: important + + Whether the package is important. + +Example: +^^^^^^^^^ +.. literalinclude:: ../examples/cache-packages.py + + + +:class:`Version` +---------------- +.. class:: Version + + The version object contains all information related to a specific package + version. + + .. attribute:: ver_str + + The version, as a string. + + .. attribute:: section + + The usual sections (eg. admin, net, etc.). Prefixed with the component + name for packages not in main (eg. non-free/admin). + + .. attribute:: arch + + The architecture of the package, eg. amd64 or all. + + .. attribute:: file_list + + A list of (:class:`PackageFile`, int: index) tuples for all Package + files containing this version of the package. + + .. attribute:: depends_list_str + + A dictionary of dependencies. The key specifies the type of the + dependency ('Depends', 'Recommends', etc.). + + + The value is a list, containing items which refer to the or-groups of + dependencies. Each of these or-groups is itself a list, containing + tuples like ('pkgname', 'version', 'relation') for each or-choice. + + An example return value for a package with a 'Depends: python (>= 2.4)' + would be:: + + {'Depends': [ + [ + ('python', '2.4', '>=') + ] + ] + } + + The same for a dependency on A (>= 1) | B (>= 2):: + + {'Depends': [ + [ + ('A', '1', '>='), + ('B', '2', '>='), + ] + ] + } + + .. attribute:: depends_list + + This is basically the same as :attr:`Version.DependsListStr`, + but instead of the ('pkgname', 'version', 'relation') tuples, + it returns :class:`Dependency` objects, which can assist you with + useful functions. + + .. attribute:: parent_pkg + + The :class:`Package` object this version belongs to. + + .. attribute:: provides_list + + This returns a list of all packages provided by this version. Like + :attr:`Package.provides_list`, it returns a list of tuples + of the form ('virtualpkgname', ???, :class:`Version`), where as the + last item is the same as the object itself. + + .. attribute:: size + + The size of the .deb file, in bytes. + + .. attribute:: installed_size + + The size of the package (in kilobytes), when unpacked on the disk. + + .. attribute:: hash + + An integer hash value. + + .. attribute:: id + + An integer id. + + .. attribute:: priority + + The integer representation of the priority. This can be used to speed + up comparisons a lot, compared to :attr:`Version.priority_str`. + + The values are defined in the :mod:`apt_pkg` extension, see + :ref:`Priorities` for more information. + + .. attribute:: priority_str + + Return the priority of the package version, as a string, eg. + "optional". + + .. attribute:: downloadable + + Whether this package can be downloaded from a remote site. + + .. attribute:: translated_description + + Return a :class:`Description` object. + + +:class:`Dependency` +------------------- +.. class:: Dependency + + Represent a dependency from one package to another one. + + .. method:: all_targets + + A list of :class:`Version` objects which satisfy the dependency, + and do not conflict with already installed ones. + + From my experience, if you use this method to select the target + version, it is the best to select the last item unless any of the + other candidates is already installed. This leads to results being + very close to the normal package installation. + + .. method:: smart_target_pkg + + Return a :class:`Version` object of a package which satisfies the + dependency and does not conflict with installed packages + (the 'natural target'). + + .. attribute:: target_ver + + The target version of the dependency, as string. Empty string if the + dependency is not versioned. + + .. attribute:: target_pkg + + The :class:`Package` object of the target package. + + .. attribute:: parent_ver + + The :class:`Version` object of the parent version, ie. the package + which declares the dependency. + + .. attribute:: parent_pkg + + The :class:`Package` object of the package which declares the + dependency. This is the same as using ParentVer.ParentPkg. + + .. attribute:: comp_type + + The type of comparison (>=, ==, >>, <=), as string. + + .. attribute:: dep_type + + The type of the dependency, as string, eg. "Depends". + + .. attribute:: id + + The ID of the package, as integer. + +Example: Find all missing dependencies +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +With the help of Dependency.AllTargets(), you can easily find all packages with +broken dependencies: + +.. literalinclude:: ../examples/missing-deps.py + + +:class:`Description` +-------------------- +.. class:: Description + + Represent the description of the package. + + .. attribute:: language_code + + The language code of the description + + .. attribute:: md5 + + The md5 hashsum of the description + + .. attribute:: file_list + + A list of tuples (:class:`PackageFile`, int: index). + + + +:class:`MetaIndex` +------------------ + +.. todo:: + + Complete them + +.. class:: MetaIndex + + .. attribute:: uri + .. attribute:: dist + .. attribute:: is_trusted + .. attribute:: index_files + + +:class:`PackageIndexFile` +------------------------- + +.. class:: PackageIndexFile + + .. method:: archive_uri(path) + + Return the full url to path in the archive. + + .. attribute:: label + + Return the Label. + + .. attribute:: exists + + Return whether the file exists. + + .. attribute:: has_packages + + Return whether the file has packages. + + .. attribute:: size + + Size of the file + + .. attribute:: is_trusted + + Whether we can trust the file. + + +Records +-------- + +.. class:: PackageRecords(cache) + + Create a new :class:`PackageRecords` object, for the packages in the cache + specified by the parameter *cache*. + + Provide access to the packages records. This provides very useful + attributes for fast (convient) access to some fields of the record. + + .. method:: lookup(verfile_iter) + + Change the actual package to the package given by the verfile_iter. + + The parameter *verfile_iter* refers to a tuple consisting + of (:class:`PackageFile()`, int: index), as returned by various + attributes, including :attr:`Version.file_list`. + + Example (shortened):: + + cand = depcache.GetCandidateVer(cache['python-apt']) + records.Lookup(cand.FileList[0]) + # Now you can access the record + print records.SourcePkg # == python-apt + + .. attribute:: filename + + Return the field 'Filename' of the record. This is the path to the + package, relative to the base path of the archive. + + .. attribute:: md5_hash + + Return the MD5 hashsum of the package This refers to the field + 'MD5Sum' in the raw record. + + .. attribute:: sha1_hash + + Return the SHA1 hashsum of the package. This refers to the field 'SHA1' + in the raw record. + + .. attribute:: sha256_hash + + Return the SHA256 hashsum of the package. This refers to the field + 'SHA256' in the raw record. + + .. versionadded:: 0.7.9 + + .. attribute:: source_pkg + + Return the source package. + + .. attribute:: source_ver + + Return the source version. + + .. attribute:: maintainer + + Return the maintainer of the package. + + .. attribute:: short_desc + + Return the short description. This is the summary on the first line of + the 'Description' field. + + .. attribute:: long_desc + + Return the long description. These are lines 2-END from the + 'Description' field. + + .. attribute:: name + + Return the name of the package. This is the 'Package' field. + + .. attribute:: homepage + + Return the Homepage. This is the 'Homepage' field. + + .. attribute:: record + + Return the whole record as a string. If you want to access fields of + the record not available as an attribute, you can use + :class:`apt_pkg.TagSection` to parse the record and access the field + name. + + Example:: + + section = apt_pkg.TagSection(records.record) + print section['SHA256'] # Use records.sha256_hash instead + + +.. class:: SourceRecords + + This represents the entries in the Sources files, ie. the dsc files of + the source packages. + + .. note:: + + If the Lookup failed, because no package could be found, no error is + raised. Instead, the attributes listed below are simply not existing + anymore (same applies when no Lookup has been made, or when it has + been restarted). + + .. method:: lookup(pkgname) + + Lookup the record for the package named *pkgname*. To access all + available records, you need to call it multiple times. + + Imagine a package P with two versions X, Y. The first ``lookup(P)`` + would set the record to version X and the second ``lookup(P)`` to + version Y. + + .. method:: restart() + + Restart the lookup. + + Imagine a package P with two versions X, Y. The first ``Lookup(P)`` + would set the record to version X and the second ``Lookup(P)`` to + version Y. + + If you now call ``restart()``, the internal position will be cleared. + Now you can call ``lookup(P)`` again to move to X. + + .. attribute:: package + + The name of the source package. + + .. attribute:: version + + A string describing the version of the source package. + + .. attribute:: maintainer + + A string describing the name of the maintainer. + + .. attribute:: section + + A string describing the section. + + .. attribute:: record + + The whole record, as a string. You can use :func:`apt_pkg.ParseSection` + if you need to parse it. + + You need to parse the record if you want to access fields not available + via the attributes, eg. 'Standards-Version' + + .. attribute:: binaries + + Return a list of strings describing the package names of the binaries + created by the source package. This matches the 'Binary' field in the + raw record. + + .. attribute:: index + + The index in the Sources files. + + .. attribute:: files + + The list of files. This returns a list of tuples with the contents + ``(str: md5, int: size, str: path, str:type)``. + + .. attribute:: build_depends + + Return a dictionary representing the build-time dependencies of the + package. The format is the same as for :attr:`Version.depends_list_str` + and possible keys being ``"Build-Depends"``, ``"Build-Depends-Indep"``, + ``"Build-Conflicts"`` or ``"Build-Conflicts-Indep"``. + + .. attribute:: BuildDepends + + Return the list of Build dependencies, as + ``(str: package, str: version, int: op, int: type)``. This is a + completely deprecated format + + .. table:: Values of *op* + + ===== ============================================= + Value Meaning + ===== ============================================= + 0x00 No Operation (no versioned build dependency) + 0x10 | (or) - this will be added to the other values + 0x01 <= (less than or equal) + 0x02 >= (greater than or equal) + 0x03 << (less than) + 0x04 >> (greater than) + 0x05 = (equal) + 0x06 != (not equal) + ===== ============================================= + + .. table:: Values of *type* + + ===== =================== + Value Meaning + ===== =================== + 0 Build-Depends + 1 Build-Depends-Indep + 2 Build-Conflicts + 3 Build-Conflicts-Indep + ===== =================== + + **Example**: In the following content, we will imagine a + build-dependency:: + + Build-Depends: A (>= 1) | B (>= 1), C + + This results in:: + + [('A', '1', 18, 0), # 18 = (16 | 2) = (0x10 | 0x2) + ('B', '1', 2, 0), + ('C', '', 0, 0)] + + This is **not** the same as returned by + :func:`apt_pkg.ParseSrcDepends`. + + + +The Acquire interface +---------------------- +The Acquire Interface is responsible for all sorts of downloading in apt. All +packages, index files, etc. downloading is done using the Acquire functionality. + +The :mod:`apt_pkg` module provides a subset of this functionality which allows +you to implement file downloading in your applications. Together with the +:class:`PackageManager` class you can also fetch all the packages marked for +installation. + + +.. class:: Acquire([progress]) + + Return an :class:`Acquire` object. The parameter *progress* refers to + an :class:`apt.progress.FetchProgress()` object. + + Acquire objects maintaing a list of items which will be fetched or have + been fetched already during the lifetime of this object. To add new items + to this list, you can create new :class:`AcquireFile` objects which allow + you to add single files. + + Acquire items have multiple methods: + + .. method:: run() + + Fetch all the items which have been added by :class:`AcquireFile`. + + .. method:: shutdown() + + Shut the fetcher down. + + .. attribute:: total_needed + + The total amount of bytes needed (including those of files which are + already present) + + .. attribute:: fetch_needed + + The total amount of bytes which need to be fetched. + + .. attribute:: partial_present + + Whether some files have been acquired already. (???) + +.. class:: AcquireItem + + The :class:`AcquireItem()` objects represent the items of a + :class:`Acquire` object. :class:`AcquireItem()` objects can not be created + by the user, they are solely available through the :attr:`Acquire.items` + list of an :class:`Acquire` object. + + .. attribute:: id + + The ID of the item. + + .. attribute:: complete + + Is the item completely acquired? + + .. attribute:: local + + Is the item a local file? + + .. attribute:: is_trusted + + Can the file be trusted? + + .. attribute:: file_size + + The size of the file, in bytes. + + .. attribute:: error_text + + The error message. For example, when a file does not exist on a http + server, this will contain a 404 error message. + + .. attribute:: dest_file + + The location the file is saved as. + + .. attribute:: desc_uri + + The source location. + + **Status**: + + .. attribute:: status + + Integer, representing the status of the item. + + .. attribute:: stat_idle + + Constant for comparing :attr:`AcquireItem.status`. + + .. attribute:: stat_fetching + + Constant for comparing :attr:`AcquireItem.status` + + .. attribute:: stat_done + + Constant for comparing :attr:`AcquireItem.status` + + .. attribute:: stat_error + + Constant for comparing :attr:`AcquireItem.status` + + .. attribute:: stat_auth_error + + Constant for comparing :attr:`AcquireItem.status` + + +.. class:: AcquireFile(owner, uri[, md5, size, descr, short_descr, destdir, destfile]) + + Create a new :class:`AcquireFile()` object and register it with *acquire*, + so it will be fetched. AcquireFile objects provide no methods or attributes + and are completely useless at the moment. + + The parameter *owner* refers to an :class:`Acquire()` object as returned + by :func:`GetAcquire`. The file will be added to the Acquire queue + automatically. + + The parameter *uri* refers to the location of the file, any protocol + of apt is supported. + + The parameter *md5* refers to the md5sum of the file. This can be used + for checking the file. + + The parameter *size* can be used to specify the size of the package, + which can then be used to calculate the progress and validate the download. + + The parameter *descr* is a descripition of the download. It may be + used to describe the item in the progress class. *short_descr* is the + short form of it. + + You can use *destdir* to manipulate the directory where the file will + be saved in. Instead of *destdir*, you can also specify the full path to + the file using the parameter *destfile*. You can not combine both. + + +Hashes +------ +The apt_pkg module also provides several hash functions. If you develop +applications with python-apt it is often easier to use these functions instead +of the ones provides in Python's :mod:`hashlib` module. + +.. class:: Hashes(object) + + Calculate all supported hashes of the object. *object* may either be a + string, in which cases the hashes of the string are calculated, or a + :class:`file()` object or file descriptor, in which case the hashes of + its contents is calculated. The calculated hashes are then available via + attributes: + + .. attribute:: md5 + + The MD5 hash of the data, as string. + + .. attribute:: sha1 + + The SHA1 hash of the data, as string. + + .. attribute:: sha256 + + The SHA256 hash of the data, as string. + +.. function:: md5sum(object) + + Return the md5sum of the object. *object* may either be a string, in + which case the md5sum of the string is returned, or a :class:`file()` + object (or a file descriptor), in which case the md5sum of its contents is + returned. + + .. versionchanged:: 0.8.0 + Added support for using file descriptors. + +.. function:: sha1sum(object) + + Return the sha1sum of the object. *object* may either be a string, in + which case the sha1sum of the string is returned, or a :class:`file()` + object (or a file descriptor), in which case the sha1sum of its contents + is returned. + + .. versionchanged:: 0.8.0 + Added support for using file descriptors. + +.. function:: sha256sum(object) + + Return the sha256sum of the object. *object* may either be a string, in + which case the sha256sum of the string is returned, or a :class:`file()` + object (or a file descriptor), in which case the sha256sum of its contents + is returned. + + .. versionchanged:: 0.8.0 + Added support for using file descriptors. + +Debian control files +-------------------- +Debian control files are files containing multiple stanzas of :RFC:`822`-style +header sections. They are widely used in the Debian community, and can represent +many kinds of information. One example for such a file is the +:file:`/var/lib/dpkg/status` file which contains a list of the currently +installed packages. + +The :mod:`apt_pkg` module provides two classes to read those files and parts +thereof and provides a function :func:`RewriteSection` which takes a +:class:`TagSection()` object and sorting information and outputs a sorted +section as a string. + +.. class:: TagFile(file) + + An object which represents a typical debian control file. Can be used for + Packages, Sources, control, Release, etc. + + An example for working with a TagFile could look like:: + + tagf = apt_pkg.TagFile(open('/var/lib/dpkg/status')) + tagf.step() + print tagf.section['Package'] + + .. method:: step + + Step forward to the next section. This simply returns ``1`` if OK, and + ``0`` if there is no section + + .. method:: offset + + Return the current offset (in bytes) from the beginning of the file. + + .. method:: jump(offset) + + Jump back/forward to *offset*. Use ``jump(0)`` to jump to the + beginning of the file again. + + .. attribute:: section + + This is the current :class:`TagSection()` instance. + +.. class:: TagSection(text) + + Represent a single section of a debian control file. + + .. describe:: section[key] + + Return the value of the field at *key*. If *key* is not available, + raise :exc:`KeyError`. + + .. describe:: key in section + + Return ``True`` if *section* has a key *key*, else ``False``. + + .. versionadded:: 0.8.0 + + .. method:: bytes + + The number of bytes in the section. + + .. method:: find(key, default='') + + Return the value of the field at the key *key* if available, + else return *default*. + + .. method:: find_flag(key) + + Find a yes/no value for the key *key*. An example for such a + field is 'Essential'. + + .. method:: get(key, default='') + + Return the value of the field at the key *key* if available, else + return *default*. + + .. method:: has_key(key) + + Check whether the field with named by *key* exists. + + .. deprecated:: 0.8.0 + + .. method:: keys() + + Return a list of keys in the section. + +.. function:: rewrite_section(section: TagSection, order: list, rewrite_list: list) -> str + + Rewrite the section given by *section* using *rewrite_list*, and order the + fields according to *order*. + + The parameter *order* is a :class:`list` object containing the names of the + fields in the order they should appear in the rewritten section. + :data:`apt_pkg.REWRITE_PACKAGE_ORDER` and + :data:`apt_pkg.REWRITE_SOURCE_ORDER` are two predefined lists for rewriting + package and source sections, respectively. + + The parameter *rewrite_list* is a list of tuples of the form + ``(tag, newvalue[, renamed_to])``, whereas *tag* describes the field which + should be changed, *newvalue* the value which should be inserted or + ``None`` to delete the field, and the optional *renamed_to* can be used + to rename the field. + +.. data:: REWRITE_PACKAGE_ORDER + + The order in which the information for binary packages should be rewritten, + i.e. the order in which the fields should appear. + +.. data:: REWRITE_SOURCE_ORDER + + The order in which the information for source packages should be rewritten, + i.e. the order in which the fields should appear. + +Dependencies +------------ +.. function:: check_dep(pkgver, op, depver) + + Check that the dependency requirements consisting of op and depver can be + satisfied by the version pkgver. + + Example:: + + >>> bool(apt_pkg.check_dep("1.0", ">=", "1")) + True + +.. function:: parse_depends(depends) + + Parse the string *depends* which contains dependency information as + specified in Debian Policy, Section 7.1. + + Returns a list. The members of this list are lists themselves and contain + one or more tuples in the format ``(package,version,operation)`` for every + 'or'-option given, e.g.:: + + >>> apt_pkg.parse_depends("PkgA (>= VerA) | PkgB (>= VerB)") + [[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]] + + + .. note:: + + The behavior of this function is different than the behavior of the + old function :func:`ParseDepends()`, because the third field + ``operation`` uses `>` instead of `>>` and `<` instead of `<<` which + is specified in control files. + + +.. function:: parse_src_depends(depends) + + Parse the string *depends* which contains dependency information as + specified in Debian Policy, Section 7.1. + + Returns a list. The members of this list are lists themselves and contain + one or more tuples in the format ``(package,version,operation)`` for every + 'or'-option given, e.g.:: + + >>> apt_pkg.parse_depends("PkgA (>= VerA) | PkgB (>= VerB)") + [[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]] + + + Furthemore, this function also supports to limit the architectures, as + used in e.g. Build-Depends:: + + >>> apt_pkg.parse_src_depends("a (>= 01) [i386 amd64]") + [[('a', '01', '>=')]] + + .. note:: + + The behavior of this function is different than the behavior of the + old function :func:`ParseDepends()`, because the third field + ``operation`` uses `>` instead of `>>` and `<` instead of `<<` which + is specified in control files. + + +Configuration +------------- + +.. class:: Configuration() + + Configuration() objects store the configuration of apt, mostly created from + the contents of :file:`/etc/apt.conf` and the files in + :file:`/etc/apt.conf.d`. + + .. describe:: key in conf + + Return ``True`` if *conf* has a key *key*, else ``False``. + + .. versionadded:: 0.8.0 + + .. describe:: conf[key] + + Return the value of the option given key *key*. If it does not + exist, raise :exc:`KeyError`. + + .. describe:: conf[key] = value + + Set the option at *key* to *value*. + + .. method:: find(key[, default='']) + + Return the value for the given key *key*. This is the same as + :meth:`Configuration.get`. + + If *key* does not exist, return *default*. + + .. method:: find_file(key[, default='']) + + Return the filename hold by the configuration at *key*. This formats the + filename correctly and supports the Dir:: stuff in the configuration. + + If *key* does not exist, return *default*. + + .. method:: find_dir(key[, default='/']) + + Return the absolute path to the directory specified in *key*. A + trailing slash is appended. + + If *key* does not exist, return *default*. + + .. method:: find_i(key[, default=0]) + + Return the integer value stored at *key*. + + If *key* does not exist, return *default*. + + .. method:: find_b(key[, default=0]) + + Return the boolean value stored at *key*. This returns an integer, but + it should be treated like True/False. + + If *key* does not exist, return *default*. + + .. method:: set(key, value) + + Set the value of *key* to *value*. + + .. method:: exists(key) + + Check whether the key *key* exists in the configuration. + + .. method:: subtree(key) + + Return a sub tree starting at *key*. The resulting object can be used + like this one. + + .. method:: list([key]) + + List all items at *key*. Normally, return the keys at the top level, + eg. APT, Dir, etc. + + Use *key* to specify a key of which the childs will be returned. + + .. method:: value_list([key]) + + Same as :meth:`Configuration.list`, but this time for the values. + + .. method:: my_tag() + + Return the tag name of the current tree. Normally this is an empty + string, but for subtrees it is the key of the subtree. + + .. method:: clear(key) + + Clear the configuration. Remove all values and keys at *key*. + + .. method:: keys([key]) + + Return all the keys, recursive. If *key* is specified, ... (FIXME) + + .. method:: has_key(key) + + Return whether the configuration contains the key *key*. + + .. deprecated:: 0.8.0 + + .. method:: get(key[, default='']) + + This behaves just like :meth:`dict.get` and :meth:`Configuration.find`, + it returns the value of key or if it does not exist, *default*. + +.. class:: ConfigurationPtr + + Behaves like a :class:`Configuration()` objects, but uses a pointer to the + underlying C++ object. This is used for the default configuration in the + :data:`Config` attribute of the module. + +.. class:: ConfigurationSub + + Behaves like a :class:`Configuration()` objects, but provides access to + a subsection of another Configuration-like object. This type of object is + returned by the :meth:`Configuration.subtree()` method. + +.. data:: config + + A :class:`ConfigurationPtr()` object with the default configuration. This + object is initialized by calling :func:`init_config`. + + +Modifying +^^^^^^^^^ + + +.. function:: read_config_file(configuration, filename) + + Read the configuration file specified by the parameter *filename* and add + the settings therein to the :class:`Configuration()` object specified by + the parameter *configuration* + +.. function:: read_config_dir(configuration, dirname) + + Read configuration files in the directory specified by the parameter + *dirname* and add the settings therein to the :class:`Configuration()` + object specified by the parameter *configuration*. + +.. function:: read_config_file_isc(configuration, filename) + + Read the configuration file specified by the parameter *filename* and add + the settings therein to the :class:`Configuration()` object specified by + the parameter *configuration* + +.. function:: parse_commandline(configuration, options, argv) + + This function is like getopt except it manipulates a configuration space. + output is a list of non-option arguments (filenames, etc). *options* is a + list of tuples of the form ``(‘c’,”long-opt or None”, + ”Configuration::Variable”,”optional type”)``. + + Where ``type`` may be one of HasArg, IntLevel, Boolean, InvBoolean, + ConfigFile, or ArbItem. The default is Boolean. + +Locking +-------- + +.. function:: get_lock(filename) + + Create an empty file at the path specified by the parameter *filename* and + lock it. + + While the file is locked by a process, calling this function in another + process returns ``-1``. + + When the lock is not required anymore, the file descriptor should be closed + using :func:`os.close`. + +.. function:: pkg_system_lock() + + Lock the global pkgsystem. + +.. function:: pkg_system_un_lock() + + Unlock the global pkgsystem. + +Other classes +-------------- +.. class:: Cdrom() + + Return a Cdrom object with the following methods: + + .. method:: ident(progress) + + Identify the cdrom. The parameter *progress* refers to an + :class:`apt.progress.CdromProgress()` object. + + .. method:: add(progress) + + Add the cdrom to the sources.list file. The parameter *progress* + refers to an :class:`apt.progress.CdromProgress()` object. + +.. class:: SourceList + + This is for :file:`/etc/apt/sources.list`. + + .. method:: find_index(pkgfile) + + Return a :class:`PackageIndexFile` object for the :class:`PackageFile` + *pkgfile*. + + .. method:: read_main_list + + Read the main list. + + .. method:: get_indexes(acq[, all]) + + Add the index files to the :class:`Acquire()` object *acq*. If *all* is + given and ``True``, all files are fetched. + +String functions +---------------- +.. function:: base64_encode(string) + + Encode the given string using base64, e.g:: + + >>> apt_pkg.base64_encode(u"A") + 'QQ==' + + +.. function:: check_domain_list(host, list) + + See if Host is in a ',' seperated list, e.g.:: + + apt_pkg.check_domain_list("alioth.debian.org","debian.net,debian.org") + +.. function:: dequote_string(string) + + Dequote the string specified by the parameter *string*, e.g.:: + + >>> apt_pkg.dequote_string("%61%70%74%20is%20cool") + 'apt is cool' + +.. function:: quote_string(string, repl) + + For every character listed in the string *repl*, replace all occurences in + the string *string* with the correct HTTP encoded value: + + >>> apt_pkg.quote_string("apt is cool","apt") + '%61%70%74%20is%20cool' + +.. function:: size_to_str(size) + + Return a string presenting the human-readable version of the integer + *size*. When calculating the units (k,M,G,etc.) the size is divided by the + factor 1000. + + Example:: + + >>> apt_pkg.size_to_str(10000) + '10.0k' + +.. function:: string_to_bool(input) + + Parse the string *input* and return one of **-1**, **0**, **1**. + + .. table:: Return values + + ===== ============================================= + Value Meaning + ===== ============================================= + -1 The string *input* is not recognized. + 0 The string *input* evaluates to **False**. + +1 The string *input* evaluates to **True**. + ===== ============================================= + + Example:: + + >>> apt_pkg.string_to_bool("yes") + 1 + >>> apt_pkg.string_to_bool("no") + 0 + >>> apt_pkg.string_to_bool("not-recognized") + -1 + +.. function:: str_to_time(rfc_time) + + Convert the :rfc:`1123` conforming string *rfc_time* to the unix time, and + return the integer. This is the opposite of :func:`TimeRFC1123`. + + Example:: + + >> apt_pkg.str_to_time('Thu, 01 Jan 1970 00:00:00 GMT') + 0 + +.. function:: time_rfc1123(seconds) + + Format the unix time specified by the integer *seconds*, according to the + requirements of :rfc:`1123`. + + Example:: + + >>> apt_pkg.time_rfc1123(0) + 'Thu, 01 Jan 1970 00:00:00 GMT' + + +.. function:: time_to_str(seconds) + + Format a given duration in a human-readable manner. The parameter *seconds* + refers to a number of seconds, given as an integer. The return value is a + string with a unit like 's' for seconds. + + Example:: + + >>> apt_pkg.time_to_str(3601) + '1h0min1s' + +.. function:: upstream_version(version) + + Return the string *version*, eliminating everything following the last + '-'. Thus, this should be equivalent to ``version.rsplit('-', 1)[0]``. + +.. function:: uri_to_filename(uri) + + Take a string *uri* as parameter and return a filename which can be used to + store the file, based on the URI. + + Example:: + + >>> apt_pkg.uri_to_filename('http://debian.org/index.html') + 'debian.org_index.html' + + +.. function:: version_compare(a, b) + + Compare two versions, *a* and *b*, and return an integer value which has + the same characteristic as the built-in :func:`cmp` function. + + .. table:: Return values + + ===== ============================================= + Value Meaning + ===== ============================================= + > 0 The version *a* is greater than version *b*. + = 0 Both versions are equal. + < 0 The version *a* is less than version *b*. + ===== ============================================= + + + + +Module Constants +---------------- +.. _CurStates: + +Package States +^^^^^^^^^^^^^^^ +.. data:: CURSTATE_CONFIG_FILES +.. data:: CURSTATE_HALF_CONFIGURED +.. data:: CURSTATE_HALF_INSTALLED +.. data:: CURSTATE_INSTALLED +.. data:: CURSTATE_NOT_INSTALLED +.. data:: CURSTATE_UNPACKED + + + + +Dependency types +^^^^^^^^^^^^^^^^ +.. data:: DEP_CONFLICTS +.. data:: DEP_DEPENDS +.. data:: DEP_OBSOLETES +.. data:: DEP_PRE_DEPENDS +.. data:: DEP_RECOMMENDS +.. data:: DEP_REPLACES +.. data:: DEP_SUGGESTS + +.. _InstStates: + +Installed states +^^^^^^^^^^^^^^^^ +.. data:: INSTSTATE_HOLD +.. data:: INSTSTATE_HOLD_REINSTREQ +.. data:: INSTSTATE_OK +.. data:: INSTSTATE_REINSTREQ + +.. _Priorities: + +Priorities +^^^^^^^^^^^ +.. data:: PRI_EXTRA +.. data:: PRI_IMPORTANT +.. data:: PRI_OPTIONAL +.. data:: PRI_REQUIRED +.. data:: PRI_STANDARD + + +.. _SelStates: + +Select states +^^^^^^^^^^^^^ +.. data:: SELSTATE_DE_INSTALL +.. data:: SELSTATE_HOLD +.. data:: SELSTATE_INSTALL +.. data:: SELSTATE_PURGE +.. data:: SELSTATE_UNKNOWN + + +Build information +^^^^^^^^^^^^^^^^^ +.. data:: DATE + + The date on which this extension has been compiled. + +.. data:: LIB_VERSION + + The version of the apt_pkg library. This is **not** the version of apt, + nor the version of python-apt. + +.. data:: TIME + + The time this extension has been built. + +.. data:: VERSION + + The version of apt (not of python-apt). + +.. data:: _COMPAT_0_7 + + A more or less internal variable defining whether this build provides an + API which is compatible to the one of python-apt 0.7. This is used in the + apt and aptsources packages to decide whether compatibility should be + enabled or not. diff --git a/doc/source/library/aptsources.distinfo.rst b/doc/source/library/aptsources.distinfo.rst new file mode 100644 index 00000000..033ef483 --- /dev/null +++ b/doc/source/library/aptsources.distinfo.rst @@ -0,0 +1,11 @@ +:mod:`aptsources.distinfo` --- provide meta information for distro repositories +=============================================================================== +.. note:: + + This part of the documentation is created automatically. + + +.. automodule:: aptsources.distinfo + :members: + :undoc-members: + diff --git a/doc/source/library/aptsources.distro.rst b/doc/source/library/aptsources.distro.rst new file mode 100644 index 00000000..6ebe438c --- /dev/null +++ b/doc/source/library/aptsources.distro.rst @@ -0,0 +1,11 @@ +:mod:`aptsources.distro` --- Distribution abstraction of the sources.list +=============================================================================== +.. note:: + + This part of the documentation is created automatically. + + +.. automodule:: aptsources.distro + :members: + :undoc-members: + diff --git a/doc/source/library/aptsources.sourceslist.rst b/doc/source/library/aptsources.sourceslist.rst new file mode 100644 index 00000000..79b8dd01 --- /dev/null +++ b/doc/source/library/aptsources.sourceslist.rst @@ -0,0 +1,11 @@ +:mod:`aptsources.sourceslist` --- Provide an abstraction of the sources.list +============================================================================ +.. note:: + + This part of the documentation is created automatically. + + +.. automodule:: aptsources.sourceslist + :members: + :undoc-members: + diff --git a/doc/source/library/index.rst b/doc/source/library/index.rst new file mode 100644 index 00000000..dfbd8eec --- /dev/null +++ b/doc/source/library/index.rst @@ -0,0 +1,36 @@ +Python APT Library +================== +Python APT's library provides access to almost every functionality supported +by the underlying apt-pkg and apt-inst libraries. This means that it is +possible to rewrite frontend programs like apt-cdrom in Python, and this is +relatively easy, as can be seen in e.g. :doc:`../tutorials/apt-cdrom`. + +When going through the library, the first two modules are :mod:`apt_pkg` and +:mod:`apt_inst`. These modules are more or less straight bindings to the +apt-pkg and apt-inst libraries and the base for the rest of python-apt. + +Going forward, the :mod:`apt` package appears. This package is using +:mod:`apt_pkg` and :mod`apt_inst` to provide easy to use ways to manipulate +the cache, fetch packages, or install new packages. It also provides useful +progress classes, for text and GTK+ interfaces. The last package is +:mod:`aptsources`. The aptsources package provides classes and functions to +read files like :file:`/etc/apt/sources.list` and to modify them. + +.. toctree:: + :maxdepth: 1 + + apt_pkg + apt_inst + + apt.cache + apt.cdrom + apt.debfile + apt.package + apt.progress.text + apt.progress.gtk2 + apt.progress.qt4 + + aptsources.distinfo + aptsources.distro + aptsources.sourceslist + diff --git a/doc/source/templates/indexcontent.html b/doc/source/templates/indexcontent.html new file mode 100644 index 00000000..e5f11cc1 --- /dev/null +++ b/doc/source/templates/indexcontent.html @@ -0,0 +1,50 @@ +{% extends "defindex.html" %} +{% block body %} +

{{ docstitle|e }}

+

+ Welcome! This is + {% block description %}the documentation for {{ project|e }} + {{ release|e }}{% if last_updated %}, last updated {{ last_updated|e }}{% endif %}{% endblock %}. +

+ +

+ This documentation has been created using Sphinx and reStructuredText files + written by Julian Andres Klode <jak@debian.org>. +

+ + + + +

Parts of the documentation:

+ + +
+ + + + + + +
+ +

Indices and tables:

+ + +
+ + + + + +
+ +{% endblock %} diff --git a/doc/source/templates/layout.html b/doc/source/templates/layout.html new file mode 100644 index 00000000..60298719 --- /dev/null +++ b/doc/source/templates/layout.html @@ -0,0 +1,10 @@ +{% extends "!layout.html" %} +{% block rootrellink %} +
  • +
  • {{ shorttitle }}{{ reldelim1 }}
  • +{% endblock %} +{% block extrahead %} + +{{ super() }} +{% endblock %} diff --git a/doc/source/tutorials/apt-cdrom.rst b/doc/source/tutorials/apt-cdrom.rst new file mode 100644 index 00000000..c66d49f7 --- /dev/null +++ b/doc/source/tutorials/apt-cdrom.rst @@ -0,0 +1,156 @@ +Writing your own apt-cdrom +========================== +:Author: Julian Andres Klode +:Release: |release| +:Date: |today| + +This article explains how to utilise python-apt to build your own clone of the +:command:`apt-cdrom` command. To do this, we will take a look at the +:mod:`apt.cdrom` and :mod:`apt.progress.text` modules, and we will learn how +to use apt_pkg.parse_commandline to parse commandline arguments. The code shown +here works on Python 2 and Python 3. + +Basics +------ +The first step in building your own :command:`apt-cdrom` clone is to import the +:mod:`apt` package, which will import :mod:`apt.cdrom` and +:mod:`apt.progress.text`:: + + import apt + +Now we have to create a new :class:`apt.cdrom.Cdrom` object and pass to it an +:class:`apt.progress.text.CdromProgress` object, which is responsible for +displaying the progress and asking questions:: + + cdrom = apt.Cdrom(apt.progress.text.CdromProgress()) + +Now we have to choose the action, depending on the given options on the +command line. For now, we simply use the value of ``sys.argv[1]``:: + + import sys + if sys.argv[1] == 'add': + cdrom.add() + elif sys.argv[1] == 'ident': + cdrom.ident() + +Now we have a basic :command:`apt-cdrom` clone which can add and identify +CD-ROMs:: + + import sys + + import apt + + cdrom = apt.Cdrom(apt.progress.text.CdromProgress()) + if sys.argv[1] == 'add': + cdrom.add() + elif sys.argv[1] == 'ident': + cdrom.ident() + +Advcaned example with command-line parsing +------------------------------------------- +Our example clearly misses a way to parse the commandline in a correct +manner. Luckily, :mod:`apt_pkg` provides us with a function to do this: +:func:`apt_pkg.parse_commandline`. To use it, we add ``import apt_pkg`` right +after import apt:: + + import sys + + import apt_pkg + import apt + + +:func:`apt_pkg.parse_commandline` is similar to :mod:`getopt` functions, it +takes a list of recognized options and the arguments and returns all unknown +arguments. If it encounters an unknown argument which starts with a leading +'-', the function raises an error indicating that the option is unknown. The +major difference is that this function manipulates the apt configuration space. + +The function takes 3 arguments. The first argument is an +:class:`apt_pkg.Configuration` object. The second argument is a list of tuples +of the form ``(shortopt, longopt, config, type)``, whereas *shortopt* is a +character indicating the short option name, *longopt* a string indicating the +corresponding long option (e.g. ``"--help"``), *config* the name of the +configuration item which should be set and *type* the type of the argument. + +For apt-cdrom, we can use the following statement:: + + arguments = apt_pkg.parse_commandline(apt_pkg.config, + [('h', "help", "help"), + ('v', "version", "version"), + ('d', "cdrom", "Acquire::cdrom::mount", "HasArg"), + ('r', "rename", "APT::CDROM::Rename"), + ('m', "no-mount", "APT::CDROM::NoMount"), + ('f', "fast", "APT::CDROM::Fast"), + ('n', "just-print", "APT::CDROM::NoAct"), + ('n', "recon", "APT::CDROM::NoAct"), + ('n', "no-act", "APT::CDROM::NoAct"), + ('a', "thorough", "APT::CDROM::Thorough"), + ('c', "config-file", "", "ConfigFile"), + ('o', "option", "", "ArbItem")], args) + + +This allows us to support all options supported by apt-cdrom. The first option +is --help. As you can see, it omits the fourth field of the tuple; which means +it is a boolean argument. Afterwards you could use +``apt_pkg.config.find_b("help")`` to see whether ``--help`` was specified. In +``('d',"cdrom","Acquire::cdrom::mount","HasArg")`` the fourth field is +``"HasArg"``. This means that the option has an argument, in this case the +location of the mount pint. ``('c',"config-file","","ConfigFile")`` shows how +to include configuration files. This option takes a parameter which points to +a configuration file which will be added to the configuration space. +('o',"option","","ArbItem") is yet another type of option, which allows users +to set configuration options on the commandline. + +Now we have to check whether help or version is specified, and print a message +and exit afterwards. To do this, we use :meth:`apt_pkg.Configuration.find_b` +which returns ``True`` if the configuration option exists and evaluates to +``True``:: + + if apt_pkg.config.find_b("help"): + print("This should be a help message") + sys.exit(0) + elif apt_pkg.config.find_b("version"): + print("Version blah.") + sys.exit(0) + + +Now we are ready to create our progress object and our cdrom object. Instead +of using :class:`apt.Cdrom` like in the first example, we will use +:class:`apt_pkg.Cdrom` which provides a very similar interface. We could also +use :class:`apt.Cdrom`, but `apt.Cdrom` provides options like *nomount* which +conflict with our commandline parsing:: + + progress = apt.progress.text.CdromProgress() + cdrom = apt_pkg.Cdrom() + + +Now we have to do the action requested by the user on the commandline. To see +which option was requested, we check the list ``arguments`` which was returned +by ``apt_pkg.parse_commandline`` above, and afterwards call ``cdrom.add`` or +``cdrom.ident``:: + + if apt_pkg.config.find_b("help"): + print("This should be a help message") + sys.exit(0) + elif apt_pkg.config.find_b("version"): + print("Version blah.") + sys.exit(0) + + if not arguments: + sys.stderr.write('E: No operation specified\n') + sys.exit(1) + elif arguments[0] == 'add': + cdrom.add(progress) + elif arguments[0] == 'ident': + cdrom.ident(progress) + else: + sys.stderr.write('E: Invalid operation %s\n' % arguments[0]) + sys.exit(1) + + +After putting all our actions into a main() function, we get a completely +working apt-cdrom clone, which just misses useful ``--help`` and ``--version`` +options. If we add a function show_help(), we get an even more complete +apt-cdrom clone: + +.. literalinclude:: ../examples/apt-cdrom.py diff --git a/doc/source/tutorials/contributing.rst b/doc/source/tutorials/contributing.rst new file mode 100644 index 00000000..f68d626e --- /dev/null +++ b/doc/source/tutorials/contributing.rst @@ -0,0 +1,312 @@ +Contributing to python-apt +========================== +:Author: Julian Andres Klode +:Release: |release| +:Date: |today| + +Let's say you need a new feature, you can develop it, and you want to get it +included in python-apt. Then be sure to follow the following guidelines. + +Available branches +------------------- +First of all, let's talk a bit about the bzr branches of python-apt. In the +following parts, we will assume that you use bzr to create your changes and +submit them. + +**mvo:** http://people.ubuntu.com/~mvo/bzr/python-apt/mvo + This is Michael Vogt's branch. Most of the development of apt happens here, + as he is the lead maintainer of python-apt. + + This branch is also available from Launchpads super mirror, via + ``lp:python-apt``. Checkouts from Launchpad are generally faster and can + use the bzr protocoll. + + VCS-Browser: https://code.launchpad.net/~mvo/python-apt/python-apt--mvo + +**debian-sid:** http://bzr.debian.org/apt/python-apt/debian-sid + This is the official Debian branch of python-apt. All code which will be + uploaded to Debian is here. It is not as up-to-date as the mvo branch, + because this branch often gets updated just right before the release + happens. + + VCS-Browser: http://bzr.debian.org/loggerhead/apt/python-apt/debian-sid/changes + +**debian-experimental:** http://bzr.debian.org/apt/python-apt/debian-experimental + + This is another official Debian branch of python-apt, for releases + targetted at Debian experimental. This branch may contain unstable code + and may thus not work correctly. + + VCS-Browser: http://bzr.debian.org/loggerhead/apt/python-apt/debian-experimental/changes + +**jak:** http://bzr.debian.org/users/jak/python-apt/jak + This is Julian Andres Klode's (the documentation author's) branch. This + is the place where cleanup and documentation updates happen. It is based + off debian-sid or mvo. + + VCS-Browser: http://bzr.debian.org/loggerhead/users/jak/python-apt/jak/changes + +**ubuntu:** ``lp:~ubuntu-core-dev/python-apt/ubuntu`` + This is the official Ubuntu development branch. The same notes apply as + for the debian-sid branch above. + + VCS-Browser: https://code.launchpad.net/~ubuntu-core-dev/python-apt/ubuntu + + +.. highlightlang:: c + +C++ Coding style +---------------- +This document gives coding conventions for the C++ code comprising +the C++ extensions of Python APT. Please see the companion +informational PEP describing style guidelines for Python code (:PEP:`8`). + +Note, rules are there to be broken. Two good reasons to break a +particular rule: + + (1) When applying the rule would make the code less readable, even + for someone who is used to reading code that follows the rules. + + (2) To be consistent with surrounding code that also breaks it + (maybe for historic reasons) -- although this is also an + opportunity to clean up someone else's mess (in true XP style). + +This part of the document is derived from :PEP:`7` which was written by +Guido van Rossum. + + +C++ dialect +^^^^^^^^^^^ + +- Use ISO standard C++ (the 1998 version of the standard). + +- All function declarations and definitions must use full + prototypes (i.e. specify the types of all arguments). + +- Use C++ style // one-line comments where useful. + +- No compiler warnings with ``gcc -std=c++98 -Wall -Wno-write-strings``. There + should also be no errors with ``-pedantic`` added. + + +Code lay-out +^^^^^^^^^^^^ + +- Use 3-space indents, in files that already use them. In new source files, + that were created after this rule was introduced, use 4-space indents. + + At some point, the whole codebase may be converted to use only + 4-space indents. + +- No line should be longer than 79 characters. If this and the + previous rule together don't give you enough room to code, your + code is too complicated -- consider using subroutines. + +- No line should end in whitespace. If you think you need + significant trailing whitespace, think again -- somebody's + editor might delete it as a matter of routine. + +- Function definition style: function name in column 2, outermost + curly braces in column 1, blank line after local variable + declarations:: + + static int extra_ivars(PyTypeObject *type, PyTypeObject *base) + { + int t_size = PyType_BASICSIZE(type); + int b_size = PyType_BASICSIZE(base); + + assert(t_size >= b_size); /* type smaller than base! */ + ... + return 1; + } + +- Code structure: one space between keywords like 'if', 'for' and + the following left paren; no spaces inside the paren; braces as + shown:: + + if (mro != NULL) { + ... + } + else { + ... + } + +- The return statement should *not* get redundant parentheses:: + + return Py_None; /* correct */ + return(Py_None); /* incorrect */ + +- Function and macro call style: ``foo(a, b, c)`` -- no space before + the open paren, no spaces inside the parens, no spaces before + commas, one space after each comma. + +- Always put spaces around assignment, Boolean and comparison + operators. In expressions using a lot of operators, add spaces + around the outermost (lowest-priority) operators. + +- Breaking long lines: if you can, break after commas in the + outermost argument list. Always indent continuation lines + appropriately, e.g.:: + + PyErr_Format(PyExc_TypeError, + "cannot create '%.100s' instances", + type->tp_name); + +- When you break a long expression at a binary operator, the + operator goes at the end of the previous line, e.g.:: + + if (type->tp_dictoffset != 0 && base->tp_dictoffset == 0 && + type->tp_dictoffset == b_size && + (size_t)t_size == b_size + sizeof(PyObject *)) + return 0; /* "Forgive" adding a __dict__ only */ + +- Put blank lines around functions, structure definitions, and + major sections inside functions. + +- Comments go before the code they describe. + +- All functions and global variables should be declared static + unless they are to be part of a published interface + + +Naming conventions +^^^^^^^^^^^^^^^^^^ + +- Use a ``Py`` prefix for public functions; never for static + functions. The ``Py_`` prefix is reserved for global service + routines like ``Py_FatalError``; specific groups of routines + (e.g. specific object type APIs) use a longer prefix, + e.g. ``PyString_`` for string functions. + +- Public functions and variables use MixedCase with underscores, + like this: ``PyObject_GetAttr``, ``Py_BuildValue``, ``PyExc_TypeError``. + +- Internal functions and variables use lowercase with underscores, like + this: ``hashes_get_sha1.`` + +- Occasionally an "internal" function has to be visible to the + loader; we use the _Py prefix for this, e.g.: ``_PyObject_Dump``. + +- Macros should have a MixedCase prefix and then use upper case, + for example: ``PyString_AS_STRING``, ``Py_PRINT_RAW``. + + +Documentation Strings +^^^^^^^^^^^^^^^^^^^^^ +- The first line of each function docstring should be a "signature + line" that gives a brief synopsis of the arguments and return + value. For example:: + + PyDoc_STRVAR(myfunction__doc__, + "myfunction(name: str, value) -> bool\n\n" + "Determine whether name and value make a valid pair."); + + The signature line should be formatted using the format for function + annotations described in :PEP:`3107`, whereas the annotations shall reflect + the name of the type (e.g. ``str``). The leading ``def`` and the trailing + ``:`` as used for function definitions must not be included. + + Always include a blank line between the signature line and the + text of the description. + + If the return value for the function is always ``None`` (because + there is no meaningful return value), do not include the + indication of the return type. + +- When writing multi-line docstrings, be sure to always use + string literal concatenation:: + + PyDoc_STRVAR(myfunction__doc__, + "myfunction(name, value) -> bool\n\n" + "Determine whether name and value make a valid pair."); + + +Python Coding Style +------------------- +The coding style for all code written in python is :PEP:`8`. Exceptions from +this rule are the documentation, where code is sometimes formatted differently +to explain aspects, and functions provided for 0.7 compatibility purposes. + +When writing code, use tools like pylint, pyflakes, pychecker and pep8.py from +http://svn.browsershots.org/trunk/devtools/pep8/ to verify that your code is +OK. Fix all the problems which seem reasonable, and mention the unfixed issues +when asking for merge. + +In order to make the automatic generation of Python 3 code using 2to possible, +code written in Python may not utilize any functionality unsupported by 2to3 or +deprecated as of Python 2.6. + +Submitting your patch +--------------------- +First of all, the patch you create should be based against the most current +branch of python-apt (debian-sid or debian-experimental). If it is a bugfix, +you should probably use debian-sid. If you choose the wrong branch, we will +ask you to rebase your patches against the correct one. + +Once you have made your change, check that it: + + * conforms to :PEP:`8` (checked with pep8.py). It should, at least not + introduce new errors. (and never have whitespace at end of line) + * produces no new errors in pychecker, pyflakes and pylint (unless you + can't fix them, but please tell so when requesting the merge, so it can + be fixed before hitting one of the main branches). + * does not change the behaviour of existing code in a non-compatible way. + +If your change follows all points of the checklist, you can commit it to your +repository. (You could commit it first, and check later, and then commit the +fixes, but commits should be logical and it makes no sense to have to commits +for one logical unit). + +Once you have made all your changes, you can run ``bzr send -o patch-name`` +to create a so called *merge-directive*, which contains your changes and +allows us to preserve the history of your changes. (But please replace patch-name +with something useful). + +Now report a bug against the python-apt package, attach the merge directive +you created in the previous step, and tag it with 'patch'. It might also be +a good idea to prefix the bug report with '[PATCH]'. + +If your patch introduces new functions, parameters, etc. , but does not update +the content of this documentation, please CC. jak@debian.org, and add a short +notice to the bug report. Also see `Documentation updates` + +Once your patch got merged, you can *pull* the branch into which it has been +merged into your local one. If you have made changes since you submitted your +patch, you may need to *merge* the branch instead. + +.. note:: + + If you plan to work on python-apt for a longer time, it may be a good + idea to publish your branch somewhere. Alioth (http://alioth.debian.org) + and Launchpad (https://launchpad.net) provide bzr hosting. You can also + use any webspace with ftp or sftp connection (for the upload). Then you do + not need to send *merge directives*, but you can point to your branch + instead. + + +Documentation updates +--------------------- +If you want to update the documentation, please follow the procedure as written +above. You can send your content in plain text, but reStructuredText is the +preferred format. I (Julian Andres Klode) will review your patch and include +it. + +.. highlightlang:: sh + +Example patch session +---------------------- +In the following example, we edit a file, create a merge directive (an enhanced +patch), and report a wishlist bug with this patch against the python-apt +package:: + + user@pc:~$ bzr clone http://bzr.debian.org/apt/python-apt/debian-sid/ + user@pc:~$ cd debian-sid + user@pc:~/debian-sid$ editor FILES + user@pc:~/debian-sid$ pep8.py FILES # PEP 8 check, see above. + user@pc:~/debian-sid$ pylint -e FILES # Check with pylint + user@pc:~/debian-sid$ pyflakes FILES # Check with pyflakes + user@pc:~/debian-sid$ pychecker FILES # Check with pychecker + user@pc:~/debian-sid$ bzr commit + user@pc:~/debian-sid$ bzr send -o my-patch + user@pc:~/debian-sid$ reportbug --severity=wishlist --tag=patch --attach=my-patch python-apt + user@pc:~/debian-sid$ # Add --list-cc=jak@debian.org if you change docs. diff --git a/doc/source/tutorials/index.rst b/doc/source/tutorials/index.rst new file mode 100644 index 00000000..06d31c6b --- /dev/null +++ b/doc/source/tutorials/index.rst @@ -0,0 +1,8 @@ +Tutorials +========= + +.. toctree:: + :maxdepth: 1 + :glob: + + * diff --git a/doc/source/whatsnew/0.8.0.rst b/doc/source/whatsnew/0.8.0.rst index 244da388..8a2b52e8 100644 --- a/doc/source/whatsnew/0.8.0.rst +++ b/doc/source/whatsnew/0.8.0.rst @@ -78,11 +78,13 @@ Yet another context manager is available for locking the package system:: with apt_pkg.SystemLock(): # do your stuff here + pass -There is also one for file based locking: +There is also one for file based locking:: with apt_pkg.FileLock(filename): # do your stuff here + pass Unification of dependency handling -- cgit v1.2.3 From 0a53a962ea50141dacd09e0e9f6228233c12e1f1 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 24 Jul 2009 21:29:41 +0200 Subject: doc/source/library: Add new classes, fix some issues. --- doc/source/library/apt_inst.rst | 14 +- doc/source/library/apt_pkg.rst | 601 +++++++++++++++++++++++++--------------- 2 files changed, 386 insertions(+), 229 deletions(-) (limited to 'doc/source') diff --git a/doc/source/library/apt_inst.rst b/doc/source/library/apt_inst.rst index eef3db9f..ae26a8a1 100644 --- a/doc/source/library/apt_inst.rst +++ b/doc/source/library/apt_inst.rst @@ -8,7 +8,7 @@ locally available Debian packages (.deb files) and tar files. Checking packages ------------------ -.. function:: arCheckMember(file, membername) +.. function:: ar_check_member(file, membername) Check if the member specified by the parameter *membername* exists in the AR file referenced by the parameter *file*, which may be a @@ -21,7 +21,7 @@ Checking packages Listing contents ----------------- -.. function:: debExtract(file, func, chunk) +.. function:: deb_extract(file, func, chunk) Call the function referenced by *func* for each member of the tar file *chunk* which is contained in the AR file referenced by the parameter @@ -30,14 +30,14 @@ Listing contents An example would be:: - debExtract(open("package.deb"), my_callback, "data.tar.gz") + deb_extract(open("package.deb"), my_callback, "data.tar.gz") See :ref:`emulating-dpkg-contents` for a more detailed example. .. versionchanged:: 0.8.0 Added support for file descriptors and objects implementing a :meth:`fileno` method. -.. function:: tarExtract(file,func,comp) +.. function:: tar_extract(file,func,comp) Call the function *func* for each member of the tar file *file*. @@ -66,7 +66,7 @@ The parameter *name* refers to the name of the member. In case of links, Extracting contents ------------------- -.. function:: debExtractArchive(file, rootdir) +.. function:: deb_extract_archive(file, rootdir) Extract the archive referenced by the :class:`file` object *file* into the directory specified by *rootdir*. @@ -84,7 +84,7 @@ Extracting contents .. versionchanged:: 0.8.0 Added support for file descriptors and objects implementing a :meth:`fileno` method. -.. function:: debExtractControl(file[, member='control']) +.. function:: deb_extract_control(file[, member='control']) Return the indicated file as a string from the control tar. The default is 'control'. @@ -95,7 +95,7 @@ Extracting contents If you want to print the control file of a given package, you could do something like:: - print debExtractControl(open("package.deb")) + print deb_extract_control(open("package.deb")) .. versionchanged:: 0.8.0 Added support for file descriptors and objects implementing a :meth:`fileno` method. diff --git a/doc/source/library/apt_pkg.rst b/doc/source/library/apt_pkg.rst index 6fccc207..ee0c33ef 100644 --- a/doc/source/library/apt_pkg.rst +++ b/doc/source/library/apt_pkg.rst @@ -6,7 +6,6 @@ The apt_pkg extensions provides a more low-level way to work with apt. It can do everything apt can, and is written in C++. It has been in python-apt since the beginning. - Module Initialization --------------------- @@ -23,7 +22,11 @@ be called without having run init*(), but will not return the expected value. .. function:: init - Deprecated function. Use init_config() and init_system() instead. + A short cut to calling :func:`init_config` and :func:`init_system`. You + can use this if you do not use the command line parsing facilities provided + by :func:`parse_commandline`, otherwise call :func:`init_config`, parse + the commandline afterwards and finally call :func:`init_system`. + Working with the cache ---------------------- @@ -38,15 +41,6 @@ Working with the cache Return the :class:`Package()` object for the package name given by *pkgname*. - .. method:: close() - - Close the package cache. - - .. method:: open([progress]) - - Open the package cache again. The parameter *progress* may be set to - an :class:`apt.progress.OpProgress()` object or `None`. - .. method:: update(progress, list) Update the package cache. @@ -62,6 +56,10 @@ Working with the cache The total number of packages available in the cache. + .. attribute:: packages + + A sequence of :class:`Package` objects. + .. attribute:: provides_count The number of provided packages. @@ -122,7 +120,6 @@ Working with the cache version of the :class:`Package` *pkg* to the :class:`Version` *version*. - .. method:: upgrade([dist_upgrade=False]) Perform an upgrade. More detailed, this marks all the upgradable @@ -136,7 +133,7 @@ Working with the cache Fix broken packages. - .. method:: read_pin_file() + .. method:: read_pinfile() Read the policy, eg. /etc/apt/preferences. @@ -148,6 +145,10 @@ Working with the cache .. todo:: Explain better.. + .. method:: mark_auto(pkg) + + Mark the :class:`Package` *pkg* as automatically installed. + .. method:: mark_keep(pkg) Mark the :class:`Package` *pkg* for keep. @@ -247,6 +248,11 @@ Working with the cache The size of the packages which are needed for the changes to be applied. + .. attribute:: policy + + The underlying :class:`Policy` object used by the :class:`DepCache` to + select candidate versions. + .. class:: PackageManager(depcache) @@ -379,84 +385,8 @@ Resolving Dependencies Try to resolve problems only by using keep. -:class:`PackageFile` --------------------- -.. class:: PackageFile - - A :class:`PackageFile` represents a Packages file, eg. - /var/lib/dpkg/status. - - .. attribute:: architecture - - The architecture of the package file. - - .. attribute:: archive - - The archive (eg. unstable) - - .. attribute:: component - - The component (eg. main) - - .. attribute:: filename - - The name of the file. - - .. attribute:: id - - The ID of the package. This is an integer which can be used to store - further information about the file [eg. as dictionary key]. - - .. attribute:: index_type - - The sort of the index file. In normal cases, this is - 'Debian Package Index'. - - .. attribute:: label - - The Label, as set in the Release file - - .. attribute:: not_automatic - - Whether packages from this list will be updated automatically. The - default for eg. example is 0 (aka false). - - .. attribute:: not_source - - Whether the file has no source from which it can be updated. In such a - case, the value is 1; else 0. /var/lib/dpkg/status is 0 for example. - - Example:: - - for pkgfile in cache.file_list: - if pkgfile.not_source: - print 'The file %s has no source.' % pkgfile.filename - - .. attribute:: origin - - The Origin, as set in the Release file - - .. attribute:: site - - The hostname of the site. - - .. attribute:: size - - The size of the file. - - .. attribute:: version - - The version, as set in the release file (eg. "4.0" for "Etch") - - -Example -^^^^^^^ -.. literalinclude:: ../examples/cache-pkgfile.py - - :class:`Package` ----------------- - +^^^^^^^^^^^^^^^^^ .. class:: Package The pkgCache::Package objects are an interface to package specific @@ -520,7 +450,7 @@ Example See :ref:`InstStates` for a list of available states. - .. attribute:: cur_state + .. attribute:: current_state The current state of the package (not installed, unpacked, installed, etc). See :ref:`CurStates` for a list of available states. @@ -541,13 +471,13 @@ Example Whether the package is important. Example: -^^^^^^^^^ +~~~~~~~~~ .. literalinclude:: ../examples/cache-packages.py :class:`Version` ----------------- +^^^^^^^^^^^^^^^^^ .. class:: Version The version object contains all information related to a specific package @@ -576,7 +506,6 @@ Example: A dictionary of dependencies. The key specifies the type of the dependency ('Depends', 'Recommends', etc.). - The value is a list, containing items which refer to the or-groups of dependencies. Each of these or-groups is itself a list, containing tuples like ('pkgname', 'version', 'relation') for each or-choice. @@ -658,7 +587,7 @@ Example: :class:`Dependency` -------------------- +^^^^^^^^^^^^^^^^^^^^ .. class:: Dependency Represent a dependency from one package to another one. @@ -711,7 +640,7 @@ Example: The ID of the package, as integer. Example: Find all missing dependencies -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ With the help of Dependency.AllTargets(), you can easily find all packages with broken dependencies: @@ -719,7 +648,7 @@ broken dependencies: :class:`Description` --------------------- +^^^^^^^^^^^^^^^^^^^^^ .. class:: Description Represent the description of the package. @@ -738,8 +667,9 @@ broken dependencies: -:class:`MetaIndex` ------------------- +Index Files +------------- + .. todo:: @@ -753,9 +683,6 @@ broken dependencies: .. attribute:: index_files -:class:`PackageIndexFile` -------------------------- - .. class:: PackageIndexFile .. method:: archive_uri(path) @@ -766,6 +693,10 @@ broken dependencies: Return the Label. + .. attribute:: describe + + A description of the :class:`PackageIndexFile`. + .. attribute:: exists Return whether the file exists. @@ -783,6 +714,80 @@ broken dependencies: Whether we can trust the file. +.. class:: PackageFile + + A :class:`PackageFile` represents a Packages file, eg. + /var/lib/dpkg/status. + + .. attribute:: architecture + + The architecture of the package file. + + .. attribute:: archive + + The archive (eg. unstable) + + .. attribute:: component + + The component (eg. main) + + .. attribute:: filename + + The name of the file. + + .. attribute:: id + + The ID of the package. This is an integer which can be used to store + further information about the file [eg. as dictionary key]. + + .. attribute:: index_type + + The sort of the index file. In normal cases, this is + 'Debian Package Index'. + + .. attribute:: label + + The Label, as set in the Release file + + .. attribute:: not_automatic + + Whether packages from this list will be updated automatically. The + default for eg. example is 0 (aka false). + + .. attribute:: not_source + + Whether the file has no source from which it can be updated. In such a + case, the value is 1; else 0. /var/lib/dpkg/status is 0 for example. + + Example:: + + for pkgfile in cache.file_list: + if pkgfile.not_source: + print 'The file %s has no source.' % pkgfile.filename + + .. attribute:: origin + + The Origin, as set in the Release file + + .. attribute:: site + + The hostname of the site. + + .. attribute:: size + + The size of the file. + + .. attribute:: version + + The version, as set in the release file (eg. "4.0" for "Etch") + + + +The following example shows how to use PackageFile: + +.. literalinclude:: ../examples/cache-pkgfile.py + + Records -------- @@ -952,53 +957,6 @@ Records and possible keys being ``"Build-Depends"``, ``"Build-Depends-Indep"``, ``"Build-Conflicts"`` or ``"Build-Conflicts-Indep"``. - .. attribute:: BuildDepends - - Return the list of Build dependencies, as - ``(str: package, str: version, int: op, int: type)``. This is a - completely deprecated format - - .. table:: Values of *op* - - ===== ============================================= - Value Meaning - ===== ============================================= - 0x00 No Operation (no versioned build dependency) - 0x10 | (or) - this will be added to the other values - 0x01 <= (less than or equal) - 0x02 >= (greater than or equal) - 0x03 << (less than) - 0x04 >> (greater than) - 0x05 = (equal) - 0x06 != (not equal) - ===== ============================================= - - .. table:: Values of *type* - - ===== =================== - Value Meaning - ===== =================== - 0 Build-Depends - 1 Build-Depends-Indep - 2 Build-Conflicts - 3 Build-Conflicts-Indep - ===== =================== - - **Example**: In the following content, we will imagine a - build-dependency:: - - Build-Depends: A (>= 1) | B (>= 1), C - - This results in:: - - [('A', '1', 18, 0), # 18 = (16 | 2) = (0x10 | 0x2) - ('B', '1', 2, 0), - ('C', '', 0, 0)] - - This is **not** the same as returned by - :func:`apt_pkg.ParseSrcDepends`. - - The Acquire interface ---------------------- @@ -1021,7 +979,7 @@ installation. to this list, you can create new :class:`AcquireFile` objects which allow you to add single files. - Acquire items have multiple methods: + Acquire items have multiple methods and attributes: .. method:: run() @@ -1044,6 +1002,16 @@ installation. Whether some files have been acquired already. (???) + .. attribute:: items + + A list of :class:`AcquireItem` objects which are attached to the + queue of this object. + + .. attribute:: workers + + A list of :class:`AcquireWorker` objects which are currently active + on this instance. + .. class:: AcquireItem The :class:`AcquireItem()` objects represent the items of a @@ -1063,11 +1031,15 @@ installation. Is the item a local file? + .. attribute:: mode + + A string indicating the current mode e.g. ``"Fetching"``. + .. attribute:: is_trusted Can the file be trusted? - .. attribute:: file_size + .. attribute:: filesize The size of the file, in bytes. @@ -1076,7 +1048,7 @@ installation. The error message. For example, when a file does not exist on a http server, this will contain a 404 error message. - .. attribute:: dest_file + .. attribute:: destfile The location the file is saved as. @@ -1110,12 +1082,11 @@ installation. Constant for comparing :attr:`AcquireItem.status` - .. class:: AcquireFile(owner, uri[, md5, size, descr, short_descr, destdir, destfile]) Create a new :class:`AcquireFile()` object and register it with *acquire*, - so it will be fetched. AcquireFile objects provide no methods or attributes - and are completely useless at the moment. + so it will be fetched. You must always keep around a reference to the + object, otherwise it will be removed from the Acquire queue again. The parameter *owner* refers to an :class:`Acquire()` object as returned by :func:`GetAcquire`. The file will be added to the Acquire queue @@ -1138,6 +1109,155 @@ installation. be saved in. Instead of *destdir*, you can also specify the full path to the file using the parameter *destfile*. You can not combine both. + In terms of attributes, this class is a subclass of :class:`AcquireItem` + and thus inherits all its attributes. + +.. class:: AcquireWorker + + An :class:`AcquireWorker` object represents a subprocess responsible for + fetching files from remote locations. This class is not instanciable from + Python. + + .. attribute:: current_item + + The item which is currently being fetched. This returns an + :class:`AcquireItemDesc` object. + + .. attribute:: current_size + + How many bytes of the file have been downloaded. Zero if the current + progress of the file cannot be determined. + + .. attribute:: resumepoint + + The amount of the file that was already downloaded prior to starting + this worker. + + .. attribute:: status + + The most recent status string received from the subprocess. + + .. attribute:: total_size + + The total number of bytes to be downloaded. Zero if the total size is + unknown. + +.. class:: AcquireItemDesc + + An :class:`AcquireItemDesc` object stores information about the item which + can be used to describe the item. + + .. attribute:: description + + The long description given to the item. + + .. attribute:: owner + + The :class:`AcquireItem` object owning this object. + + .. attribute:: shortdesc + + A short description which has been given to this item. + + .. attribute:: uri + + The URI from which to download this item. + +.. class:: AcquireProgress + + A monitor object for downloads controlled by the Acquire class. This is + an mostly abstract class. You should subclass it and implement the + methods to get something useful. + + Methods defined here: + + .. method:: done(item: AcquireItemDesc) + + Invoked when an item is successfully and completely fetched. + + .. method:: fail(item: AcquireItemDesc) + + Invoked when the process of fetching an item encounters a fatal error. + + .. method:: fetch(item: AcquireItemDesc) + + Invoked when some of an item's data is fetched. + + .. method:: ims_hit(item: AcquireItemDesc) + + Invoked when an item is confirmed to be up-to-date. For instance, + when an HTTP download is informed that the file on the server was + not modified. + + .. method:: media_change(media: str, drive: str) -> bool + + Invoked when the user should be prompted to change the inserted + removable media. + + This method should not return until the user has confirmed to the user + interface that the media change is complete. + + The parameter *media* is the name of the media type that should be + changed, the parameter *drive* is the identifying name of the drive + whose media should be changed. + + Return True if the user confirms the media change, False if it is + cancelled. + + .. method:: pulse(owner: Acquire) -> bool + + Periodically invoked while the Acquire process is underway. + + Return False if the user asked to cancel the whole Acquire process. + + .. method:: start() + + Invoked when the Acquire process starts running. + + .. method:: stop() + + Invoked when the Acquire process stops running. + + There are also some data descriptors: + + .. attribute:: current_bytes + + The number of bytes fetched. + + .. attribute:: current_cps + + The current rate of download, in bytes per second. + + .. attribute:: current_items + + The number of items that have been successfully downloaded. + + .. attribute:: elapsed_time + + The amount of time that has elapsed since the download started. + + .. attribute:: fetched_bytes + + The total number of bytes accounted for by items that were + successfully fetched. + + .. attribute:: last_bytes + + The number of bytes fetched as of the previous call to pulse(), + including local items. + + .. attribute:: total_bytes + + The total number of bytes that need to be fetched. This member is + inaccurate, as new items might be enqueued while the download is + in progress! + + .. attribute:: total_items + + The total number of items that need to be fetched. This member is + inaccurate, as new items might be enqueued while the download is + in progress! + Hashes ------ @@ -1145,6 +1265,9 @@ The apt_pkg module also provides several hash functions. If you develop applications with python-apt it is often easier to use these functions instead of the ones provides in Python's :mod:`hashlib` module. +The module provides the two classes :class:`Hashes` and :class:`HashString` for +generic hash support: + .. class:: Hashes(object) Calculate all supported hashes of the object. *object* may either be a @@ -1165,6 +1288,31 @@ of the ones provides in Python's :mod:`hashlib` module. The SHA256 hash of the data, as string. +.. class:: HashString(type: str, hash: str) + + HashString objects store the type of a hash and the corresponding hash. + They are used by e.g :meth:`IndexRecords.lookup`. The first parameter, + *type* refers to one of MD5Sum, SHA1 and SHA256. The second parameter + *hash* is the corresponding hash. + + .. describe:: str(hashstring) + + Convert the HashString to a string by joining the hash type and the + hash using ':', e.g. ``"MD5Sum:d41d8cd98f00b204e9800998ecf8427e"``. + + .. attribute:: hashtype + + The type of the hash. This may be MD5Sum, SHA1 or SHA256. + + .. method:: verify_file(filename: str) -> bool + + Verify that the file given by the parameter *filename* matches the hash + stored in this object. + +The :mod:`apt_pkg` module also provides the functions :func:`md5sum`, +:func:`sha1sum` and :func:`sha256sum` for creating a single hash from a +:class:`bytes` or :class:`file` object: + .. function:: md5sum(object) Return the md5sum of the object. *object* may either be a string, in @@ -1271,12 +1419,6 @@ section as a string. Return the value of the field at the key *key* if available, else return *default*. - .. method:: has_key(key) - - Check whether the field with named by *key* exists. - - .. deprecated:: 0.8.0 - .. method:: keys() Return a list of keys in the section. @@ -1320,6 +1462,9 @@ Dependencies >>> bool(apt_pkg.check_dep("1.0", ">=", "1")) True +The following two functions provide the ability to parse dependencies. They +use the same format as :attr:`Version.depends_list_str`. + .. function:: parse_depends(depends) Parse the string *depends* which contains dependency information as @@ -1373,16 +1518,14 @@ Configuration .. class:: Configuration() - Configuration() objects store the configuration of apt, mostly created from - the contents of :file:`/etc/apt.conf` and the files in + Configuration() objects store the configuration of apt, mostly created + from the contents of :file:`/etc/apt.conf` and the files in :file:`/etc/apt.conf.d`. .. describe:: key in conf Return ``True`` if *conf* has a key *key*, else ``False``. - .. versionadded:: 0.8.0 - .. describe:: conf[key] Return the value of the option given key *key*. If it does not @@ -1463,39 +1606,17 @@ Configuration Return all the keys, recursive. If *key* is specified, ... (FIXME) - .. method:: has_key(key) - - Return whether the configuration contains the key *key*. - - .. deprecated:: 0.8.0 - .. method:: get(key[, default='']) This behaves just like :meth:`dict.get` and :meth:`Configuration.find`, it returns the value of key or if it does not exist, *default*. -.. class:: ConfigurationPtr - - Behaves like a :class:`Configuration()` objects, but uses a pointer to the - underlying C++ object. This is used for the default configuration in the - :data:`Config` attribute of the module. - -.. class:: ConfigurationSub - - Behaves like a :class:`Configuration()` objects, but provides access to - a subsection of another Configuration-like object. This type of object is - returned by the :meth:`Configuration.subtree()` method. - .. data:: config - A :class:`ConfigurationPtr()` object with the default configuration. This + A :class:`Configuration()` object with the default configuration. This object is initialized by calling :func:`init_config`. -Modifying -^^^^^^^^^ - - .. function:: read_config_file(configuration, filename) Read the configuration file specified by the parameter *filename* and add @@ -1518,33 +1639,86 @@ Modifying This function is like getopt except it manipulates a configuration space. output is a list of non-option arguments (filenames, etc). *options* is a - list of tuples of the form ``(‘c’,”long-opt or None”, - ”Configuration::Variable”,”optional type”)``. + list of tuples of the form ``('c',"long-opt or None", + "Configuration::Variable","optional type")``. Where ``type`` may be one of HasArg, IntLevel, Boolean, InvBoolean, ConfigFile, or ArbItem. The default is Boolean. Locking -------- +When working on the global cache, it is important to lock the cache so other +programs do not modify it. This module provides two context managers for +locking the package system or file-based locking. + +.. class:: SystemLock + + Context manager for locking the package system. The lock is established + as soon as the method __enter__() is called. It is released when + __exit__() is called. If the lock can not be acquired or can not be + released an exception is raised. + + This should be used via the 'with' statement, e.g.:: + + with apt_pkg.SystemLock(): + ... # Do your stuff here. + ... # Now it's unlocked again + + Once the block is left, the lock is released automatically. The object + can be used multiple times:: + + lock = apt_pkg.SystemLock() + with lock: + ... + with lock: + ... + +.. class:: FileLock(filename: str) -.. function:: get_lock(filename) + Context manager for locking using a file. The lock is established + as soon as the method __enter__() is called. It is released when + __exit__() is called. If the lock can not be acquired or can not be + released, an exception is raised. + + This should be used via the 'with' statement, e.g.:: + + with apt_pkg.FileLock(filename): + ... + + Once the block is left, the lock is released automatically. The object + can be used multiple times:: + + lock = apt_pkg.FileLock(filename) + with lock: + ... + with lock: + ... + +For Python versions prior to 2.5, similar functionality is provided by the +following three functions: + +.. function:: get_lock(filename, errors=False) -> int Create an empty file at the path specified by the parameter *filename* and - lock it. + lock it. If this fails and *errors* is **True**, the function raises an + error. If *errors* is **False**, the function returns -1. - While the file is locked by a process, calling this function in another - process returns ``-1``. + The lock can be acquired multiple times within the same process, and can be + released by calling :func:`os.close` on the return value which is the file + descriptor of the created file. - When the lock is not required anymore, the file descriptor should be closed - using :func:`os.close`. +.. function:: pkgsystem_lock() -.. function:: pkg_system_lock() + Lock the global pkgsystem. The lock should be released by calling + :func:`pkgsystem_unlock` again. If this function is called n-times, the + :func:`pkgsystem_unlock` function must be called n-times as well to release + all acquired locks. - Lock the global pkgsystem. +.. function:: pkgsystem_unlock() -.. function:: pkg_system_un_lock() + Unlock the global pkgsystem. This reverts the effect of + :func:`pkgsystem_unlock`. - Unlock the global pkgsystem. Other classes -------------- @@ -1580,6 +1754,10 @@ Other classes Add the index files to the :class:`Acquire()` object *acq*. If *all* is given and ``True``, all files are fetched. + .. attribute:: list + + A list of :class:`MetaIndex` objects. + String functions ---------------- .. function:: base64_encode(string) @@ -1589,7 +1767,6 @@ String functions >>> apt_pkg.base64_encode(u"A") 'QQ==' - .. function:: check_domain_list(host, list) See if Host is in a ',' seperated list, e.g.:: @@ -1724,19 +1901,6 @@ Package States .. data:: CURSTATE_NOT_INSTALLED .. data:: CURSTATE_UNPACKED - - - -Dependency types -^^^^^^^^^^^^^^^^ -.. data:: DEP_CONFLICTS -.. data:: DEP_DEPENDS -.. data:: DEP_OBSOLETES -.. data:: DEP_PRE_DEPENDS -.. data:: DEP_RECOMMENDS -.. data:: DEP_REPLACES -.. data:: DEP_SUGGESTS - .. _InstStates: Installed states @@ -1761,7 +1925,7 @@ Priorities Select states ^^^^^^^^^^^^^ -.. data:: SELSTATE_DE_INSTALL +.. data:: SELSTATE_DEINSTALL .. data:: SELSTATE_HOLD .. data:: SELSTATE_INSTALL .. data:: SELSTATE_PURGE @@ -1786,10 +1950,3 @@ Build information .. data:: VERSION The version of apt (not of python-apt). - -.. data:: _COMPAT_0_7 - - A more or less internal variable defining whether this build provides an - API which is compatible to the one of python-apt 0.7. This is used in the - apt and aptsources packages to decide whether compatibility should be - enabled or not. -- cgit v1.2.3 From fbb6facf0135cf9cfde0f24e7beb132cb4d69f33 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 18 Aug 2009 16:45:50 +0200 Subject: doc/source/c++/: Add C++ API documentation (no content yet). --- doc/source/c++/api.rst | 2 ++ doc/source/c++/embedding.rst | 2 ++ doc/source/c++/index.rst | 8 ++++++++ 3 files changed, 12 insertions(+) create mode 100644 doc/source/c++/api.rst create mode 100644 doc/source/c++/embedding.rst create mode 100644 doc/source/c++/index.rst (limited to 'doc/source') diff --git a/doc/source/c++/api.rst b/doc/source/c++/api.rst new file mode 100644 index 00000000..fc1929e4 --- /dev/null +++ b/doc/source/c++/api.rst @@ -0,0 +1,2 @@ +Python APT C++ API +================== diff --git a/doc/source/c++/embedding.rst b/doc/source/c++/embedding.rst new file mode 100644 index 00000000..b6ab265a --- /dev/null +++ b/doc/source/c++/embedding.rst @@ -0,0 +1,2 @@ +Embedding Python APT +==================== diff --git a/doc/source/c++/index.rst b/doc/source/c++/index.rst new file mode 100644 index 00000000..8f598f3f --- /dev/null +++ b/doc/source/c++/index.rst @@ -0,0 +1,8 @@ +Python APT and C++ +================== + +.. toctree:: + :maxdepth: 1 + + api + embedding -- cgit v1.2.3 From 2ccb7545bb8c869f5f6192569a47a7522b6fbc83 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sun, 25 Oct 2009 14:57:38 +0100 Subject: Add a tutorial on how to do things which are possible with apt-get, like apt-get --print-uris update (cf. #551164). --- debian/changelog | 4 ++- doc/source/examples/update-print-uris.py | 22 ++++++++++++++++ doc/source/tutorials/apt-get.rst | 45 ++++++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 doc/source/examples/update-print-uris.py create mode 100644 doc/source/tutorials/apt-get.rst (limited to 'doc/source') diff --git a/debian/changelog b/debian/changelog index 7588d35a..fb3b72f9 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,6 +1,8 @@ -python-apt (0.7.93) experimental; urgency=low +python-apt (0.7.93) UNRELEASED; urgency=low * Merge 0.7.13.0 - 0.7.13.3 from unstable. + * Add a tutorial on how to do things which are possible with apt-get, + like apt-get --print-uris update (cf. #551164). -- Julian Andres Klode Wed, 16 Sep 2009 19:26:17 +0200 diff --git a/doc/source/examples/update-print-uris.py b/doc/source/examples/update-print-uris.py new file mode 100644 index 00000000..f078cdc5 --- /dev/null +++ b/doc/source/examples/update-print-uris.py @@ -0,0 +1,22 @@ +#!/usr/bin/python +"""Print out the URIs of all indexes files. + +This behaves somewhat like apt-get --print-uris update.""" +import apt_pkg + +def main(): + apt_pkg.init_config() + apt_pkg.init_system() + acquire = apt_pkg.Acquire() + slist = apt_pkg.SourceList() + # Read the list + slist.read_main_list() + # Add all indexes to the fetcher. + slist.get_indexes(acquire, True) + + # Now print the URI of every item. + for item in acquire.items: + print item.desc_uri + +if __name__ == '__main__': + main() diff --git a/doc/source/tutorials/apt-get.rst b/doc/source/tutorials/apt-get.rst new file mode 100644 index 00000000..575f0c46 --- /dev/null +++ b/doc/source/tutorials/apt-get.rst @@ -0,0 +1,45 @@ +Doing stuff :command:`apt-get` does +=================================== +:Author: Julian Andres Klode +:Release: |release| +:Date: |today| + +The following article will show how you can use python-apt to do actions done +by the :command:`apt-get` command. + + +Printing the URIs of all index files +------------------------------------ +We all now that we can print the URIs of all our index files by running a +simple ``apt-get -s --print-uris update``. We can do the same. Responsible for +the source entries is the class :class:`apt_pkg.SourceList`, which can be +combined with an :class:`apt_pkg.Acquire` object using :meth:`get_indexes`. + +First of all, we have to create the objects:: + + acquire = apt_pkg.Acquire() + slist = apt_pkg.SourceList() + +Now we have to parse /etc/apt/sources.list and its friends, by using +:meth:`apt_pkg.SourceList.read_main_list`:: + slist.read_main_list() + +Now the **slist** object knows about the location of the indexes. We now have +to load those indexes into the *acquire* object by calling +:meth:`apt_pkg.SourceList.get_indexes`:: + + slist.get_indexes(acquire, True) + +The first argument is the acquire object into which we will load these indexes, +and the second argument means that we want to fetch all indexes. Now the only +thing left to do is iterating over the list of items and printing out their +URIs. Luckily, there is :attr:`apt_pkg.Acquire.items` which allows us to +iterate over the items:: + + for item in acquire.items: + print item.desc_uri + +In the end a program could look like this: + +.. literalinclude:: ../examples/update-print-uris.py + -- cgit v1.2.3 From 6dae07e834445c193f392cf53a252b83c68f2bcd Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 15 Jan 2010 15:42:44 +0100 Subject: Make all class-level constants have uppercase names. --- apt/cache.py | 14 +++++++------- apt/package.py | 4 ++-- apt/progress/base.py | 2 +- apt/progress/text.py | 2 +- debian/changelog | 1 + doc/source/library/apt_pkg.rst | 16 ++++++++-------- python/apt_pkgmodule.cc | 18 +++++++++--------- 7 files changed, 29 insertions(+), 28 deletions(-) (limited to 'doc/source') diff --git a/apt/cache.py b/apt/cache.py index eea06d56..d339f377 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -223,9 +223,9 @@ class Cache(object): transient = False err_msg = "" for item in fetcher.items: - if item.status == item.stat_done: + if item.status == item.STAT_DONE: continue - if item.stat_idle: + if item.STAT_IDLE: transient = True continue err_msg += "Failed to fetch %s %s\n" % (item.desc_uri, @@ -311,7 +311,7 @@ class Cache(object): pulse_interval) if res == apt_pkg.Acquire.result_cancelled and raise_on_error: raise FetchCancelledException() - if res == apt_pkg.Acquire.result_failed and raise_on_error: + if res == apt_pkg.Acquire.RESULT_FAILED and raise_on_error: raise FetchFailedException() else: return res @@ -369,17 +369,17 @@ class Cache(object): # then install res = self.install_archives(pm, install_progress) - if res == pm.result_completed: + if res == pm.RESULT_COMPLETED: break - elif res == pm.result_failed: + elif res == pm.RESULT_FAILED: raise SystemError("installArchives() failed") - elif res == pm.result_incomplete: + elif res == pm.RESULT_INCOMPLETE: pass else: raise SystemError("internal-error: unknown result code from InstallArchives: %s" % res) # reload the fetcher for media swaping fetcher.shutdown() - return (res == pm.result_completed) + return (res == pm.RESULT_COMPLETED) def clear(self): """ Unmark all changes """ diff --git a/apt/package.py b/apt/package.py index 315a7589..8171f57d 100644 --- a/apt/package.py +++ b/apt/package.py @@ -500,7 +500,7 @@ class Version(object): self.size, base, destfile=destfile) acq.run() - if acqfile.status != acqfile.stat_done: + if acqfile.status != acqfile.STAT_DONE: raise FetchError("The item %r could not be fetched: %s" % (acqfile.destfile, acqfile.error_text)) print self._records.filename @@ -548,7 +548,7 @@ class Version(object): acq.run() for item in acq.items: - if item.status != item.stat_done: + if item.status != item.STAT_DONE: raise FetchError("The item %r could not be fetched: %s" % (item.destfile, item.error_text)) diff --git a/apt/progress/base.py b/apt/progress/base.py index fd6bc475..adb39e93 100644 --- a/apt/progress/base.py +++ b/apt/progress/base.py @@ -192,7 +192,7 @@ class InstallProgress(object): os._exit(os.spawnlp(os.P_WAIT, "dpkg", "dpkg", "--status-fd", str(self.writefd.fileno()), "-i", obj)) except Exception: - os._exit(apt_pkg.PackageManager.result_failed) + os._exit(apt_pkg.PackageManager.RESULT_FAILED) self.child_pid = pid res = self.wait_child() diff --git a/apt/progress/text.py b/apt/progress/text.py index 3a6d3e65..796577e2 100644 --- a/apt/progress/text.py +++ b/apt/progress/text.py @@ -125,7 +125,7 @@ class AcquireProgress(base.AcquireProgress, TextProgress): def fail(self, item): """Called when an item is failed.""" base.AcquireProgress.fail(self, item) - if item.owner.status == item.owner.stat_done: + if item.owner.status == item.owner.STAT_DONE: self._write(_("Ign ") + item.description) else: self._write(_("Err ") + item.description) diff --git a/debian/changelog b/debian/changelog index a7204a0a..acd9c3ca 100644 --- a/debian/changelog +++ b/debian/changelog @@ -8,6 +8,7 @@ python-apt (0.7.93) UNRELEASED; urgency=low - Disable 2.6 and 3.1 builds previously available in experimental. * Merge lp:~forest-bond/python-apt/cache-is-virtual-package-catch-key-error - Return False in Cache.is_virtual_package if the package does not exist. + * Make all class-level constants have uppercase names. [ Colin Watson ] * apt/progress/__init__.py: diff --git a/doc/source/library/apt_pkg.rst b/doc/source/library/apt_pkg.rst index 5876fb8d..c3a74267 100644 --- a/doc/source/library/apt_pkg.rst +++ b/doc/source/library/apt_pkg.rst @@ -282,21 +282,21 @@ Working with the cache Fix the installation if a package could not be downloaded. - .. attribute:: result_completed + .. attribute:: RESULT_COMPLETED A constant for checking whether the the result is 'completed'. Compare it against the return value of :meth:`PackageManager.get_archives` or :meth:`PackageManager.do_install`. - .. attribute:: result_failed + .. attribute:: RESULT_FAILED A constant for checking whether the the result is 'failed'. Compare it against the return value of :meth:`PackageManager.get_archives` or :meth:`PackageManager.do_install`. - .. attribute:: result_incomplete + .. attribute:: RESULT_INCOMPLETE A constant for checking whether the the result is 'incomplete'. @@ -1110,23 +1110,23 @@ installation. Integer, representing the status of the item. - .. attribute:: stat_idle + .. attribute:: STAT_IDLE Constant for comparing :attr:`AcquireItem.status`. - .. attribute:: stat_fetching + .. attribute:: STAT_FETCHING Constant for comparing :attr:`AcquireItem.status` - .. attribute:: stat_done + .. attribute:: STAT_DONE Constant for comparing :attr:`AcquireItem.status` - .. attribute:: stat_error + .. attribute:: STAT_ERROR Constant for comparing :attr:`AcquireItem.status` - .. attribute:: stat_auth_error + .. attribute:: STAT_AUTH_ERROR Constant for comparing :attr:`AcquireItem.status` diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index f20b0c87..cdd23705 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -670,7 +670,7 @@ extern "C" void initapt_pkg() Py_BuildValue("i", pkgAcquire::Cancelled)); PyDict_SetItemString(PyAcquire_Type.tp_dict, "result_continue", Py_BuildValue("i", pkgAcquire::Continue)); - PyDict_SetItemString(PyAcquire_Type.tp_dict, "result_failed", + PyDict_SetItemString(PyAcquire_Type.tp_dict, "RESULT_FAILED", Py_BuildValue("i", pkgAcquire::Failed)); #ifdef COMPAT_0_7 PyDict_SetItemString(PyAcquire_Type.tp_dict, "ResultCancelled", @@ -702,11 +702,11 @@ extern "C" void initapt_pkg() // PackageManager constants - PyDict_SetItemString(PyPackageManager_Type.tp_dict, "result_completed", + PyDict_SetItemString(PyPackageManager_Type.tp_dict, "RESULT_COMPLETED", Py_BuildValue("i", pkgPackageManager::Completed)); - PyDict_SetItemString(PyPackageManager_Type.tp_dict, "result_failed", + PyDict_SetItemString(PyPackageManager_Type.tp_dict, "RESULT_FAILED", Py_BuildValue("i", pkgPackageManager::Failed)); - PyDict_SetItemString(PyPackageManager_Type.tp_dict, "result_incomplete", + PyDict_SetItemString(PyPackageManager_Type.tp_dict, "RESULT_INCOMPLETE", Py_BuildValue("i", pkgPackageManager::Incomplete)); #ifdef COMPAT_0_7 @@ -719,15 +719,15 @@ extern "C" void initapt_pkg() #endif // AcquireItem Constants. - PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "stat_idle", + PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "STAT_IDLE", Py_BuildValue("i", pkgAcquire::Item::StatIdle)); - PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "stat_fetching", + PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "STAT_FETCHING", Py_BuildValue("i", pkgAcquire::Item::StatFetching)); - PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "stat_done", + PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "STAT_DONE", Py_BuildValue("i", pkgAcquire::Item::StatDone)); - PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "stat_error", + PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "STAT_ERROR", Py_BuildValue("i", pkgAcquire::Item::StatError)); - PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "stat_auth_error", + PyDict_SetItemString(PyAcquireItem_Type.tp_dict, "STAT_AUTH_ERROR", Py_BuildValue("i", pkgAcquire::Item::StatAuthError)); #ifdef COMPAT_0_7 -- cgit v1.2.3 From 8d1861288d29d2ce7218c19d2dc6ff9ea9726229 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 15 Jan 2010 17:38:22 +0100 Subject: doc/source/library/apt_inst.rst: Update to the new API. --- doc/source/library/apt_inst.rst | 380 ++++++++++++++++++++++++++++++++-------- 1 file changed, 306 insertions(+), 74 deletions(-) (limited to 'doc/source') diff --git a/doc/source/library/apt_inst.rst b/doc/source/library/apt_inst.rst index ae26a8a1..d9403a9e 100644 --- a/doc/source/library/apt_inst.rst +++ b/doc/source/library/apt_inst.rst @@ -2,121 +2,353 @@ ==================================================== .. module:: apt_inst -The :mod:`apt_inst` extension provides access to functions for working with -locally available Debian packages (.deb files) and tar files. +This module provides useful classes and functions to work with archives, +modelled after the :class:`tarfile.TarFile` class. For working with Debian +packages, the :class:`DebFile` class should be used as it provides easy access +to the control.tar.* and data.tar.* members. +The classes are mostly modeled after the :class:`tarfile.TarFile` class and +enhanced with APT-specific methods. Because APT only provides a stream based +view on a tar archive, this module's :class:`TarFile` class only provides a +very small subset of those functions. -Checking packages ------------------- -.. function:: ar_check_member(file, membername) +AR Archives +----------- +.. class:: ArArchive(file) - Check if the member specified by the parameter *membername* exists in - the AR file referenced by the parameter *file*, which may be a - :class:`file()` object, a file descriptor, or anything implementing a - :meth:`fileno` method. + An ArArchive object represents an archive in the 4.4 BSD AR format, + which is used for e.g. deb packages. - .. versionchanged:: 0.8.0 - Added support for file descriptors and objects implementing a :meth:`fileno` method. + The parameter *file* may be a string specifying the path of a file, or + a :class:`file`-like object providing the :meth:`fileno` method. It may + also be an int specifying a file descriptor (returned by e.g. + :func:`os.open`). The recommended way is to pass in the path to the file. + ArArchive (and its subclasses) support the iterator protocol, meaning that + an :class:`ArArchive` object can be iterated over yielding the members in + the archive (same as :meth:`getmembers`). -Listing contents ------------------ -.. function:: deb_extract(file, func, chunk) + .. describe:: archive[key] - Call the function referenced by *func* for each member of the tar file - *chunk* which is contained in the AR file referenced by the parameter - *file*, which may be a :class:`file()` object, a file descriptor, or - anything implementing a :meth:`fileno` method. + Return a ArMember object for the member given by *key*. Raise + LookupError if there is no ArMember with the given name. - An example would be:: + .. describe:: key in archive - deb_extract(open("package.deb"), my_callback, "data.tar.gz") + Return True if a member with the name *key* is found in the archive, it + is the same function as :meth:`getmember`. - See :ref:`emulating-dpkg-contents` for a more detailed example. + .. method:: extract(name[, target: str]) -> bool - .. versionchanged:: 0.8.0 - Added support for file descriptors and objects implementing a :meth:`fileno` method. + Extract the member given by *name* into the directory given by + *target*. If the extraction failed, an error is raised. Otherwise, + the method returns True if the owner could be set or False if the + owner could not be changed. It may also raise LookupError if there + is no member with the given name. -.. function:: tar_extract(file,func,comp) + The parameter *target* is completely optional. If it is not given, the + function extracts into the current directory. - Call the function *func* for each member of the tar file *file*. + .. method:: extractall([target: str]) -> bool - The parameter *comp* is a string determining the compressor used. Possible - options are "lzma", "bzip2" and "gzip". + Extract all into the directory given by target or the current + directory if target is not given. If the extraction failed, an error + is raised. Otherwise, the method returns True if the owner could be + set or False if the owner could not be changed. - The parameter *file* may be a :class:`file()` object, a file descriptor, or - anything implementing a :meth:`fileno` method. + .. method:: extractdata(name: str) -> bytes - .. versionchanged:: 0.8.0 - Added support for file descriptors and objects implementing a :meth:`fileno` method. + Return the contents of the member given by *name*, as a bytes object. + Raise LookupError if there is no ArMember with the given name. + .. method:: getmember(name: str) -> ArMember -Callback -^^^^^^^^^ -Both of these functions expect a callback with the signature -``(what, name, link, mode, uid, gid, size, mtime, major, minor)``. + Return a ArMember object for the member given by *name*. Raise + LookupError if there is no ArMember with the given name. -The parameter *what* describes the type of the member. It can be 'FILE', -'DIR', or 'HARDLINK'. + .. method:: getmembers() -> list -The parameter *name* refers to the name of the member. In case of links, -*link* refers to the target of the link. + Return a list of all members in the AR archive. + .. method:: getnames() -> list -Extracting contents -------------------- + Return a list of the names of all members in the AR archive. -.. function:: deb_extract_archive(file, rootdir) + .. method:: gettar(name: str, comp: str) -> TarFile - Extract the archive referenced by the :class:`file` object *file* - into the directory specified by *rootdir*. + Return a TarFile object for the member given by *name* which will be + decompressed using the compression algorithm given by *comp*. + This is almost equal to:: - The parameter *file* may be a :class:`file()` object, a file descriptor, or - anything implementing a :meth:`fileno` method. + member = arfile.getmember(name) + tarfile = TarFile(file, member.start, member.size, 'gzip')' - See :ref:`emulating-dpkg-extract` for an example. + It just opens a new TarFile on the given position in the stream. - .. warning:: +.. class:: ArMember - If the directory given by *rootdir* does not exist, the package is - extracted into the current directory. + An ArMember object represents a single file within an AR archive. For + Debian packages this can be e.g. control.tar.gz. This class provides + information about this file, such as the mode and size. It has no + constructor. - .. versionchanged:: 0.8.0 - Added support for file descriptors and objects implementing a :meth:`fileno` method. + .. attribute:: gid -.. function:: deb_extract_control(file[, member='control']) + The group id of the owner. - Return the indicated file as a string from the control tar. The default - is 'control'. + .. attribute:: mode - The parameter *file* may be a :class:`file()` object, a file descriptor, or + The mode of the file. + + .. attribute:: mtime + + Last time of modification. + + .. attribute:: name + + The name of the file. + + .. attribute:: size + + The size of the files. + + .. attribute:: start + + The offset in the archive where the file starts. + + .. attribute:: uid + + The user id of the owner. + +Debian Packages +--------------- +.. class:: DebFile(file) + + A DebFile object represents a file in the .deb package format. It inherits + :class:`ArArchive`. In addition to the attributes and methods from + :class:`ArArchive`, DebFile provides the following methods: + + .. attribute:: control + + The :class:`TarFile` object associated with the control.tar.gz member. + + .. attribute:: data + + The :class:`TarFile` object associated with the data.tar.{gz,bz2,lzma} + member. + + .. attribute:: debian_binary + + The package version, as contained in debian-binary. + +Tar Archives +------------- +.. class:: TarFile(file[, min: int, max: int, comp: str]) + + A TarFile object represents a single .tar file stream. + + The parameter *file* may be a string specifying the path of a file, or + a :class:`file`-like object providing the :meth:`fileno` method. It may + also be an int specifying a file descriptor (returned by e.g. + :func:`os.open`). + + The parameter *min* describes the offset in the file where the archive + begins and the parameter *max* is the size of the archive. + + The compression of the archive is set by the parameter *comp*. It can + be set to any program supporting the -d switch, the default being gzip. + + .. method:: extractall([rootdir: str]) -> True + + Extract the archive in the current directory. The argument *rootdir* + can be used to change the target directory. + + .. method:: extractdata(member: str) -> bytes + + Return the contents of the member, as a bytes object. Raise + LookupError if there is no member with the given name. + + .. method:: go(callback: callable[, member: str]) -> True + + Go through the archive and call the callable *callback* for each + member with 2 arguments. The first argument is the :class:`TarMember` + and the second one is the data, as bytes. + + The optional parameter *member* can be used to specify the member for + which call the callback. If not specified, it will be called for all + members. If specified and not found, LookupError will be raised. + +.. class:: TarMember + + Represent a single member of a 'tar' archive. + + This class which has been modelled after :class:`tarfile.TarInfo` + represents information about a given member in an archive. + + .. method:: isblk() + + Determine whether the member is a block device. + + .. method:: ischr() + + Determine whether the member is a character device. + + .. method:: isdev() + + Determine whether the member is a device (block,character or FIFO). + + .. method:: isdir() + + Determine whether the member is a directory. + + .. method:: isfifo() + + Determine whether the member is a FIFO. + + .. method:: isfile() + + Determine whether the member is a regular file. + + .. method:: islnk() + + Determine whether the member is a hardlink. + + .. method:: isreg() + + Determine whether the member is a regular file, same as isfile(). + + .. method:: issym() + + Determine whether the member is a symbolic link. + + .. attribute:: gid + + The owner's group id + + .. attribute:: linkname + + The target of the link. + + .. attribute:: major + + The major ID of the device. + + .. attribute:: minor + + The minor ID of the device. + + .. attribute:: mode + + The mode (permissions). + + .. attribute:: mtime + + Last time of modification. + + .. attribute:: name + + The name of the file. + + .. attribute:: size + + The size of the file. + + .. attribute:: uid + + The owner's user id. + + + +Deprecated functions +--------------------- +The following functions have been shipped in python-apt for a longer time and +are deprecated as of release 0.7.92. They are listed here to help developers +to port their applications to the new API which is completely different. For +this purpose each function documentation includes an example showing how the +function can be replaced. + +.. function:: arCheckMember(file, membername) + + Check if the member specified by the parameter *membername* exists in + the AR file referenced by the parameter *file*, which may be a + :class:`file()` object, a file descriptor, or anything implementing a + :meth:`fileno` method. + + This function has been replaced by using the :keyword:`in` check on an + :class:`ArArchive` object:: + + member in ArArchive(file) + +.. function:: debExtract(file, func, chunk) + + Call the function referenced by *func* for each member of the tar file + *chunk* which is contained in the AR file referenced by the parameter + *file*, which may be a :class:`file()` object, a file descriptor, or anything implementing a :meth:`fileno` method. - If you want to print the control file of a given package, you could do - something like:: + The function *func* is a callback with the signature + ``(what, name, link, mode, uid, gid, size, mtime, major, minor)``. The + parameter *what* describes the type of the member. It can be 'FILE', + 'DIR', or 'HARDLINK'. The parameter *name* refers to the name of the + member. In case of links, *link* refers to the target of the link. - print deb_extract_control(open("package.deb")) + This function is deprecated and has been replaced by the :meth:`TarFile.go` + method. The following example shows the old code and the new code:: - .. versionchanged:: 0.8.0 - Added support for file descriptors and objects implementing a :meth:`fileno` method. + debExtract(open("package.deb"), my_callback, "data.tar.gz") #old + DebFile("package.deb").data.go(my_callback) -.. _emulating-dpkg-extract: + Please note that the signature of the callback is different in + :meth:`TarFile.go`. -Example: Emulating :program:`dpkg` :option:`--extract` -------------------------------------------------------- -Here is a code snippet which emulates dpkg -x. It can be run as -:program:`tool` :option:`pkg.deb` :option:`outdir`. +.. function:: tarExtract(file,func,comp) -.. literalinclude:: ../examples/dpkg-extract.py + Call the function *func* for each member of the tar file *file*. + + The parameter *comp* is a string determining the compressor used. Possible + options are "lzma", "bzip2" and "gzip". The parameter *file* may be + a :class:`file()` object, a file descriptor, or anything implementing + a :meth:`fileno` method. + The function *func* is a callback with the signature + ``(what, name, link, mode, uid, gid, size, mtime, major, minor)``. The + parameter *what* describes the type of the member. It can be 'FILE', + 'DIR', or 'HARDLINK'. The parameter *name* refers to the name of the + member. In case of links, *link* refers to the target of the link. -.. _emulating-dpkg-contents: + This function is deprecated and has been replaced by the :meth:`TarFile.go` + method. The following example shows the old code and the new code:: + + tarExtract(open("archive.tar.gz"), my_callback, "gzip") #old + TarFile("archive.tar.gz", 0, 0, "gzip").go(my_callback) + + Please note that the signature of the callback is different in + :meth:`TarFile.go`. + +.. function:: debExtractArchive(file, rootdir) + + Extract the archive referenced by the :class:`file` object *file* + into the directory specified by *rootdir*. + + The parameter *file* may be a :class:`file()` object, a file descriptor, or + anything implementing a :meth:`fileno` method. + + This function has been replaced by :meth:`TarFile.extractall` and + :attr:`DebFile.data`:: + + debExtractArchive(open("package.deb"), rootdir) # old + DebFile("package.deb").data.extractall(rootdir) # new + +.. function:: debExtractControl(file[, member='control']) + + Return the indicated file as a string from the control tar. The default + is 'control'. The parameter *file* may be a :class:`file()` object, a + file descriptor, or anything implementing a :meth:`fileno` method. -Example: Emulating :program:`dpkg` :option:`--contents` -------------------------------------------------------- -.. literalinclude:: ../examples/dpkg-contents.py + This function has been replaced by :attr:`DebFile.control` and + :meth:`TarFile.extractdata`. In the following example, both commands + return the contents of the control file:: -Example: Emulating :program:`dpkg` :option:`--info` ----------------------------------------------------- -.. literalinclude:: ../examples/dpkg-info.py + debExtractControl(open("package.deb")) + DebFile("package.deb").control.extractdata("control") -- cgit v1.2.3 From c04ba87f403e624005c337f6440e68bbfacc4356 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 15 Jan 2010 17:48:17 +0100 Subject: Change version from 0.8 to 0.7.100 to indicate compatibility. --- doc/source/c++/api.rst | 4 + doc/source/c++/embedding.rst | 3 + doc/source/conf.py | 20 ++-- doc/source/templates/indexcontent.html | 2 +- doc/source/whatsnew/0.7.100.rst | 199 +++++++++++++++++++++++++++++++++ doc/source/whatsnew/0.8.0.rst | 185 ------------------------------ 6 files changed, 216 insertions(+), 197 deletions(-) create mode 100644 doc/source/whatsnew/0.7.100.rst delete mode 100644 doc/source/whatsnew/0.8.0.rst (limited to 'doc/source') diff --git a/doc/source/c++/api.rst b/doc/source/c++/api.rst index fc1929e4..50788a5b 100644 --- a/doc/source/c++/api.rst +++ b/doc/source/c++/api.rst @@ -1,2 +1,6 @@ Python APT C++ API ================== + +.. note:: + + The C++ API is experimental and not really documented yet. diff --git a/doc/source/c++/embedding.rst b/doc/source/c++/embedding.rst index b6ab265a..e5816eb7 100644 --- a/doc/source/c++/embedding.rst +++ b/doc/source/c++/embedding.rst @@ -1,2 +1,5 @@ Embedding Python APT ==================== +.. note:: + + The C++ API is experimental and not really documented yet. diff --git a/doc/source/conf.py b/doc/source/conf.py index 0a9d5ed5..85ce61d8 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -19,17 +19,11 @@ import os import glob import sys -# If your extensions are in another directory, add it here. If the directory -# is relative to the documentation root, use os.path.abspath to make it -# absolute, like shown here. -sys.path.insert(0, os.path.abspath('..')) -sys.path.insert(0, os.path.abspath('../..')) - # Find the path to the built apt_pkg and apt_inst extensions if os.path.exists("../../build"): version = '.'.join(str(x) for x in sys.version_info[:2]) for apt_pkg_path in glob.glob('../../build/lib*%s/apt_pkg.so' % version): - sys.path.insert(0, os.path.dirname(apt_pkg_path)) + sys.path.insert(0, os.path.abspath(os.path.dirname(apt_pkg_path))) try: import apt_pkg except ImportError, exc: @@ -67,7 +61,7 @@ source_suffix = '.rst' # General information about the project. project = u'python-apt' -copyright = u'2009, Julian Andres Klode ' +copyright = u'2009-2010, Julian Andres Klode ' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -83,11 +77,15 @@ except KeyError: p2 = Popen(["sed", "-n", 's/^Version: //p'], stdin=p1.stdout, stdout=PIPE) release = p2.communicate()[0] -# Handle the alpha release scheme. +# Handle the alpha release scheme if int(release.split("~")[0].split(".")[2]) >= 90: version_s = release.split("~")[0].split(".")[:3] - version_s[1] = str(int(version_s[1]) + 1) - version_s[2] = "0" + # Set the version to 0.X.100 if the release is 0.X.9Y (0.7.90 => 0.7.100) + # Use + # version_s[1] = str(int(version_s[1]) + 1) + # version_s[2] = "0" + # if the version of a 0.X.9Y release should be 0.X+1.0 (0.7.90=>0.8) + version_s[2] = "100" version = '.'.join(version_s) del version_s else: diff --git a/doc/source/templates/indexcontent.html b/doc/source/templates/indexcontent.html index e5f11cc1..394b46d5 100644 --- a/doc/source/templates/indexcontent.html +++ b/doc/source/templates/indexcontent.html @@ -18,7 +18,7 @@

    Parts of the documentation:

    - diff --git a/doc/source/whatsnew/0.7.100.rst b/doc/source/whatsnew/0.7.100.rst new file mode 100644 index 00000000..110336a3 --- /dev/null +++ b/doc/source/whatsnew/0.7.100.rst @@ -0,0 +1,199 @@ +What's New In python-apt 0.7.100 +================================ +Python-apt 0.7.100 is a new major release of the python bindings for the APT +package management libraries. It provides support for Python 3, new language +features and an API conforming to :PEP:`8`. + +Despite the many changes made in python-apt 0.7.100, the release still provides +backwards compatibility to the 0.7 series. This makes it possible to run your +old applications. + +.. note:: + + Applications using the old API should be updated to the new API because + the old ones will be dropped in the 0.8 release. To build a python-apt + variant without the deprecated API, build it without the -DCOMPAT_0_7 + compiler flag. + +Support for Python 3 +-------------------- +Python-apt is the first Debian package to support the third major release of +Python. The port is straight forward and integrates as nicely in Python 3 as +the Python 2 builds integrate in Python 2. + +Please be aware that python-apt builds for Python 3 are built without the +compatibility options enabled for Python 2 builds. They also do not provide +methods like :meth:`has_key` on mapping objects, because it has been removed +in Python 3. + +Python 3 support may be disabled by distributions. + +Real classes in :mod:`apt_pkg` +------------------------------ +The 0.7.100 release introduces real classes in the :mod:`apt_pkg` extension. This +is an important step forward and makes writing code much easier, because you +can see the classes without having to create an object first. It also makes +it easier to talk about those classes, because they have a real name now. + +The 0.7 series shipped many functions for creating new objects, because the +classes were not exported. In 0.7.100, the classes themselves replace those +functions, as you can see in the following table. + +.. table:: + + ===================================== ================================= + Function Replacing class + ===================================== ================================= + :func:`apt_pkg.GetAcquire` :class:`apt_pkg.Acquire` + :func:`apt_pkg.GetCache()` :class:`apt_pkg.Cache` + :func:`apt_pkg.GetCdrom()` :class:`apt_pkg.Cdrom` + :func:`apt_pkg.GetDepCache()` :class:`apt_pkg.DepCache` + :func:`apt_pkg.GetPackageManager` :class:`apt_pkg.PackageManager` + :func:`apt_pkg.GetPkgAcqFile` :class:`apt_pkg.AcquireFile` + :func:`apt_pkg.GetPkgActionGroup` :class:`apt_pkg.ActionGroup` + :func:`apt_pkg.GetPkgProblemResolver` :class:`apt_pkg.ProblemResolver` + :func:`apt_pkg.GetPkgRecords` :class:`apt_pkg.PackageRecords` + :func:`apt_pkg.GetPkgSourceList` :class:`apt_pkg.SourceList` + :func:`apt_pkg.GetPkgSrcRecords` :class:`apt_pkg.SourceRecords` + :func:`apt_pkg.ParseSection` :class:`apt_pkg.TagSection` + :func:`apt_pkg.ParseTagFile` :class:`apt_pkg.TagFile` + ===================================== ================================= + +Complete rename of functions, methods and attributes +----------------------------------------------------- +In May 2008, Ben Finney reported bug 481061 against the python-apt package, +asking for PEP8 conformant names. With the release of python-apt 0.7.100, this +is finally happening. + +Context managers for the :keyword:`with` statement +-------------------------------------------------- +This is not a real big change, but it's good to have it: +:class:`apt_pkg.ActionGroup` can now be used as a context manager for the +:keyword:`with` statement. This makes it more obvious that you are using an +action group, and is just cooler:: + + with apt_pkg.ActionGroup(depcache): + for package in my_selected_packages: + depcache.mark_install(package) + +This also works for :class:`apt.Cache`:: + + with cache.actiongroup(): # cache is an Instance of apt.Cache + for package in my_selected_packages: + package.mark_install() # Instance of apt.Package + +Yet another context manager is available for locking the package system:: + + with apt_pkg.SystemLock(): + # do your stuff here + pass + +There is also one for file based locking:: + + with apt_pkg.FileLock(filename): + # do your stuff here + pass + + +Unification of dependency handling +---------------------------------- +In apt 0.7.XX, there were three different return types of functions parsing +dependencies. + +First of all, there were :func:`apt_pkg.ParseDepends()` and +:func:`apt_pkg.ParseSrcDepends()` which returned a list of or groups (which +are lists themselves) which contain tuples in the format ``(package,ver,op)``, +whereas op is one of "<=",">=","<<",">>","=","!=". + +Secondly, there was Package.DependsListStr which returned a dictionary mapping +the type of the dependency (e.g. 'Depends', 'Recommends') to a list similar to +those of :func:`apt_pkg.ParseDepends()`. The only difference was that the +values ">>", "<<" of op are ">", "<" instead. + +Thirdly, there was SourceRecords.BuildDepends, which returned a simple list +of tuples in the format ``(package, version, op, type)``, whereas ``op`` was +the integer representation of those ">>", "<<" actions and ``type`` an integer +representing the type of the dependency (e.g. 'Build-Depends'). The whole +format was almost useless from the Python perspective because the string +representations or constants for checking the values were not exported. + +python-apt 0.7.100 puts an end to this confusion and uses one basic format, which +is the format known from Package.DependsListStr. The format change only applies +to the new functions and attributes, i.e. :attr:`SourceRecords.build_depends` +will now return a dict, whereas :attr:`SourceRecords.BuildDepends` will still +return the classic format. The functions :func:`apt_pkg.parse_depends` and +:func:`apt_pkg.parse_src_depends` now use the same values for ``op`` as +:attr:`Package.DependsListStr` does. + +Example:: + + >>> s = apt_pkg.SourceRecords() + >>> s.lookup("apt") + 1 + >>> s.build_depends + {'Build-Depends': [[('debhelper', '5.0', '>=')], + [('libdb-dev', '', '')], + [('gettext', '0.12', '>=')], + [('libcurl4-gnutls-dev', '', ''), + ('libcurl3-gnutls-dev', '7.15.5', '>=')], + [('debiandoc-sgml', '', '')], + [('docbook-utils', '0.6.12', '>=')], + [('xsltproc', '', '')], + [('docbook-xsl', '', '')], + [('xmlto', '', '')]]} + >>> s.BuildDepends + [('debhelper', '5.0', 2, 0), + ('libdb-dev', '', 0, 0), + ('gettext', '0.12', 2, 0), + ('libcurl4-gnutls-dev', '', 16, 0), + ('libcurl3-gnutls-dev', '7.15.5', 2, 0), + ('debiandoc-sgml', '', 0, 0), + ('docbook-utils', '0.6.12', 2, 0), + ('xsltproc', '', 0, 0), + ('docbook-xsl', '', 0, 0), + ('xmlto', '', 0, 0)] + +C++ headers +------------ +The 0.7.100 release introduces python-apt-dev which provides headers for +developers to provide Python support in the libapt-pkg-using application. + +.. warning:: + + As of 0.7.93, those headers are still considered experimental and their + API may change without prior notice. + +Other changes +------------- +This release of python-apt also features several other, smaller changes: + + * Reduced memory usage by making :class:`apt.Cache` create + :class:`apt.Package()` object dynamically, instead of creating all of + them during the cache initialization. + * Support to set the candidate version in :class:`apt.package.Package` + +Porting your applications to python-apt 0.8 API +------------------------------------------------ +Porting your application to the new python-apt 0.8 API may be trivial. You +should download the source tarball of python-apt and run the tool +utils/migrate-0.8 using Python 2.6 over your code:: + + python2.6 utils/migrate-0.8.py -c myapp.py mypackage/ + +This will search your code for places where possibly deprecated names are +used. Using the argument ``-c``, you can turn colorized output on. + +Now that you know which parts of your code have to be changed, you have to know +how to do this. For classes, please look at the table. For all attributes, +methods, functions, and their parameters the following rules apply: + + 1. Replace leading [A-Z] with [a-z] (e.g DescURI => descURI) + 2. Replace multiple [A-Z] with [A-Z][a-z] (e.g. descURI => descUri) + 3. Replace every [A-Z] with the corresponding [a-z] (descUri => desc_uri) + +As an exception, refixes such as 'de' (e.g. 'dequote') or 'un' (e.g. 'unlock') +are normally not seperated by underscores from the next word. There are also +some other exceptions which are listed here, and apply to any name containing +this word: **filename**, **filesize**, **destdir**, **destfile**, **dequote**, +**unlock**, **reinstall**, **pinfile**, **REINSTREQ**, **UNPACKED**, +**parse_commandline**. diff --git a/doc/source/whatsnew/0.8.0.rst b/doc/source/whatsnew/0.8.0.rst deleted file mode 100644 index 8a2b52e8..00000000 --- a/doc/source/whatsnew/0.8.0.rst +++ /dev/null @@ -1,185 +0,0 @@ -What's New In python-apt 0.8 -============================ -Python-apt 0.8 is a new major release of the python bindings for the APT -package management libraries. It provides support for Python 3, new language -features and an API conforming to :PEP:`8`. - -Despite the many changes made in python-apt 0.8, the release still provides -backwards compatibility to the 0.7 series. This makes it possible to run your -old applications. Applications using the old API should be updated to the new -API, because the old one will be removed after some time. - -Support for Python 3 --------------------- -Python-apt is the first Debian package to support the third major release of -Python. The port is straight forward and integrates as nicely in Python 3 as -the Python 2 builds integrate in Python 2. - -Please be aware that python-apt builds for Python 3 are built without the -compatibility options enabled for Python 2 builds. They also do not provide -methods like :meth:`has_key` on mapping objects, because it has been removed -in Python 3. - -Real classes in :mod:`apt_pkg` ------------------------------- -The 0.8 release introduces real classes in the :mod:`apt_pkg` extension. This -is an important step forward and makes writing code much easier, because you -can see the classes without having to create an object first. It also makes -it easier to talk about those classes, because they have a real name now. - -The 0.7 series shipped many functions for creating new objects, because the -classes were not exported. In 0.8, the classes themselves replace those -functions, as you can see in the following table. - -.. table:: - - ===================================== ================================= - Function Replacing class - ===================================== ================================= - :func:`apt_pkg.GetAcquire` :class:`apt_pkg.Acquire` - :func:`apt_pkg.GetCache()` :class:`apt_pkg.Cache` - :func:`apt_pkg.GetCdrom()` :class:`apt_pkg.Cdrom` - :func:`apt_pkg.GetDepCache()` :class:`apt_pkg.DepCache` - :func:`apt_pkg.GetPackageManager` :class:`apt_pkg.PackageManager` - :func:`apt_pkg.GetPkgAcqFile` :class:`apt_pkg.AcquireFile` - :func:`apt_pkg.GetPkgActionGroup` :class:`apt_pkg.ActionGroup` - :func:`apt_pkg.GetPkgProblemResolver` :class:`apt_pkg.ProblemResolver` - :func:`apt_pkg.GetPkgRecords` :class:`apt_pkg.PackageRecords` - :func:`apt_pkg.GetPkgSourceList` :class:`apt_pkg.SourceList` - :func:`apt_pkg.GetPkgSrcRecords` :class:`apt_pkg.SourceRecords` - :func:`apt_pkg.ParseSection` :class:`apt_pkg.TagSection` - :func:`apt_pkg.ParseTagFile` :class:`apt_pkg.TagFile` - ===================================== ================================= - -Complete rename of functions, methods and attributes ------------------------------------------------------ -In May 2008, Ben Finney reported bug 481061 against the python-apt package, -asking for PEP8 conformant names. With the release of python-apt 0.8, this -is finally happening. - -Context managers for the :keyword:`with` statement --------------------------------------------------- -This is not a real big change, but it's good to have it: -:class:`apt_pkg.ActionGroup` can now be used as a context manager for the -:keyword:`with` statement. This makes it more obvious that you are using an -action group, and is just cooler:: - - with apt_pkg.ActionGroup(depcache): - for package in my_selected_packages: - depcache.mark_install(package) - -This also works for :class:`apt.Cache`:: - - with cache.actiongroup(): # cache is an Instance of apt.Cache - for package in my_selected_packages: - package.mark_install() # Instance of apt.Package - -Yet another context manager is available for locking the package system:: - - with apt_pkg.SystemLock(): - # do your stuff here - pass - -There is also one for file based locking:: - - with apt_pkg.FileLock(filename): - # do your stuff here - pass - - -Unification of dependency handling ----------------------------------- -In apt 0.7, there were three different return types of functions parsing -dependencies. - -First of all, there were :func:`apt_pkg.ParseDepends()` and -:func:`apt_pkg.ParseSrcDepends()` which returned a list of or groups (which -are lists themselves) which contain tuples in the format ``(package,ver,op)``, -whereas op is one of "<=",">=","<<",">>","=","!=". - -Secondly, there was Package.DependsListStr which returned a dictionary mapping -the type of the dependency (e.g. 'Depends', 'Recommends') to a list similar to -those of :func:`apt_pkg.ParseDepends()`. The only difference was that the -values ">>", "<<" of op are ">", "<" instead. - -Thirdly, there was SourceRecords.BuildDepends, which returned a simple list -of tuples in the format ``(package, version, op, type)``, whereas ``op`` was -the integer representation of those ">>", "<<" actions and ``type`` an integer -representing the type of the dependency (e.g. 'Build-Depends'). The whole -format was almost useless from the Python perspective because the string -representations or constants for checking the values were not exported. - -python-apt 0.8 puts an end to this confusion and uses one basic format, which -is the format known from Package.DependsListStr. The format change only applies -to the new functions and attributes, i.e. :attr:`SourceRecords.build_depends` -will now return a dict, whereas :attr:`SourceRecords.BuildDepends` will still -return the classic format. The functions :func:`apt_pkg.parse_depends` and -:func:`apt_pkg.parse_src_depends` now use the same values for ``op`` as -:attr:`Package.DependsListStr` does. - -Example:: - - >>> s = apt_pkg.SourceRecords() - >>> s.lookup("apt") - 1 - >>> s.build_depends - {'Build-Depends': [[('debhelper', '5.0', '>=')], - [('libdb-dev', '', '')], - [('gettext', '0.12', '>=')], - [('libcurl4-gnutls-dev', '', ''), - ('libcurl3-gnutls-dev', '7.15.5', '>=')], - [('debiandoc-sgml', '', '')], - [('docbook-utils', '0.6.12', '>=')], - [('xsltproc', '', '')], - [('docbook-xsl', '', '')], - [('xmlto', '', '')]]} - >>> s.BuildDepends - [('debhelper', '5.0', 2, 0), - ('libdb-dev', '', 0, 0), - ('gettext', '0.12', 2, 0), - ('libcurl4-gnutls-dev', '', 16, 0), - ('libcurl3-gnutls-dev', '7.15.5', 2, 0), - ('debiandoc-sgml', '', 0, 0), - ('docbook-utils', '0.6.12', 2, 0), - ('xsltproc', '', 0, 0), - ('docbook-xsl', '', 0, 0), - ('xmlto', '', 0, 0)] - - - - - -Other changes -------------- -This release of python-apt also features several other, smaller changes: - - * Reduced memory usage by making :class:`apt.Cache` create - :class:`apt.Package()` object dynamically, instead of creating all of - them during the cache initialization. - * Support to set the candidate version in :class:`apt.package.Package` - -Porting your applications to python-apt 0.8 -------------------------------------------- -Porting your application to python-apt 0.8 may be trivial. You should download -the source tarball of python-apt and run the tool utils/migrate-0.8 using -Python 2.6 over your code:: - - python2.6 utils/migrate-0.8.py -c myapp.py mypackage/ - -This will search your code for places where possibly deprecated names are -used. Using the argument ``-c``, you can turn colorized output on. - -Now that you know which parts of your code have to be changed, you have to know -how to do this. For classes, please look at the table. For all attributes, -methods, functions, and their parameters the following rules apply: - - 1. Replace leading [A-Z] with [a-z] (e.g DescURI => descURI) - 2. Replace multiple [A-Z] with [A-Z][a-z] (e.g. descURI => descUri) - 3. Replace every [A-Z] with the corresponding [a-z] (descUri => desc_uri) - -As an exception, refixes such as 'de' (e.g. 'dequote') or 'un' (e.g. 'unlock') -are normally not seperated by underscores from the next word. There are also -some other exceptions which are listed here, and apply to any name containing -this word: **filename**, **filesize**, **destdir**, **destfile**, **dequote**, -**unlock**, **reinstall**, **pinfile**, **REINSTREQ**, **UNPACKED**, -**parse_commandline**. -- cgit v1.2.3 From 6caa1261cfa8dd971111f1e8e4af73437c99c7b6 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 15 Jan 2010 17:56:22 +0100 Subject: fix typo --- doc/source/tutorials/apt-cdrom.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'doc/source') diff --git a/doc/source/tutorials/apt-cdrom.rst b/doc/source/tutorials/apt-cdrom.rst index c66d49f7..0561e082 100644 --- a/doc/source/tutorials/apt-cdrom.rst +++ b/doc/source/tutorials/apt-cdrom.rst @@ -46,7 +46,7 @@ CD-ROMs:: elif sys.argv[1] == 'ident': cdrom.ident() -Advcaned example with command-line parsing +Advanced example with command-line parsing ------------------------------------------- Our example clearly misses a way to parse the commandline in a correct manner. Luckily, :mod:`apt_pkg` provides us with a function to do this: -- cgit v1.2.3 From 4f3788456a453c132c130f9beb570bbe33c47904 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 15 Jan 2010 18:47:00 +0100 Subject: doc/source/conf.py: Fix documentation in debugging variants of Python. --- doc/source/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'doc/source') diff --git a/doc/source/conf.py b/doc/source/conf.py index 85ce61d8..5f82d5eb 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -22,7 +22,7 @@ import sys # Find the path to the built apt_pkg and apt_inst extensions if os.path.exists("../../build"): version = '.'.join(str(x) for x in sys.version_info[:2]) - for apt_pkg_path in glob.glob('../../build/lib*%s/apt_pkg.so' % version): + for apt_pkg_path in glob.glob('../../build/lib*%s/*.so' % version): sys.path.insert(0, os.path.abspath(os.path.dirname(apt_pkg_path))) try: import apt_pkg -- cgit v1.2.3 From 34b01eb60ec315bc542d0cad7239091219a8388c Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Fri, 15 Jan 2010 19:09:10 +0100 Subject: Rewrite apt.progress.gtk2 documentation by hand and drop python-gtk2 build-time dependency. --- debian/changelog | 2 + debian/control | 4 +- doc/source/library/apt.progress.gtk2.rst | 128 +++++++++++++++++++++++++++---- 3 files changed, 118 insertions(+), 16 deletions(-) (limited to 'doc/source') diff --git a/debian/changelog b/debian/changelog index 35a949db..c2b8d7e6 100644 --- a/debian/changelog +++ b/debian/changelog @@ -9,6 +9,8 @@ python-apt (0.7.93) UNRELEASED; urgency=low * Merge lp:~forest-bond/python-apt/cache-is-virtual-package-catch-key-error - Return False in Cache.is_virtual_package if the package does not exist. * Make all class-level constants have uppercase names. + * Rewrite apt.progress.gtk2 documentation by hand and drop python-gtk2 + build-time dependency. [ Colin Watson ] * apt/progress/__init__.py: diff --git a/debian/control b/debian/control index 3554942a..294deb1a 100644 --- a/debian/control +++ b/debian/control @@ -12,9 +12,7 @@ Build-Depends: apt-utils, python-all-dev, python-central (>= 0.5), python-distutils-extra (>= 2.0), - python-gtk2 [!kfreebsd-amd64 !kfreebsd-i386], - python-sphinx (>= 0.5), - python-vte [!kfreebsd-amd64 !kfreebsd-i386] + python-sphinx (>= 0.5) Vcs-Bzr: http://bzr.debian.org/apt/python-apt/debian-sid Vcs-Browser: http://bzr.debian.org/loggerhead/apt/python-apt/debian-sid/changes diff --git a/doc/source/library/apt.progress.gtk2.rst b/doc/source/library/apt.progress.gtk2.rst index b16c903c..6c00e731 100644 --- a/doc/source/library/apt.progress.gtk2.rst +++ b/doc/source/library/apt.progress.gtk2.rst @@ -1,27 +1,129 @@ :mod:`apt.progress.gtk2` --- Progress reporting for GTK+ interfaces =================================================================== -.. automodule:: apt.progress.gtk2 +.. module:: apt.progress.gtk2 + +The :mod:`apt.progress.gtk2` module provides classes with GObject signals and +a class with a GTK+ widget for progress handling. GObject progress classes ------------------------- +.. class:: GInstallProgress + + An implementation of :class:`apt.progress.base.InstallProgress` supporting + GObject signals. The class emits the following signals: + + .. describe:: status-changed(status: str, percent: int) + + Emitted when the status of an operation changed. + + .. describe:: status-started() + + Emitted when the installation started. + + .. describe:: status-finished() + + Emitted when the installation finished. + + .. describe:: status-timeout() + + Emitted when a timeout happens + + .. describe:: status-error() + + Emitted in case of an error. + + .. describe:: status-conffile() + + Emitted when a conffile update is happening. + + +.. class:: GFetchProgress + + An implementation of :class:`apt.progress.old.FetchProgress` supporting + GObject signals. The class emits the following signals: + + .. describe:: status-changed(description: str, percent: int) + + Emitted when the status of the fetcher changed, e.g. when the + percentage increased. + + .. describe:: status-started() + + Emitted when the fetcher starts to fetch. + + .. describe:: status-finished() + + Emitted when the fetcher finished. + + +.. class:: GDpkgInstallProgress + + An implementation of :class:`apt.progress.base.InstallProgress` supporting + GObject signals. This is the same as :class:`GInstallProgress` and is thus + completely deprecated. + +.. class:: GOpProgress + + An implementation of :class:`apt.progress.old.FetchProgress` supporting + GObject signals. The class emits the following signals: + + .. describe:: status-changed(operation: str, percent: int) + + Emitted when the status of an operation changed. + + .. describe:: status-started() + + Emitted when it starts - Not implemented yet. + + .. describe:: status-finished() + + Emitted when all operations have finished. + +GTK+ Widget +----------- +.. class:: GtkAptProgress + + Graphical progress for installation/fetch/operations, providing + a progress bar, a terminal and a status bar for showing the progress + of package manipulation tasks. + + .. method:: cancel_download() + + Cancel a currently running download. + + .. method:: clear() + + Reset all status information. + + .. attribute:: dpkg_install + + Return the install progress handler for dpkg. + + .. attribute:: fetch + + Return the fetch progress handler. + + .. method:: hide_terminal() -.. autoclass:: GDpkgInstallProgress - :members: + Hide the expander with the terminal widget. -.. autoclass:: GFetchProgress - :members: + .. attribute:: install + + Return the install progress handler. -.. autoclass:: GInstallProgress - :members: + .. attribute:: open -.. autoclass:: GOpProgress - :members: + Return the cache opening progress handler. + + .. method:: show() + + Show the Box -GTK+ Class ----------- -.. autoclass:: GtkAptProgress - :members: + .. method:: show_terminal(expanded=False) + + Show an expander with a terminal widget which provides a way to + interact with dpkg. Example -- cgit v1.2.3 From 9e02af1e9a2509f4c443d5dba21a80ef935f479c Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 20 Jan 2010 14:58:56 +0100 Subject: doc/source/library/apt.progress.base.rst: Document Progress classes. --- doc/source/library/apt.progress.base.rst | 335 +++++++++++++++++++++++++++++++ doc/source/library/index.rst | 1 + 2 files changed, 336 insertions(+) create mode 100644 doc/source/library/apt.progress.base.rst (limited to 'doc/source') diff --git a/doc/source/library/apt.progress.base.rst b/doc/source/library/apt.progress.base.rst new file mode 100644 index 00000000..3fd2a7a0 --- /dev/null +++ b/doc/source/library/apt.progress.base.rst @@ -0,0 +1,335 @@ +:mod:`apt.progress.base` --- Abstract classes for progress reporting +==================================================================== +.. module:: apt.progress.base + +This module provides base classes for progress handlers from which all +progress classes should inherit from. Progress reporting classes not +inheriting from those classes may not work and are not supported. + +When creating a subclass of one of those classes, all overridden methods should +call the parent's method first before doing anything else, because the parent +method may have to set some attributes. Subclasses not doing so may not work +correctly or may not work at all and are completely unsupported. + +AcquireProgress +--------------- +.. class:: AcquireProgress + + A monitor object for downloads controlled by the Acquire class. This base + class does nothing and should only be used as a base class to inherit + from. Instances of this class can be passed to the constructor of + :class:`apt_pkg.Acquire` and the Acquire object then uses it to report + its progress. + + This class provides several methods which may be overridden by subclasses + to implement progress reporting: + + .. method:: done(item: apt_pkg.AcquireItemDesc) + + Invoked when an item is successfully and completely fetched. + + .. method:: fail(item: apt_pkg.AcquireItemDesc) + + Invoked when the process of fetching an item encounters a fatal error + like a non existing file or no connection to the server. + + .. method:: fetch(item: apt_pkg.AcquireItemDesc) + + Invoked when some of the item's data is fetched. This normally means + that the file is being fetched now and e.g. the headers have been + retrieved already. + + .. method:: ims_hit(item: apt_pkg.AcquireItemDesc) + + Invoked when an item is confirmed to be up-to-date. For instance, + when an HTTP download is informed that the file on the server was + not modified. + + .. method:: media_change(media: str, drive: str) -> bool + + Prompt the user to change the inserted removable media. This function + is called whenever a media change is needed to ask the user to insert + the needed media. + + The parameter *media* decribes the name of the the media type that + should be changed, whereas the parameter *drive* should be the + identifying name of the drive whose media should be changed. + + This method should not return until the user has confirmed to the user + interface that the media change is complete. It must return True if + the user confirms the media change, or False to cancel it. + + .. method:: pulse(owner: apt_pkg.Acquire) -> bool + + This method gets invoked while the Acquire progress given by the + parameter *owner* is underway. It should display information about + the current state. It must return ``True`` to continue the acquistion + or ``False`` to cancel it. This base implementation always returns + ``True``. + + .. method:: start() + + Invoked when the Acquire process starts running. + + .. method:: stop() + + Invoked when the Acquire process stops running. + + In addition to those methods, this class provides several attributes which + are set automatically and represent the fetch progress: + + .. attribute:: current_bytes + + The number of bytes fetched. + + .. attribute:: current_cps + + The current rate of download, in bytes per second. + + .. attribute:: current_items + + The number of items that have been successfully downloaded. + + .. attribute:: elapsed_time + + The amount of time that has elapsed since the download started. + + .. attribute:: fetched_bytes + + The total number of bytes accounted for by items that were + successfully fetched. + + .. attribute:: last_bytes + + The number of bytes fetched as of the previous call to pulse(), + including local items. + + .. attribute:: total_bytes + + The total number of bytes that need to be fetched. This member is + inaccurate, as new items might be enqueued while the download is + in progress! + + .. attribute:: total_items + + The total number of items that need to be fetched. This member is + inaccurate, as new items might be enqueued while the download is + in progress! + + +CdromProgress +------------- +.. class:: CdromProgress + + Base class for reporting the progress of adding a cdrom which could be + used with apt_pkg.Cdrom to produce an utility like apt-cdrom. + + Methods defined here: + + .. method:: ask_cdrom_name() -> str + + Ask for the name of the cdrom. This method is called when a CD-ROM + is added (e.g. via :meth:`apt_pkg.Cdrom.add`) and no label for the + CD-ROM can be found. + + Implementations should request a label from the user (e.g. via + :func:`raw_input`) and return this label from the function. The + operation can be cancelled if the function returns ``None`` instead + of a string. + + .. method:: change_cdrom() -> bool + + Ask for the CD-ROM to be changed. This method should return ``True`` + if the CD-ROM has been changed or ``False`` if the CD-ROM has not been + changed and the operation should be cancelled. This base implementation + returns ``False`` and thus cancels the operation. + + .. method:: update(text: str, current: int) + + Periodically invoked in order to update the interface and give + information about the progress of the operation. + + This method has two parameters. The first parameter *text* defines + the text which should be displayed to the user as the progress + message. The second parameter *current* is an integer describing how + many steps have been completed already. + + .. attribute:: total_steps + + The number of total steps, set automatically by python-apt. It may be + used in conjunction with the parameter *current* of the :meth:`update` + method to show how far the operation progressed. + + +OpProgress +---------- +.. class:: OpProgress + + OpProgress classes are used for reporting the progress of operations + such as opening the cache. It is based on the concept of one operation + consisting of a series of sub operations. + + Methods defined here: + + .. method:: done() + + Called once an operation has been completed. + + .. method:: update([percent=None]) + + Called periodically to update the user interface. This function should + use the attributes defined below to display the progress information. + + The optional parameter *percent* is included for compatibility + reasons and may be removed at a later time. + + The following attributes are available and are changed by the classes + wanting to emit progress: + + .. attribute:: major_change + + An automatically set boolean value describing whether the current call + to update is caused by a major change. In this case, the last operation + has finished. + + .. attribute:: op + + An automatically set string which describes the current operation in + an human-readable way. + + .. attribute:: percent + + An automatically set float value describing how much of the operation + has been completed, in percent. + + .. attribute:: subop + + An automatically set string which describes the current sub-operation + in an human-readable way. + + +InstallProgress +--------------- +.. class:: InstallProgress + + InstallProgress classes make it possible to monitor the progress of dpkg + and APT and emit information at certain stages. It uses file descriptors + to read the status lines from APT/dpkg and parses them and afterwards calls + the callback methods. + + Subclasses should override the following methods in order to implement + progress reporting: + + .. method:: conffile(current, new) + + Called when a conffile question from dpkg is detected. + + .. note:: + + This part of the API is semi-stable and may be extended with 2 more + parameters before the release of 0.7.100. + + .. method:: error(pkg, errormsg) + + (Abstract) Called when a error is detected during the install. + + The following method should be overriden to implement progress reporting + for dpkg-based runs i.e. calls to :meth:`run` with a filename: + + .. method:: processing(pkg, stage) + + This method is called just before a processing stage starts. The + parameter *pkg* is the name of the package and the parameter *stage* + is one of the stages listed in the dpkg manual under the status-fd + option, i.e. "upgrade", "install" (both sent before unpacking), + "configure", "trigproc", "remove", "purge". + + .. method:: dpkg_status_change(pkg: str, status: str) + + This method is called whenever the dpkg status of the package + changes. The parameter *pkg* is the name of the package and the + parameter *status* is one of the status strings used in the status + file (:file:`/var/lib/dpkg/status`) and documented + in :manpage:`dpkg(1)`. + + The following methods should be overriden to implement progress reporting + for :meth:`run` calls with an :class:`apt_pkg.PackageManager` object as + their parameter: + + .. method:: status_change(pkg, percent, status) + + This method implements progress reporting for package installation by + APT and may be extended to dpkg at a later time. + + This method takes two parameters: The parameter *percent* is a float + value describing the overall progress and the parameter *status* is a + string describing the current status in an human-readable manner. + + .. method:: start_update() + + This method is called before the installation of any package starts. + + .. method:: finish_update() + + This method is called when all changes have been applied. + + There are also several methods which are fully implemented and should not + be overriden by subclasses unless the subclass has very special needs: + + .. method:: fork() -> int + + Fork a child process and return 0 to the child process and the PID of + the child to the parent process. This implementation just calls + :func:`os.fork` and returns its value. + + .. method:: run(obj) + + This method runs install actions. The parameter *obj* may either + be a PackageManager object in which case its **do_install()** method is + called or the path to a deb file. + + If the object is a :class:`apt_pkg.PackageManager`, the functions + returns the result of calling its ``do_install()`` method. Otherwise, + the function returns the exit status of dpkg. In both cases, ``0`` + means that there were no problems and ``!= 0`` means that there were + issues. + + .. method:: update_interface() + + This method is responsible for reading the status from dpkg/APT and + calling the correct callback methods. Subclasses should not override + this method. + + .. method:: wait_child() + + This method is responsible for calling :meth:`update_interface` from + time to time. It exits once the child has exited. The return value + is the full status returned by :func:`os.waitpid` (not only the + return code). Subclasses should not override this method. + + The class also provides several attributes which may be useful: + + .. attribute:: percent + + The percentage of completion as it was in the last call to + :meth:`status_change`. + + .. attribute:: status + + The status string passed in the last call to :meth:`status_change`. + + .. attribute:: select_timeout + + Used in :meth:`wait_child` to when calling :func:`select.select` + on dpkg's/APT's status descriptor. Subclasses may set their own value + if needed. + + .. attribute:: statusfd + + A readable :class:`file` object from which the status information from + APT or dpkg is read. + + .. attribute:: writefd + + A writable :class:`file` object to which dpkg or APT write their status + information. diff --git a/doc/source/library/index.rst b/doc/source/library/index.rst index dfbd8eec..f049efb8 100644 --- a/doc/source/library/index.rst +++ b/doc/source/library/index.rst @@ -26,6 +26,7 @@ read files like :file:`/etc/apt/sources.list` and to modify them. apt.cdrom apt.debfile apt.package + apt.progress.base apt.progress.text apt.progress.gtk2 apt.progress.qt4 -- cgit v1.2.3 From c75e060f3834aace962e65a578370806406d608a Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 20 Jan 2010 15:35:52 +0100 Subject: apt/progress/gtk2.py: Add GAcquireProgress. --- apt/progress/gtk2.py | 124 +++++++++++++++++++++++++------ doc/source/library/apt.progress.gtk2.rst | 4 +- 2 files changed, 105 insertions(+), 23 deletions(-) (limited to 'doc/source') diff --git a/apt/progress/gtk2.py b/apt/progress/gtk2.py index 22788984..29e730a3 100644 --- a/apt/progress/gtk2.py +++ b/apt/progress/gtk2.py @@ -39,10 +39,14 @@ import vte import apt_pkg from apt_pkg import gettext as _ from apt.deprecation import function_deprecated_by, AttributeDeprecatedBy -from apt.progress import base, old +from apt.progress import base +if apt_pkg._COMPAT_0_7: + from apt.progress import old -__all__ = ['GInstallProgress', 'GOpProgress', 'GtkAptProgress'] + +__all__ = ['GAcquireProgress', 'GInstallProgress', 'GOpProgress', + 'GtkAptProgress'] def mksig(params=(), run=gobject.SIGNAL_RUN_FIRST, rettype=gobject.TYPE_NONE): @@ -213,7 +217,7 @@ class GInstallProgress(gobject.GObject, base.InstallProgress): GDpkgInstallProgress = GInstallProgress -class GFetchProgress(gobject.GObject, old.FetchProgress): +class GAcquireProgress(gobject.GObject, base.AcquireProgress): """A Fetch Progress with GObject signals. Signals: @@ -230,40 +234,98 @@ class GFetchProgress(gobject.GObject, old.FetchProgress): "status-finished": mksig()} def __init__(self): - old.FetchProgress.__init__(self) + base.AcquireProgress.__init__(self) gobject.GObject.__init__(self) self._continue = True self._context = glib.main_context_default() def start(self): + base.AcquireProgress.start(self) self.emit("status-started") def stop(self): + base.AcquireProgress.stop(self) self.emit("status-finished") def cancel(self): self._continue = False - def pulse(self): - old.FetchProgress.pulse(self) - current_item = self.currentItems + 1 - if current_item > self.totalItems: - current_item = self.totalItems + def pulse(self, owner): + base.AcquireProgress.pulse(self, owner) + current_item = self.current_items + 1 + if current_item > self.total_items: + current_item = self.total_items if self.current_cps > 0: text = (_("Downloading file %(current)li of %(total)li with " "%(speed)s/s") % \ {"current": current_item, - "total": self.totalItems, - "speed": apt_pkg.size_to_str(self.currentCPS)}) + "total": self.total_items, + "speed": apt_pkg.size_to_str(self.current_cps)}) else: text = (_("Downloading file %(current)li of %(total)li") % \ {"current": current_item, - "total": self.totalItems}) - self.emit("status-changed", text, self.percent) + "total": self.total_items}) + + percent = (((self.current_bytes + self.current_items) * 100.0) / + float(self.total_bytes + self.total_items)) + self.emit("status-changed", text, percent) while self._context.pending(): self._context.iteration() return self._continue +if apt_pkg._COMPAT_0_7: + + class GFetchProgress(gobject.GObject, old.FetchProgress): + """A Fetch Progress with GObject signals. + + Signals: + + * status-changed(str: description, int: percent) + * status-started() + * status-finished() + + DEPRECATED. + """ + + __gsignals__ = {"status-changed": mksig((str, int)), + "status-started": mksig(), + "status-finished": mksig()} + + def __init__(self): + old.FetchProgress.__init__(self) + gobject.GObject.__init__(self) + self._continue = True + self._context = glib.main_context_default() + + def start(self): + self.emit("status-started") + + def stop(self): + self.emit("status-finished") + + def cancel(self): + self._continue = False + + def pulse(self): + old.FetchProgress.pulse(self) + current_item = self.currentItems + 1 + if current_item > self.totalItems: + current_item = self.totalItems + if self.current_cps > 0: + text = (_("Downloading file %(current)li of %(total)li with " + "%(speed)s/s") % \ + {"current": current_item, + "total": self.totalItems, + "speed": apt_pkg.size_to_str(self.currentCPS)}) + else: + text = (_("Downloading file %(current)li of %(total)li") % \ + {"current": current_item, + "total": self.totalItems}) + self.emit("status-changed", text, self.percent) + while self._context.pending(): + self._context.iteration() + return self._continue + class GtkAptProgress(gtk.VBox): """Graphical progress for installation/fetch/operations. @@ -298,11 +360,15 @@ class GtkAptProgress(gtk.VBox): self._progress_open.connect("status-started", self._on_status_started) self._progress_open.connect("status-finished", self._on_status_finished) - self._progress_fetch = GFetchProgress() - self._progress_fetch.connect("status-changed", self._on_status_changed) - self._progress_fetch.connect("status-started", self._on_status_started) - self._progress_fetch.connect("status-finished", + self._progress_acquire = GAcquireProgress() + self._progress_acquire.connect("status-changed", + self._on_status_changed) + self._progress_acquire.connect("status-started", + self._on_status_started) + self._progress_acquire.connect("status-finished", self._on_status_finished) + + self._progress_fetch = None self._progress_install = GInstallProgress(self._terminal) self._progress_install.connect("status-changed", self._on_status_changed) @@ -338,10 +404,25 @@ class GtkAptProgress(gtk.VBox): """Return the install progress handler for dpkg.""" return self._progress_install + if apt_pkg._COMPAT_0_7: + + @property + def fetch(self): + """Return the fetch progress handler.""" + if self._progress_fetch is None: + self._progress_fetch = GFetchProgress() + self._progress_fetch.connect("status-changed", + self._on_status_changed) + self._progress_fetch.connect("status-started", + self._on_status_started) + self._progress_fetch.connect("status-finished", + self._on_status_finished) + return self._progress_fetch + @property - def fetch(self): - """Return the fetch progress handler.""" - return self._progress_fetch + def acquire(self): + """Return the acquire progress handler.""" + return self._progress_acquire def _on_status_started(self, progress): """Called when something starts.""" @@ -423,12 +504,13 @@ def _test(): pkg.mark_install() apt_progress.show_terminal(True) try: - cache.commit(apt_progress.fetch, apt_progress.install) + cache.commit(apt_progress.acquire, apt_progress.install) except Exception, exc: print >> sys.stderr, "Exception happened:", exc if len(sys.argv) > 1: deb = DebPackage(sys.argv[1], cache) deb.install(apt_progress.dpkg_install) + win.connect("destroy", gtk.main_quit) gtk.main() diff --git a/doc/source/library/apt.progress.gtk2.rst b/doc/source/library/apt.progress.gtk2.rst index 6c00e731..0d53ad41 100644 --- a/doc/source/library/apt.progress.gtk2.rst +++ b/doc/source/library/apt.progress.gtk2.rst @@ -38,9 +38,9 @@ GObject progress classes Emitted when a conffile update is happening. -.. class:: GFetchProgress +.. class:: GAcquireProgress - An implementation of :class:`apt.progress.old.FetchProgress` supporting + An implementation of :class:`apt.progress.base.AcquireProgress` supporting GObject signals. The class emits the following signals: .. describe:: status-changed(description: str, percent: int) -- cgit v1.2.3 From 074ecc0a9157027d7dbeff4fe70f0668eb5b93cb Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 20 Jan 2010 16:46:03 +0100 Subject: doc/source/c++/api.rst: Document the C++ bindings. --- doc/source/c++/api.rst | 797 ++++++++++++++++++++++++++++++++++++++++++- doc/source/c++/embedding.rst | 26 +- 2 files changed, 820 insertions(+), 3 deletions(-) (limited to 'doc/source') diff --git a/doc/source/c++/api.rst b/doc/source/c++/api.rst index 50788a5b..2abd3ab8 100644 --- a/doc/source/c++/api.rst +++ b/doc/source/c++/api.rst @@ -1,6 +1,801 @@ Python APT C++ API ================== +The C++ API provides functions to create Python objects from C++ objects and +to retrieve the C++ object stored in the Python object. There are two types +of Python objects: owned ones and unowned ones. An owned object has another +Python object as its owner and keeps its owner alive for its lifetime. An +unowned object has no such owner. + +The C++ API names use the name of the class in apt_pkg and are prefixed with +Py. For each supported class, there is a _Type object, a _Check() function, +a _CheckExact() function, a _FromCpp() and a _ToCpp() function. .. note:: - The C++ API is experimental and not really documented yet. + This API is experimental and should not be used in stable program + releases. + +Acquire (pkgAcquire) +-------------------- +.. cvar:: PyTypeObject PyAcquire_Type + + The type object for :class:`apt_pkg.Acquire` objects. + +.. cfunction:: int PyAcquire_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Acquire` object, or + a subclass thereof. + +.. cfunction:: int PyAcquire_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Acquire` object and no + subclass thereof. + +.. cfunction:: PyObject* PyAcquire_FromCpp(pkgAcquire *acquire, bool delete=false) + + Create a new :class:`apt_pkg.Acquire` object from the :ctype:`pkgAcquire` + pointer given by the parameter *acquire*. If the parameter *delete* is + true, the object pointed to by *acquire* will be deleted when the refcount + of the return value reaches 0. + +.. cfunction:: pkgAcquire* PyAcquire_ToCpp(PyObject *acquire) + + Return the :ctype:`pkgAcquire` pointer contained in the Python object + *acquire*. + + +AcquireFile (pkgAcqFile) +------------------------ +.. cvar:: PyTypeObject PyAcquireFile_Type + + The type object for :class:`apt_pkg.AcquireFile` objects. + +.. cfunction:: int PyAcquireFile_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.AcquireFile` object, or + a subclass thereof. + +.. cfunction:: int PyAcquireFile_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.AcquireFile` object + and no subclass thereof. + +.. cfunction:: PyObject* PyAcquireFile_FromCpp(pkgAcqFile *file, bool delete=false, PyObject *owner=NULL) + + Create a new :class:`apt_pkg.AcquireFile` object from the :ctype:`pkgAcqFile` + pointer given by the parameter *file*. If the parameter *delete* is + true, the object pointed to by *file* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* should point + to a :class:`apt_pkg.Acquire` object. + +.. cfunction:: pkgAcqFile* PyAcquireFile_ToCpp(PyObject *acquire) + + Return the :ctype:`pkgAcqFile` pointer contained in the Python object + *acquire*. + +AcquireItem (pkgAcquire::Item) +------------------------------ +.. cvar:: PyTypeObject PyAcquireItem_Type + + The type object for :class:`apt_pkg.AcquireItem` objects. + +.. cfunction:: int PyAcquireItem_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.AcquireItem` object, or + a subclass thereof. + +.. cfunction:: int PyAcquireItem_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.AcquireItem` object + and no subclass thereof. + +.. cfunction:: PyObject* PyAcquireItem_FromCpp(pkgAcquire::Item *item, bool delete=false, PyObject *owner=NULL) + + Create a new :class:`apt_pkg.AcquireItem` object from the :ctype:`pkgAcquire::Item` + pointer given by the parameter *item*. If the parameter *delete* is + true, the object pointed to by *item* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* should point + to a :class:`apt_pkg.Acquire` object. + +.. cfunction:: pkgAcquire::Item* PyAcquireItem_ToCpp(PyObject *object) + + Return the :ctype:`pkgAcquire::Item` pointer contained in the Python object + *object*. + +AcquireItemDesc (pkgAcquire::ItemDesc) +-------------------------------------- +.. cvar:: PyTypeObject PyAcquireItemDesc_Type + + The type object for :class:`apt_pkg.AcquireItemDesc` objects. + +.. cfunction:: int PyAcquireItemDesc_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.AcquireItemDesc` object, or + a subclass thereof. + +.. cfunction:: int PyAcquireItemDesc_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.AcquireItemDesc` object + and no subclass thereof. + +.. cfunction:: PyObject* PyAcquireItemDesc_FromCpp(pkgAcquire::ItemDesc *desc, bool delete=false, PyObject *owner=NULL) + + Create a new :class:`apt_pkg.AcquireItemDesc` object from the :ctype:`pkgAcquire::ItemDesc` + pointer given by the parameter *desc*. If the parameter *delete* is + true, the object pointed to by *desc* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* should point + to a :class:`apt_pkg.AcquireItem` object. + +.. cfunction:: pkgAcquire::ItemDesc* PyAcquireItemDesc_ToCpp(PyObject *object) + + Return the :ctype:`pkgAcquire::ItemDesc` pointer contained in the Python object + *object*. + +AcquireWorker (pkgAcquire::Worker) +---------------------------------- +.. cvar:: PyTypeObject PyAcquireWorker_Type + + The type object for :class:`apt_pkg.AcquireWorker` objects. + +.. cfunction:: int PyAcquireWorker_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.AcquireWorker` object, or + a subclass thereof. + +.. cfunction:: int PyAcquireWorker_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.AcquireWorker` object + and no subclass thereof. + +.. cfunction:: PyObject* PyAcquireWorker_FromCpp(pkgAcquire::Worker *worker, bool delete=false, PyObject *owner=NULL) + + Create a new :class:`apt_pkg.AcquireWorker` object from the :ctype:`pkgAcquire::Worker` + pointer given by the parameter *worker*. If the parameter *delete* is + true, the object pointed to by *worker* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* should point + to a :class:`apt_pkg.Acquire` object. + +.. cfunction:: pkgAcquire::Worker* PyAcquireWorker_ToCpp(PyObject *object) + + Return the :ctype:`pkgAcquire::Worker` pointer contained in the Python object + *object*. + +ActionGroup (pkgDepCache::ActionGroup) +-------------------------------------- +.. cvar:: PyTypeObject PyActionGroup_Type + + The type object for :class:`apt_pkg.ActionGroup` objects. + +.. cfunction:: int PyActionGroup_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.ActionGroup` object, or + a subclass thereof. + +.. cfunction:: int PyActionGroup_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.ActionGroup` object + and no subclass thereof. + +.. cfunction:: PyObject* PyActionGroup_FromCpp(pkgDepCache::ActionGroup *agroup, bool delete=false, PyObject *owner=NULL) + + Create a new :class:`apt_pkg.ActionGroup` object from the :ctype:`pkgDepCache::ActionGroup` + pointer given by the parameter *agroup*. If the parameter *delete* is + true, the object pointed to by *agroup* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* should point + to a :class:`apt_pkg.DepCache` object. + +.. cfunction:: pkgDepCache::ActionGroup* PyActionGroup_ToCpp(PyObject *object) + + Return the :ctype:`pkgDepCache::ActionGroup` pointer contained in the + Python object *object*. + +Cache (pkgCache) +------------------------ +.. cvar:: PyTypeObject PyCache_Type + + The type object for :class:`apt_pkg.Cache` objects. + +.. cfunction:: int PyCache_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Cache` object, or + a subclass thereof. + +.. cfunction:: int PyCache_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Cache` object + and no subclass thereof. + +.. cfunction:: PyObject* PyCache_FromCpp(pkgCache *cache, bool delete=false, PyObject *owner=NULL) + + Create a new :class:`apt_pkg.Cache` object from the :ctype:`pkgCache` + pointer given by the parameter *cache*. If the parameter *delete* is + true, the object pointed to by *cache* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* shall point + to a object of the type :cdata:`PyCacheFile_Type`. + +.. cfunction:: pkgCache* PyCache_ToCpp(PyObject *object) + + Return the :ctype:`pkgCache` pointer contained in the Python object + *object*. + + +CacheFile (pkgCacheFile) +------------------------ +.. cvar:: PyTypeObject PyCacheFile_Type + + The type object for CacheFile. This type is internal and not exported to + Python anywhere. + +.. cfunction:: int PyCacheFile_Check(PyObject *object) + + Check that the object *object* is of the type :cdata:`PyCacheFile_Type` or + a subclass thereof. + +.. cfunction:: int PyCacheFile_CheckExact(PyObject *object) + + Check that the object *object* is of the type :cdata:`PyCacheFile_Type` and + no subclass thereof. + +.. cfunction:: PyObject* PyCacheFile_FromCpp(pkgCacheFile *file, bool delete=false) + + Create a new :class:`apt_pkg.CacheFile` object from the :ctype:`pkgCacheFile` + pointer given by the parameter *file* If the parameter *delete* is + true, the object pointed to by *file* will be deleted when the reference + count of the returned object reaches 0. + +.. cfunction:: pkgCacheFile* PyCacheFile_ToCpp(PyObject *object) + + Return the :ctype:`pkgCacheFile` pointer contained in the Python object + *object*. + +Cdrom (pkgCdrom) +------------------------ +.. cvar:: PyTypeObject PyCdrom_Type + + The type object for :class:`apt_pkg.Cdrom` objects. + +.. cfunction:: int PyCdrom_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Cdrom` object, or + a subclass thereof. + +.. cfunction:: int PyCdrom_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Cdrom` object + and no subclass thereof. + +.. cfunction:: PyObject* PyCdrom_FromCpp(pkgCdrom &cdrom, bool delete=false) + + Create a new :class:`apt_pkg.Cdrom` object from the :ctype:`pkgCdrom` + reference given by the parameter *cdrom*. If the parameter *delete* is + true, *cdrom* will be deleted when the reference count of the returned + object reaches 0. + +.. cfunction:: pkgCdrom& PyCdrom_ToCpp(PyObject *object) + + Return the :ctype:`pkgCdrom` reference contained in the Python object + *object*. + +Configuration (Configuration) +------------------------------- +.. cvar:: PyTypeObject PyConfiguration_Type + + The type object for :class:`apt_pkg.Configuration` objects. + +.. cfunction:: int PyConfiguration_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Configuration` object, or + a subclass thereof. + +.. cfunction:: int PyConfiguration_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Configuration` object + and no subclass thereof. + +.. cfunction:: PyObject* PyConfiguration_FromCpp(Configuration *cpp, bool delete=false, PyObject *owner=null) + + Create a new :class:`apt_pkg.Configuration` object from the :ctype:`Configuration` + pointer given by the parameter *cpp*. If the parameter *delete* is + true, the object pointed to by *cpp* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* may refer to + a parent object (e.g. when exposing a sub tree of a configuration object). + +.. cfunction:: Configuration* PyConfiguration_ToCpp(PyObject *object) + + Return the :ctype:`Configuration` pointer contained in the Python object + *object*. + +DepCache (pkgDepCache) +------------------------ +.. cvar:: PyTypeObject PyDepCache_Type + + The type object for :class:`apt_pkg.DepCache` objects. + +.. cfunction:: int PyDepCache_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.DepCache` object, or + a subclass thereof. + +.. cfunction:: int PyDepCache_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.DepCache` object + and no subclass thereof. + +.. cfunction:: PyObject* PyDepCache_FromCpp(pkgDepCache *cpp, bool delete=false, PyObject *owner) + + Create a new :class:`apt_pkg.DepCache` object from the :ctype:`pkgDepCache` + pointer given by the parameter *cpp*. If the parameter *delete* is + true, the object pointed to by *cpp* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* must be + a PyObject of the type :cdata:`PyCache_Type`. + +.. cfunction:: pkgDepCache* PyDepCache_ToCpp(PyObject *object) + + Return the :ctype:`pkgDepCache` pointer contained in the Python object + *object*. + +Dependency (pkgCache::DepIterator) +---------------------------------- +.. cvar:: PyTypeObject PyDependency_Type + + The type object for :class:`apt_pkg.Dependency` objects. + +.. cfunction:: int PyDependency_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Dependency` object, or + a subclass thereof. + +.. cfunction:: int PyDependency_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Dependency` object + and no subclass thereof. + +.. cfunction:: PyObject* PyDependency_FromCpp(pkgCache::DepIterator &cpp, bool delete=false, PyObject *owner) + + Create a new :class:`apt_pkg.Dependency` object from the :ctype:`pkgCache::DepIterator` + reference given by the parameter *cpp*. If the parameter *delete* is + true, *cpp* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* must be + a PyObject of the type :cdata:`PyPackage_Type`. + +.. cfunction:: pkgCache::DepIterator& PyDependency_ToCpp(PyObject *object) + + Return the :ctype:`pkgCache::DepIterator` reference contained in the + Python object *object*. + +Description (pkgCache::DescIterator) +------------------------------------ +.. cvar:: PyTypeObject PyDescription_Type + + The type object for :class:`apt_pkg.Description` objects. + +.. cfunction:: int PyDescription_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Description` object, or + a subclass thereof. + +.. cfunction:: int PyDescription_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Description` object + and no subclass thereof. + +.. cfunction:: PyObject* PyDescription_FromCpp(pkgCache::DescIterator &cpp, bool delete=false, PyObject *owner) + + Create a new :class:`apt_pkg.Description` object from the :ctype:`pkgCache::DescIterator` + reference given by the parameter *cpp*. If the parameter *delete* is + true, *cpp* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* must be + a PyObject of the type :cdata:`PyPackage_Type`. + +.. cfunction:: pkgCache::DescIterator& PyDescription_ToCpp(PyObject *object) + + Return the :ctype:`pkgCache::DescIterator` reference contained in the + Python object *object*. + +Hashes (Hashes) +---------------------------------- +.. cvar:: PyTypeObject PyHashes_Type + + The type object for :class:`apt_pkg.Hashes` objects. + +.. cfunction:: int PyHashes_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Hashes` object, or + a subclass thereof. + +.. cfunction:: int PyHashes_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Hashes` object + and no subclass thereof. + +.. cfunction:: PyObject* PyHashes_FromCpp(Hashes &cpp, bool delete=false) + + Create a new :class:`apt_pkg.Hashes` object from the :ctype:`Hashes` + reference given by the parameter *cpp*. If the parameter *delete* is + true, *cpp* will be deleted when the reference count of the returned + object reaches 0. + +.. cfunction:: Hashes& PyHashes_ToCpp(PyObject *object) + + Return the :ctype:`Hashes` reference contained in the + Python object *object*. + +HashString (HashString) +------------------------ +.. cvar:: PyTypeObject PyHashString_Type + + The type object for :class:`apt_pkg.HashString` objects. + +.. cfunction:: int PyHashString_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.HashString` object, or + a subclass thereof. + +.. cfunction:: int PyHashString_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.HashString` object + and no subclass thereof. + +.. cfunction:: PyObject* PyHashString_FromCpp(HashString *cpp, bool delete=false) + + Create a new :class:`apt_pkg.HashString` object from the :ctype:`HashString` + pointer given by the parameter *cpp*. If the parameter *delete* is + true, the object pointed to by *cpp* will be deleted when the reference + count of the returned object reaches 0. + +.. cfunction:: HashString* PyHashString_ToCpp(PyObject *object) + + Return the :ctype:`HashString` pointer contained in the Python object + *object*. + +IndexRecords (indexRecords) +---------------------------- +.. cvar:: PyTypeObject PyIndexRecords_Type + + The type object for :class:`apt_pkg.IndexRecords` objects. + +.. cfunction:: int PyIndexRecords_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.IndexRecords` object, or + a subclass thereof. + +.. cfunction:: int PyIndexRecords_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.IndexRecords` object + and no subclass thereof. + +.. cfunction:: PyObject* PyIndexRecords_FromCpp(indexRecords *cpp, bool delete=false) + + Create a new :class:`apt_pkg.IndexRecords` object from the :ctype:`indexRecords` + pointer given by the parameter *cpp*. If the parameter *delete* is + true, the object pointed to by *cpp* will be deleted when the reference + count of the returned object reaches 0. + +.. cfunction:: indexRecords* PyIndexRecords_ToCpp(PyObject *object) + + Return the :ctype:`indexRecords` pointer contained in the Python object + *object*. + + +MetaIndex (metaIndex) +------------------------ +.. cvar:: PyTypeObject PyMetaIndex_Type + + The type object for :class:`apt_pkg.MetaIndex` objects. + +.. cfunction:: int PyMetaIndex_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.MetaIndex` object, or + a subclass thereof. + +.. cfunction:: int PyMetaIndex_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.MetaIndex` object + and no subclass thereof. + +.. cfunction:: PyObject* PyMetaIndex_FromCpp(metaIndex *cpp, bool delete=false, PyObject *owner) + + Create a new :class:`apt_pkg.MetaIndex` object from the :ctype:`metaIndex` + pointer given by the parameter *cpp*. If the parameter *delete* is + true, the object pointed to by *cpp* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* should be + a PyObject of the type :cdata:`PySourceList_Type`. + +.. cfunction:: metaIndex* PyMetaIndex_ToCpp(PyObject *object) + + Return the :ctype:`metaIndex` pointer contained in the Python object + *object*. + +Package (pkgCache::PkgIterator) +---------------------------------- +.. cvar:: PyTypeObject PyPackage_Type + + The type object for :class:`apt_pkg.Package` objects. + +.. cfunction:: int PyPackage_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Package` object, or + a subclass thereof. + +.. cfunction:: int PyPackage_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Package` object + and no subclass thereof. + +.. cfunction:: PyObject* PyPackage_FromCpp(pkgCache::PkgIterator &cpp, bool delete=false, PyObject *owner) + + Create a new :class:`apt_pkg.Package` object from the :ctype:`pkgCache::PkgIterator` + reference given by the parameter *cpp*. If the parameter *delete* is + true, *cpp* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* should be + a PyObject of the type :cdata:`PyCache_Type`. + +.. cfunction:: pkgCache::PkgIterator& PyPackage_ToCpp(PyObject *object) + + Return the :ctype:`pkgCache::PkgIterator` reference contained in the + Python object *object*. + +PackageFile (pkgCache::PkgFileIterator) +---------------------------------------- +.. cvar:: PyTypeObject PyPackageFile_Type + + The type object for :class:`apt_pkg.PackageFile` objects. + +.. cfunction:: int PyPackageFile_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.PackageFile` object, or + a subclass thereof. + +.. cfunction:: int PyPackageFile_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.PackageFile` object + and no subclass thereof. + +.. cfunction:: PyObject* PyPackageFile_FromCpp(pkgCache::PkgFileIterator &cpp, bool delete=false, PyObject *owner) + + Create a new :class:`apt_pkg.PackageFile` object from the :ctype:`pkgCache::PkgFileIterator` + reference given by the parameter *cpp*. If the parameter *delete* is + true, *cpp* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* should be + a PyObject of the type :cdata:`PyCache_Type`. + +.. cfunction:: pkgCache::PkgFileIterator& PyPackageFile_ToCpp(PyObject *object) + + Return the :ctype:`pkgCache::PkgFileIterator` reference contained in the + Python object *object*. + +PackageIndexFile (pkgIndexFile) +-------------------------------------- +.. cvar:: PyTypeObject PyPackageIndexFile_Type + + The type object for :class:`apt_pkg.PackageIndexFile` objects. + +.. cfunction:: int PyPackageIndexFile_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.PackageIndexFile` object, or + a subclass thereof. + +.. cfunction:: int PyPackageIndexFile_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.PackageIndexFile` object + and no subclass thereof. + +.. cfunction:: PyObject* PyPackageIndexFile_FromCpp(pkgIndexFile *cpp, bool delete=false, PyObject *owner) + + Create a new :class:`apt_pkg.PackageIndexFile` object from the :ctype:`pkgIndexFile` + pointer given by the parameter *cpp*. If the parameter *delete* is + true, the object pointed to by *cpp* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* should be + a PyObject of the type :cdata:`PyMetaIndex_Type`. + +.. cfunction:: pkgIndexFile* PyPackageIndexFile_ToCpp(PyObject *object) + + Return the :ctype:`pkgIndexFile` pointer contained in the Python object + *object*. + + +PackageManager (pkgPackageManager) +---------------------------------- +.. cvar:: PyTypeObject PyPackageManager_Type + + The type object for :class:`apt_pkg.PackageManager` objects. + +.. cfunction:: int PyPackageManager_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.PackageManager` object, or + a subclass thereof. + +.. cfunction:: int PyPackageManager_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.PackageManager` object + and no subclass thereof. + +.. cfunction:: PyObject* PyPackageManager_FromCpp(pkgPackageManager *cpp, bool delete=false) + + Create a new :class:`apt_pkg.PackageManager` object from the :ctype:`pkgPackageManager` + pointer given by the parameter *cpp*. If the parameter *delete* is + true, the object pointed to by *cpp* will be deleted when the reference + count of the returned object reaches 0. + +.. cfunction:: pkgPackageManager* PyPackageManager_ToCpp(PyObject *object) + + Return the :ctype:`pkgPackageManager` pointer contained in the Python object + *object*. + + +Policy (pkgPolicy) +------------------ +.. cvar:: PyTypeObject PyPolicy_Type + + The type object for :class:`apt_pkg.Policy` objects. + +.. cfunction:: int PyPolicy_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Policy` object, or + a subclass thereof. + +.. cfunction:: int PyPolicy_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Policy` object + and no subclass thereof. + +.. cfunction:: PyObject* PyPolicy_FromCpp(pkgPolicy *cpp, bool delete=false, PyObject *owner) + + Create a new :class:`apt_pkg.Policy` object from the :ctype:`pkgPolicy` + pointer given by the parameter *cpp*. If the parameter *delete* is + true, the object pointed to by *cpp* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* must be + a PyObject of the type :cdata:`PyCache_Type`. + +.. cfunction:: pkgPolicy* PyPolicy_ToCpp(PyObject *object) + + Return the :ctype:`pkgPolicy` pointer contained in the Python object + *object*. + + +ProblemResolver (pkgProblemResolver) +-------------------------------------- +.. cvar:: PyTypeObject PyProblemResolver_Type + + The type object for :class:`apt_pkg.ProblemResolver` objects. + +.. cfunction:: int PyProblemResolver_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.ProblemResolver` object, or + a subclass thereof. + +.. cfunction:: int PyProblemResolver_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.ProblemResolver` object + and no subclass thereof. + +.. cfunction:: PyObject* PyProblemResolver_FromCpp(pkgProblemResolver *cpp, bool delete=false, PyObject *owner) + + Create a new :class:`apt_pkg.ProblemResolver` object from the :ctype:`pkgProblemResolver` + pointer given by the parameter *cpp*. If the parameter *delete* is + true, the object pointed to by *cpp* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* must be + a PyObject of the type :cdata:`PyDepCache_Type`. + +.. cfunction:: pkgProblemResolver* PyProblemResolver_ToCpp(PyObject *object) + + Return the :ctype:`pkgProblemResolver` pointer contained in the Python object + *object*. + + + +SourceList (pkgSourceList) +--------------------------- +.. cvar:: PyTypeObject PySourceList_Type + + The type object for :class:`apt_pkg.SourceList` objects. + +.. cfunction:: int PySourceList_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.SourceList` object, or + a subclass thereof. + +.. cfunction:: int PySourceList_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.SourceList` object + and no subclass thereof. + +.. cfunction:: PyObject* PySourceList_FromCpp(pkgSourceList *cpp, bool delete=false) + + Create a new :class:`apt_pkg.SourceList` object from the :ctype:`pkgSourceList` + pointer given by the parameter *cpp*. If the parameter *delete* is + true, the object pointed to by *cpp* will be deleted when the reference + count of the returned object reaches 0. + +.. cfunction:: pkgSourceList* PySourceList_ToCpp(PyObject *object) + + Return the :ctype:`pkgSourceList` pointer contained in the Python object + *object*. + + +TagFile (pkgTagFile) +---------------------------------- +.. cvar:: PyTypeObject PyTagFile_Type + + The type object for :class:`apt_pkg.TagFile` objects. + +.. cfunction:: int PyTagFile_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.TagFile` object, or + a subclass thereof. + +.. cfunction:: int PyTagFile_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.TagFile` object + and no subclass thereof. + +.. cfunction:: PyObject* PyTagFile_FromCpp(pkgTagFile &cpp, bool delete=false, PyObject *owner) + + Create a new :class:`apt_pkg.TagFile` object from the :ctype:`pkgTagFile` + reference given by the parameter *cpp*. If the parameter *delete* is + true, *cpp* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* may be any + Python object. + +.. cfunction:: pkgTagFile& PyTagFile_ToCpp(PyObject *object) + + Return the :ctype:`pkgTagFile` reference contained in the + Python object *object*. + +TagSection (pkgTagSection) +---------------------------------- +.. cvar:: PyTypeObject PyTagSection_Type + + The type object for :class:`apt_pkg.TagSection` objects. + +.. cfunction:: int PyTagSection_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.TagSection` object, or + a subclass thereof. + +.. cfunction:: int PyTagSection_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.TagSection` object + and no subclass thereof. + +.. cfunction:: PyObject* PyTagSection_FromCpp(pkgTagSection &cpp, bool delete=false, PyObject *owner) + + Create a new :class:`apt_pkg.TagSection` object from the :ctype:`pkgTagSection` + reference given by the parameter *cpp*. If the parameter *delete* is + true, *cpp* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* may be + a PyObject of the type :cdata:`PyTagFile_Type`. + +.. cfunction:: pkgTagSection& PyTagSection_ToCpp(PyObject *object) + + Return the :ctype:`pkgTagSection` reference contained in the + Python object *object*. + +Version (pkgCache::VerIterator) +---------------------------------- +.. cvar:: PyTypeObject PyVersion_Type + + The type object for :class:`apt_pkg.Version` objects. + +.. cfunction:: int PyVersion_Check(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Version` object, or + a subclass thereof. + +.. cfunction:: int PyVersion_CheckExact(PyObject *object) + + Check that the object *object* is an :class:`apt_pkg.Version` object + and no subclass thereof. + +.. cfunction:: PyObject* PyVersion_FromCpp(pkgCache::VerIterator &cpp, bool delete=false, PyObject *owner) + + Create a new :class:`apt_pkg.Version` object from the :ctype:`pkgCache::VerIterator` + reference given by the parameter *cpp*. If the parameter *delete* is + true, *cpp* will be deleted when the reference + count of the returned object reaches 0. The parameter *owner* must be + a PyObject of the type :cdata:`PyPackage_Type`. + +.. cfunction:: pkgCache::VerIterator& PyVersion_ToCpp(PyObject *object) + + Return the :ctype:`pkgCache::VerIterator` reference contained in the + Python object *object*. diff --git a/doc/source/c++/embedding.rst b/doc/source/c++/embedding.rst index e5816eb7..b04e0d78 100644 --- a/doc/source/c++/embedding.rst +++ b/doc/source/c++/embedding.rst @@ -1,5 +1,27 @@ +.. highlightlang:: c++ + Embedding Python APT ==================== -.. note:: +This is a very basic tutorial for working with the C++ bindings. + +Basics +------- +To use the python-apt C++ bindings, first include the +``python-apt/python-apt.h`` header:: + + #include + +Now, the module needs to be initialized. This is done by calling the function +:cfunc:`import_apt_pkg`. This function returns 0 on success and a negative +value in case of failure:: + + if (import_apt_pkg() < 0) + return; + +Longer example +-------------- +The following code will create a standalone application which provides a +module ``client`` with the attribute ``hash`` which stores an object of the +type :class:`apt_pkg.HashString`: - The C++ API is experimental and not really documented yet. +.. literalinclude:: ../../client-example.cc -- cgit v1.2.3 From 86bad92b26e6c7af7deb7dfcdd25e70ce1ce5a85 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 20 Jan 2010 16:58:54 +0100 Subject: doc/source/c++/embedding.rst: Add compile command. --- doc/source/c++/embedding.rst | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'doc/source') diff --git a/doc/source/c++/embedding.rst b/doc/source/c++/embedding.rst index b04e0d78..754ad398 100644 --- a/doc/source/c++/embedding.rst +++ b/doc/source/c++/embedding.rst @@ -25,3 +25,10 @@ module ``client`` with the attribute ``hash`` which stores an object of the type :class:`apt_pkg.HashString`: .. literalinclude:: ../../client-example.cc + + +.. highlightlang:: sh + +If this file were called client-example.cc, you could compile it using:: + + g++ -lapt-pkg -lpython2.5 -I/usr/include/python2.5 -o client client-example.cc -- cgit v1.2.3 From 2e32d8d27f84b585ef8196a28bdd2e649de02607 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Wed, 20 Jan 2010 17:06:11 +0100 Subject: Rename apt_pkg.PackageIndexFile to apt_pkg.IndexFile. --- debian/changelog | 1 + doc/source/c++/api.rst | 20 +++++++-------- doc/source/library/apt_pkg.rst | 6 ++--- python/apt_pkgmodule.cc | 4 +-- python/apt_pkgmodule.h | 2 +- python/indexfile.cc | 58 +++++++++++++++++++++--------------------- python/metaindex.cc | 2 +- python/pkgsrcrecords.cc | 2 +- python/python-apt.h | 10 ++++---- python/sourcelist.cc | 4 +-- 10 files changed, 55 insertions(+), 54 deletions(-) (limited to 'doc/source') diff --git a/debian/changelog b/debian/changelog index 7b711e1d..409cf44e 100644 --- a/debian/changelog +++ b/debian/changelog @@ -18,6 +18,7 @@ python-apt (0.7.93) UNRELEASED; urgency=low - Fix some parsing of dpkg status fd. * apt/progress/text.py: - Replace one print statement with a .write() call. + * Rename apt_pkg.PackageIndexFile to apt_pkg.IndexFile. [ Colin Watson ] * apt/progress/__init__.py: diff --git a/doc/source/c++/api.rst b/doc/source/c++/api.rst index 2abd3ab8..749e2bc0 100644 --- a/doc/source/c++/api.rst +++ b/doc/source/c++/api.rst @@ -564,31 +564,31 @@ PackageFile (pkgCache::PkgFileIterator) Return the :ctype:`pkgCache::PkgFileIterator` reference contained in the Python object *object*. -PackageIndexFile (pkgIndexFile) +IndexFile (pkgIndexFile) -------------------------------------- -.. cvar:: PyTypeObject PyPackageIndexFile_Type +.. cvar:: PyTypeObject PyIndexFile_Type - The type object for :class:`apt_pkg.PackageIndexFile` objects. + The type object for :class:`apt_pkg.IndexFile` objects. -.. cfunction:: int PyPackageIndexFile_Check(PyObject *object) +.. cfunction:: int PyIndexFile_Check(PyObject *object) - Check that the object *object* is an :class:`apt_pkg.PackageIndexFile` object, or + Check that the object *object* is an :class:`apt_pkg.IndexFile` object, or a subclass thereof. -.. cfunction:: int PyPackageIndexFile_CheckExact(PyObject *object) +.. cfunction:: int PyIndexFile_CheckExact(PyObject *object) - Check that the object *object* is an :class:`apt_pkg.PackageIndexFile` object + Check that the object *object* is an :class:`apt_pkg.IndexFile` object and no subclass thereof. -.. cfunction:: PyObject* PyPackageIndexFile_FromCpp(pkgIndexFile *cpp, bool delete=false, PyObject *owner) +.. cfunction:: PyObject* PyIndexFile_FromCpp(pkgIndexFile *cpp, bool delete=false, PyObject *owner) - Create a new :class:`apt_pkg.PackageIndexFile` object from the :ctype:`pkgIndexFile` + Create a new :class:`apt_pkg.IndexFile` object from the :ctype:`pkgIndexFile` pointer given by the parameter *cpp*. If the parameter *delete* is true, the object pointed to by *cpp* will be deleted when the reference count of the returned object reaches 0. The parameter *owner* should be a PyObject of the type :cdata:`PyMetaIndex_Type`. -.. cfunction:: pkgIndexFile* PyPackageIndexFile_ToCpp(PyObject *object) +.. cfunction:: pkgIndexFile* PyIndexFile_ToCpp(PyObject *object) Return the :ctype:`pkgIndexFile` pointer contained in the Python object *object*. diff --git a/doc/source/library/apt_pkg.rst b/doc/source/library/apt_pkg.rst index c3a74267..90b3062a 100644 --- a/doc/source/library/apt_pkg.rst +++ b/doc/source/library/apt_pkg.rst @@ -731,7 +731,7 @@ Index Files .. attribute:: index_files -.. class:: PackageIndexFile +.. class:: IndexFile .. method:: archive_uri(path) @@ -743,7 +743,7 @@ Index Files .. attribute:: describe - A description of the :class:`PackageIndexFile`. + A description of the :class:`IndexFile`. .. attribute:: exists @@ -1790,7 +1790,7 @@ Other classes .. method:: find_index(pkgfile) - Return a :class:`PackageIndexFile` object for the :class:`PackageFile` + Return a :class:`IndexFile` object for the :class:`PackageFile` *pkgfile*. .. method:: read_main_list diff --git a/python/apt_pkgmodule.cc b/python/apt_pkgmodule.cc index 56594c61..df443c10 100644 --- a/python/apt_pkgmodule.cc +++ b/python/apt_pkgmodule.cc @@ -545,7 +545,7 @@ static struct _PyAptPkgAPIStruct API = { &PyMetaIndex_Type, // metaindex_type &PyPackage_Type, // package_type &PyPackageFile_Type, // packagefile_type - &PyPackageIndexFile_Type, // packageindexfile_type + &PyIndexFile_Type, // packageindexfile_type &PyPackageList_Type, // packagelist_type &PyPackageManager_Type, // packagemanager_type &PyPackageRecords_Type, // packagerecords_type @@ -638,7 +638,7 @@ extern "C" void initapt_pkg() ADDTYPE(Module,"DepCache",&PyDepCache_Type); ADDTYPE(Module,"ProblemResolver",&PyProblemResolver_Type); /* ========================= indexfile.cc ========================= */ - ADDTYPE(Module,"PackageIndexFile",&PyPackageIndexFile_Type); // NO __new__() + ADDTYPE(Module,"IndexFile",&PyIndexFile_Type); // NO __new__() /* ========================= metaindex.cc ========================= */ ADDTYPE(Module,"MetaIndex",&PyMetaIndex_Type); // NO __new__() /* ========================= pkgmanager.cc ========================= */ diff --git a/python/apt_pkgmodule.h b/python/apt_pkgmodule.h index 97ba05a7..bc2f747b 100644 --- a/python/apt_pkgmodule.h +++ b/python/apt_pkgmodule.h @@ -103,7 +103,7 @@ extern PyTypeObject PySourceList_Type; PyObject *GetPkgSourceList(PyObject *Self,PyObject *Args); // pkgSourceList -extern PyTypeObject PyPackageIndexFile_Type; +extern PyTypeObject PyIndexFile_Type; // metaIndex extern PyTypeObject PyMetaIndex_Type; diff --git a/python/indexfile.cc b/python/indexfile.cc index a6f8904e..7accaa50 100644 --- a/python/indexfile.cc +++ b/python/indexfile.cc @@ -15,7 +15,7 @@ #include -static PyObject *PackageIndexFileArchiveURI(PyObject *Self,PyObject *Args) +static PyObject *IndexFileArchiveURI(PyObject *Self,PyObject *Args) { pkgIndexFile *File = GetCpp(Self); char *path; @@ -25,38 +25,38 @@ static PyObject *PackageIndexFileArchiveURI(PyObject *Self,PyObject *Args) return HandleErrors(Safe_FromString(File->ArchiveURI(path).c_str())); } -static PyMethodDef PackageIndexFileMethods[] = +static PyMethodDef IndexFileMethods[] = { - {"archive_uri",PackageIndexFileArchiveURI,METH_VARARGS,"Returns the ArchiveURI"}, + {"archive_uri",IndexFileArchiveURI,METH_VARARGS,"Returns the ArchiveURI"}, #ifdef COMPAT_0_7 - {"ArchiveURI",PackageIndexFileArchiveURI,METH_VARARGS,"Returns the ArchiveURI"}, + {"ArchiveURI",IndexFileArchiveURI,METH_VARARGS,"Returns the ArchiveURI"}, #endif {} }; #define File (GetCpp(Self)) -static PyObject *PackageIndexFileGetLabel(PyObject *Self,void*) { +static PyObject *IndexFileGetLabel(PyObject *Self,void*) { return Safe_FromString(File->GetType()->Label); } -static PyObject *PackageIndexFileGetDescribe(PyObject *Self,void*) { +static PyObject *IndexFileGetDescribe(PyObject *Self,void*) { return Safe_FromString(File->Describe().c_str()); } -static PyObject *PackageIndexFileGetExists(PyObject *Self,void*) { +static PyObject *IndexFileGetExists(PyObject *Self,void*) { return Py_BuildValue("i",(File->Exists())); } -static PyObject *PackageIndexFileGetHasPackages(PyObject *Self,void*) { +static PyObject *IndexFileGetHasPackages(PyObject *Self,void*) { return Py_BuildValue("i",(File->HasPackages())); } -static PyObject *PackageIndexFileGetSize(PyObject *Self,void*) { +static PyObject *IndexFileGetSize(PyObject *Self,void*) { return Py_BuildValue("i",(File->Size())); } -static PyObject *PackageIndexFileGetIsTrusted(PyObject *Self,void*) { +static PyObject *IndexFileGetIsTrusted(PyObject *Self,void*) { return Py_BuildValue("i",(File->IsTrusted())); } #undef File #define S(x) (x ? x : "") -static PyObject *PackageIndexFileRepr(PyObject *Self) +static PyObject *IndexFileRepr(PyObject *Self) { pkgIndexFile *File = GetCpp(Self); return PyString_FromFormat("), // tp_basicsize 0, // tp_itemsize // Methods @@ -100,7 +100,7 @@ PyTypeObject PyPackageIndexFile_Type = 0, // tp_getattr 0, // tp_setattr 0, // tp_compare - PackageIndexFileRepr, // tp_repr + IndexFileRepr, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping @@ -118,9 +118,9 @@ PyTypeObject PyPackageIndexFile_Type = 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext - PackageIndexFileMethods, // tp_methods + IndexFileMethods, // tp_methods 0, // tp_members - PackageIndexFileGetSet, // tp_getset + IndexFileGetSet, // tp_getset }; diff --git a/python/metaindex.cc b/python/metaindex.cc index 4e059f0c..2c5b0bd9 100644 --- a/python/metaindex.cc +++ b/python/metaindex.cc @@ -38,7 +38,7 @@ static PyObject *MetaIndexGetIndexFiles(PyObject *Self,void*) { I != indexFiles->end(); I++) { CppOwnedPyObject *Obj; - Obj = CppOwnedPyObject_NEW(Self, &PyPackageIndexFile_Type,*I); + Obj = CppOwnedPyObject_NEW(Self, &PyIndexFile_Type,*I); // Do not delete pkgIndexFile*, they are managed by metaIndex. Obj->NoDelete = true; PyList_Append(List,Obj); diff --git a/python/pkgsrcrecords.cc b/python/pkgsrcrecords.cc index 086ec8d5..0b54c2fe 100644 --- a/python/pkgsrcrecords.cc +++ b/python/pkgsrcrecords.cc @@ -124,7 +124,7 @@ static PyObject *PkgSrcRecordsGetIndex(PyObject *Self,void*) { return 0; const pkgIndexFile &tmp = Struct.Last->Index(); CppOwnedPyObject *PyObj; - PyObj = CppOwnedPyObject_NEW(Self,&PyPackageIndexFile_Type, + PyObj = CppOwnedPyObject_NEW(Self,&PyIndexFile_Type, (pkgIndexFile*)&tmp); // Do not delete the pkgIndexFile*, it is managed by PkgSrcRecords::Parser. PyObj->NoDelete=true; diff --git a/python/python-apt.h b/python/python-apt.h index 08242c08..3e413dff 100644 --- a/python/python-apt.h +++ b/python/python-apt.h @@ -79,7 +79,7 @@ struct _PyAptPkgAPIStruct { # define PyMetaIndex_Type *(_PyAptPkg_API->metaindex_type) # define PyPackage_Type *(_PyAptPkg_API->package_type) # define PyPackageFile_Type *(_PyAptPkg_API->packagefile_type) -# define PyPackageIndexFile_Type *(_PyAptPkg_API->packageindexfile_type) +# define PyIndexFile_Type *(_PyAptPkg_API->packageindexfile_type) # define PyPackageList_Type *(_PyAptPkg_API->packagelist_type) # define PyPackageManager_Type *(_PyAptPkg_API->packagemanager_type) # define PyPackageRecords_Type *(_PyAptPkg_API->packagerecords_type) @@ -140,7 +140,7 @@ static int import_apt_pkg(void) { # define PyMetaIndex_Check(op) PyObject_TypeCheck(op, &PyMetaIndex_Type) # define PyPackage_Check(op) PyObject_TypeCheck(op, &PyPackage_Type) # define PyPackageFile_Check(op) PyObject_TypeCheck(op, &PyPackageFile_Type) -# define PyPackageIndexFile_Check(op) PyObject_TypeCheck(op, &PyPackageIndexFile_Type) +# define PyIndexFile_Check(op) PyObject_TypeCheck(op, &PyIndexFile_Type) # define PyPackageList_Check(op) PyObject_TypeCheck(op, &PyPackageList_Type) # define PyPackageManager_Check(op) PyObject_TypeCheck(op, &PyPackageManager_Type) # define PyPackageRecords_Check(op) PyObject_TypeCheck(op, &PyPackageRecords_Type) @@ -172,7 +172,7 @@ static int import_apt_pkg(void) { # define PyMetaIndex_CheckExact(op) (op->op_type == &PyMetaIndex_Type) # define PyPackage_CheckExact(op) (op->op_type == &PyPackage_Type) # define PyPackageFile_CheckExact(op) (op->op_type == &PyPackageFile_Type) -# define PyPackageIndexFile_CheckExact(op) (op->op_type == &PyPackageIndexFile_Type) +# define PyIndexFile_CheckExact(op) (op->op_type == &PyIndexFile_Type) # define PyPackageList_CheckExact(op) (op->op_type == &PyPackageList_Type) # define PyPackageManager_CheckExact(op) (op->op_type == &PyPackageManager_Type) # define PyPackageRecords_CheckExact(op) (op->op_type == &PyPackageRecords_Type) @@ -205,7 +205,7 @@ static int import_apt_pkg(void) { # define PyMetaIndex_ToCpp GetCpp # define PyPackage_ToCpp GetCpp # define PyPackageFile_ToCpp GetCpp -# define PyPackageIndexFile_ToCpp GetCpp +# define PyIndexFile_ToCpp GetCpp //# define PyPackageList_ToCpp GetCpp // NOT EXPORTED. # define PyPackageManager_ToCpp GetCpp //# define PyPackageRecords_ToCpp GetCpp // NOT EXPORTED @@ -256,7 +256,7 @@ inline CppOwnedPyObject *FromCppOwned(PyTypeObject *pytype, Cpp const &obj, # define PyIndexRecords_FromCpp(...) FromCpp(&PyIndexRecords_Type,##__VA_ARGS__) # define PyMetaIndex_FromCpp(...) FromCppOwned(&PyMetaIndex_Type,##__VA_ARGS__) # define PyPackage_FromCpp(...) FromCppOwned(&PyPackage_Type,##__VA_ARGS__) -# define PyPackageIndexFile_FromCpp(...) FromCppOwned(&PyPackageIndexFile_Type,##__VA_ARGS__) +# define PyIndexFile_FromCpp(...) FromCppOwned(&PyIndexFile_Type,##__VA_ARGS__) # define PyPackageFile_FromCpp(...) FromCppOwned(&PyPackageFile_Type,##__VA_ARGS__) //# define PyPackageList_FromCpp(...) FromCppOwned(&PyPackageList_Type,##__VA_ARGS__) # define PyPackageManager_FromCpp(...) FromCpp(&PyPackageManager_Type,##__VA_ARGS__) diff --git a/python/sourcelist.cc b/python/sourcelist.cc index e86f7fd3..52c0e6a8 100644 --- a/python/sourcelist.cc +++ b/python/sourcelist.cc @@ -35,13 +35,13 @@ static PyObject *PkgSourceListFindIndex(PyObject *Self,PyObject *Args) pkgIndexFile *index; if(list->FindIndex(i, index)) { - pyPkgIndexFile = CppOwnedPyObject_NEW(pyPkgFileIter,&PyPackageIndexFile_Type,index); + pyPkgIndexFile = CppOwnedPyObject_NEW(pyPkgFileIter,&PyIndexFile_Type,index); // Do not delete the pkgIndexFile*, it is managed by pkgSourceList. pyPkgIndexFile->NoDelete = true; return pyPkgIndexFile; } - //&PyPackageIndexFile_Type,&pyPkgIndexFile) + //&PyIndexFile_Type,&pyPkgIndexFile) Py_INCREF(Py_None); return Py_None; -- cgit v1.2.3 From 4609ac0f0102e5427419ed4c122c6824ca7d7716 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 2 Feb 2010 17:31:23 +0100 Subject: Fix typo seperated => separated in multiple files (reported by lintian). --- debian/changelog | 1 + doc/source/library/apt_pkg.rst | 2 +- doc/source/whatsnew/0.7.100.rst | 2 +- python/hashstring.cc | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) (limited to 'doc/source') diff --git a/debian/changelog b/debian/changelog index fd87a576..368b45c6 100644 --- a/debian/changelog +++ b/debian/changelog @@ -25,6 +25,7 @@ python-apt (0.7.93.1) UNRELEASED; urgency=low * apt/progress/base.py: - select.error objects do not have an errno attribute (Closes: #568005) * doc/client-example.cc: Update against the new API. + * Fix typo seperated => separated in multiple files (reported by lintian). -- Julian Andres Klode Sat, 23 Jan 2010 15:35:55 +0100 diff --git a/doc/source/library/apt_pkg.rst b/doc/source/library/apt_pkg.rst index 90b3062a..7989a68a 100644 --- a/doc/source/library/apt_pkg.rst +++ b/doc/source/library/apt_pkg.rst @@ -1817,7 +1817,7 @@ String functions .. function:: check_domain_list(host, list) - See if Host is in a ',' seperated list, e.g.:: + See if Host is in a ',' separated list, e.g.:: apt_pkg.check_domain_list("alioth.debian.org","debian.net,debian.org") diff --git a/doc/source/whatsnew/0.7.100.rst b/doc/source/whatsnew/0.7.100.rst index 110336a3..a3888b3a 100644 --- a/doc/source/whatsnew/0.7.100.rst +++ b/doc/source/whatsnew/0.7.100.rst @@ -192,7 +192,7 @@ methods, functions, and their parameters the following rules apply: 3. Replace every [A-Z] with the corresponding [a-z] (descUri => desc_uri) As an exception, refixes such as 'de' (e.g. 'dequote') or 'un' (e.g. 'unlock') -are normally not seperated by underscores from the next word. There are also +are normally not separated by underscores from the next word. There are also some other exceptions which are listed here, and apply to any name containing this word: **filename**, **filesize**, **destdir**, **destfile**, **dequote**, **unlock**, **reinstall**, **pinfile**, **REINSTREQ**, **UNPACKED**, diff --git a/python/hashstring.cc b/python/hashstring.cc index d4b7a3b2..59d533f8 100644 --- a/python/hashstring.cc +++ b/python/hashstring.cc @@ -87,7 +87,7 @@ static char *hashstring_doc = "HashString(type, hash) OR HashString('type:hash')\n\n" "Create a new HashString object. The first form allows you to specify\n" "a type and a hash, and the second form a single string where type and\n" - "hash are seperated by a colon, e.g.::\n\n" + "hash are separated by a colon, e.g.::\n\n" " HashString('MD5Sum', '6cc1b6e6655e3555ac47e5b5fe26d04e')\n\n" "Valid options for 'type' are: MD5Sum, SHA1, SHA256."; PyTypeObject PyHashString_Type = { -- cgit v1.2.3 From 76b75e9acc4c1a85cc150efcdb55d446868002c8 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Tue, 2 Feb 2010 17:59:43 +0100 Subject: doc/source/c++/api.rst: Update for the API changes. --- doc/source/c++/api.rst | 62 +++++++++++++++++++++++++------------------------- 1 file changed, 31 insertions(+), 31 deletions(-) (limited to 'doc/source') diff --git a/doc/source/c++/api.rst b/doc/source/c++/api.rst index 749e2bc0..e807f4bb 100644 --- a/doc/source/c++/api.rst +++ b/doc/source/c++/api.rst @@ -1,10 +1,10 @@ Python APT C++ API ================== The C++ API provides functions to create Python objects from C++ objects and -to retrieve the C++ object stored in the Python object. There are two types -of Python objects: owned ones and unowned ones. An owned object has another -Python object as its owner and keeps its owner alive for its lifetime. An -unowned object has no such owner. +to retrieve the C++ object stored in the Python object. An object may have +another Python object as its owner and keeps its owner alive for its +lifetime. Some objects require an owner of a specific type, while others +require none. Refer to the sections below for details. The C++ API names use the name of the class in apt_pkg and are prefixed with Py. For each supported class, there is a _Type object, a _Check() function, @@ -31,7 +31,7 @@ Acquire (pkgAcquire) Check that the object *object* is an :class:`apt_pkg.Acquire` object and no subclass thereof. -.. cfunction:: PyObject* PyAcquire_FromCpp(pkgAcquire *acquire, bool delete=false) +.. cfunction:: PyObject* PyAcquire_FromCpp(pkgAcquire *acquire, bool delete, PyObject *owner) Create a new :class:`apt_pkg.Acquire` object from the :ctype:`pkgAcquire` pointer given by the parameter *acquire*. If the parameter *delete* is @@ -60,7 +60,7 @@ AcquireFile (pkgAcqFile) Check that the object *object* is an :class:`apt_pkg.AcquireFile` object and no subclass thereof. -.. cfunction:: PyObject* PyAcquireFile_FromCpp(pkgAcqFile *file, bool delete=false, PyObject *owner=NULL) +.. cfunction:: PyObject* PyAcquireFile_FromCpp(pkgAcqFile *file, bool delete, PyObject *owner) Create a new :class:`apt_pkg.AcquireFile` object from the :ctype:`pkgAcqFile` pointer given by the parameter *file*. If the parameter *delete* is @@ -89,7 +89,7 @@ AcquireItem (pkgAcquire::Item) Check that the object *object* is an :class:`apt_pkg.AcquireItem` object and no subclass thereof. -.. cfunction:: PyObject* PyAcquireItem_FromCpp(pkgAcquire::Item *item, bool delete=false, PyObject *owner=NULL) +.. cfunction:: PyObject* PyAcquireItem_FromCpp(pkgAcquire::Item *item, bool delete, PyObject *owner) Create a new :class:`apt_pkg.AcquireItem` object from the :ctype:`pkgAcquire::Item` pointer given by the parameter *item*. If the parameter *delete* is @@ -118,7 +118,7 @@ AcquireItemDesc (pkgAcquire::ItemDesc) Check that the object *object* is an :class:`apt_pkg.AcquireItemDesc` object and no subclass thereof. -.. cfunction:: PyObject* PyAcquireItemDesc_FromCpp(pkgAcquire::ItemDesc *desc, bool delete=false, PyObject *owner=NULL) +.. cfunction:: PyObject* PyAcquireItemDesc_FromCpp(pkgAcquire::ItemDesc *desc, bool delete, PyObject *owner) Create a new :class:`apt_pkg.AcquireItemDesc` object from the :ctype:`pkgAcquire::ItemDesc` pointer given by the parameter *desc*. If the parameter *delete* is @@ -147,7 +147,7 @@ AcquireWorker (pkgAcquire::Worker) Check that the object *object* is an :class:`apt_pkg.AcquireWorker` object and no subclass thereof. -.. cfunction:: PyObject* PyAcquireWorker_FromCpp(pkgAcquire::Worker *worker, bool delete=false, PyObject *owner=NULL) +.. cfunction:: PyObject* PyAcquireWorker_FromCpp(pkgAcquire::Worker *worker, bool delete, PyObject *owner) Create a new :class:`apt_pkg.AcquireWorker` object from the :ctype:`pkgAcquire::Worker` pointer given by the parameter *worker*. If the parameter *delete* is @@ -176,7 +176,7 @@ ActionGroup (pkgDepCache::ActionGroup) Check that the object *object* is an :class:`apt_pkg.ActionGroup` object and no subclass thereof. -.. cfunction:: PyObject* PyActionGroup_FromCpp(pkgDepCache::ActionGroup *agroup, bool delete=false, PyObject *owner=NULL) +.. cfunction:: PyObject* PyActionGroup_FromCpp(pkgDepCache::ActionGroup *agroup, bool delete, PyObject *owner) Create a new :class:`apt_pkg.ActionGroup` object from the :ctype:`pkgDepCache::ActionGroup` pointer given by the parameter *agroup*. If the parameter *delete* is @@ -205,7 +205,7 @@ Cache (pkgCache) Check that the object *object* is an :class:`apt_pkg.Cache` object and no subclass thereof. -.. cfunction:: PyObject* PyCache_FromCpp(pkgCache *cache, bool delete=false, PyObject *owner=NULL) +.. cfunction:: PyObject* PyCache_FromCpp(pkgCache *cache, bool delete, PyObject *owner) Create a new :class:`apt_pkg.Cache` object from the :ctype:`pkgCache` pointer given by the parameter *cache*. If the parameter *delete* is @@ -236,7 +236,7 @@ CacheFile (pkgCacheFile) Check that the object *object* is of the type :cdata:`PyCacheFile_Type` and no subclass thereof. -.. cfunction:: PyObject* PyCacheFile_FromCpp(pkgCacheFile *file, bool delete=false) +.. cfunction:: PyObject* PyCacheFile_FromCpp(pkgCacheFile *file, bool delete, PyObject *owner) Create a new :class:`apt_pkg.CacheFile` object from the :ctype:`pkgCacheFile` pointer given by the parameter *file* If the parameter *delete* is @@ -264,7 +264,7 @@ Cdrom (pkgCdrom) Check that the object *object* is an :class:`apt_pkg.Cdrom` object and no subclass thereof. -.. cfunction:: PyObject* PyCdrom_FromCpp(pkgCdrom &cdrom, bool delete=false) +.. cfunction:: PyObject* PyCdrom_FromCpp(pkgCdrom &cdrom, bool delete, PyObject *owner) Create a new :class:`apt_pkg.Cdrom` object from the :ctype:`pkgCdrom` reference given by the parameter *cdrom*. If the parameter *delete* is @@ -292,7 +292,7 @@ Configuration (Configuration) Check that the object *object* is an :class:`apt_pkg.Configuration` object and no subclass thereof. -.. cfunction:: PyObject* PyConfiguration_FromCpp(Configuration *cpp, bool delete=false, PyObject *owner=null) +.. cfunction:: PyObject* PyConfiguration_FromCpp(Configuration *cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.Configuration` object from the :ctype:`Configuration` pointer given by the parameter *cpp*. If the parameter *delete* is @@ -321,7 +321,7 @@ DepCache (pkgDepCache) Check that the object *object* is an :class:`apt_pkg.DepCache` object and no subclass thereof. -.. cfunction:: PyObject* PyDepCache_FromCpp(pkgDepCache *cpp, bool delete=false, PyObject *owner) +.. cfunction:: PyObject* PyDepCache_FromCpp(pkgDepCache *cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.DepCache` object from the :ctype:`pkgDepCache` pointer given by the parameter *cpp*. If the parameter *delete* is @@ -350,7 +350,7 @@ Dependency (pkgCache::DepIterator) Check that the object *object* is an :class:`apt_pkg.Dependency` object and no subclass thereof. -.. cfunction:: PyObject* PyDependency_FromCpp(pkgCache::DepIterator &cpp, bool delete=false, PyObject *owner) +.. cfunction:: PyObject* PyDependency_FromCpp(pkgCache::DepIterator &cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.Dependency` object from the :ctype:`pkgCache::DepIterator` reference given by the parameter *cpp*. If the parameter *delete* is @@ -379,7 +379,7 @@ Description (pkgCache::DescIterator) Check that the object *object* is an :class:`apt_pkg.Description` object and no subclass thereof. -.. cfunction:: PyObject* PyDescription_FromCpp(pkgCache::DescIterator &cpp, bool delete=false, PyObject *owner) +.. cfunction:: PyObject* PyDescription_FromCpp(pkgCache::DescIterator &cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.Description` object from the :ctype:`pkgCache::DescIterator` reference given by the parameter *cpp*. If the parameter *delete* is @@ -408,7 +408,7 @@ Hashes (Hashes) Check that the object *object* is an :class:`apt_pkg.Hashes` object and no subclass thereof. -.. cfunction:: PyObject* PyHashes_FromCpp(Hashes &cpp, bool delete=false) +.. cfunction:: PyObject* PyHashes_FromCpp(Hashes &cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.Hashes` object from the :ctype:`Hashes` reference given by the parameter *cpp*. If the parameter *delete* is @@ -436,7 +436,7 @@ HashString (HashString) Check that the object *object* is an :class:`apt_pkg.HashString` object and no subclass thereof. -.. cfunction:: PyObject* PyHashString_FromCpp(HashString *cpp, bool delete=false) +.. cfunction:: PyObject* PyHashString_FromCpp(HashString *cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.HashString` object from the :ctype:`HashString` pointer given by the parameter *cpp*. If the parameter *delete* is @@ -464,7 +464,7 @@ IndexRecords (indexRecords) Check that the object *object* is an :class:`apt_pkg.IndexRecords` object and no subclass thereof. -.. cfunction:: PyObject* PyIndexRecords_FromCpp(indexRecords *cpp, bool delete=false) +.. cfunction:: PyObject* PyIndexRecords_FromCpp(indexRecords *cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.IndexRecords` object from the :ctype:`indexRecords` pointer given by the parameter *cpp*. If the parameter *delete* is @@ -493,7 +493,7 @@ MetaIndex (metaIndex) Check that the object *object* is an :class:`apt_pkg.MetaIndex` object and no subclass thereof. -.. cfunction:: PyObject* PyMetaIndex_FromCpp(metaIndex *cpp, bool delete=false, PyObject *owner) +.. cfunction:: PyObject* PyMetaIndex_FromCpp(metaIndex *cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.MetaIndex` object from the :ctype:`metaIndex` pointer given by the parameter *cpp*. If the parameter *delete* is @@ -522,7 +522,7 @@ Package (pkgCache::PkgIterator) Check that the object *object* is an :class:`apt_pkg.Package` object and no subclass thereof. -.. cfunction:: PyObject* PyPackage_FromCpp(pkgCache::PkgIterator &cpp, bool delete=false, PyObject *owner) +.. cfunction:: PyObject* PyPackage_FromCpp(pkgCache::PkgIterator &cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.Package` object from the :ctype:`pkgCache::PkgIterator` reference given by the parameter *cpp*. If the parameter *delete* is @@ -551,7 +551,7 @@ PackageFile (pkgCache::PkgFileIterator) Check that the object *object* is an :class:`apt_pkg.PackageFile` object and no subclass thereof. -.. cfunction:: PyObject* PyPackageFile_FromCpp(pkgCache::PkgFileIterator &cpp, bool delete=false, PyObject *owner) +.. cfunction:: PyObject* PyPackageFile_FromCpp(pkgCache::PkgFileIterator &cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.PackageFile` object from the :ctype:`pkgCache::PkgFileIterator` reference given by the parameter *cpp*. If the parameter *delete* is @@ -580,7 +580,7 @@ IndexFile (pkgIndexFile) Check that the object *object* is an :class:`apt_pkg.IndexFile` object and no subclass thereof. -.. cfunction:: PyObject* PyIndexFile_FromCpp(pkgIndexFile *cpp, bool delete=false, PyObject *owner) +.. cfunction:: PyObject* PyIndexFile_FromCpp(pkgIndexFile *cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.IndexFile` object from the :ctype:`pkgIndexFile` pointer given by the parameter *cpp*. If the parameter *delete* is @@ -610,7 +610,7 @@ PackageManager (pkgPackageManager) Check that the object *object* is an :class:`apt_pkg.PackageManager` object and no subclass thereof. -.. cfunction:: PyObject* PyPackageManager_FromCpp(pkgPackageManager *cpp, bool delete=false) +.. cfunction:: PyObject* PyPackageManager_FromCpp(pkgPackageManager *cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.PackageManager` object from the :ctype:`pkgPackageManager` pointer given by the parameter *cpp*. If the parameter *delete* is @@ -639,7 +639,7 @@ Policy (pkgPolicy) Check that the object *object* is an :class:`apt_pkg.Policy` object and no subclass thereof. -.. cfunction:: PyObject* PyPolicy_FromCpp(pkgPolicy *cpp, bool delete=false, PyObject *owner) +.. cfunction:: PyObject* PyPolicy_FromCpp(pkgPolicy *cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.Policy` object from the :ctype:`pkgPolicy` pointer given by the parameter *cpp*. If the parameter *delete* is @@ -669,7 +669,7 @@ ProblemResolver (pkgProblemResolver) Check that the object *object* is an :class:`apt_pkg.ProblemResolver` object and no subclass thereof. -.. cfunction:: PyObject* PyProblemResolver_FromCpp(pkgProblemResolver *cpp, bool delete=false, PyObject *owner) +.. cfunction:: PyObject* PyProblemResolver_FromCpp(pkgProblemResolver *cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.ProblemResolver` object from the :ctype:`pkgProblemResolver` pointer given by the parameter *cpp*. If the parameter *delete* is @@ -700,7 +700,7 @@ SourceList (pkgSourceList) Check that the object *object* is an :class:`apt_pkg.SourceList` object and no subclass thereof. -.. cfunction:: PyObject* PySourceList_FromCpp(pkgSourceList *cpp, bool delete=false) +.. cfunction:: PyObject* PySourceList_FromCpp(pkgSourceList *cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.SourceList` object from the :ctype:`pkgSourceList` pointer given by the parameter *cpp*. If the parameter *delete* is @@ -729,7 +729,7 @@ TagFile (pkgTagFile) Check that the object *object* is an :class:`apt_pkg.TagFile` object and no subclass thereof. -.. cfunction:: PyObject* PyTagFile_FromCpp(pkgTagFile &cpp, bool delete=false, PyObject *owner) +.. cfunction:: PyObject* PyTagFile_FromCpp(pkgTagFile &cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.TagFile` object from the :ctype:`pkgTagFile` reference given by the parameter *cpp*. If the parameter *delete* is @@ -758,7 +758,7 @@ TagSection (pkgTagSection) Check that the object *object* is an :class:`apt_pkg.TagSection` object and no subclass thereof. -.. cfunction:: PyObject* PyTagSection_FromCpp(pkgTagSection &cpp, bool delete=false, PyObject *owner) +.. cfunction:: PyObject* PyTagSection_FromCpp(pkgTagSection &cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.TagSection` object from the :ctype:`pkgTagSection` reference given by the parameter *cpp*. If the parameter *delete* is @@ -787,7 +787,7 @@ Version (pkgCache::VerIterator) Check that the object *object* is an :class:`apt_pkg.Version` object and no subclass thereof. -.. cfunction:: PyObject* PyVersion_FromCpp(pkgCache::VerIterator &cpp, bool delete=false, PyObject *owner) +.. cfunction:: PyObject* PyVersion_FromCpp(pkgCache::VerIterator &cpp, bool delete, PyObject *owner) Create a new :class:`apt_pkg.Version` object from the :ctype:`pkgCache::VerIterator` reference given by the parameter *cpp*. If the parameter *delete* is -- cgit v1.2.3 From c8fa835540d60393f2a1168625bf5d5ae01c4538 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sat, 13 Feb 2010 15:34:24 +0100 Subject: python/tagfile.cc: Implement the iterator protocol in TagFile. --- apt/debfile.py | 3 +-- apt/utils.py | 6 +++--- debian/changelog | 2 ++ doc/source/library/apt_pkg.rst | 29 ++++++++++++++++++++++++++--- python/tag.cc | 36 +++++++++++++++++++++++++++++++----- 5 files changed, 63 insertions(+), 13 deletions(-) (limited to 'doc/source') diff --git a/apt/debfile.py b/apt/debfile.py index 65f43f20..e27917d5 100644 --- a/apt/debfile.py +++ b/apt/debfile.py @@ -448,9 +448,8 @@ class DscSrcPackage(DebPackage): fobj = open(file) tagfile = apt_pkg.TagFile(fobj) - sec = tagfile.section try: - while tagfile.step() == 1: + for sec in tagfile: for tag in depends_tags: if not tag in sec: continue diff --git a/apt/utils.py b/apt/utils.py index 8949c2ab..61d5d54f 100644 --- a/apt/utils.py +++ b/apt/utils.py @@ -39,10 +39,10 @@ def get_release_date_from_release_file(path): if not path or not os.path.exists(path): return None tag = apt_pkg.TagFile(open(path)) - tag.step() - if not "Date" in tag.section: + section = tag.next() + if not "Date" in section: return None - date = tag.section["Date"] + date = section["Date"] return apt_pkg.str_to_time(date) def get_release_filename_for_pkg(cache, pkgname, label, release): diff --git a/debian/changelog b/debian/changelog index b09fb684..fe0d3b9a 100644 --- a/debian/changelog +++ b/debian/changelog @@ -7,6 +7,8 @@ python-apt (0.7.93.2) UNRELEASED; urgency=low * utils/migrate-0.8.py: - Improve C++ parsing and add apt.progress.old to the modules, reduces false positives. + * python/tagfile.cc: + - Implement the iterator protocol in TagFile. -- Julian Andres Klode Sun, 07 Feb 2010 19:58:40 +0100 diff --git a/doc/source/library/apt_pkg.rst b/doc/source/library/apt_pkg.rst index 7989a68a..05b3e1fc 100644 --- a/doc/source/library/apt_pkg.rst +++ b/doc/source/library/apt_pkg.rst @@ -1407,9 +1407,32 @@ section as a string. .. class:: TagFile(file) An object which represents a typical debian control file. Can be used for - Packages, Sources, control, Release, etc. + Packages, Sources, control, Release, etc. Such an object provides two + kinds of API which should not be used together: - An example for working with a TagFile could look like:: + The first API implements the iterator protocol and should be used whenever + possible because it has less side effects than the other one. It may be + used e.g. with a for loop:: + + tagf = apt_pkg.TagFile(open('/var/lib/dpkg/status')) + for section in tagfile: + print section['Package'] + + .. method:: next() + + A TagFile is its own iterator. This method is part of the iterator + protocol and returns a :class:`TagSection` object for the next + section in the file. If there is no further section, this method + raises the :exc:`StopIteration` exception. + + From Python 3 on, this method is not available anymore, and the + global function ``next()`` replaces it. + + The second API uses a shared :class:`TagSection` object which is exposed + through the :attr:`section` attribute. This object is modified by calls + to :meth:`step` and :meth:`jump`. This API provides more control and may + use less memory, but is not recommended because it works by modifying + one object. It can be used like this:: tagf = apt_pkg.TagFile(open('/var/lib/dpkg/status')) tagf.step() @@ -1418,7 +1441,7 @@ section as a string. .. method:: step Step forward to the next section. This simply returns ``1`` if OK, and - ``0`` if there is no section + ``0`` if there is no section. .. method:: offset diff --git a/python/tag.cc b/python/tag.cc index 2aaf3beb..4971a03d 100644 --- a/python/tag.cc +++ b/python/tag.cc @@ -258,6 +258,28 @@ static PyObject *TagFileStep(PyObject *Self,PyObject *Args) return HandleErrors(Py_BuildValue("i",1)); } +// TagFile Wrappers /*{{{*/ +static PyObject *TagFileNext(PyObject *Self) +{ + TagFileData &Obj = *(TagFileData *)Self; + // Replace the section. + Py_CLEAR(Obj.Section); + Obj.Section = (TagSecData*)(&PyTagSection_Type)->tp_alloc(&PyTagSection_Type, 0); + new (&Obj.Section->Object) pkgTagSection(); + Obj.Section->Owner = Self; + Py_INCREF(Obj.Section->Owner); + Obj.Section->Data = 0; + if (Obj.Object.Step(Obj.Section->Object) == false) + return HandleErrors(NULL); + Py_INCREF(Obj.Section); + return HandleErrors(Obj.Section); +} + +static PyObject *TagFileIter(PyObject *Self) { + Py_INCREF(Self); + return Self; +} + static char *doc_Offset = "Offset() -> Integer"; static PyObject *TagFileOffset(PyObject *Self,PyObject *Args) { @@ -541,9 +563,13 @@ static PyGetSetDef TagFileGetSet[] = { static char *doc_TagFile = "TagFile(file) -> TagFile() object. \n\n" "TagFile() objects provide access to debian control files, which consists\n" "of multiple RFC822-like formatted sections.\n\n" - "A file may consists of multiple sections, and you can use Step() to move\n" - "forward. The current TagSection() is available via the attribute section" - ".\n\n" + "To provide access to those sections, TagFile objects provide an iterator\n" + "which yields TagSection objects for each section.\n\n" + "TagFile objects also provide another API which uses a shared TagSection\n" + "object in the 'section' member. The functions step() and jump() can be\n" + "used to navigate in the file; and offset() tells the current position.\n\n" + "It is important to not mix the use of both APIs, because this can have\n" + "unwanted effects.\n\n" "The parameter *file* refers to an object providing a fileno() method or\n" "a file descriptor (an integer)"; @@ -578,8 +604,8 @@ PyTypeObject PyTagFile_Type = TagFileClear, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter - 0, // tp_iternext + TagFileIter, // tp_iter + TagFileNext, // tp_iternext TagFileMethods, // tp_methods 0, // tp_members TagFileGetSet, // tp_getset -- cgit v1.2.3 From 523c71a6c9b722804c65efdb79daafc56248488f Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Sat, 27 Feb 2010 14:33:50 +0100 Subject: doc: Document the new Cache functionality. --- doc/source/library/apt_pkg.rst | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'doc/source') diff --git a/doc/source/library/apt_pkg.rst b/doc/source/library/apt_pkg.rst index 05b3e1fc..bcdf2f7a 100644 --- a/doc/source/library/apt_pkg.rst +++ b/doc/source/library/apt_pkg.rst @@ -41,6 +41,11 @@ Working with the cache Return the :class:`Package()` object for the package name given by *pkgname*. + .. describe:: pkgname in cache + + Check whether a package with the name given by *pkgname* exists in + the cache. + .. method:: update(progress, list[, pulse_interval]) Update the package cache. -- cgit v1.2.3 From 78e152429187ef145124b0ac0a69ffd1d52f4ed7 Mon Sep 17 00:00:00 2001 From: Julian Andres Klode Date: Mon, 1 Mar 2010 17:12:09 +0100 Subject: Style fixes. --- apt/cache.py | 27 ++++++++++++++------------- apt/package.py | 1 - apt/progress/base.py | 6 ++++-- apt/progress/old.py | 3 ++- apt/utils.py | 14 ++++++++++---- aptsources/distro.py | 2 ++ doc/source/examples/apt-cdrom.py | 3 ++- doc/source/examples/update-print-uris.py | 1 + 8 files changed, 35 insertions(+), 22 deletions(-) (limited to 'doc/source') diff --git a/apt/cache.py b/apt/cache.py index b5733d98..e8688d64 100644 --- a/apt/cache.py +++ b/apt/cache.py @@ -46,12 +46,12 @@ class Cache(object): """Dictionary-like package cache. This class has all the packages that are available in it's - dictionary. + dictionary. Keyword arguments: progress -- a OpProgress object - rootdir -- a alternative root directory. if that is given - the system sources.list and system lists/ files are + rootdir -- a alternative root directory. if that is given + the system sources.list and system lists/ files are not read, only files relative to the given rootdir memonly -- build the cache in memory only """ @@ -95,12 +95,12 @@ class Cache(object): "/var/lib/apt/lists/partial", ] for d in dirs: - if not os.path.exists(rootdir+d): - print "creating: ",rootdir+d - os.makedirs(rootdir+d) + if not os.path.exists(rootdir + d): + print "creating: ", rootdir + d + os.makedirs(rootdir + d) for f in files: - if not os.path.exists(rootdir+f): - open(rootdir+f,"w") + if not os.path.exists(rootdir + f): + open(rootdir + f, "w") def _run_callbacks(self, name): """ internal helper to run a callback """ @@ -125,12 +125,12 @@ class Cache(object): self._weakref.clear() progress.op = _("Building data structures") - i=last=0 - size=len(self._cache.packages) + i = last = 0 + size = len(self._cache.packages) for pkg in self._cache.packages: if progress is not None and last+100 < i: progress.update(i/float(size)*100) - last=i + last = i # drop stuff with no versions (cruft) if len(pkg.version_list) > 0: self._set.add(pkg.name) @@ -376,9 +376,10 @@ class Cache(object): elif res == pm.RESULT_FAILED: raise SystemError("installArchives() failed") elif res == pm.RESULT_INCOMPLETE: - pass + pass else: - raise SystemError("internal-error: unknown result code from InstallArchives: %s" % res) + raise SystemError("internal-error: unknown result code " + "from InstallArchives: %s" % res) # reload the fetcher for media swaping fetcher.shutdown() return (res == pm.RESULT_COMPLETED) diff --git a/apt/package.py b/apt/package.py index 84a1f1e6..6bf9554b 100644 --- a/apt/package.py +++ b/apt/package.py @@ -79,7 +79,6 @@ class BaseDependency(object): def __ne__(self, other): return str.__eq__(self, other) and str.__ne__(2 * self, other) - def __init__(self, name, rel, ver, pre, rawtype=None): self.name = name self.relation = len(rel) == 1 and self.__dstr(rel) or rel diff --git a/apt/progress/base.py b/apt/progress/base.py index 8075f790..d4342de8 100644 --- a/apt/progress/base.py +++ b/apt/progress/base.py @@ -197,7 +197,8 @@ class InstallProgress(object): os._exit(obj.do_install(self.write_stream.fileno())) except AttributeError: os._exit(os.spawnlp(os.P_WAIT, "dpkg", "dpkg", "--status-fd", - str(self.write_stream.fileno()), "-i", obj)) + str(self.write_stream.fileno()), "-i", + obj)) except Exception: os._exit(apt_pkg.PackageManager.RESULT_FAILED) @@ -266,7 +267,8 @@ class InstallProgress(object): (pid, res) = (0, 0) while True: try: - select.select([self.status_stream], [], [], self.select_timeout) + select.select([self.status_stream], [], [], + self.select_timeout) except select.error, (errno_, errstr): if errno_ != errno.EINTR: raise diff --git a/apt/progress/old.py b/apt/progress/old.py index 15ead890..b2f6f0d5 100644 --- a/apt/progress/old.py +++ b/apt/progress/old.py @@ -191,7 +191,8 @@ class InstallProgress(DumbInstallProgress, base.InstallProgress): selectTimeout = AttributeDeprecatedBy('select_timeout') statusChange = function_deprecated_by(base.InstallProgress.status_change) - updateInterface = function_deprecated_by(base.InstallProgress.update_interface) + updateInterface = function_deprecated_by( + base.InstallProgress.update_interface) waitChild = function_deprecated_by(base.InstallProgress.wait_child) diff --git a/apt/utils.py b/apt/utils.py index 61d5d54f..dd52f824 100644 --- a/apt/utils.py +++ b/apt/utils.py @@ -17,9 +17,11 @@ # this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -import apt_pkg import os.path +import apt_pkg + + def get_maintenance_end_date(release_date, m_months): """ get the (year, month) tuple when the maintenance for the distribution @@ -28,10 +30,12 @@ def get_maintenance_end_date(release_date, m_months): """ years = m_months / 12 months = m_months % 12 - support_end_year = release_date.year + years + (release_date.month + months)/12 + support_end_year = (release_date.year + years + + (release_date.month + months)/12) support_end_month = (release_date.month + months) % 12 return (support_end_year, support_end_month) + def get_release_date_from_release_file(path): """ return the release date as time_t for the given release file @@ -45,6 +49,7 @@ def get_release_date_from_release_file(path): date = section["Date"] return apt_pkg.str_to_time(date) + def get_release_filename_for_pkg(cache, pkgname, label, release): " get the release file that provides this pkg " if pkgname not in cache: @@ -54,7 +59,7 @@ def get_release_filename_for_pkg(cache, pkgname, label, release): # look for the version that comes from the repos with # the given label and origin for aver in pkg._pkg.version_list: - if aver == None or aver.file_list == None: + if aver is None or aver.file_list is None: continue for ver_file, index in aver.file_list: #print verFile @@ -71,6 +76,7 @@ def get_release_filename_for_pkg(cache, pkgname, label, release): indexfile.describe == m.describe and indexfile.is_trusted): dir = apt_pkg.config.find_dir("Dir::State::lists") - name = apt_pkg.uri_to_filename(metaindex.uri)+"dists_%s_Release" % metaindex.dist + name = (apt_pkg.uri_to_filename(metaindex.uri) + + "dists_%s_Release" % metaindex.dist) return dir+name return None diff --git a/aptsources/distro.py b/aptsources/distro.py index 1e60a0ed..e51fbe9f 100644 --- a/aptsources/distro.py +++ b/aptsources/distro.py @@ -437,6 +437,7 @@ class UbuntuDistribution(Distribution): Distribution.get_mirrors( self, mirror_template="http://%s.archive.ubuntu.com/ubuntu/") + def _lsb_release(): """Call lsb_release --idrc and return a mapping.""" from subprocess import Popen, PIPE @@ -454,6 +455,7 @@ def _lsb_release(): print 'WARNING: lsb_release failed, using defaults:', exc return result + def get_distro(id=None, codename=None, description=None, release=None): """ Check the currently used distribution and return the corresponding diff --git a/doc/source/examples/apt-cdrom.py b/doc/source/examples/apt-cdrom.py index a20b0f12..cb23e97d 100644 --- a/doc/source/examples/apt-cdrom.py +++ b/doc/source/examples/apt-cdrom.py @@ -30,7 +30,8 @@ def show_help(): " -f Fast mode, don't check package files\n" " -a Thorough scan mode\n" " -c=? Read this configuration file\n" - " -o=? Set an arbitrary configuration option, eg -o dir::cache=/tmp\n" + " -o=? Set an arbitrary configuration option, eg -o " + "dir::cache=/tmp\n" "See fstab(5)") return 0 diff --git a/doc/source/examples/update-print-uris.py b/doc/source/examples/update-print-uris.py index f078cdc5..dbe1dfde 100644 --- a/doc/source/examples/update-print-uris.py +++ b/doc/source/examples/update-print-uris.py @@ -4,6 +4,7 @@ This behaves somewhat like apt-get --print-uris update.""" import apt_pkg + def main(): apt_pkg.init_config() apt_pkg.init_system() -- cgit v1.2.3