debian.deb822 module¶
Dictionary-like interfaces to RFC822-like files
The Python deb822 aims to provide a dict-like interface to various RFC822-like
Debian data formats, like Packages/Sources, .changes/.dsc, pdiff Index files,
etc. As well as the generic Deb822
class, the specialised versions
of these classes (Packages
, Sources
, Changes
etc)
know about special fields that contain specially formatted data such as
dependency lists or whitespace separated sub-fields.
This module has few external dependencies, but can use python-apt if available to parse the data, which gives a very significant performance boost when iterating over big Packages files.
Whitespace separated data within fields are known as “multifields”. The “Files” field in Sources files, for instance, has three subfields, while “Files” in .changes files, has five; the relevant classes here know this and correctly handle these cases.
Key lookup in Deb822 objects and their multifields is case-insensitive, but the original case is always preserved, for example when printing the object.
The Debian project and individual developers make extensive use of GPG signatures including in-line signatures. GPG signatures are automatically detected, verified and the payload then offered to the parser.
Relevant documentation on the Deb822 file formats available here.
- deb-control(5), the control file in the binary package (generated from debian/control in the source package)
- deb-changes(5), changes files that developers upload to add new packages to the archive.
- dsc(5), Debian Source Control file that defines the files that are part of a source package.
- Debian mirror format, including documentation for Packages, Sources files etc.
Overview of deb822 Classes¶
Classes that deb822 provides:
Deb822
base class with no multifields. A Deb822 object holds a single entry from a Deb822-style file, where paragraphs are separated by blank lines and there may be many paragraphs within a file. Theiter_paragraphs()
function yields paragraphs from a data source.
Packages
represents a Packages file from a Debian mirror. It extends the Deb822 class by interpreting fields that are package relationships (Depends, Recommends etc). Iteration is forced through python-apt for performance and conformance.
Dsc
represents .dsc files (Debian Source Control) that are the metadata file of the source package.Multivalued fields:
- Files: md5sum, size, name
- Checksums-Sha1: sha1, size, name
- Checksums-Sha256: sha256, size, name
- Checksums-Sha512: sha512, size, name
Sources
represents a Sources file from a Debian mirror. It extends the Dsc class by interpreting fields that are package relationships (Build-Depends, Build-Conflicts etc). Iteration is forced through python-apt for performance and conformance.
Release
represents a Release file from a Debian mirror.Multivalued fields:
- MD5Sum: md5sum, size, name
- SHA1: sha1, size, name
- SHA256: sha256, size, name
- SHA512: sha512, size, name
Changes
represents a .changes file that is uploaded to “change the archive” by including new source or binary packages.Multivalued fields:
- Files: md5sum, size, section, priority, name
- Checksums-Sha1: sha1, size, name
- Checksums-Sha256: sha256, size, name
- Checksums-Sha512: sha512, size, name
PdiffIndex
represents a pdiff Index file (foo.diff/Index) file from a Debian mirror.Multivalued fields:
- SHA1-Current: SHA1, size
- SHA1-History: SHA1, size, date
- SHA1-Patches: SHA1, size, date
Removals
represents the ftp-master removals file listing when and why source and binary packages are removed from the archive.
Input¶
Deb822 objects are normally initialized from a file object (from which at most one paragraph is read) or a string. Alternatively, any sequence that returns one line of input at a time may be used, e.g a list of strings.
PGP signatures, if present, will be stripped.
Example:
>>> from debian.deb822 import Deb822
>>> filename = '/var/lib/apt/lists/deb.debian.org_debian_dists_sid_InRelease'
>>> with open(filename) as fh:
... rel = Deb822(fh)
>>> print('Origin: {Origin}\nCodename: {Codename}\nDate: {Date}'.format_map(rel))
Origin: Debian
Codename: sid
Date: Sat, 07 Apr 2018 14:41:12 UTC
>>> print(list(rel.keys()))
['Origin', 'Label', 'Suite', 'Codename', 'Changelogs', 'Date',
'Valid-Until', 'Acquire-By-Hash', 'Architectures', 'Components',
'Description', 'MD5Sum', 'SHA256']
In the above, the MD5Sum and SHA256 fields are just a very long string. If
instead the Release
class is used, these fields are interpreted and
can be addressed:
>>> from debian.deb822 import Release
>>> filename = '/var/lib/apt/lists/deb.debian.org_debian_dists_sid_InRelease'
>>> with open(filename) as fh:
... rel = Release(fh)
>>> wanted = 'main/binary-amd64/Packages'
>>> [(l['sha256'], l['size']) for l in rel['SHA256'] if l['name'] == wanted]
[('c0f7aa0b92ebd6971c0b64f93f52a8b2e15b0b818413ca13438c50eb82586665', '45314424')]
Iteration¶
All classes use the iter_paragraphs()
class method to easily
iterate through each paragraph in a file that contains multiple entries
(e.g. a Packages.gz file).
For example:
>>> with open('/mirror/debian/dists/sid/main/binary-i386/Sources') as f:
... for src in Sources.iter_paragraphs(f):
... print(src['Package'], src['Version'])
The iter_paragraphs methods can use python-apt if available to parse
the data, since it significantly boosts performance.
If python-apt is not present and the
file is a compressed file, it must first be decompressed manually. Note that
python-apt should not be used on debian/control files since python-apt is
designed to be strict and fast while the syntax of debian/control is a
superset of what python-apt is designed to parse.
This function is overridden to force use of the
python-apt parser using use_apt_pkg in the iter_paragraphs()
and iter_paragraphs()
functions.
Sample usage¶
Manipulating a .dsc file:
from debian import deb822
with open('foo_1.1.dsc') as f:
d = deb822.Dsc(f)
source = d['Source']
version = d['Version']
for f in d['Files']:
print('Name:', f['name'])
print('Size:', f['size'])
print('MD5sum:', f['md5sum'])
# If we like, we can change fields
d['Standards-Version'] = '3.7.2'
# And then dump the new contents
with open('foo_1.1.dsc2', 'w') as new_dsc:
d.dump(new_dsc)
(TODO: Improve, expand)
Deb822 Classes¶
-
class
debian.deb822.
Changes
(*args, **kwargs)¶ Bases:
debian.deb822._gpg_multivalued
Representation of a .changes (archive changes) file
This class is a thin wrapper around the transparent GPG handling of
_gpg_multivalued
and the parsing ofDeb822
.-
_multivalued_fields
= {'checksums-sha1': ['sha1', 'size', 'name'], 'checksums-sha256': ['sha256', 'size', 'name'], 'files': ['md5sum', 'size', 'section', 'priority', 'name'], 'checksums-sha512': ['sha512', 'size', 'name']}¶
-
get_pool_path
()¶ Return the path in the pool where the files would be installed
-
-
class
debian.deb822.
Deb822
(sequence=None, fields=None, _parsed=None, encoding='utf-8')¶ Bases:
debian.deb822.Deb822Dict
Generic Deb822 data
Parameters: - sequence – a string, or any any object that returns a line of input each time, normally a file. Alternately, sequence can be a dict that contains the initial key-value pairs. When python-apt is present, sequence can also be a compressed object, for example a file object associated to something.gz.
- fields – if given, it is interpreted as a list of fields that should be parsed (the rest will be discarded).
- _parsed – internal parameter.
- encoding – When parsing strings, interpret them in this encoding. (All values are given back as unicode objects, so an encoding is necessary in order to properly interpret the strings.)
-
_internal_parser
(sequence, fields=None)¶
-
_mergeFields
(*args, **kwargs)¶
-
_merge_fields
(s1, s2)¶
-
static
_skip_useless_lines
(sequence)¶ Yields only lines that do not begin with ‘#’.
Also skips any blank lines at the beginning of the input.
-
dump
(fd=None, encoding=None, text_mode=False)¶ Dump the the contents in the original format
Parameters: - fd – file-like object to which the data should be written (see notes below)
- encoding – str, optional (Defaults to object default). Encoding to use when writing out the data.
- text_mode – bool, optional (Defaults to
False
). Encoding should be undertaken by this function rather than by the caller.
If fd is None, returns a unicode object. Otherwise, fd is assumed to be a file-like object, and this method will write the data to it instead of returning a unicode object.
If fd is not none and text_mode is False, the data will be encoded to a byte string before writing to the file. The encoding used is chosen via the encoding parameter; None means to use the encoding the object was initialized with (utf-8 by default). This will raise UnicodeEncodeError if the encoding can’t support all the characters in the Deb822Dict values.
-
get_as_string
(key)¶ Return the self[key] as a string (or unicode)
The default implementation just returns unicode(self[key]); however, this can be overridden in subclasses (e.g. _multivalued) that can take special values.
-
get_gpg_info
(keyrings=None)¶ Return a GpgInfo object with GPG signature information
This method will raise ValueError if the signature is not available (e.g. the original text cannot be found).
Parameters: keyrings – list of keyrings to use (see GpgInfo.from_sequence)
-
classmethod
gpg_stripped_paragraph
(sequence)¶
-
isMultiLine
(*args, **kwargs)¶
-
isSingleLine
(*args, **kwargs)¶
-
static
is_multi_line
(s)¶
-
static
is_single_line
(s)¶
-
classmethod
iter_paragraphs
(sequence, fields=None, use_apt_pkg=False, shared_storage=False, encoding='utf-8')¶ Generator that yields a Deb822 object for each paragraph in sequence.
Parameters: - sequence – same as in __init__.
- fields – likewise.
- use_apt_pkg – if sequence is a file, apt_pkg can be used if available to parse the file, since it’s much much faster. Set this parameter to True to enable use of apt_pkg. Note that the TagFile parser from apt_pkg is a much stricter parser of the Deb822 format, particularly with regards whitespace between paragraphs and comments within paragraphs. If these features are required (for example in debian/control files), ensure that this parameter is set to False.
- shared_storage – not used, here for historical reasons. Deb822 objects never use shared storage anymore.
- encoding – Interpret the paragraphs in this encoding. (All values are given back as unicode objects, so an encoding is necessary in order to properly interpret the strings.)
-
mergeFields
(*args, **kwargs)¶
-
merge_fields
(key, d1, d2=None)¶
-
static
split_gpg_and_payload
(sequence)¶ Return a (gpg_pre, payload, gpg_post) tuple
Each element of the returned tuple is a list of lines (with trailing whitespace stripped).
-
static
validate_input
(key, value)¶ Raise ValueError if value is not a valid value for key
Subclasses that do interesting things for different keys may wish to override this method.
-
class
debian.deb822.
Deb822Dict
(_dict=None, _parsed=None, _fields=None, encoding='utf-8')¶ Bases:
collections.abc.MutableMapping
A dictionary-like object suitable for storing RFC822-like data.
- Deb822Dict behaves like a normal dict, except:
- key lookup is case-insensitive
- key order is preserved
- if initialized with a _parsed parameter, it will pull values from that dictionary-like object as needed (rather than making a copy). The _parsed dict is expected to be able to handle case-insensitive keys.
If _parsed is not None, an optional _fields parameter specifies which keys in the _parsed dictionary are exposed.
-
_detect_encoding
(value)¶ If value is not already Unicode, decode it intelligently.
-
copy
()¶
-
class
debian.deb822.
Dsc
(*args, **kwargs)¶ Bases:
debian.deb822._gpg_multivalued
Representation of a .dsc (Debian Source Control) file
This class is a thin wrapper around the transparent GPG handling of
_gpg_multivalued
and the parsing ofDeb822
.-
_multivalued_fields
= {'checksums-sha1': ['sha1', 'size', 'name'], 'checksums-sha256': ['sha256', 'size', 'name'], 'files': ['md5sum', 'size', 'name'], 'checksums-sha512': ['sha512', 'size', 'name']}¶
-
-
exception
debian.deb822.
Error
¶ Bases:
Exception
Base class for custom exceptions in this module.
-
class
debian.deb822.
GpgInfo
(*args, **kwargs)¶ Bases:
dict
A wrapper around gnupg parsable output obtained via –status-fd
This class is really a dictionary containing parsed output from gnupg plus some methods to make sense of the data. Keys are keywords and values are arguments suitably split. See /usr/share/doc/gnupg/DETAILS.gz
-
static
_get_full_bytes
(sequence)¶ Return a byte string from a sequence of lines of bytes.
This method detects if the sequence’s lines are newline-terminated, and constructs the byte string appropriately.
-
classmethod
from_file
(target, *args, **kwargs)¶ Create a new GpgInfo object from the given file.
See GpgInfo.from_sequence.
-
classmethod
from_output
(out, err=None)¶ Create a GpgInfo object based on the gpg or gpgv output
Create a new GpgInfo object from gpg(v) –status-fd output (out) and optionally collect stderr as well (err).
Both out and err can be lines in newline-terminated sequence or regular strings.
-
classmethod
from_sequence
(sequence, keyrings=None, executable=None)¶ Create a new GpgInfo object from the given sequence.
Parameters: - sequence – sequence of lines of bytes or a single byte string
- keyrings – list of keyrings to use (default: [‘/usr/share/keyrings/debian-keyring.gpg’])
- executable – list of args for subprocess.Popen, the first element being the gpgv executable (default: [‘/usr/bin/gpgv’])
-
uid
()¶ Return the primary ID of the signee key, None is not available
-
uidkeys
= ('GOODSIG', 'EXPSIG', 'EXPKEYSIG', 'REVKEYSIG', 'BADSIG')¶
-
valid
()¶ Is the signature valid?
-
static
-
class
debian.deb822.
OrderedSet
(iterable=None)¶ Bases:
object
A set-like object that preserves order when iterating over it
We use this to keep track of keys in Deb822Dict, because it’s much faster to look up if a key is in a set than in a list.
-
add
(item)¶
-
append
(item)¶
-
extend
(iterable)¶
-
remove
(item)¶
-
-
class
debian.deb822.
Packages
(*args, **kwargs)¶ Bases:
debian.deb822.Deb822
,debian.deb822._PkgRelationMixin
Represent an APT binary package list
This class is a thin wrapper around the parsing of
Deb822
, using the field parsing of_PkgRelationMixin
.-
_relationship_fields
= ['depends', 'pre-depends', 'recommends', 'suggests', 'breaks', 'conflicts', 'provides', 'replaces', 'enhances']¶
-
classmethod
iter_paragraphs
(sequence, fields=None, use_apt_pkg=True, shared_storage=False, encoding='utf-8')¶ Generator that yields a Deb822 object for each paragraph in Packages.
Note that this overloaded form of the generator uses apt_pkg (a strict but fast parser) by default.
See the
iter_paragraphs()
function for details.
-
-
class
debian.deb822.
PdiffIndex
(*args, **kwargs)¶ Bases:
debian.deb822._multivalued
Representation of a foo.diff/Index file from a Debian mirror
This class is a thin wrapper around the transparent GPG handling of
_gpg_multivalued
and the parsing ofDeb822
.-
_fixed_field_lengths
¶
-
_get_size_field_length
(key)¶
-
_multivalued_fields
= {'sha1-patches': ['SHA1', 'size', 'date'], 'sha1-current': ['SHA1', 'size'], 'sha1-history': ['SHA1', 'size', 'date']}¶
-
-
class
debian.deb822.
PkgRelation
¶ Bases:
object
Inter-package relationships
Structured representation of the relationships of a package to another, i.e. of what can appear in a Deb882 field like Depends, Recommends, Suggests, ... (see Debian Policy 7.1).
-
class
ArchRestriction
(enabled, arch)¶ Bases:
tuple
-
_asdict
()¶ Return a new OrderedDict which maps field names to their values.
-
_fields
= ('enabled', 'arch')¶
-
classmethod
_make
(iterable, new=<built-in method __new__ of type object>, len=<built-in function len>)¶ Make a new ArchRestriction object from a sequence or iterable
-
_replace
(_self, **kwds)¶ Return a new ArchRestriction object replacing specified fields with new values
-
_source
= "from builtins import property as _property, tuple as _tuple\nfrom operator import itemgetter as _itemgetter\nfrom collections import OrderedDict\n\nclass ArchRestriction(tuple):\n 'ArchRestriction(enabled, arch)'\n\n __slots__ = ()\n\n _fields = ('enabled', 'arch')\n\n def __new__(_cls, enabled, arch):\n 'Create new instance of ArchRestriction(enabled, arch)'\n return _tuple.__new__(_cls, (enabled, arch))\n\n @classmethod\n def _make(cls, iterable, new=tuple.__new__, len=len):\n 'Make a new ArchRestriction object from a sequence or iterable'\n result = new(cls, iterable)\n if len(result) != 2:\n raise TypeError('Expected 2 arguments, got %d' % len(result))\n return result\n\n def _replace(_self, **kwds):\n 'Return a new ArchRestriction object replacing specified fields with new values'\n result = _self._make(map(kwds.pop, ('enabled', 'arch'), _self))\n if kwds:\n raise ValueError('Got unexpected field names: %r' % list(kwds))\n return result\n\n def __repr__(self):\n 'Return a nicely formatted representation string'\n return self.__class__.__name__ + '(enabled=%r, arch=%r)' % self\n\n def _asdict(self):\n 'Return a new OrderedDict which maps field names to their values.'\n return OrderedDict(zip(self._fields, self))\n\n def __getnewargs__(self):\n 'Return self as a plain tuple. Used by copy and pickle.'\n return tuple(self)\n\n enabled = _property(_itemgetter(0), doc='Alias for field number 0')\n\n arch = _property(_itemgetter(1), doc='Alias for field number 1')\n\n"¶
-
arch
¶ Alias for field number 1
-
enabled
¶ Alias for field number 0
-
-
class
PkgRelation.
BuildRestriction
(enabled, profile)¶ Bases:
tuple
-
_asdict
()¶ Return a new OrderedDict which maps field names to their values.
-
_fields
= ('enabled', 'profile')¶
-
classmethod
_make
(iterable, new=<built-in method __new__ of type object>, len=<built-in function len>)¶ Make a new BuildRestriction object from a sequence or iterable
-
_replace
(_self, **kwds)¶ Return a new BuildRestriction object replacing specified fields with new values
-
_source
= "from builtins import property as _property, tuple as _tuple\nfrom operator import itemgetter as _itemgetter\nfrom collections import OrderedDict\n\nclass BuildRestriction(tuple):\n 'BuildRestriction(enabled, profile)'\n\n __slots__ = ()\n\n _fields = ('enabled', 'profile')\n\n def __new__(_cls, enabled, profile):\n 'Create new instance of BuildRestriction(enabled, profile)'\n return _tuple.__new__(_cls, (enabled, profile))\n\n @classmethod\n def _make(cls, iterable, new=tuple.__new__, len=len):\n 'Make a new BuildRestriction object from a sequence or iterable'\n result = new(cls, iterable)\n if len(result) != 2:\n raise TypeError('Expected 2 arguments, got %d' % len(result))\n return result\n\n def _replace(_self, **kwds):\n 'Return a new BuildRestriction object replacing specified fields with new values'\n result = _self._make(map(kwds.pop, ('enabled', 'profile'), _self))\n if kwds:\n raise ValueError('Got unexpected field names: %r' % list(kwds))\n return result\n\n def __repr__(self):\n 'Return a nicely formatted representation string'\n return self.__class__.__name__ + '(enabled=%r, profile=%r)' % self\n\n def _asdict(self):\n 'Return a new OrderedDict which maps field names to their values.'\n return OrderedDict(zip(self._fields, self))\n\n def __getnewargs__(self):\n 'Return self as a plain tuple. Used by copy and pickle.'\n return tuple(self)\n\n enabled = _property(_itemgetter(0), doc='Alias for field number 0')\n\n profile = _property(_itemgetter(1), doc='Alias for field number 1')\n\n"¶
-
enabled
¶ Alias for field number 0
-
profile
¶ Alias for field number 1
-
-
PkgRelation.
_PkgRelation__blank_sep_RE
= re.compile('\\s+')¶
-
PkgRelation.
_PkgRelation__comma_sep_RE
= re.compile('\\s*,\\s*')¶
-
PkgRelation.
_PkgRelation__dep_RE
= re.compile('^\\s*(?P<name>[a-zA-Z0-9.+\\-]{2,})(:(?P<archqual>([a-zA-Z0-9][a-zA-Z0-9-]*)))?(\\s*\\(\\s*(?P<relop>[>=<]+)\\s*(?P<version>[0-9a-zA-Z:\\-+~.]+)\\s*\\))?(\\s*\\[(?P<archs>[\\s!\\w\\-]+)\\])?\\s*((?P<)¶
-
PkgRelation.
_PkgRelation__pipe_sep_RE
= re.compile('\\s*\\|\\s*')¶
-
PkgRelation.
_PkgRelation__restriction_RE
= re.compile('(?P<enabled>\\!)?(?P<profile>[^\\s]+)')¶
-
PkgRelation.
_PkgRelation__restriction_sep_RE
= re.compile('>\\s*<')¶
-
classmethod
PkgRelation.
parse_relations
(raw)¶ Parse a package relationship string (i.e. the value of a field like Depends, Recommends, Build-Depends ...)
-
static
PkgRelation.
str
(rels)¶ Format to string structured inter-package relationships
Perform the inverse operation of parse_relations, returning a string suitable to be written in a package stanza.
-
class
-
class
debian.deb822.
Release
(*args, **kwargs)¶ Bases:
debian.deb822._multivalued
Represents a Release file
Set the size_field_behavior attribute to “dak” to make the size field length only as long as the longest actual value. The default, “apt-ftparchive” makes the field 16 characters long regardless.
This class is a thin wrapper around the parsing of
Deb822
.-
_Release__size_field_behavior
= 'apt-ftparchive'¶
-
_fixed_field_lengths
¶
-
_get_size_field_length
(key)¶
-
_multivalued_fields
= {'sha256': ['sha256', 'size', 'name'], 'md5sum': ['md5sum', 'size', 'name'], 'sha1': ['sha1', 'size', 'name'], 'sha512': ['sha512', 'size', 'name']}¶
-
set_size_field_behavior
(value)¶
-
size_field_behavior
¶
-
-
class
debian.deb822.
Removals
(*args, **kwargs)¶ Bases:
debian.deb822.Deb822
Represent an ftp-master removals.822 file
Removal of packages from the archive are recorded by ftp-masters. See https://ftp-master.debian.org/#removed
Note: this API is experimental and backwards-incompatible changes might be required in the future. Please use it and help us improve it!
-
_Removals__binaries_line_re
= re.compile('\\s*(?P<package>.+?)_(?P<version>[^\\s]+)\\s+\\[(?P<archs>.+)\\]')¶
-
_Removals__sources_line_re
= re.compile('\\s*(?P<package>.+?)_(?P<version>[^\\s]+)\\s*')¶
-
also_bugs
¶ list of bug numbers in the package closed by the removal
The bug numbers are returned as integers.
Removal of a package implicitly also closes all bugs associated with the package.
-
also_wnpp
¶ list of WNPP bug numbers closed by the removal
The bug numbers are returned as integers.
-
binaries
¶ list of binary packages that were removed
A list of dicts is returned, each dict has the form:
{ 'package': 'some-package-name', 'version': '1.2.3-1', 'architectures': set(['i386', 'amd64']) }
-
bug
¶ list of bug numbers that had requested the package removal
The bug numbers are returned as integers.
Note: there is normally only one entry in this list but there may be more than one.
-
date
¶ a datetime object for the removal action
-
sources
¶ list of source packages that were removed
A list of dicts is returned, each dict has the form:
{ 'source': 'some-package-name', 'version': '1.2.3-1' }
Note: There may be no source packages removed at all if the removal is only of a binary package. An empty list is returned in that case.
-
-
class
debian.deb822.
RestrictedField
¶ Bases:
debian.deb822.RestrictedField
Placeholder for a property providing access to a restricted field.
Use this as an attribute when defining a subclass of RestrictedWrapper. It will be replaced with a property. See the RestrictedWrapper documentation for an example.
-
exception
debian.deb822.
RestrictedFieldError
¶ Bases:
debian.deb822.Error
Raised when modifying the raw value of a field is not allowed.
-
class
debian.deb822.
RestrictedWrapper
(data)¶ Bases:
object
Base class to wrap a Deb822 object, restricting write access to some keys.
The underlying data is hidden internally. Subclasses may keep a reference to the data before giving it to this class’s constructor, if necessary, but RestrictedProperty should cover most use-cases. The dump method from Deb822 is directly proxied.
Typical usage:
class Foo(object): def __init__(self, ...): # ... @staticmethod def from_str(self, s): # Parse s... return Foo(...) def to_str(self): # Return in string format. return ... class MyClass(deb822.RestrictedWrapper): def __init__(self): data = deb822.Deb822() data['Bar'] = 'baz' super(MyClass, self).__init__(data) foo = deb822.RestrictedProperty( 'Foo', from_str=Foo.from_str, to_str=Foo.to_str) bar = deb822.RestrictedProperty('Bar', allow_none=False) d = MyClass() d['Bar'] # returns 'baz' d['Bar'] = 'quux' # raises RestrictedFieldError d.bar = 'quux' d.bar # returns 'quux' d['Bar'] # returns 'quux' d.foo = Foo(...) d['Foo'] # returns string representation of foo
-
classmethod
_RestrictedWrapper__init_restricted_field
(attr_name, field)¶
-
_RestrictedWrapper__restricted_fields
= frozenset()¶
-
classmethod
_class_init
(new_attrs)¶
-
dump
(*args, **kwargs)¶ Calls dump() on the underlying data object.
See Deb822.dump for more information.
-
classmethod
-
class
debian.deb822.
Sources
(*args, **kwargs)¶ Bases:
debian.deb822.Dsc
,debian.deb822._PkgRelationMixin
Represent an APT source package list
This class is a thin wrapper around the parsing of
Deb822
, using the field parsing of_PkgRelationMixin
.-
_relationship_fields
= ['build-depends', 'build-depends-indep', 'build-conflicts', 'build-conflicts-indep', 'binary']¶
-
classmethod
iter_paragraphs
(sequence, fields=None, use_apt_pkg=True, shared_storage=False, encoding='utf-8')¶ Generator that yields a Deb822 object for each paragraph in Sources.
Note that this overloaded form of the generator uses apt_pkg (a strict but fast parser) by default.
See the
iter_paragraphs()
function for details.
-
-
class
debian.deb822.
TagSectionWrapper
(section)¶ Bases:
collections.abc.Mapping
Wrap a TagSection object, using its find_raw method to get field values
This allows us to pick which whitespace to strip off the beginning and end of the data, so we don’t lose leading newlines.
-
class
debian.deb822.
_ClassInitMeta
(name, bases, attrs)¶ Bases:
type
Metaclass for classes that can be initialized at creation time.
Implement the method:
@classmethod def _class_init(cls, new_attrs): pass
on a class, and apply this metaclass to it. The _class_init method will be called right after the class is created. The ‘new_attrs’ param is a dict containing the attributes added in the definition of the class.
-
class
debian.deb822.
_PkgRelationMixin
(*args, **kwargs)¶ Bases:
object
Package relationship mixin
Inheriting from this mixin you can extend a
Deb822
object with attributes letting you access inter-package relationship in a structured way, rather than as strings. For example, while you can usually usepkg['depends']
to obtain the Depends string of package pkg, mixing in with this class you gain pkg.depends to access Depends as a Pkgrel instanceTo use, subclass _PkgRelationMixin from a class with a _relationship_fields attribute. It should be a list of field names for which structured access is desired; for each of them a method wild be added to the inherited class. The method name will be the lowercase version of field name; ‘-‘ will be mangled as ‘_’. The method would return relationships in the same format of the PkgRelation’ relations property.
See Packages and Sources as examples.
-
relations
¶ Return a dictionary of inter-package relationships among the current and other packages.
Dictionary keys depend on the package kind. Binary packages have keys like ‘depends’, ‘recommends’, ... while source packages have keys like ‘build-depends’, ‘build-depends-indep’ and so on. See the Debian policy for the comprehensive field list.
Dictionary values are package relationships returned as lists of lists of dictionaries (see below for some examples).
The encoding of package relationships is as follows:
the top-level lists corresponds to the comma-separated list of
Deb822
, their components form a conjunction, i.e. they have to be AND-ed togetherthe inner lists corresponds to the pipe-separated list of
Deb822
, their components form a disjunction, i.e. they have to be OR-ed togethermember of the inner lists are dictionaries with the following keys:
name
package (or virtual package) name
version
A pair <operator, version> if the relationship is versioned, None otherwise. operator is one of
<<
,<=
,=
,>=
,>>
; version is the given version as a string.arch
A list of pairs <enabled, arch> if the relationship is architecture specific, None otherwise. Enabled is a boolean (
False
if the architecture is negated with!
,True
otherwise), arch the Debian architecture name as a string.restrictions
A list of lists of tuples <enabled, profile> if there is a restriction formula defined,
None
otherwise. Each list of tuples represents a restriction list while each tuple represents an individual term within the restriction list. Enabled is a boolean (False
if the restriction is negated with!
,True
otherwise). The profile is the name of the build restriction. https://wiki.debian.org/BuildProfileSpec
The arch and restrictions tuples are available as named tuples so elements are available as term[0] or alternatively as term.enabled (and so forth).
Examples:
"emacs | emacsen, make, debianutils (>= 1.7)"
becomes:[ [ {'name': 'emacs'}, {'name': 'emacsen'} ], [ {'name': 'make'} ], [ {'name': 'debianutils', 'version': ('>=', '1.7')} ] ]
"tcl8.4-dev, procps [!hurd-i386]"
becomes:[ [ {'name': 'tcl8.4-dev'} ], [ {'name': 'procps', 'arch': (false, 'hurd-i386')} ] ]
"texlive <!cross>"
becomes:[ [ {'name': 'texlive', 'restriction': [[(false, 'cross')]]} ] ]
-
-
class
debian.deb822.
_gpg_multivalued
(*args, **kwargs)¶ Bases:
debian.deb822._multivalued
A _multivalued class that can support gpg signed objects
This class’s feature is that it stores the raw text before parsing so that gpg can verify the signature. Use it just like you would use the _multivalued class.
This class only stores raw text if it is given a raw string, or if it detects a gpg signature when given a file or sequence of lines (see Deb822.split_gpg_and_payload for details).
-
static
_bytes
(s, encoding)¶ Converts s to bytes if necessary, using encoding.
If s is already bytes type, returns it directly.
-
static
-
debian.deb822.
_is_real_file
(f)¶
-
class
debian.deb822.
_lowercase_dict
¶ Bases:
dict
Dictionary wrapper which lowercase keys upon lookup.
-
class
debian.deb822.
_multivalued
(*args, **kwargs)¶ Bases:
debian.deb822.Deb822
A class with (R/W) support for multivalued fields.
To use, create a subclass with a _multivalued_fields attribute. It should be a dictionary with lower-case keys, with lists of human-readable identifiers of the fields as the values. Please see
Dsc
,Changes
, andPdiffIndex
as examples.-
_multivalued_fields
= {}¶
-
get_as_string
(key)¶
-
validate_input
(key, value)¶
-
-
debian.deb822.
_strI
¶ alias of
_CaseInsensitiveString