| 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 |
"""Generate decopy's shipped licence-text data from the SPDX corpus. |
| 18 |
|
| 19 |
Offline maintenance aid: reads the SPDX JSON vendored under tests/testdata/ and |
| 20 |
writes the committed package-data under decopy/licensing/data/. It is NOT part |
| 21 |
of the test suite and must never run in CI; re-run it by hand after refreshing |
| 22 |
the SPDX corpus, then commit the regenerated files. |
| 23 |
|
| 24 |
scripts/emit-license-data.py --headers # data/headers/<decopy-name>.txt |
| 25 |
scripts/emit-license-data.py --licenses # data/licenses/<decopy-name>.txt |
| 26 |
scripts/emit-license-data.py --exceptions # data/exceptions/<dep5-label>.txt |
| 27 |
|
| 28 |
Headers are the cleaned ``standardLicenseHeader`` keyed by decopy's DEP-5 name |
| 29 |
(so GPL-2.0-only -> GPL-2, GPL-2.0-or-later -> GPL-2+). Only the common-licenses |
| 30 |
families are emitted: the renderer prepends a header solely when it emits a |
| 31 |
common-licenses reference (to disambiguate the +/only variant), so other SPDX |
| 32 |
headers would never be read. When several SPDX ids canonicalise to one name the |
| 33 |
smallest id wins, so the result is deterministic. |
| 34 |
""" |
| 35 |
|
| 36 |
from __future__ import annotations |
| 37 |
|
| 38 |
import argparse |
| 39 |
import json |
| 40 |
import re |
| 41 |
import sys |
| 42 |
from pathlib import Path |
| 43 |
|
| 44 |
ROOT = Path(__file__).resolve().parent.parent |
| 45 |
sys.path.insert(0, str(ROOT)) |
| 46 |
|
| 47 |
from decopy.licensing.data.common_licenses import COMMON_LICENSES # noqa: E402 |
| 48 |
from decopy.licensing.spdx import ( # noqa: E402 |
| 49 |
canonical_license_name, |
| 50 |
exception_to_spdx, |
| 51 |
) |
| 52 |
|
| 53 |
LICENSES_DIR = ROOT / "tests" / "testdata" / "licenses" |
| 54 |
EXCEPTIONS_DIR = ROOT / "tests" / "testdata" / "exceptions" |
| 55 |
DATA_DIR = ROOT / "decopy" / "licensing" / "data" |
| 56 |
HEADERS_DIR = DATA_DIR / "headers" |
| 57 |
LICENSES_OUT = DATA_DIR / "licenses" |
| 58 |
EXCEPTIONS_OUT = DATA_DIR / "exceptions" |
| 59 |
|
| 60 |
# Short / widely used licences embedded as full verbatim text instead of a |
| 61 |
# common-licenses reference (they are too short for the indirection and are not |
| 62 |
# in common-licenses). SPDX ids; the output is keyed by the decopy DEP-5 name. |
| 63 |
# The original seed (MIT/ISC/Zlib/X11 + BSD-2/3) was extended 2026-07-02 from |
| 64 |
# the completed tag-mode codesearch ranking (scripts/rank-license-usage- |
| 65 |
# codesearch.py, .claude/reports/s3.5-license-status.md): every short candidate |
| 66 |
# was queried and those at or above ~5 distinct source packages were added. The |
| 67 |
# SPDX-License-Identifier signal is biased toward tag-adopting ecosystems |
| 68 |
# (Rust/Go/modern) so it undercounts untagged C/Perl, but with the whole batch |
| 69 |
# ranked it is a usable relative shortlist. BSD-2-Clause-FreeBSD is a deprecated |
| 70 |
# SPDX id, kept because it still sees real (22-package) usage. |
| 71 |
_EMBEDDED_LICENSE_IDS: tuple[str, ...] = ( |
| 72 |
"0BSD", |
| 73 |
"BSD-1-Clause", |
| 74 |
"BSD-2-Clause", |
| 75 |
"BSD-2-Clause-FreeBSD", |
| 76 |
"BSD-3-Clause", |
| 77 |
"BSD-3-Clause-Clear", |
| 78 |
"BSD-4-Clause", |
| 79 |
"CC-PDDC", |
| 80 |
"FSFAP", |
| 81 |
"FSFUL", |
| 82 |
"FSFULLR", |
| 83 |
"ISC", |
| 84 |
"MIT", |
| 85 |
"MIT-0", |
| 86 |
"PSF-2.0", |
| 87 |
"Unicode-3.0", |
| 88 |
"Unlicense", |
| 89 |
"X11", |
| 90 |
"Zlib", |
| 91 |
"curl", |
| 92 |
) |
| 93 |
|
| 94 |
# Widely used licence exceptions embedded as full verbatim text so a |
| 95 |
# "<base> with <label> exception" stanza is complete. These are decopy DEP-5 |
| 96 |
# labels (as find_licenses emits them); emit_exceptions maps each to its SPDX |
| 97 |
# exception id via exception_to_spdx. The GPL-family seed was extended |
| 98 |
# 2026-07-02 from the exception ranking (.claude/reports/s4.3-exception-status.md, |
| 99 |
# which tag-queried all 84 SPDX exceptions): every uncovered exception at or |
| 100 |
# above ~5 distinct source packages was added. Same SPDX-`WITH` tag bias as the |
| 101 |
# licence ranking, so these are a relative shortlist, not a hard gate. |
| 102 |
_EMBEDDED_EXCEPTION_LABELS: tuple[str, ...] = ( |
| 103 |
"AutoConf", |
| 104 |
"AutoConf-3", |
| 105 |
"AutoConf-macro", |
| 106 |
"Bison", |
| 107 |
"Bootloader", |
| 108 |
"ClassPath", |
| 109 |
"Font", |
| 110 |
"GCC", |
| 111 |
"GCC-3.1", |
| 112 |
"LLVM", |
| 113 |
"Linux-syscall", |
| 114 |
"OCaml-LGPL", |
| 115 |
"PCRE2", |
| 116 |
"Qt-GPL-1", |
| 117 |
"Qt-LGPL-1.1", |
| 118 |
) |
| 119 |
|
| 120 |
# The resolver prepends a header only when it emits a common-licenses reference, |
| 121 |
# so only these names are ever consumed; other SPDX headers would be dead data. |
| 122 |
# Each family covers both the base and its "+" (or-later) variant. |
| 123 |
_CONSUMED_HEADERS = set(COMMON_LICENSES) | {f"{name}+" for name in COMMON_LICENSES} |
| 124 |
|
| 125 |
# A leading copyright-notice prefix: "Copyright" (opt. "Portions"), an optional |
| 126 |
# (C)/© mark, an optional year token/placeholder, and an optional holder |
| 127 |
# placeholder. Stripped from the START of a line so a header that packs the |
| 128 |
# notice and the grant on one line (GFDL) keeps the grant; a line that is only |
| 129 |
# the notice (GPL/Apache/AGPL/LGPL) strips to empty and is dropped. The holder |
| 130 |
# belongs in the paragraph's Copyright field, not the shared text. |
| 131 |
_COPYRIGHT_PREFIX = re.compile( |
| 132 |
r"^(?:portions\s+)?copyright\b\s*(?:\([cC]\)|©)?\s*" |
| 133 |
r"(?:year|yyyy|\[[^\]]*\]|<[^>]*>|\d{4}(?:-\d{4})?)?\s*" |
| 134 |
r"(?:your name|name of author|name of copyright owner|\[[^\]]*\]|<[^>]*>)?" |
| 135 |
r"\s*\.?\s*", |
| 136 |
re.IGNORECASE, |
| 137 |
) |
| 138 |
# A whole-line angle-bracketed instruction, e.g. |
| 139 |
# "<one line to give the program's name ...>". A bare <url> has no internal |
| 140 |
# space, so it is kept. |
| 141 |
_INSTRUCTION_LINE = re.compile(r"^<[^>]*\s[^>]*>$") |
| 142 |
# The same "how to apply" instruction the LGPL headers write without brackets: |
| 143 |
# "one line to give the library's name and an idea of what it does." |
| 144 |
_INSTRUCTION_PHRASE = re.compile(r"^<?one line to give\b", re.IGNORECASE) |
| 145 |
# A fill-in-the-blank template line ("Contributor(s): ______", "[___] License"). |
| 146 |
_TEMPLATE_BLANK = re.compile(r"_{3,}") |
| 147 |
# A standalone clerical "All Rights Reserved." fragment. |
| 148 |
_RESERVED_LINE = re.compile(r"^all rights reserved\.?$", re.IGNORECASE) |
| 149 |
# Copyright-notice lines and the licence's own heading are dropped from an |
| 150 |
# embedded full-text licence: the holder goes in the Copyright field and the |
| 151 |
# License field already names the licence, so neither belongs in the shared |
| 152 |
# text. The substantive terms are kept verbatim. |
| 153 |
_COPYRIGHT_START = re.compile(r"^copyright\b", re.IGNORECASE) |
| 154 |
# The leading heading is recognised structurally rather than by keyword, so |
| 155 |
# it catches "MIT License", "The FreeBSD Copyright", "UNICODE LICENSE V3", |
| 156 |
# "MIT No Attribution" and "PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2" |
| 157 |
# alike: a short first line (the substantive terms are always full sentences |
| 158 |
# far longer than this) that does not read as a sentence (no closing period). |
| 159 |
_TITLE_MAX_LEN = 55 |
| 160 |
|
| 161 |
|
| 162 |
def _is_title_line(line: str) -> bool: |
| 163 |
stripped = line.strip() |
| 164 |
return 0 < len(stripped) <= _TITLE_MAX_LEN and not stripped.endswith(".") |
| 165 |
|
| 166 |
|
| 167 |
def clean_license(text: str) -> str: |
| 168 |
"""Embedded full-text cleaning: drop a leading title/heading line, any |
| 169 |
copyright notice lines and standalone "All rights reserved." lines; keep |
| 170 |
the rest verbatim (trailing whitespace trimmed).""" |
| 171 |
lines = [line.rstrip() for line in text.splitlines()] |
| 172 |
first = next((i for i, line in enumerate(lines) if line.strip()), None) |
| 173 |
if first is not None and _is_title_line(lines[first]): |
| 174 |
del lines[first] |
| 175 |
kept = [ |
| 176 |
line |
| 177 |
for line in lines |
| 178 |
if not _COPYRIGHT_START.match(line.strip()) |
| 179 |
and not _RESERVED_LINE.match(line.strip()) |
| 180 |
] |
| 181 |
return "\n".join(kept).strip("\n") |
| 182 |
|
| 183 |
|
| 184 |
# A GFDL no-invariants SPDX id; decopy names these GFDL-NIV-<version>. |
| 185 |
_GFDL_NIV_ID = re.compile(r"^GFDL-(\d+\.\d+)-no-invariants-(only|or-later)$") |
| 186 |
|
| 187 |
|
| 188 |
def _header_name(license_id: str) -> str | None: |
| 189 |
"""The decopy name to key a header by, or None to skip this licence. |
| 190 |
|
| 191 |
GFDL is special: decopy detection names it GFDL-<v> (invariants allowed) and |
| 192 |
GFDL-NIV-<v> (no invariants). The invariants-allowing notice carries |
| 193 |
unfillable "Invariant Sections being LIST ..." placeholders (and unfilled it |
| 194 |
is non-free), so only the no-invariants variant gets a header, keyed by the |
| 195 |
detection name GFDL-NIV-<v>. |
| 196 |
""" |
| 197 |
if license_id.startswith("GFDL-"): |
| 198 |
match = _GFDL_NIV_ID.match(license_id) |
| 199 |
if match is None: |
| 200 |
return None |
| 201 |
suffix = "+" if match.group(2) == "or-later" else "" |
| 202 |
return f"GFDL-NIV-{match.group(1)}{suffix}" |
| 203 |
return canonical_license_name(license_id) |
| 204 |
|
| 205 |
|
| 206 |
def _strip_edge_quote(text: str, *, leading: bool) -> str: |
| 207 |
"""Drop one wrapping quote at the given edge of a paragraph, if present. |
| 208 |
|
| 209 |
Applied to the first/last surviving paragraph rather than the raw header: |
| 210 |
once copyright/template lines are removed, the wrapper quote can end up on a |
| 211 |
new edge line. A leading/trailing quote is never real content in this corpus, |
| 212 |
whereas inner quotes (the "License") are. |
| 213 |
""" |
| 214 |
if leading: |
| 215 |
return text[1:].strip() if text[:1] in ('"', "'") else text |
| 216 |
return text[:-1].strip() if text[-1:] in ('"', "'") else text |
| 217 |
|
| 218 |
|
| 219 |
def _is_noise_line(line: str) -> bool: |
| 220 |
return bool( |
| 221 |
_INSTRUCTION_LINE.match(line) |
| 222 |
or _INSTRUCTION_PHRASE.match(line) |
| 223 |
or _TEMPLATE_BLANK.search(line) |
| 224 |
or _RESERVED_LINE.match(line) |
| 225 |
) |
| 226 |
|
| 227 |
|
| 228 |
def _clean_line(line: str) -> str: |
| 229 |
"""A header line with its leading copyright-notice prefix removed, or "". |
| 230 |
|
| 231 |
Returns "" for a line that is only noise (instruction/template/reserved) or |
| 232 |
only a copyright notice; otherwise the kept text (the grant that may follow |
| 233 |
the notice on the same line). |
| 234 |
""" |
| 235 |
if _is_noise_line(line): |
| 236 |
return "" |
| 237 |
return _COPYRIGHT_PREFIX.sub("", line, count=1).strip() |
| 238 |
|
| 239 |
|
| 240 |
def clean_header(text: str) -> str: |
| 241 |
"""Clean an SPDX standardLicenseHeader into a shared-text notice. |
| 242 |
|
| 243 |
Drops copyright/template, instruction-placeholder and fill-in-the-blank |
| 244 |
lines, collapses each surviving paragraph to a single normalised line (the |
| 245 |
resolver reflows to width; blank lines mark paragraphs), then strips a quote |
| 246 |
wrapping the first/last surviving paragraph. |
| 247 |
""" |
| 248 |
paragraphs: list[str] = [] |
| 249 |
current: list[str] = [] |
| 250 |
for raw in text.splitlines(): |
| 251 |
line = _clean_line(raw.strip()) |
| 252 |
if not line: |
| 253 |
if current: |
| 254 |
paragraphs.append(" ".join(current)) |
| 255 |
current = [] |
| 256 |
continue |
| 257 |
current.append(line) |
| 258 |
if current: |
| 259 |
paragraphs.append(" ".join(current)) |
| 260 |
if not paragraphs: |
| 261 |
return "" |
| 262 |
paragraphs[0] = _strip_edge_quote(paragraphs[0], leading=True) |
| 263 |
paragraphs[-1] = _strip_edge_quote(paragraphs[-1], leading=False) |
| 264 |
return "\n\n".join(p for p in paragraphs if p) |
| 265 |
|
| 266 |
|
| 267 |
def emit_headers() -> int: |
| 268 |
HEADERS_DIR.mkdir(parents=True, exist_ok=True) |
| 269 |
for stale in HEADERS_DIR.glob("*.txt"): |
| 270 |
stale.unlink() |
| 271 |
chosen: dict[str, str] = {} |
| 272 |
for path in sorted(LICENSES_DIR.glob("*.json"), key=lambda p: p.stem): |
| 273 |
data = json.loads(path.read_text(encoding="utf-8")) |
| 274 |
# Skip deprecated ids (the bare GPL-2.0 / GFDL-1.3 forms); the explicit |
| 275 |
# -only / -or-later ids carry the header that matches the decopy name's |
| 276 |
# meaning (GFDL-1.3 -> the "only" notice, not the "or later" one). |
| 277 |
if data.get("isDeprecatedLicenseId"): |
| 278 |
continue |
| 279 |
raw = (data.get("standardLicenseHeader") or "").strip() |
| 280 |
if not raw: |
| 281 |
continue |
| 282 |
name = _header_name(data.get("licenseId") or path.stem) |
| 283 |
if name is None or name not in _CONSUMED_HEADERS: |
| 284 |
continue |
| 285 |
cleaned = clean_header(raw) |
| 286 |
if cleaned and name not in chosen: # smallest id wins (sorted iteration) |
| 287 |
chosen[name] = cleaned |
| 288 |
for name, text in chosen.items(): |
| 289 |
(HEADERS_DIR / f"{name}.txt").write_text(text + "\n", encoding="utf-8") |
| 290 |
return len(chosen) |
| 291 |
|
| 292 |
|
| 293 |
def emit_licenses() -> int: |
| 294 |
"""Write each curated licence's verbatim SPDX licenseText to data/licenses. |
| 295 |
|
| 296 |
The text is authoritative, so it is copied unchanged (not cleaned or wrapped |
| 297 |
like headers); the resolver embeds it as-is. Keyed by the decopy DEP-5 name. |
| 298 |
""" |
| 299 |
LICENSES_OUT.mkdir(parents=True, exist_ok=True) |
| 300 |
for stale in LICENSES_OUT.glob("*.txt"): |
| 301 |
stale.unlink() |
| 302 |
written = 0 |
| 303 |
for spdx_id in sorted(_EMBEDDED_LICENSE_IDS): |
| 304 |
path = LICENSES_DIR / f"{spdx_id}.json" |
| 305 |
if not path.is_file(): |
| 306 |
print(f"warning: no SPDX json for {spdx_id!r}", file=sys.stderr) |
| 307 |
continue |
| 308 |
raw = json.loads(path.read_text(encoding="utf-8")).get("licenseText") or "" |
| 309 |
text = clean_license(raw) |
| 310 |
if not text: |
| 311 |
print(f"warning: {spdx_id} has no licenseText", file=sys.stderr) |
| 312 |
continue |
| 313 |
name = canonical_license_name(spdx_id) |
| 314 |
(LICENSES_OUT / f"{name}.txt").write_text(text + "\n", encoding="utf-8") |
| 315 |
written += 1 |
| 316 |
return written |
| 317 |
|
| 318 |
|
| 319 |
def _exception_text_for(label: str) -> str | None: |
| 320 |
"""The verbatim licenseExceptionText for a DEP-5 label, or None (warning).""" |
| 321 |
spdx_id = exception_to_spdx(label) |
| 322 |
if spdx_id is None: |
| 323 |
print(f"warning: no SPDX exception id for label {label!r}", file=sys.stderr) |
| 324 |
return None |
| 325 |
path = EXCEPTIONS_DIR / f"{spdx_id}.json" |
| 326 |
if not path.is_file(): |
| 327 |
print(f"warning: no SPDX json for {spdx_id!r}", file=sys.stderr) |
| 328 |
return None |
| 329 |
raw = json.loads(path.read_text(encoding="utf-8")).get("licenseExceptionText") |
| 330 |
text = (raw or "").strip() |
| 331 |
if not text: |
| 332 |
print(f"warning: {spdx_id} has no licenseExceptionText", file=sys.stderr) |
| 333 |
return None |
| 334 |
return text |
| 335 |
|
| 336 |
|
| 337 |
def emit_exceptions() -> int: |
| 338 |
"""Write each curated exception's verbatim licenseExceptionText, keyed by |
| 339 |
the decopy DEP-5 label. The text is authoritative and copied unchanged (only |
| 340 |
surrounding blank lines trimmed); the resolver appends it as-is.""" |
| 341 |
EXCEPTIONS_OUT.mkdir(parents=True, exist_ok=True) |
| 342 |
for stale in EXCEPTIONS_OUT.glob("*.txt"): |
| 343 |
stale.unlink() |
| 344 |
written = 0 |
| 345 |
for label in sorted(_EMBEDDED_EXCEPTION_LABELS): |
| 346 |
text = _exception_text_for(label) |
| 347 |
if text is None: |
| 348 |
continue |
| 349 |
(EXCEPTIONS_OUT / f"{label}.txt").write_text(text + "\n", encoding="utf-8") |
| 350 |
written += 1 |
| 351 |
return written |
| 352 |
|
| 353 |
|
| 354 |
def main() -> None: |
| 355 |
parser = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0]) |
| 356 |
parser.add_argument( |
| 357 |
"--headers", action="store_true", help="emit data/headers/<name>.txt" |
| 358 |
) |
| 359 |
parser.add_argument( |
| 360 |
"--licenses", action="store_true", help="emit data/licenses/<name>.txt" |
| 361 |
) |
| 362 |
parser.add_argument( |
| 363 |
"--exceptions", action="store_true", help="emit data/exceptions/<label>.txt" |
| 364 |
) |
| 365 |
args = parser.parse_args() |
| 366 |
if not (args.headers or args.licenses or args.exceptions): |
| 367 |
parser.error("nothing to do: pass --headers, --licenses and/or --exceptions") |
| 368 |
if args.headers: |
| 369 |
count = emit_headers() |
| 370 |
print(f"wrote {count} headers to {HEADERS_DIR.relative_to(ROOT)}") |
| 371 |
if args.licenses: |
| 372 |
count = emit_licenses() |
| 373 |
print(f"wrote {count} licences to {LICENSES_OUT.relative_to(ROOT)}") |
| 374 |
if args.exceptions: |
| 375 |
count = emit_exceptions() |
| 376 |
print(f"wrote {count} exceptions to {EXCEPTIONS_OUT.relative_to(ROOT)}") |
| 377 |
|
| 378 |
|
| 379 |
if __name__ == "__main__": |
| 380 |
main() |