Debian Codegraph @

scripts/audit-spdx-roundtrip.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 the SPDX name/exception round-trip tables from the conversions.
18
19 For every SPDX licence (and, with --exceptions, every SPDX exception) shipped
20 in the testdata, run the full conversion loop and record it:
21
22 licence: SPDX id --replace_spdx--> DEP-5 name --dep5_to_spdx--> id'
23 exception: SPDX id --exception_to_dep5--> label --exception_to_spdx--> id'
24
25 The tables (tests/testdata/spdx-name-roundtrip.tsv,
26 tests/testdata/spdx-exception-roundtrip.tsv) lock both conversion directions so
27 neither a refreshed SPDX data drop nor a conversion change can shift coverage
28 silently. The status column is auto-classified but PRESERVED across runs once
29 present, so a manual `wrong:<note>` annotation survives a regenerate (mirroring
30 audit-license-coverage.py).
31
32 Run from the repository root:
33
34 python3 scripts/audit-spdx-roundtrip.py # licences
35 python3 scripts/audit-spdx-roundtrip.py --exceptions # exceptions
36 """
37
38 from __future__ import annotations
39
40 import argparse
41 import json
42 import sys
43 from pathlib import Path
44
45 ROOT = Path(__file__).resolve().parent.parent
46 sys.path.insert(0, str(ROOT))
47
48 from decopy.licensing import spdx # noqa: E402
49
50 LICENSES_DIR = ROOT / "tests" / "testdata" / "licenses"
51 EXCEPTIONS_DIR = ROOT / "tests" / "testdata" / "exceptions"
52 NAME_TSV = ROOT / "tests" / "testdata" / "spdx-name-roundtrip.tsv"
53 EXCEPTION_TSV = ROOT / "tests" / "testdata" / "spdx-exception-roundtrip.tsv"
54 _STATUS_COL = 3 # fourth column (id, dep5, back, status)
55
56 NAME_HEADER = (
57 "# SPDX licence name round-trip (regenerate with "
58 "scripts/audit-spdx-roundtrip.py).\n"
59 "# Columns: spdx_id <TAB> dep5_name <TAB> spdx_back <TAB> status\n"
60 "# dep5_name = replace_spdx(spdx_id); spdx_back = dep5_to_spdx(dep5_name).\n"
61 "# status: identity = spdx_back == spdx_id (decopy maps and round-trips);\n"
62 "# passthrough = decopy does not special-case it (dep5_name == id);\n"
63 "# deprecated = a deprecated SPDX id that collapses to its canonical\n"
64 "# form; wrong:<note> = a conversion asymmetry/defect to fix.\n"
65 )
66
67 EXCEPTION_HEADER = (
68 "# SPDX exception round-trip (regenerate with "
69 "scripts/audit-spdx-roundtrip.py --exceptions).\n"
70 "# Columns: spdx_exception_id <TAB> dep5_label <TAB> spdx_back <TAB> status\n"
71 "# dep5_label = exception_to_dep5(id); spdx_back = exception_to_spdx(label).\n"
72 "# status: identity = spdx_back == id; collapse = many SPDX ids share one\n"
73 "# label so back is the pinned representative; unmapped = no label.\n"
74 )
75
76
77 def classify_name(spdx_id: str, dep5_name: str, back: str, *, deprecated: bool) -> str:
78 if back == spdx_id:
79 return "passthrough" if dep5_name == spdx_id else "identity"
80 if deprecated:
81 return "deprecated"
82 return "wrong"
83
84
85 def classify_exception(spdx_id: str, label: str | None, back: str | None) -> str:
86 if label is None:
87 return "unmapped"
88 return "identity" if back == spdx_id else "collapse"
89
90
91 def _load_status(tsv: Path) -> dict[str, str]:
92 """Preserve only *annotated* statuses across regenerations.
93
94 A status carrying a note (e.g. ``wrong:accepted <reason>``) is a human
95 decision and is kept verbatim. A bare auto-status (``identity`` / ``wrong``
96 / ...) is re-derived from the current conversions, so a row that starts
97 round-tripping after a fix flips automatically instead of staying stale.
98 """
99 prev: dict[str, str] = {}
100 if not tsv.exists():
101 return prev
102 for line in tsv.read_text().splitlines():
103 if line.startswith("#") or not line.strip():
104 continue
105 cols = line.split("\t")
106 if len(cols) > _STATUS_COL and ":" in cols[_STATUS_COL]:
107 prev[cols[0]] = cols[_STATUS_COL]
108 return prev
109
110
111 def _write(tsv: Path, header: str, rows: list[tuple[str, str, str, str]]) -> None:
112 lines = [header]
113 lines.extend(f"{a}\t{b}\t{c}\t{d}\n" for a, b, c, d in rows)
114 tsv.write_text("".join(lines))
115
116
117 def audit_names() -> None:
118 prev = _load_status(NAME_TSV)
119 rows: list[tuple[str, str, str, str]] = []
120 for path in sorted(LICENSES_DIR.glob("*.json")):
121 spdx_id = path.stem
122 deprecated = bool(json.loads(path.read_text()).get("isDeprecatedLicenseId"))
123 dep5_name = spdx.replace_spdx(spdx_id)
124 back = spdx.dep5_to_spdx(dep5_name)
125 status = prev.get(spdx_id) or classify_name(
126 spdx_id, dep5_name, back, deprecated=deprecated
127 )
128 rows.append((spdx_id, dep5_name, back, status))
129 _write(NAME_TSV, NAME_HEADER, rows)
130 _report(rows)
131
132
133 def audit_exceptions() -> None:
134 prev = _load_status(EXCEPTION_TSV)
135 rows: list[tuple[str, str, str, str]] = []
136 for path in sorted(EXCEPTIONS_DIR.glob("*.json")):
137 spdx_id = path.stem
138 label = spdx.exception_to_dep5(spdx_id)
139 back = spdx.exception_to_spdx(label) if label is not None else None
140 status = prev.get(spdx_id) or classify_exception(spdx_id, label, back)
141 rows.append((spdx_id, label or "", back or "", status))
142 _write(EXCEPTION_TSV, EXCEPTION_HEADER, rows)
143 _report(rows)
144
145
146 def _report(rows: list[tuple[str, str, str, str]]) -> None:
147 counts: dict[str, int] = {}
148 for *_, status in rows:
149 key = status.split(":", 1)[0]
150 counts[key] = counts.get(key, 0) + 1
151 summary = ", ".join(f"{k}={v}" for k, v in sorted(counts.items()))
152 print(f"{len(rows)} rows: {summary}")
153
154
155 def main() -> None:
156 parser = argparse.ArgumentParser(description=__doc__)
157 parser.add_argument(
158 "--exceptions",
159 action="store_true",
160 help="audit SPDX exceptions instead of licences",
161 )
162 args = parser.parse_args()
163 if args.exceptions:
164 audit_exceptions()
165 else:
166 audit_names()
167
168
169 if __name__ == "__main__":
170 main()