diff mbox series

[4/7] go-mod-update-modules: identify licenses with licensecheck

Message ID 20261201034910.25521-5-tim.orling@konsulko.com
State New
Headers show
Series go-mod-update-modules: identify licenses with licensecheck | expand

Commit Message

Tim Orling Dec. 1, 2026, 3:49 a.m. UTC
A hash finds a license only when the text matches common-licenses, and
only one license per file. Go modules often ship a variant of a license
text, or several licenses in one file, which become spdx=Unknown and
need a line each in license-hashes.csv.

Add GO_MOD_LICENSE_SCANNER. Set to "licensecheck", do_update_modules
scans each license file with licensecheck-native and:

- uses an SPDX-License-Identifier line as it is
- otherwise declares every license found that has a text in
  COMMON_LICENSE_DIR or LICENSE_PATH, with -only or -or-later for the
  GNU licenses
- joins them with OR only when the file offers a choice and they cover
  at least 80% of it, and with AND otherwise
- names a public domain dedication LicenseRef-PD
- warns when it finds less than the hash match
- leaves out files such as COPYRIGHT or NOTICE that add no license to
  the ones that the module's other license files declare

AI-Generated: Claude Opus 5.5
Signed-off-by: Tim Orling <tim.orling@konsulko.com>
---
 .../go-mod-update-modules.bbclass             | 43 +++++++++
 meta/lib/oe/license_finder.py                 | 93 +++++++++++++++++++
 2 files changed, 136 insertions(+)
diff mbox series

Patch

diff --git a/meta/classes-recipe/go-mod-update-modules.bbclass b/meta/classes-recipe/go-mod-update-modules.bbclass
index fc618dd750..bcb80e130d 100644
--- a/meta/classes-recipe/go-mod-update-modules.bbclass
+++ b/meta/classes-recipe/go-mod-update-modules.bbclass
@@ -12,6 +12,13 @@  do_update_modules[network] = "1"
 #
 # These files are machine-generated and should not be modified.
 
