diff mbox series

[1/2] fetch: Add package_identity() to the fetchers

Message ID 20261118092831.201831-2-stondo@gmail.com
State New
Headers show
Series fetch: package identity of crate, gomod and npm URLs | expand

Commit Message

Stefano Tondo Nov. 18, 2026, 9:28 a.m. UTC
From: Stefano Tondo <stefano.tondo.ext@siemens.com>

Fetchers of package registries know which package a URL downloads:
its name and its version are part of the URL. SBOM generation needs
this data, but it can only get it today by parsing fetcher internals.

Add FetchMethod.package_identity(). It returns the name, the version
and the Package URL (purl) of the downloaded package as a dict, or
None when the URL does not name a package. It uses only the URL and
the datastore, so it works before the fetch and without network
access. Add bb.fetch.package_url() to build the purl with the correct
encoding.

Signed-off-by: Stefano Tondo <stefano.tondo.ext@siemens.com>
---
 lib/bb/fetch/__init__.py | 27 +++++++++++++++++++++++++++
 1 file changed, 27 insertions(+)
diff mbox series

Patch

diff --git a/lib/bb/fetch/__init__.py b/lib/bb/fetch/__init__.py
index ce2bd62ad..a4b5860c0 100644
--- a/lib/bb/fetch/__init__.py
+++ b/lib/bb/fetch/__init__.py
@@ -1765,6 +1765,33 @@  class FetchMethod(object):
         """
         return []
 
+    def package_identity(self, ud, d):
+        """
+        Return the identity of the package that the URL downloads, for
+        fetchers of package registries that know it, as a dict with the
+        keys "name", "version" and "purl" (Package URL). Return None when
+        the URL does not name a package.
+
+        The result depends only on the URL and the datastore. It is
+        available as soon as the FetchData exists, before the fetch and
+        without network access. It is meant for SBOM generation.
+        """
+        return None
+
+
+def package_url(purl_type, name, version, qualifiers=None):
+    """
+    Return a Package URL (https://github.com/package-url/purl-spec) for a
+    package. name can contain "/": the segments before the last one are
+    the namespace. Each segment, the version and the qualifier values are
+    percent-encoded. qualifiers is a dict, written sorted by key.
+    """
+    quote = lambda s: urllib.parse.quote(s, safe="")
+    purl = "pkg:%s/%s@%s" % (purl_type, "/".join(quote(s) for s in name.split("/")), quote(version))
+    if qualifiers:
+        purl += "?" + "&".join("%s=%s" % (k, quote(v)) for k, v in sorted(qualifiers.items()))
+    return purl
+
 
 class DummyUnpackTracer(object):
     """