Debian Codegraph @

scripts/audit-license-coverage.py

raw
1 #!/usr/bin/env python3
2 # Copyright: 2026, Maximiliano Curia <[email protected]>
3 #
4 # License: ISC
5 # Permission to use, copy, modify, and/or distribute this software for any
6 # purpose with or without fee is hereby granted, provided that the above
7 # copyright notice and this permission notice appear in all copies.
8 # .
9 # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10 # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11 # AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12 # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13 # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15 # PERFORMANCE OF THIS SOFTWARE.
16
17 """Regenerate tests/testdata/license-coverage.tsv from the current matchers.
18
19 For every licence in tests/testdata/licenses/, record what find_licenses()
20 currently produces (its DEP-5 name, or empty if undetected). The table is the
21 regression baseline and audit log: rows with an empty result are the coverage
22 gaps still to close. The `status` column are annotations (ok / undetected /
23 wrong / ...); it is preserved across regenerations so manual review is not
24 lost.
25
26 Run from the repository root:
27
28 python3 scripts/audit-license-coverage.py
29 """
30
31 from __future__ import annotations
32
33 import json
34 import sys
35 from pathlib import Path
36
37 ROOT = Path(__file__).resolve().parent.parent
38 sys.path.insert(0, str(ROOT))
39
40 from decopy.licensing import licenses # noqa: E402
41
42 LICENSES_DIR = ROOT / "tests" / "testdata" / "licenses"
43 TSV = ROOT / "tests" / "testdata" / "license-coverage.tsv"
44
45 _STATUS_COL = 2 # third column (spdx_id, dep5_result, status)
46
47 HEADER = (
48 "# SPDX licence coverage baseline (regenerate with "
49 "scripts/audit-license-coverage.py).\n"
50 "# Columns: spdx_id <TAB> dep5_result <TAB> status <TAB> fields\n"
51 "# dep5_result is find_licenses() joined with ' or '; empty = undetected.\n"
52 "# status: ok = detected (correctness reviewed); undetected = no match yet;\n"
53 "# wrong:<note> = detected as the wrong licence.\n"
54 "# fields: comma-separated SPDX field(s) to validate against (default\n"
55 "# licenseText). e.g. standardLicenseHeader when the licenseText is\n"
56 "# shared across an id's -only/-or-later variants.\n"
57 )
58
59 DEFAULT_FIELDS = ("licenseText",)
60 _FIELDS_COL = 3
61
62
63 def detect(license_text: str) -> str:
64 found = licenses.find_licenses(licenses.clean_comments(license_text))
65 return " or ".join(sorted(found))
66
67
68 def load_curated() -> dict[str, tuple[str, str]]:
69 """Preserve the status and fields columns from the table."""
70 curated: dict[str, tuple[str, str]] = {}
71 if not TSV.exists():
72 return curated
73 for line in TSV.read_text().splitlines():
74 if line.startswith("#") or not line.strip():
75 continue
76 cols = line.split("\t")
77 status = cols[_STATUS_COL] if len(cols) > _STATUS_COL else ""
78 fields = cols[_FIELDS_COL] if len(cols) > _FIELDS_COL else ""
79 curated[cols[0]] = (status, fields)
80 return curated
81
82
83 def main() -> None:
84 prev = load_curated()
85 rows: list[tuple[str, str, str, str]] = []
86 for path in sorted(LICENSES_DIR.glob("*.json")):
87 spdx_id = path.stem
88 data = json.loads(path.read_text())
89 prev_status, fields = prev.get(spdx_id, ("", ""))
90 field_names = [f for f in fields.split(",") if f] or list(DEFAULT_FIELDS)
91 # Result comes from the first listed field that is present.
92 result = next(
93 (detect(data[f]) for f in field_names if data.get(f)),
94 "",
95 )
96 status = prev_status or ("ok" if result else "undetected")
97 rows.append((spdx_id, result, status, fields))
98
99 lines = [HEADER]
100 lines.extend(f"{s}\t{r}\t{st}\t{f}\n" for s, r, st, f in rows)
101 TSV.write_text("".join(lines))
102
103 detected = sum(1 for _, result, _, _ in rows if result)
104 undetected = len(rows) - detected
105 print(f"{len(rows)} licences: {detected} detected, {undetected} undetected")
106
107
108 if __name__ == "__main__":
109 main()