diff options
Diffstat (limited to 'doc/source')
42 files changed, 3101 insertions, 2040 deletions
diff --git a/doc/source/apt/index.rst b/doc/source/apt/index.rst deleted file mode 100644 index bf39354f..00000000 --- a/doc/source/apt/index.rst +++ /dev/null @@ -1,61 +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 - :members: - - - - -.. 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. - -.. class:: ProblemResolver - - Please see :class:`apt.cache.ProblemResolver` for documentation. 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_pkg/cache.rst b/doc/source/apt_pkg/cache.rst deleted file mode 100644 index ca9f8b49..00000000 --- a/doc/source/apt_pkg/cache.rst +++ /dev/null @@ -1,1239 +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:: 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*. - - .. 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[, pulseInterval]) - - 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`. - - The optional parameter *pulseInterval* describes the interval between - the calls to the :meth:`FetchProgress.pulse` method. - - .. 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 translated string, eg. "Depends". - - .. attribute:: UntranslatedDepType - - The type of the dependency, as string, eg. "Depends". - - .. attribute:: DepTypeEnum - - The type of the dependency, as integer that matches a value - of :ref:`Dependency types <DependencyTypes>`. - - .. 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`. - - .. 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. - - .. 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 4256d971..00000000 --- a/doc/source/apt_pkg/index.rst +++ /dev/null @@ -1,396 +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 ---------------------- - - -.. 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. - -.. function:: newConfiguration() - - Return a new :class:`Configuration` 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, in which case the md5sum of its contents is returned. - -.. 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. - -.. 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. - -Other functions ----------------- - -.. 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:: 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*. - ===== ============================================= - - -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 -.. data:: CurStateInstalled -.. data:: CurStateNotInstalled -.. data:: CurStateUnPacked - -.. _DependencyTypes: - - -Dependency types -^^^^^^^^^^^^^^^^ -.. data:: DepConflicts -.. data:: DepDepends -.. data:: DepDpkgBreaks -.. data:: DepEnhances -.. 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/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/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 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/conf.py b/doc/source/conf.py index 40154a6f..0a9d5ed5 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,9 +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 + + # General configuration # --------------------- @@ -41,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' @@ -50,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' @@ -60,13 +73,25 @@ copyright = u'2009, Julian Andres Klode <jak@debian.org>' # |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 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. @@ -134,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. @@ -145,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 @@ -183,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 <jak@debian.org>', '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/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/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() diff --git a/doc/source/examples/cache-packages.py b/doc/source/examples/cache-packages.py index 1abe7cf2..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() - cache = apt_pkg.GetCache() + 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 f25975d3..f4cc2e66 100644 --- a/doc/source/examples/cache-pkgfile.py +++ b/doc/source/examples/cache-pkgfile.py @@ -5,20 +5,20 @@ import apt_pkg def main(): """Example for PackageFile()""" apt_pkg.init() - cache = apt_pkg.GetCache() - for pkgfile in cache.FileList: - print 'Package-File:', pkgfile.FileName - print 'Index-Type:', pkgfile.IndexType # 'Debian Package Index' - if pkgfile.NotSource: + cache = apt_pkg.Cache() + for pkgfile in cache.file_list: + print 'Package-File:', pkgfile.filename + 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 3ca16e45..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.GetCache() + 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 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/index.rst b/doc/source/index.rst deleted file mode 100644 index 23ea4cca..00000000 --- a/doc/source/index.rst +++ /dev/null @@ -1,41 +0,0 @@ -Welcome to python-apt's documentation! -====================================== - -.. note:: - - This documentation can not be considered complete at the moment. But it - provides better documentation than the documentation available through - pydoc. - -.. note:: - - - This documentation has been created by Sphinx, using reStructuredText files - written by Julian Andres Klode <jak@debian.org>, and in case of the apt - package, from the documentation shipped in the modules. - - -Contents: - -.. toctree:: - :maxdepth: 2 - - apt/index - apt_pkg/index - apt_inst - aptsources/index - coding - - - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` - - -TODO -====== -.. todolist:: diff --git a/doc/source/apt/cache.rst b/doc/source/library/apt.cache.rst index beae74a2..d0e44598 100644 --- a/doc/source/apt/cache.rst +++ b/doc/source/library/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 The ProblemResolver class diff --git a/doc/source/apt/cdrom.rst b/doc/source/library/apt.cdrom.rst index 56381f14..56381f14 100644 --- a/doc/source/apt/cdrom.rst +++ b/doc/source/library/apt.cdrom.rst diff --git a/doc/source/apt/debfile.rst b/doc/source/library/apt.debfile.rst index 7133b5a8..7133b5a8 100644 --- a/doc/source/apt/debfile.rst +++ b/doc/source/library/apt.debfile.rst diff --git a/doc/source/apt/package.rst b/doc/source/library/apt.package.rst index bb74915e..4b143b8a 100644 --- a/doc/source/apt/package.rst +++ b/doc/source/library/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/apt/progress.gtk2.rst b/doc/source/library/apt.progress.gtk2.rst index a83ab111..b16c903c 100644 --- a/doc/source/apt/progress.gtk2.rst +++ b/doc/source/library/apt.progress.gtk2.rst @@ -1,5 +1,5 @@ -:mod:`apt.progress.gtk2` --- GTK widgets -======================================== +:mod:`apt.progress.gtk2` --- Progress reporting for GTK+ interfaces +=================================================================== .. automodule:: apt.progress.gtk2 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/apt_inst.rst b/doc/source/library/apt_inst.rst index 97705f61..ae26a8a1 100644 --- a/doc/source/apt_inst.rst +++ b/doc/source/library/apt_inst.rst @@ -8,32 +8,47 @@ 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 :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.8.0 + Added support for file descriptors and objects implementing a :meth:`fileno` method. 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 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:: - 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. -.. function:: tarExtract(file,func,comp) + .. versionchanged:: 0.8.0 + Added support for file descriptors and objects implementing a :meth:`fileno` method. + +.. function:: tar_extract(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.8.0 + Added support for file descriptors and objects implementing a :meth:`fileno` method. Callback @@ -51,11 +66,14 @@ 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*. + 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. -.. function:: debExtractControl(file[, member='control']) + .. versionchanged:: 0.8.0 + Added support for file descriptors and objects implementing a :meth:`fileno` method. + +.. function:: deb_extract_control(file[, member='control']) + + Return the indicated file as a string from the control tar. The default + is 'control'. - Return the indicated file 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")) + print deb_extract_control(open("package.deb")) - :return: The contents of the file, as :class:`str`. + .. versionchanged:: 0.8.0 + Added support for file descriptors and objects implementing a :meth:`fileno` method. .. _emulating-dpkg-extract: @@ -82,15 +108,15 @@ 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 +.. literalinclude:: ../examples/dpkg-extract.py .. _emulating-dpkg-contents: Example: Emulating :program:`dpkg` :option:`--contents` ------------------------------------------------------- -.. literalinclude:: examples/dpkg-contents.py +.. literalinclude:: ../examples/dpkg-contents.py Example: Emulating :program:`dpkg` :option:`--info` ---------------------------------------------------- -.. literalinclude:: examples/dpkg-info.py +.. 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..5876fb8d --- /dev/null +++ b/doc/source/library/apt_pkg.rst @@ -0,0 +1,2000 @@ +: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 + + 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 +---------------------- +.. 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:: update(progress, list[, pulse_interval]) + + Update the package cache. + + The parameter *progress* points to an :class:`apt.progress.FetchProgress()` + object. The parameter *list* refers to a :class:`SourceList()` object. + + The optional parameter *pulse_interval* describes the interval between + the calls to the :meth:`FetchProgress.pulse` method. + + .. attribute:: depends_count + + The total number of dependencies. + + .. attribute:: package_count + + 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. + + .. 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_pinfile() + + 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_auto(pkg) + + Mark the :class:`Package` *pkg* as automatically installed. + + .. 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. + + .. attribute:: policy + + The underlying :class:`Policy` object used by the :class:`DepCache` to + select candidate versions. + + +.. 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:`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:: current_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:: dep_type_enum + + The type of the dependency, as an integer which can be compared to + one of the TYPE_* constants below. + + .. attribute:: dep_type_untranslated + + The type of the depndency, as an untranslated string. + + .. attribute:: id + + The ID of the package, as integer. + + .. attribute:: TYPE_CONFLICTS + + Constant for checking against dep_type_enum + + .. attribute:: TYPE_DEPENDS + + Constant for checking against dep_type_enum + + .. attribute:: TYPE_DPKG_BREAKS + + Constant for checking against dep_type_enum + + .. attribute:: TYPE_ENHANCES + + Constant for checking against dep_type_enum + + .. attribute:: TYPE_OBSOLETES + + Constant for checking against dep_type_enum + + .. attribute:: TYPE_PREDEPENDS + + Constant for checking against dep_type_enum + + .. attribute:: TYPE_RECOMMENDS + + Constant for checking against dep_type_enum + + .. attribute:: TYPE_REPLACES + + Constant for checking against dep_type_enum + + .. attribute:: TYPE_SUGGESTS + + Constant for checking against dep_type_enum + +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). + + + +Index Files +------------- + + +.. todo:: + + Complete them + +.. class:: MetaIndex + + .. attribute:: uri + .. attribute:: dist + .. attribute:: is_trusted + .. attribute:: index_files + + +.. class:: PackageIndexFile + + .. method:: archive_uri(path) + + Return the full url to path in the archive. + + .. attribute:: label + + Return the Label. + + .. attribute:: describe + + A description of the :class:`PackageIndexFile`. + + .. 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. + + +.. 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 +-------- + +.. 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"``. + + +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 and attributes: + + .. 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. (???) + + .. 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 + :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:: mode + + A string indicating the current mode e.g. ``"Fetching"``. + + .. attribute:: is_trusted + + Can the file be trusted? + + .. attribute:: filesize + + 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:: destfile + + 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. 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 + 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. + + 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 +------ +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 + 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. + +.. 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 + 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:: 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 + +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 + 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``. + + .. 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:: 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*. + +.. data:: config + + A :class:`Configuration()` object with the default configuration. This + object is initialized by calling :func:`init_config`. + + +.. 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 +-------- +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) + + 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. If this fails and *errors* is **True**, the function raises an + error. If *errors* is **False**, the function 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. + +.. function:: pkgsystem_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. + +.. function:: pkgsystem_unlock() + + Unlock the global pkgsystem. This reverts the effect of + :func:`pkgsystem_unlock`. + + +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. + + .. attribute:: list + + A list of :class:`MetaIndex` objects. + +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 + +.. _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_DEINSTALL +.. 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). diff --git a/doc/source/aptsources/distinfo.rst b/doc/source/library/aptsources.distinfo.rst index 96f9445d..033ef483 100644 --- a/doc/source/aptsources/distinfo.rst +++ b/doc/source/library/aptsources.distinfo.rst @@ -1,10 +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: - .. note:: - - This part of the documentation is created automatically. diff --git a/doc/source/aptsources/distro.rst b/doc/source/library/aptsources.distro.rst index 06ca0fda..6ebe438c 100644 --- a/doc/source/aptsources/distro.rst +++ b/doc/source/library/aptsources.distro.rst @@ -1,10 +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: - .. note:: - - This part of the documentation is created automatically. diff --git a/doc/source/aptsources/sourceslist.rst b/doc/source/library/aptsources.sourceslist.rst index 509db3ce..79b8dd01 100644 --- a/doc/source/aptsources/sourceslist.rst +++ b/doc/source/library/aptsources.sourceslist.rst @@ -1,10 +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: - .. note:: - - This part of the documentation is created automatically. 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 %} + <h1>{{ docstitle|e }}</h1> + <p> + Welcome! This is + {% block description %}the documentation for {{ project|e }} + {{ release|e }}{% if last_updated %}, last updated {{ last_updated|e }}{% endif %}{% endblock %}. + </p> + + <p> + This documentation has been created using Sphinx and reStructuredText files + written by Julian Andres Klode <jak@debian.org>. + </p> + + + + + <p><strong>Parts of the documentation:</strong></p> + <table class="contentstable" align="center"><tr> + <td width="50%"> + <p class="biglink"><a class="biglink" href="{{ pathto("whatsnew/" + version) }}">What's new in Python {{ version }}?</a><br/> + <span class="linkdescr">or <a href="{{ pathto("whatsnew/index") }}">all "What's new" documents</a></span></span></p> + <p class="biglink"><a class="biglink" href="{{ pathto("library/index") }}">Library Reference</a><br/> + <span class="linkdescr">keep this under your pillow</span></p> + <p class="biglink"><a class="biglink" href="{{ pathto("tutorials/index") }}">Tutorials</a><br/> + <span class="linkdescr">examples and more...</span></p> + </td><td width="50%"> + <p class="biglink"><a class="biglink" href="{{ pathto("c++/embedding") }}">Embedding</a><br/> + <span class="linkdescr">tutorial for C++ programmers</span></p> + <p class="biglink"><a class="biglink" href="{{ pathto("c++/api") }}">C++ API</a><br/> + <span class="linkdescr">reference for C++ programmers</span></p> + </td></tr> + </table> + + <p><strong>Indices and tables:</strong></p> + <table class="contentstable" align="center"><tr> + <td width="50%"> + <p class="biglink"><a class="biglink" href="{{ pathto("modindex") }}">Global Module Index</a><br/> + <span class="linkdescr">quick access to all modules</span></p> + <p class="biglink"><a class="biglink" href="{{ pathto("genindex") }}">General Index</a><br/> + <span class="linkdescr">all functions, classes, terms</span></p> + </td><td width="50%"> + <p class="biglink"><a class="biglink" href="{{ pathto("search") }}">Search page</a><br/> + <span class="linkdescr">search this documentation</span></p> + <p class="biglink"><a class="biglink" href="{{ pathto("contents") }}">Complete Table of Contents</a><br/> + <span class="linkdescr">lists all sections and subsections</span></p> + </td></tr> + </table> + +{% 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 %} + <li><img src="{{ pathto('_static/py.png', 1) }}" alt="" + style="vertical-align: middle; margin-top: -1px"/></li> + <li><a href="{{ pathto('index') }}">{{ shorttitle }}</a>{{ reldelim1 }}</li> +{% endblock %} +{% block extrahead %} + <link rel="shortcut icon" type="image/png" href="{{ pathto('_static/py.png', 1) }}" /> +{{ 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 <jak@debian.org> +: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/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 <jak@debian.org> +: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 + 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 <jak@debian.org> +: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 new file mode 100644 index 00000000..8a2b52e8 --- /dev/null +++ b/doc/source/whatsnew/0.8.0.rst @@ -0,0 +1,185 @@ +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**. 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: + + * + |
