Skip to contentSkip to conversation

go-mod-update-modules: identify licenses with licensecheck

PATCH New Tim Orling 1 participant 8 messages Dec 1

lore
Share & tools
lore

Tim Orling

author
#0 lore raw

cover go-mod-update-modules: identify licenses with licensecheck

go-mod-update-modules identifies the license files of Go module dependencies by hash. Variant license texts, several licenses in one file and several license files in one directory end up as spdx=Unknown, which fails do_populate_lic, or are left out.

This series adds licensecheck, the license detection library of pkg.go.dev, and an opt-in GO_MOD_LICENSE_SCANNER = "licensecheck" that scans each license file with it. Hash matching stays the default. It also:

- keeps every license file of the nearest directory
- stops files with no license text from matching "Proprietary"
- adds GO_MOD_LICENSE_STRICT, to fail do_update_modules on a license that is not identified
- otherwise names such a license LicenseRef-go-<module>-<file>, with NO_GENERIC_LICENSE, so that the recipe builds

Tested on qemux86-64: licensecheck and licensecheck-native build, and the oelib.license_finder, distrodata test_maintainers and recipetool test_recipetool_create_go selftests pass. For yq, hash matching leaves 5 of 30 license files unidentified (MPL-2.0, BSD-2-Clause, MIT, Apache-2.0, BSD-3-Clause variants); licensecheck identifies all 5. With either result, yq builds and do_create_spdx passes.

AI-Generated: Uses Claude Code (Claude Opus 5.5, Claude Fable 5.2)

Tim Orling (7):
license_finder: keep all license files of the nearest directory
licensecheck: add recipe
license_finder: do not match files that have no license text
go-mod-update-modules: identify licenses with licensecheck
go-mod-update-modules: add GO_MOD_LICENSE_STRICT
go-mod-update-modules: name unidentified licenses with a LicenseRef oeqa/selftest/oelib: add tests for license_finder

 .../go-mod-update-modules.bbclass             |  84 +++++++++-
 meta/conf/distro/include/maintainers.inc      |   1 +
 meta/lib/oe/license_finder.py                 | 115 +++++++++++++-
 .../selftest/cases/oelib/license_finder.py    | 146 ++++++++++++++++++
 .../licensecheck/files/main.go                |  49 ++++++
 .../licensecheck/licensecheck_0.3.1.bb        |  31 ++++
 6 files changed, 416 insertions(+), 10 deletions(-)
 create mode 100644 meta/lib/oeqa/selftest/cases/oelib/license_finder.py
 create mode 100644 meta/recipes-devtools/licensecheck/files/main.go
 create mode 100644 meta/recipes-devtools/licensecheck/licensecheck_0.3.1.bb
Signature · 1 line
2.56.1
author
#1 lore raw

PATCH 1/7 license_finder: keep all license files of the nearest directory

find_license_files() with first_only returned only the first license file, in name order, of the nearest directory. github.com/klauspost/pgzip has LICENSE (MIT) and GO_LICENSE (BSD-3-Clause), so go-mod-update-modules left out MIT.

Return every license file of that directory. The top-down search that recipetool uses is unchanged.

AI-Generated: Claude Opus 5.5

---
 meta/lib/oe/license_finder.py | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)
meta/lib/oe/license_finder.py +8 -6
index 9c217cf891..d08d4af5d2 100644
@@ -127,7 +127,10 @@ def _crunch_license(licfile):
 def find_license_files(srctree, first_only=False, bottom=""):
     """
     Search srctree for files that look like they could be licenses.
-    If first_only is True, only return the first file found.
+    If first_only is True, only return the first file found. When searching
+    upwards from bottom, return all files from the first directory that has
+    any instead, because a directory can hold several licenses, for example
+    LICENSE for the project and GO_LICENSE for code copied from Go.
     If bottom is not empty, start at bottom and continue upwards to the top.
     """
     licspecs = ['*LICEN[CS]E*', 'COPYING*', '*[Ll]icense*', 'LEGAL*', '[Ll]egal*', '*GPL*', 'README.lic*', 'COPYRIGHT*', '[Cc]opyright*', 'e[dp]l-v10']