+# Set to "licensecheck" to identify the licenses with licensecheck-native, the
+# license detection that pkg.go.dev uses. It finds every license in a file,
+# also when a file holds several, and texts that differ from the ones in
+# common-licenses.
+GO_MOD_LICENSE_SCANNER ??= ""
+do_update_modules[depends] += "${@'licensecheck-native:do_populate_sysroot' if d.getVar('GO_MOD_LICENSE_SCANNER') == 'licensecheck' else ''}"
+
 python do_update_modules() {
     import subprocess, tempfile, json, re, urllib.parse
     from oe.license_finder import find_licenses_up
@@ -77,6 +84,42 @@  python do_update_modules() {
             for node, file, md5 in find_licenses_up(pkg_dir, mod_dir, d, first_only=True, extra_hashes=extra_hashes):
                 lic_files[os.path.join(path, file)] = (node, md5)
 
+        scanner = d.getVar("GO_MOD_LICENSE_SCANNER")
+        if scanner not in ("", "licensecheck"):
+            bb.fatal(f"GO_MOD_LICENSE_SCANNER: unsupported value {scanner!r}")
+        if scanner:
+            from oe.license_finder import scan_licenses
+            tool = os.path.join(d.getVar("STAGING_BINDIR_NATIVE"), "licensecheck")
+            scanned = scan_licenses([os.path.join(mod_cache_dir, f) for f in lic_files], tool, d)
+            found_ids = {}
+            for lic_file, (node, md5) in list(lic_files.items()):
+                new, ids = scanned[os.path.join(mod_cache_dir, lic_file)]
+                found_ids[lic_file] = ids
+                if new is None:
+                    continue
+                if not isinstance(node, oe.spdx_license.UnknownId):
+                    old = {i.to_string() for i in node.iter() if isinstance(i, oe.spdx_license.LicenseId)}
+                    if not old <= ids:
+                        bb.warn(f"{lic_file}: the hash matches {node.to_string()}, licensecheck finds {new.to_string()}")
+                lic_files[lic_file] = (new, md5)
+
+            # Files such as COPYRIGHT or NOTICE next to the license files often
+            # hold no license text. Leave out a file that is not identified when
+            # the other license files of its module declare every license that
+            # licensecheck finds in it, so that no license is left out.
+            for lic_file, (node, md5) in list(lic_files.items()):
+                if not isinstance(node, oe.spdx_license.UnknownId):
+                    continue
+                licdir = os.path.dirname(lic_file)
+                declared = set()
+                for other, (onode, _) in lic_files.items():
+                    if other != lic_file and os.path.dirname(other) == licdir \
+                            and not isinstance(onode, oe.spdx_license.UnknownId):
+                        declared |= {i.to_string() for i in onode.iter() if isinstance(i, oe.spdx_license.LicenseId)}
+                if declared and found_ids[lic_file] <= declared:
+                    bb.note(f"{lic_file}: no license beyond {' '.join(sorted(declared))}, left out")
+                    del lic_files[lic_file]
+
         licenses = []
         lic_files_chksum = []
         for lic_file in lic_files:
diff --git a/meta/lib/oe/license_finder.py b/meta/lib/oe/license_finder.py
index cd290adf59..e8e44dab4a 100644
--- a/meta/lib/oe/license_finder.py
+++ b/meta/lib/oe/license_finder.py
@@ -218,3 +218,96 @@  def find_licenses(srctree, d, first_only=False, extra_hashes={}):
 def find_licenses_up(srcdir, topdir, d, first_only=False, extra_hashes={}):
     licfiles = find_license_files(topdir, first_only, srcdir)
     return match_licenses(licfiles, topdir, d, extra_hashes)
+
+
+# licensecheck still uses SPDX's deprecated GNU identifiers
+_DEPRECATED_GNU = {'GPL-1.0', 'GPL-2.0', 'GPL-3.0', 'LGPL-2.0', 'LGPL-2.1', 'LGPL-3.0',
+                   'AGPL-1.0', 'AGPL-3.0', 'GFDL-1.1', 'GFDL-1.2', 'GFDL-1.3'}
+_LATER_RE = re.compile(r'(or|\(at\s+your\s+option\))\s+any\s+later\s+version', re.I)
+# A choice between licenses, not GPL's "at your option, any later version"
+_CHOICE_RE = re.compile(r'at\s+your\s+option,?\s+(under\s+)?either|dual[-\s]licen[sc]ed|'
+                        r'licensed\s+under\s+either|you\s+(may|can)\s+choose\s+(either|between)', re.I)
+_PUBLIC_DOMAIN_RE = re.compile(r'(dedicated|released|put|placed)\s+(in)?to\s+the\s+public\s+domain', re.I)
+_SPDX_HEADER_RE = re.compile(r'SPDX-License-Identifier:\s*([^\s`*][^\n`*]*)')
+
+
+def _available_licenses(d):
+    lic_dirs = [d.getVar('COMMON_LICENSE_DIR')] + (d.getVar('LICENSE_PATH') or "").split()
+    return {fn for lic_dir in lic_dirs if os.path.isdir(lic_dir) for fn in os.listdir(lic_dir)}
+
+
+def _licensecheck_expression(result, text, available, min_percent):
+    """Turn one licensecheck result into an SPDX expression, or None."""
+    ids = []
+    for m in result.get('matches', []):
+        if m.get('url'):
+            continue
+        ident = m['id']
+        if ident in _DEPRECATED_GNU:
+            near = text[m['start']:m['end'] + 2000]
+            later = _LATER_RE.search(near) or _LATER_RE.search(text[:2000])
+            ident += '-or-later' if later else '-only'
+        if ident not in ids:
+            ids.append(ident)
+    if not ids or any(i not in available for i in ids):
+        return None, set(ids)
+    # A match is a complete license text, even when other text lowers the
+    # coverage. Offer a choice only when the licenses cover most of the file.
+    choice = result.get('percent', 0) >= min_percent and _CHOICE_RE.search(text)
+    op = ' OR ' if len(ids) > 1 and choice else ' AND '
+    return op.join(sorted(ids)), set(ids)
+
+
+def scan_licenses(paths, licensecheck, d, min_percent=80.0):
+    """
+    Identify the licenses in files with the licensecheck tool.
+
+    Returns a dict that maps each path to (node, ids): node is an
+    oe.spdx_license node, or None when the licenses in the file are not
+    identified with confidence; ids is the set of license identifiers that
+    were found, also when node is None.
+
+    An SPDX-License-Identifier line is used as it is. Otherwise every
+    license that licensecheck finds is used, if each one has a text in
+    COMMON_LICENSE_DIR or LICENSE_PATH. The licenses are joined with OR when
+    they cover at least min_percent of the file and the file offers a choice
+    between them, and with AND otherwise. A file without a license that only
+    dedicates the code to the public domain is LicenseRef-PD.
+    """
+    import json
+    import subprocess
+
+    available = _available_licenses(d)
+    results = {}
+    paths = list(paths)
+    for i in range(0, len(paths), 200):
+        chunk = paths[i:i + 200]
+        output = subprocess.check_output([licensecheck] + chunk, text=True)
+        for line in output.splitlines():
+            r = json.loads(line)
+            results[r['file']] = r
+
+    scanned = {}
+    for path in paths:
+        with open(path, 'r', errors='replace') as f:
+            text = f.read()
+        node = None
+        header = _SPDX_HEADER_RE.search(text)
+        expr = header.group(1).strip() if header else None
+        ids = set(re.findall(r'[A-Za-z0-9.+-]+', expr)) - {'AND', 'OR', 'WITH'} if expr else set()
+        # Use the header only when each license has a text; exceptions have none
+        lics = set(re.findall(r'[A-Za-z0-9.+-]+', re.sub(r'\bWITH\s+\S+', '', expr or ''))) - {'AND', 'OR'}
+        if not expr or any(i not in available for i in lics):
+            expr, ids = _licensecheck_expression(results.get(path, {}), text, available, min_percent)
+            if not ids and _PUBLIC_DOMAIN_RE.search(text):
+                expr, ids = 'LicenseRef-PD', {'LicenseRef-PD'}
+        if expr:
+            try:
+                node = oe.spdx_license.parse(expr)
+            except oe.spdx_license.ParseError:
+                node = None
+            if node is not None and any(
+                    isinstance(n, oe.spdx_license.LicenseId) and n.deprecated for n in node.iter()):
+                node = None
+        scanned[path] = (node, ids)
+    return scanned