meta_package_manager.package module¶
Manager-agnostic package data model, and its metadata companion.
meta_package_manager.package.Package is the model.
meta_package_manager.package.PackageMetadata augments it with data pulled from
sources outside the package manager itself.
Defines the lightweight representation of a package (ID, name, installed and latest
versions, architecture) that every manager operation yields, plus
meta_package_manager.package.packages_asdict() to serialize a subset of its
fields for output.
Package is the inventory plane: what the package manager itself
reports through its native query commands. It backs every operation in
meta_package_manager.manager.
PackageMetadata is the enrichment plane:
licenses, supplier, checksums, declared dependency graph, on-disk per-package
SBOMs, and other facts gathered through extra queries (CLI sub-commands, on-disk
parsers, upstream registries). Populated by
meta_package_manager.manager.PackageManager.package_metadata_batch(),
consumed by meta_package_manager.sbom today and reserved for any
future caller that wants more than the bare inventory.
Kept deliberately free of manager logic, so it can be imported without pulling in the
manager engine (meta_package_manager.manager).
- meta_package_manager.package.PURL_QUALIFYING_NAMESPACES = frozenset({'alpm', 'apk', 'cpan', 'deb', 'luarocks', 'rpm'})¶
pURL types whose namespace qualifies a package without being part of its ID.
For these types, the namespace names who distributes the package: the vendor for
alpm,apk,debandrpm, the author’s CPAN ID forcpan, the user manifest forluarocks.parse_purl()keeps the name alone for them, where joining the two would askaptfordebian/curl. Every other type reads the namespace as the part of the package ID before its last slash: an npm scope, a Composer vendor, a Homebrew tap.Each type’s
namespace_definitionin the pURL type definitions settles which side it falls on.
- class meta_package_manager.package.PurlType(namespace, lowercase=(), qualifiers=())[source]¶
Bases:
NamedTupleThe rules the definition of a registered pURL type sets on its components.
Create new instance of PurlType(namespace, lowercase, qualifiers)
- namespace: Literal['optional', 'prohibited', 'required']¶
Whether a pURL of the type carries a namespace.
- meta_package_manager.package.PURL_TYPES: dict[str, PurlType] = {'alpm': ('required', ('namespace', 'name'), ()), 'apk': ('required', ('namespace', 'name'), ()), 'bazel': ('prohibited', (), ()), 'bitbucket': ('required', ('namespace', 'name'), ()), 'bitnami': ('prohibited', ('name',), ()), 'brew': ('optional', ('namespace', 'name'), ()), 'cargo': ('prohibited', (), ()), 'chrome-extension': ('prohibited', ('name',), ()), 'cocoapods': ('prohibited', (), ()), 'composer': ('required', ('namespace', 'name'), ()), 'conan': ('optional', (), ()), 'conda': ('prohibited', (), ()), 'cpan': ('optional', (), ()), 'cran': ('prohibited', (), ()), 'deb': ('required', ('namespace', 'name'), ()), 'docker': ('optional', (), ()), 'gem': ('prohibited', (), ()), 'generic': ('optional', (), ()), 'git': ('required', (), ()), 'github': ('required', ('namespace', 'name'), ()), 'golang': ('required', (), ()), 'hackage': ('prohibited', (), ()), 'hex': ('optional', ('namespace', 'name'), ()), 'huggingface': ('required', ('version',), ()), 'julia': ('prohibited', (), ('uuid',)), 'luarocks': ('optional', ('namespace', 'name'), ()), 'maven': ('required', (), ()), 'mlflow': ('prohibited', (), ()), 'npm': ('optional', (), ()), 'nuget': ('prohibited', (), ()), 'oci': ('prohibited', ('name', 'version'), ()), 'opam': ('prohibited', (), ()), 'otp': ('prohibited', ('name',), ()), 'pub': ('prohibited', ('name',), ()), 'pypi': ('prohibited', ('name', 'version'), ()), 'qpkg': ('required', ('namespace',), ()), 'rpm': ('required', ('namespace',), ()), 'swid': ('optional', (), ('tag_id',)), 'swift': ('required', (), ()), 'vcpkg': ('prohibited', (), ()), 'vscode-extension': ('required', ('namespace', 'name', 'version'), ()), 'yocto': ('optional', ('namespace',), ())}¶
The registered pURL types, with the rules their definitions state.
Taken from the type definitions of purl-spec v1.1.0.
tests/purl-spec/holds a copy of them, andtests/test_purl_spec.pychecks this table against it.Clause 5.7 of ECMA-427 2nd edition makes a pURL invalid when it breaks the rules of its registered type. A pURL of a type outside this table is valid when its syntax is.
- exception meta_package_manager.package.PurlRuleError[source]¶
Bases:
ValueErrorA pURL with a valid syntax, which breaks a rule of the specification.
parse_purl()raises it for a rule of a registered type, and for a qualifier key not in lowercase.
- meta_package_manager.package.purl_parts(package_id)[source]¶
Split
package_idinto the namespace and the name of its pURL.Everything before the last slash is the namespace. The whole ID stays the name when the split would leave an empty segment, like an absolute path or a URL: a pURL parser drops empty segments, so the ID would not read back.
PURL_QUALIFYING_NAMESPACESplays no part here. A pURL mpm writes carries a manager ID as its type, and the managers whose ID is one of those types (apk,cpan,luarocks) never put a slash in a package ID, whichtests/test_docstring_corpus.pyholds across every documented package ID.
- meta_package_manager.package.manager_purl(manager_id, package_id, version=None)[source]¶
Render the pURL tying
package_idtomanager_id, the manager ID as its type.parse_purl()reads it back to the same manager ID, package ID and version, so a command handed this pURL skips looking the package up.Rendered here, not by packageurl-python, which the default install does not carry. Its
PackageURL.to_string()would also lowercase the name of some types, npm among them (package-url/packageurl-python#230), where the npm type definition keeps names case-sensitive, since packages published before 2015 may carry uppercase letters:JSONStreamwould come back asjsonstream. And it leaves a/unencoded in a name (package-url/packageurl-python#123).- Return type:
- meta_package_manager.package.purl_quote(text)[source]¶
Percent-encode one pURL segment, a
/included, keeping:as is.- Return type:
- class meta_package_manager.package.PurlParts(type, namespace, name, version)[source]¶
Bases:
NamedTupleThe parts of a pURL string that
mpmreads, asparse_purl()splits them.Each part is percent-decoded, and normalized by the rules of its registered type.
Create new instance of PurlParts(type, namespace, name, version)
- meta_package_manager.package.parse_purl(purl, *, strict=True)[source]¶
Split
purlinto its parts, or raiseValueErrorif it is not a pURL.Refuses a string without the
pkg:scheme, without a type or with a malformed one, without a name, or with a qualifier missing its=or carrying a malformed key. Takes the leading@of annpmpath as the start of its scope. Splits off the qualifiers and the subpath withurllib.parse.urlsplit():mpmreads neither, but for the rules below.Each part comes back percent-decoded, and normalized by the rules of its type in
PURL_TYPES: a part the type compares without case is lowercased. The type definitions state some rules in prose only, which the purl-spec test suite checks. Apypiname turns_into-. Agitname is the whole repository path after the host. Anmlflowname is lowercased when itsrepository_urlis on Databricks.In
strictmode, raisesPurlRuleErrorfor a pURL breaking the rules of its type: a namespace the type requires or prohibits, or a qualifier it requires. So does acpanname holding::, achrome-extensionname other than 32 letters fromatopor a version of more than four numbers, aswiftnamespace without both the host and the owner, and a qualifier key not in lowercase. Outsidestrictmode, such a pURL comes back like a valid one.tests/test_purl_spec.pyruns the purl-spec test suite against it.- Return type:
- meta_package_manager.package.render_purl(purl_type, namespace, name, version=None, qualifiers=None, subpath=None)[source]¶
Render the canonical pURL string of its parts, or raise
ValueError.The reverse of
parse_purl()in strict mode: normalizes the parts by the rules of their type, and refuses those breaking a rule withPurlRuleError. Percent-encodes each segment of the namespace and the subpath, the name, the version and each qualifier value, keeping:. Sorts the qualifiers by key and drops those without a value, and drops the.and..segments of the subpath.tests/test_purl_spec.pyruns the build cases of the purl-spec test suite against it.- Return type:
- class meta_package_manager.package.Package(id, manager_id, name=None, description=None, installed_version=None, latest_version=None, arch=None)[source]¶
Bases:
objectLightweight representation of a package and its metadata.
- manager_id: str¶
Handy to backtrack whose manager this package belongs to.
The manager ID is good enough and allows for no coupling with the parent manager object.
- name: str | None = None¶
Optional human-readable display name. Falls back to
idin output rendering, so only set this when the manager provides a name that differs from the package ID.An exact query matches it as well as the ID, so a manager whose IDs carry a namespace sets it to the bare name, like the
gzipofapp-arch/gzip.
- installed_version: TokenizedString | str | None = None¶
- latest_version: TokenizedString | str | None = None¶
Installed and latest versions are optional: they’re not always provided by the package manager.
installed_versionandlatest_versionare allowed to temporarily be strings between__init__and__post_init__. Once they reach the later, they’re parsed and normalized into eitherTokenizedStringorNone. They can’t be strings beyond that point, i.e. after the Package instance has been fully instantiated. We don’t know how to declare this transient state with type hints, so we’re just going to allow string type.
- static query_parts(query)[source]¶
Split
queryinto its contiguous alphanumeric segments.Contrary to
meta_package_manager.version.TokenizedString, does not split on collated number/alphabetic junctions.Canonical tokenizer behind
matches()and thesearch/installed/outdatedquery matching. Cached, since a run asks it the same question once per package of every manager.
- matches(query, extended=False, exact=False)[source]¶
Tell whether this package matches the free-form
query.Shared predicate behind the
search,installedandoutdatedsubcommands, so all three honor the same matching semantics:Fuzzy (default): a case-insensitive, tokenized substring match. Any alphanumeric segment of
query(seequery_parts()) found in the package ID or name counts as a match.Exact (
exact=True): the rawquerymust equal the package ID or name verbatim (case-sensitive, whole-string).Extended (
extended=True): also look into the packagedescription. Only meaningful when the description is populated, as it is forsearchresults.
A query with no alphanumeric segment (empty or punctuation-only) never matches.
- Return type:
- meta_package_manager.package.packages_asdict(packages, keep_fields)[source]¶
Yield each package as a
dictholding thekeep_fieldssubset of its fields.The fields are read straight off the instance rather than through
dataclasses.asdict(), which deep-copies every value: a version is an immutableTokenizedStringthat the renderers only read, and copying thousands of them per query cost more than the query’s own parsing.
- class meta_package_manager.package.DependencyScope(*values)[source]¶
Bases:
StrEnumMaps loosely onto SPDX
RelationshipTypevariants.SBOM renderers translate these into
RUNTIME_DEPENDENCY_OF,BUILD_DEPENDENCY_OF, etc.; CycloneDX collapses everything to its flatdependenciesgraph. Future non-SBOM consumers can apply their own mapping or just expose the raw scope label.- RUNTIME = 'runtime'¶
- BUILD = 'build'¶
- DEV = 'dev'¶
- OPTIONAL = 'optional'¶
- TEST = 'test'¶
- RECOMMENDED = 'recommended'¶
- class meta_package_manager.package.ChecksumAlgorithm(*values)[source]¶
Bases:
StrEnumSubset of algorithms shared by SPDX and CycloneDX schemas.
Used by
Checksumto identify a content hash without coupling the data model to any specific SBOM library’s enum.- MD5 = 'MD5'¶
- SHA1 = 'SHA1'¶
- SHA256 = 'SHA256'¶
- SHA512 = 'SHA512'¶
- SHA3_256 = 'SHA3-256'¶
- SHA3_512 = 'SHA3-512'¶
- BLAKE2B_256 = 'BLAKE2b-256'¶
- BLAKE2B_512 = 'BLAKE2b-512'¶
- class meta_package_manager.package.Checksum(algorithm, value)[source]¶
Bases:
objectA single
(algorithm, value)pair.- algorithm: ChecksumAlgorithm¶
- class meta_package_manager.package.Supplier(name, url=None)[source]¶
Bases:
objectDistributor of the package.
Distinct from the originator: the supplier is whoever served the bits (Homebrew, Debian, PyPI), the originator is the upstream author.
- class meta_package_manager.package.Originator(name, email=None, is_organization=False)[source]¶
Bases:
objectUpstream author or organization that produced the package.
- class meta_package_manager.package.Dependency(target_id, scope=DependencyScope.RUNTIME, version_constraint=None)[source]¶
Bases:
objectA single edge in the package’s declared dependency graph.
target_idis the dependency’s manager-native identifier (e.g.openssl@3for Homebrew). Renderers match it against the inventory’s installed packages to decide whether to emit a relationship.- scope: DependencyScope = 'runtime'¶
- class meta_package_manager.package.FileEntry(path, sha256=None, sha1=None, md5=None)[source]¶
Bases:
objectAn installed file shipped by the package.
Only populated for managers that can cheaply enumerate file contents and hashes (dpkg
.md5sums, pipRECORD). Omitted otherwise; the SBOM renderer leavesfilesAnalyzed=Falseon the SPDX Package.
- class meta_package_manager.package.PackageMetadata(download_url=None, homepage=None, vcs_url=None, issue_tracker_url=None, distribution_url=None, license_declared=None, license_concluded=None, copyright_text=None, supplier=None, originator=None, description=None, summary=None, cpe=None, dependencies=(), checksums=(), files=(), files_analyzed=False, install_date=None, build_date=None, release_date=None, external_sbom_path=None, extra_purls=(), extras=dict())[source]¶
Bases:
objectMaximalist metadata collected for a single installed package.
Distinct from
Packagein scope: wherePackagecarries only what the package manager itself surfaces through its inventory commands (id, name, version, arch),PackageMetadatacarries the augmentations gathered through extra queries (richer CLI sub-commands, on-disk parsing of dist-info or per-package SBOMs, upstream registry lookups). Today it powers the maximalistmpm sbom --bundledoutput; the structure is deliberately generic so a future search, audit, or info display can reuse it.All fields are optional.
extrasis the escape hatch for manager- native fields that don’t fit the portable model: a Homebrew tap, a pip classifier list, an aptSection. SBOM renderers consult known keys and surface the rest as CycloneDXproperties.- originator: Originator | None = None¶
- dependencies: tuple[Dependency, ...] = ()¶
- external_sbom_path: Path | None = None¶
Path to an on-disk upstream SBOM document for this package.
Brew formulae installed with
HOMEBREW_SBOM=1write a per-formula SPDX 2.3 file at<prefix>/sbom.spdx.json. The Homebrew extractor sets this so the SBOM renderer can merge the upstream document into the aggregate output (or attach it by reference).
- extra_purls: tuple[str, ...] = ()¶
Additional purls when the manager identifies the same package through multiple coordinate systems (multi-arch, multi-origin, or the upstream registry a recipe builds from).
SBOM renderers emit them as extra package-manager references and index them as aliases of the package’s own purl, so a vulnerability scan can query a coordinate an advisory database recognizes. Each is a string
parse_purl()accepts, which the renderers normalize with packageurl-python.
- meta_package_manager.package.EMPTY_METADATA = PackageMetadata(download_url=None, homepage=None, vcs_url=None, issue_tracker_url=None, distribution_url=None, license_declared=None, license_concluded=None, copyright_text=None, supplier=None, originator=None, description=None, summary=None, cpe=None, dependencies=(), checksums=(), files=(), files_analyzed=False, install_date=None, build_date=None, release_date=None, external_sbom_path=None, extra_purls=(), extras={})¶
Sentinel returned by the default no-op extractor on the base
meta_package_manager.manager.PackageManager. Consumers (the SBOM renderers today) treatEMPTY_METADATAexactly like--minimalmode for the package: no enrichment, no placeholders.