@@ -144,11 +147,10 @@ def find_license_files(srctree, first_only=False, bottom=""):
             for name in sorted(files):
                 if name.endswith(skip_extensions):
                     continue
-                for spec in licspecs:
-                    if fnmatch.fnmatch(name, spec):
-                        licfiles.append(os.path.join(srcdir, name))
-                        if first_only:
-                            return licfiles
+                if any(fnmatch.fnmatch(name, spec) for spec in licspecs):
+                    licfiles.append(os.path.join(srcdir, name))
+            if first_only and licfiles:
+                return licfiles
             srcdir = os.path.dirname(srcdir)
         return licfiles
 
Signature · 1 line
2.56.1
author
#2 lore raw

PATCH 2/7 licensecheck: add recipe

In reply to Tim Orling

Add licensecheck 0.3.1, the license detection library that pkg.go.dev uses, for go-mod-update-modules. main.go is a small front end that prints, as JSON, the licenses found in each file and how much of the file they cover.

The library is BSD-3-Clause; main.go is MIT.

AI-Generated: Claude Fable 5.2 (maintainers.inc entry, CVE_PRODUCT)

---
 meta/conf/distro/include/maintainers.inc      |  1 +
 .../licensecheck/files/main.go                | 49 +++++++++++++++++++
 .../licensecheck/licensecheck_0.3.1.bb        | 31 ++++++++++++
 3 files changed, 81 insertions(+)
 create mode 100644 meta/recipes-devtools/licensecheck/files/main.go
 create mode 100644 meta/recipes-devtools/licensecheck/licensecheck_0.3.1.bb
meta/conf/distro/include/maintainers.inc +1 -0
index 62de04001e..8024be3383 100644
@@ -473,6 +473,7 @@ RECIPE_MAINTAINER:pn-libxvmc = "Unassigned <[email protected]>"
 RECIPE_MAINTAINER:pn-libxxf86vm = "Unassigned <[email protected]>"
 RECIPE_MAINTAINER:pn-libyaml = "Wang Mingyu <[email protected]>"
 RECIPE_MAINTAINER:pn-libzip = "Igor Opaniuk <[email protected]>"
+RECIPE_MAINTAINER:pn-licensecheck = "Tim Orling <[email protected]>"
 RECIPE_MAINTAINER:pn-lighttpd = "Unassigned <[email protected]>"
 RECIPE_MAINTAINER:pn-linux-dummy = "Unassigned <[email protected]>"
 RECIPE_MAINTAINER:pn-linux-firmware = "Vivek Puar <[email protected]>"
meta/recipes-devtools/licensecheck/files/main.go new file +49 -0

49 lines not on this page · raw message

meta/recipes-devtools/licensecheck/licensecheck_0.3.1.bb new file +31 -0
new file mode 100644
index 0000000000..a8fe6ef22f
@@ -0,0 +1,31 @@
+SUMMARY = "Identify the licenses in license files"
+DESCRIPTION = "A command line front end for the Go licensecheck library, which \
+pkg.go.dev uses to detect the licenses of Go modules. For each file, it lists \
+every license that it finds, where in the file, and how much of the file the \
+licenses cover. go-mod-update-modules.bbclass uses it to identify the licenses \
+of Go module dependencies."
+HOMEPAGE = "https://github.com/google/licensecheck"
+BUGTRACKER = "https://github.com/google/licensecheck/issues"
+SECTION = "devel"
+
+# No CPE in the NVD yet. Name the vendor, as other projects are also
+# called licensecheck.
+CVE_PRODUCT = "google:licensecheck"
+
+LICENSE = "BSD-3-Clause AND MIT"
+LIC_FILES_CHKSUM = "file://src/${GO_IMPORT}/LICENSE;md5=a413d6b3884e141783f23d00d5838777 \
+                    file://src/${GO_IMPORT}/cmd/licensecheck/main.go;beginline=1;endline=1;md5=6ec41034e04432ee375d0e14fba596f4"
+
+SRC_URI = "git://github.com/google/licensecheck;protocol=https;nobranch=1;destsuffix=${GO_SRCURI_DESTSUFFIX} \
+           file://main.go;subdir=${GO_SRCURI_DESTSUFFIX}/cmd/licensecheck"
+SRCREV = "16aaea36649f556bae5a5ee972c247f58a0de1c4"
+
+GO_IMPORT = "github.com/google/licensecheck"
+GO_INSTALL = "${GO_IMPORT}/cmd/licensecheck"
+
+# The library only uses the standard library
+export GO111MODULE = "off"
+
+inherit go
+
+BBCLASSEXTEND = "native"
Signature · 1 line
2.56.1
author
#3 lore raw

PATCH 3/7 license_finder: do not match files that have no license text

In reply to Tim Orling

_crunch_license() drops titles, copyright lines and URLs, so a file with nothing else hashes as an empty text, as does common-licenses/Proprietary. Such a file matched "Proprietary", which is not an SPDX identifier, and go-mod-update-modules failed with "Unknown Expression 'Proprietary'".

Return None when no text is left, and do not register None as the hash of a known license. An exact copy of a license file still matches by its plain md5.

AI-Generated: Claude Opus 5.5

---
 meta/lib/oe/license_finder.py | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
meta/lib/oe/license_finder.py +7 -1
index d08d4af5d2..cd290adf59 100644
@@ -55,7 +55,8 @@ def _crunch_known_licenses(d):
             md5sums[md5value] = fn
             # Also hash a "crunched" version
             md5value = _crunch_license(path)
-            md5sums[md5value] = fn
+            if md5value:
+                md5sums[md5value] = fn
 
     return md5sums
 
@@ -115,6 +116,11 @@ def _crunch_license(licfile):
             if line:
                 lictext.append(line)
 
+    # Only titles, copyright lines or URLs: there is no license text to
+    # compare, and an empty text would match every other empty text
+    if not lictext:
+        return None
+
     m = hashlib.md5()
     try:
         m.update(' '.join(lictext).encode('utf-8'))
Signature · 1 line
2.56.1
author
#4 lore raw

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

In reply to Tim Orling

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

---
 .../go-mod-update-modules.bbclass             | 43 +++++++++
 meta/lib/oe/license_finder.py                 | 93 +++++++++++++++++++
 2 files changed, 136 insertions(+)
meta/classes-recipe/go-mod-update-modules.bbclass +43 -0
index fc618dd750..bcb80e130d 100644
@@ -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:
meta/lib/oe/license_finder.py +93 -0

96 lines not on this page · raw message

Signature · 1 line
2.56.1
author
#5 lore raw

PATCH 5/7 go-mod-update-modules: add GO_MOD_LICENSE_STRICT

In reply to Tim Orling

A license file that is not identified only gives a warning, which is easy to miss in an upgrade.

Add GO_MOD_LICENSE_STRICT. Set to "1", do_update_modules fails without writing the files, and lists the unidentified files and the md5,SPDX lines to complete and add to a license-hashes.csv.

AI-Generated: Claude Opus 5.5

---
 meta/classes-recipe/go-mod-update-modules.bbclass | 13 +++++++++++++
 1 file changed, 13 insertions(+)
meta/classes-recipe/go-mod-update-modules.bbclass +13 -0
index bcb80e130d..030099fb0f 100644
@@ -19,6 +19,10 @@ do_update_modules[network] = "1"
 GO_MOD_LICENSE_SCANNER ??= ""
 do_update_modules[depends] += "${@'licensecheck-native:do_populate_sysroot' if d.getVar('GO_MOD_LICENSE_SCANNER') == 'licensecheck' else ''}"
 
+# Set to "1" to fail, without writing the files, when the license of a file is
+# not identified. The error lists the hashes to add to a license-hashes.csv.
+GO_MOD_LICENSE_STRICT ??= "0"
+
 python do_update_modules() {
     import subprocess, tempfile, json, re, urllib.parse
     from oe.license_finder import find_licenses_up
@@ -120,6 +124,15 @@ python do_update_modules() {
                     bb.note(f"{lic_file}: no license beyond {' '.join(sorted(declared))}, left out")
                     del lic_files[lic_file]
 
+        unknown = [(f, md5) for f, (node, md5) in lic_files.items()
+                   if isinstance(node, oe.spdx_license.UnknownId)]
+        if unknown and bb.utils.to_boolean(d.getVar("GO_MOD_LICENSE_STRICT")):
+            bb.fatal("Licenses not identified, %s-licenses.inc not written:\n%s\n"
+                     "Once each license is verified, add md5,SPDX lines like these to a "
+                     "files/license-hashes.csv in a layer:\n%s" % (
+                         bpn, "\n".join(f"  {f}" for f, _ in unknown),
+                         "\n".join(sorted({f"  {md5},Unknown" for _, md5 in unknown}))))
+
         licenses = []
         lic_files_chksum = []
         for lic_file in lic_files:
Signature · 1 line
2.56.1
author
#6 lore raw

PATCH 6/7 go-mod-update-modules: name unidentified licenses with a LicenseRef

In reply to Tim Orling

A license file that is not identified was written as "Unknown", which has no license text, so do_populate_lic failed.

Name it LicenseRef-go-<module>-<file>, warn, and point NO_GENERIC_LICENSE at the module's own text, so that the recipe builds and its SBOM names the file. GO_MOD_LICENSE_STRICT still fails first.

AI-Generated: Claude Opus 5.5

---
 .../go-mod-update-modules.bbclass             | 28 +++++++++++++++++--
 1 file changed, 25 insertions(+), 3 deletions(-)
meta/classes-recipe/go-mod-update-modules.bbclass +25 -3
index 030099fb0f..9ec41c7b57 100644
@@ -133,13 +133,31 @@ python do_update_modules() {
                          bpn, "\n".join(f"  {f}" for f, _ in unknown),
                          "\n".join(sorted({f"  {md5},Unknown" for _, md5 in unknown}))))
 
+        # Name a license that is not identified LicenseRef-go-<module>-<file>,
+        # with NO_GENERIC_LICENSE pointing at the module's own text, as
+        # "Unknown" has no text and would fail do_populate_lic.
+        for lic_file, (node, md5) in list(lic_files.items()):
+            if not isinstance(node, oe.spdx_license.UnknownId):
+                continue
+            module, _, rest = lic_file.partition('@')
+            in_module = rest.partition('/')[2]
+            name = re.sub(r'[^A-Za-z0-9.-]+', '-', f"go-{unescape_path(module)}-{in_module}").strip('-')
+            node = oe.spdx_license.parse("LicenseRef-" + name)
+            bb.warn(f"{lic_file}: license not identified, using its own text as {node.to_string()}")
+            lic_files[lic_file] = (node, md5)
+
+        lic_dirs = [d.getVar("COMMON_LICENSE_DIR")] + (d.getVar("LICENSE_PATH") or "").split()
+        no_generic = {}
+        for lic_file, (node, _) in lic_files.items():
+            for ref in node.iter():
+                if isinstance(ref, oe.spdx_license.LicenseRef) and not any(
+                        os.path.isfile(os.path.join(ld, n)) for ld in lic_dirs for n in (ref.name, ref.ident)):
+                    no_generic.setdefault(ref.name, f"pkg/mod/{lic_file}")
+
         licenses = []
         lic_files_chksum = []
         for lic_file in lic_files:
             node, license_md5 = lic_files[lic_file]
-            if isinstance(node, oe.spdx_license.UnknownId):
-                bb.warn(f"Unknown license: {lic_file} {license_md5}")
-
             licenses.append(node)
             lic_files_chksum.append(
                 f'file://pkg/mod/{lic_file};md5={license_md5};spdx={urllib.parse.quote_plus(node.to_string())}')
@@ -156,6 +174,10 @@ python do_update_modules() {
             for lic in sorted(lic_files_chksum, key=fold_uri):
                 f.write('    ' + lic + ' \\\n')
             f.write('"\n')
+            if no_generic:
+                f.write('\n')
+            for name in sorted(no_generic):
+                f.write(f'NO_GENERIC_LICENSE[{name}] = "{no_generic[name]}"\n')
 
         #
         # Sources
Signature · 1 line
2.56.1
author
#7 lore raw

PATCH 7/7 oeqa/selftest/oelib: add tests for license_finder

In reply to Tim Orling

Cover files without license text, the license files of the nearest directory, and how licensecheck results become SPDX expressions. scan_licenses() is tested with a stand-in for licensecheck, so no build is needed.

AI-Generated: Claude Opus 5.5

---
 .../selftest/cases/oelib/license_finder.py    | 146 ++++++++++++++++++
 1 file changed, 146 insertions(+)
 create mode 100644 meta/lib/oeqa/selftest/cases/oelib/license_finder.py
meta/lib/oeqa/selftest/cases/oelib/license_finder.py new file +146 -0
new file mode 100644
index 0000000000..866ce8c785
@@ -0,0 +1,146 @@
+#
+# Copyright OpenEmbedded Contributors
+#
+# SPDX-License-Identifier: MIT
+#
+
+import json
+import os
+import stat
+import sys
+import tempfile
+from unittest.case import TestCase
+
+import oe.license_finder as lf
+
+COMMON_LICENSE_DIR = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "..",
+                                  "files", "common-licenses")
+
+
+class Datastore:
+    """Just enough of a datastore for license_finder."""
+    def __init__(self, **values):
+        self.values = values
+
+    def getVar(self, name, expand=True):
+        return self.values.get(name)
+
+    def expand(self, s):
+        return s
+
+
+def datastore():
+    return Datastore(COMMON_LICENSE_DIR=os.path.normpath(COMMON_LICENSE_DIR), LICENSE_PATH="", BBPATH="")
+
+
+class TempDirTestCase(TestCase):
+    def setUp(self):
+        self.tmp = tempfile.TemporaryDirectory()
+        self.addCleanup(self.tmp.cleanup)
+
+    def write(self, name, text):
+        path = os.path.join(self.tmp.name, name)
+        os.makedirs(os.path.dirname(path), exist_ok=True)
+        with open(path, "w") as f:
+            f.write(text)
+        return path
+
+
+class TestCrunch(TempDirTestCase):
+    def test_no_license_text(self):
+        # Only a copyright line, like common-licenses/Proprietary only a title
+        path = self.write("COPYRIGHT", "Copyright (c) 2026 Example Corp.\nAll rights reserved.\n")
+        self.assertIsNone(lf._crunch_license(path))
+        self.assertIsNone(lf._crunch_license(os.path.join(COMMON_LICENSE_DIR, "Proprietary")))
+        self.assertIsNotNone(lf._crunch_license(os.path.join(COMMON_LICENSE_DIR, "MIT")))
+
+    def test_no_match_on_empty_text(self):
+        path = self.write("COPYRIGHT", "Copyright (c) 2026 Example Corp.\n")
+        self.assertNotIn(None, lf._crunch_known_licenses(datastore()))
+        [(node, _, _)] = lf.match_licenses([path], self.tmp.name, datastore())
+        self.assertEqual(node.to_string(), "Unknown")
+
+
+class TestFindLicenseFiles(TempDirTestCase):
+    def test_nearest_directory(self):
+        # A module with its own license and one for code taken from Go
+        self.write("mod/LICENSE", "MIT\n")
+        self.write("mod/GO_LICENSE", "BSD-3-Clause\n")
+        self.write("mod/pkg/file.go", "package pkg\n")
+        top = os.path.join(self.tmp.name, "mod")
+        found = lf.find_license_files(top, True, os.path.join(top, "pkg"))
+        self.assertEqual(sorted(os.path.basename(f) for f in found), ["GO_LICENSE", "LICENSE"])
+
+    def test_nearest_directory_only(self):
+        self.write("mod/LICENSE", "MIT\n")
+        self.write("mod/pkg/LICENSE", "BSD-3-Clause\n")
+        top = os.path.join(self.tmp.name, "mod")
+        found = lf.find_license_files(top, True, os.path.join(top, "pkg"))
+        self.assertEqual(found, [os.path.join(top, "pkg", "LICENSE")])
+
+
+class TestLicensecheckExpression(TestCase):
+    available = {"Apache-2.0", "BSD-3-Clause", "GPL-2.0-only", "GPL-2.0-or-later", "MIT", "MPL-2.0"}
+
+    def expression(self, percent, ids, text=""):
+        result = {"percent": percent,
+                  "matches": [{"id": i, "start": 0, "end": len(text)} for i in ids]}
+        return lf._licensecheck_expression(result, text, self.available, 80.0)[0]
+
+    def test_choice(self):
+        # As in github.com/spdx/tools-golang, the choice spans two lines
+        text = ("may be used, at your option,\nunder either:\n* Apache\n"
+                "* GPL version 2, or (at your option) any later version")
+        self.assertEqual(self.expression(99, ["Apache-2.0", "GPL-2.0"], text),
+                         "Apache-2.0 OR GPL-2.0-or-later")
+
+    def test_gpl_later_is_no_choice(self):
+        text = "or (at your option) any later version"
+        self.assertEqual(self.expression(95, ["MIT", "GPL-2.0"], text), "GPL-2.0-or-later AND MIT")
+
+    def test_gpl_only(self):
+        self.assertEqual(self.expression(99, ["GPL-2.0"], "version 2 of the License"), "GPL-2.0-only")
+
+    def test_partial_coverage(self):
+        # A list of third-party licenses: all of them, never a choice
+        text = "licensed under either of the licenses below"
+        self.assertEqual(self.expression(74, ["MIT", "Apache-2.0", "MPL-2.0"], text),
+                         "Apache-2.0 AND MIT AND MPL-2.0")
+
+    def test_no_text(self):
+        self.assertIsNone(self.expression(95, ["Zlib"]))
+        self.assertIsNone(self.expression(0, []))
+
+    def test_urls_are_not_licenses(self):
+        result = {"percent": 90, "matches": [{"id": "MIT", "start": 0, "end": 10, "url": True}]}
+        self.assertIsNone(lf._licensecheck_expression(result, "", self.available, 80.0)[0])
+
+
+class TestScanLicenses(TempDirTestCase):
+    def licensecheck(self):
+        """A licensecheck that finds nothing, as for texts it does not know."""
+        path = self.write("licensecheck", "#!%s\nimport json, sys\n"
+                          "for f in sys.argv[1:]:\n"
+                          "    print(json.dumps({'file': f, 'percent': 0, 'matches': []}))\n"
+                          % sys.executable)
+        os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR)
+        return path
+
+    def scan(self, text):
+        path = self.write("LICENSE", text)
+        node, _ = lf.scan_licenses([path], self.licensecheck(), datastore())[path]
+        return node.to_string() if node else None
+
+    def test_spdx_header(self):
+        self.assertEqual(self.scan("SPDX-License-Identifier: Apache-2.0 OR MIT\n"), "Apache-2.0 OR MIT")
+        self.assertEqual(self.scan("`SPDX-License-Identifier: MPL-2.0 AND BSD-3-Clause`\n"),
+                         "MPL-2.0 AND BSD-3-Clause")
+
+    def test_public_domain(self):
+        self.assertEqual(self.scan("All of the code has been dedicated to the public domain.\n"),
+                         "LicenseRef-PD")
+        self.assertEqual(self.scan("All these files have been put\ninto the public domain.\n"),
+                         "LicenseRef-PD")
+
+    def test_unknown(self):
+        self.assertIsNone(self.scan("Copyright (c) Example. See LICENSE for the full license text.\n"))
Signature · 1 line
2.56.1