| 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 |
"""Convert an SPDX template field into a regex aligned with clean_comments(). |
| 18 |
|
| 19 |
SPDX licence and exception JSON files ship templated forms of their text using |
| 20 |
the SPDX template markup: |
| 21 |
|
| 22 |
* ``<<beginOptional>> ... <<endOptional>>`` wraps an omissible span; |
| 23 |
* ``<<var;name=..;original=..;match="RE">>`` marks a slot whose allowed |
| 24 |
variation is given by the ``match`` regex. |
| 25 |
|
| 26 |
Three fields use this markup: |
| 27 |
|
| 28 |
============================== ========================= |
| 29 |
template field corresponding text field |
| 30 |
============================== ========================= |
| 31 |
standardLicenseTemplate licenseText |
| 32 |
standardLicenseHeaderTemplate standardLicenseHeader |
| 33 |
licenseExceptionTemplate licenseExceptionText |
| 34 |
============================== ========================= |
| 35 |
|
| 36 |
``template_to_regex()`` converts the markup into a Python regex that matches |
| 37 |
the corresponding text *after* decopy's ``clean_comments()`` normalisation, |
| 38 |
so the output can seed a hand-written matcher in ``decopy/res.py``. The |
| 39 |
generated regex is deliberately permissive (and large); it is a starting |
| 40 |
point to read the required-vs-optional structure from, not a drop-in |
| 41 |
production matcher. |
| 42 |
|
| 43 |
``template_literal_spans()`` and ``distinctive_window()`` serve a different |
| 44 |
consumer: picking a short, distinctive, non-template substring of a licence's |
| 45 |
text to search for verbatim (e.g. against a source-code search engine, to |
| 46 |
estimate real-world usage independently of whether anyone tagged the file |
| 47 |
with an SPDX identifier). That needs the *raw* text, not the |
| 48 |
clean_comments-normalised form, so it deliberately does not reuse |
| 49 |
``_literal_to_regex``'s charset-stripping cleanup. |
| 50 |
|
| 51 |
Run from the repository root, e.g.: |
| 52 |
|
| 53 |
python3 scripts/spdx_template_as_re.py tests/testdata/licenses/HPND.json |
| 54 |
python3 scripts/spdx_template_as_re.py tests/testdata/exceptions/\ |
| 55 |
GCC-exception-2.0.json --field licenseExceptionTemplate --validate |
| 56 |
""" |
| 57 |
|
| 58 |
from __future__ import annotations |
| 59 |
|
| 60 |
import argparse |
| 61 |
import json |
| 62 |
import sys |
| 63 |
import typing as t |
| 64 |
from pathlib import Path |
| 65 |
|
| 66 |
import regex as rex |
| 67 |
|
| 68 |
ROOT = Path(__file__).resolve().parent.parent |
| 69 |
sys.path.insert(0, str(ROOT)) |
| 70 |
|
| 71 |
from decopy.licensing import licenses # noqa: E402 |
| 72 |
|
| 73 |
# The text field each template field describes (and a stable processing order). |
| 74 |
TEMPLATE_FIELDS: dict[str, str] = { |
| 75 |
"standardLicenseTemplate": "licenseText", |
| 76 |
"standardLicenseHeaderTemplate": "standardLicenseHeader", |
| 77 |
"licenseExceptionTemplate": "licenseExceptionText", |
| 78 |
} |
| 79 |
|
| 80 |
# A template marker: an optional-span delimiter or a variable slot. |
| 81 |
_TOKEN_RE = rex.compile(r"<<(beginOptional|endOptional|var;.*?)>>", rex.DOTALL) |
| 82 |
_MATCH_RE = rex.compile(r'match="((?:[^"\\]|\\.)*)"') |
| 83 |
|
| 84 |
# clean_comments() keeps these characters; everything else becomes whitespace. |
| 85 |
_KEPT = r" \w'.,@:;()/+-" |
| 86 |
|
| 87 |
# Unbounded wildcards in a slot's match expression are clamped to this many |
| 88 |
# characters so the generated regex cannot backtrack catastrophically. |
| 89 |
_WILDCARD_BOUND = 200 |
| 90 |
|
| 91 |
|
| 92 |
def _literal_to_regex(literal: str) -> str: |
| 93 |
"""Turn template literal text into a clean_comments-tolerant regex.""" |
| 94 |
cleaned = rex.sub(rf"[^{_KEPT}]", " ", literal) |
| 95 |
cleaned = rex.sub(r"\s+", " ", cleaned).strip() |
| 96 |
if not cleaned: |
| 97 |
return "" |
| 98 |
return "".join(r"\s+" if ch == " " else rex.escape(ch) for ch in cleaned) |
| 99 |
|
| 100 |
|
| 101 |
def _var_to_regex(spec: str) -> str: |
| 102 |
"""Turn a ``var;..;match="RE"`` slot into a bounded regex group.""" |
| 103 |
match = _MATCH_RE.search(spec) |
| 104 |
expr = match.group(1) if match else ".*" |
| 105 |
expr = expr.replace(".*", rf".{{0,{_WILDCARD_BOUND}}}") |
| 106 |
expr = expr.replace(".+", rf".{{1,{_WILDCARD_BOUND}}}") |
| 107 |
return f"(?:{expr})" |
| 108 |
|
| 109 |
|
| 110 |
def _iter_segments(template: str) -> t.Iterator[tuple[str, str]]: |
| 111 |
"""Yield (kind, text) pairs walking a template's literal/token runs. |
| 112 |
|
| 113 |
``kind`` is ``"literal"`` for a text run, or the token's own name |
| 114 |
(``beginOptional``, ``endOptional``, or the raw ``var;...`` spec). |
| 115 |
""" |
| 116 |
pos = 0 |
| 117 |
for token in _TOKEN_RE.finditer(template): |
| 118 |
yield "literal", template[pos : token.start()] |
| 119 |
yield token.group(1), token.group(1) |
| 120 |
pos = token.end() |
| 121 |
yield "literal", template[pos:] |
| 122 |
|
| 123 |
|
| 124 |
def template_to_regex(template: str) -> str: |
| 125 |
"""Convert SPDX template markup into a single regex string.""" |
| 126 |
pieces: list[str] = [] |
| 127 |
for kind, text in _iter_segments(template): |
| 128 |
if kind == "literal": |
| 129 |
pieces.append(_literal_to_regex(text)) |
| 130 |
elif kind == "beginOptional": |
| 131 |
pieces.append("(?:") |
| 132 |
elif kind == "endOptional": |
| 133 |
pieces.append(")?") |
| 134 |
else: |
| 135 |
pieces.append(_var_to_regex(kind)) |
| 136 |
# Tolerate whitespace between every piece; clean_comments single-spaces. |
| 137 |
return r"\s*".join(piece for piece in pieces if piece) |
| 138 |
|
| 139 |
|
| 140 |
# A blank line (paragraph break) ends a literal span, same as a <<var>> |
| 141 |
# token: a source-code search engine may bridge an ordinary wrapped newline |
| 142 |
# but not a blank line, so no search window may straddle one. |
| 143 |
_PARA_BREAK_RE = rex.compile(r"\n[ \t]*\n") |
| 144 |
|
| 145 |
# Shapes that suggest an unmarked template placeholder the SPDX curators |
| 146 |
# forgot to tag with <<var>> (a bracket/underscore fill-in, or a bare |
| 147 |
# placeholder word) rather than stable prose. Conservative and imprecise: it |
| 148 |
# also flags stable disclaimer prose that happens to use one of these words |
| 149 |
# (e.g. 0BSD's "THE AUTHOR DISCLAIMS..."). A hit means "check this by hand", |
| 150 |
# not "reject automatically". |
| 151 |
_DUBIOUS_RE = rex.compile( |
| 152 |
r"[\[\]<>]|_{3,}|\b(?:LIST|NAME|YEAR|HOLDER|AUTHOR|ORGANIZATION|TITLE|OWNER|COMPANY|DATE)\b" |
| 153 |
) |
| 154 |
|
| 155 |
|
| 156 |
def _normalize_ws(text: str) -> str: |
| 157 |
return rex.sub(r"\s+", " ", text).strip() |
| 158 |
|
| 159 |
|
| 160 |
def template_literal_spans(template: str) -> list[str]: |
| 161 |
"""Literal chunks between ``<<var>>``/optional tokens and blank lines. |
| 162 |
|
| 163 |
Unlike ``_literal_to_regex``, this only collapses whitespace runs and |
| 164 |
leaves every other character as-is, so the result stays a substring of |
| 165 |
the real (raw) licence text - suitable for a verbatim/raw-text search, |
| 166 |
not for matching decopy's own clean_comments-normalised text. |
| 167 |
""" |
| 168 |
raw_spans = [text for kind, text in _iter_segments(template) if kind == "literal"] |
| 169 |
return [ |
| 170 |
cleaned |
| 171 |
for raw in raw_spans |
| 172 |
for para in _PARA_BREAK_RE.split(raw) |
| 173 |
if (cleaned := _normalize_ws(para)) |
| 174 |
] |
| 175 |
|
| 176 |
|
| 177 |
def is_dubious(span: str) -> bool: |
| 178 |
"""Flag literal text that looks like an unmarked template placeholder.""" |
| 179 |
return bool(_DUBIOUS_RE.search(span)) |
| 180 |
|
| 181 |
|
| 182 |
def _windows_from_words(words: list[str], min_len: int, max_len: int) -> list[str]: |
| 183 |
"""Word-windows of ``words`` whose joined length falls in [min_len, max_len].""" |
| 184 |
out: list[str] = [] |
| 185 |
for start in range(len(words)): |
| 186 |
for end in range(start + 1, len(words) + 1): |
| 187 |
window = " ".join(words[start:end]) |
| 188 |
if len(window) > max_len: |
| 189 |
break |
| 190 |
if len(window) >= min_len: |
| 191 |
out.append(window) |
| 192 |
return out |
| 193 |
|
| 194 |
|
| 195 |
def _candidate_windows(spans: list[str], min_len: int, max_len: int) -> list[str]: |
| 196 |
"""Every span's word-windows in [min_len, max_len] chars, longest first.""" |
| 197 |
windows: list[str] = [] |
| 198 |
for span in spans: |
| 199 |
windows.extend(_windows_from_words(span.split(), min_len, max_len)) |
| 200 |
windows.sort(key=len, reverse=True) |
| 201 |
return windows |
| 202 |
|
| 203 |
|
| 204 |
def distinctive_window( |
| 205 |
spans: list[str], |
| 206 |
other_texts: list[str], |
| 207 |
*, |
| 208 |
min_len: int = 40, |
| 209 |
max_len: int = 140, |
| 210 |
) -> str | None: |
| 211 |
"""Longest word-window that is not dubious and absent from ``other_texts``. |
| 212 |
|
| 213 |
``spans`` is one licence's ``template_literal_spans()``. ``other_texts`` |
| 214 |
is the concatenated literal text of every other licence this one must |
| 215 |
stay distinguishable from; scope it to the licences actually competing in |
| 216 |
a given ranking pass (not the whole SPDX corpus) - a global-uniqueness |
| 217 |
bar rejects e.g. BSD-2-Clause/BSD-3-Clause/HPND for colliding with |
| 218 |
obscure, practically-irrelevant SPDX ids that would never affect a real |
| 219 |
embedding decision. Returns ``None`` if nothing qualifies. |
| 220 |
""" |
| 221 |
for window in _candidate_windows(spans, min_len, max_len): |
| 222 |
if is_dubious(window): |
| 223 |
continue |
| 224 |
if any(window in text for text in other_texts): |
| 225 |
continue |
| 226 |
return window |
| 227 |
return None |
| 228 |
|
| 229 |
|
| 230 |
def window_to_regexp_query(window: str) -> str: |
| 231 |
"""Plain-text window -> source-search ``regexp``-mode query (``\\s+`` gaps). |
| 232 |
|
| 233 |
Each word is regex-escaped and the words are joined by ``\\s+`` so the |
| 234 |
query tolerates re-wrapped whitespace (including across a line break) |
| 235 |
without asserting whitespace anywhere the raw text doesn't actually have |
| 236 |
it (``template_literal_spans`` already keeps punctuation literal for |
| 237 |
exactly this reason). |
| 238 |
""" |
| 239 |
return r"\s+".join(rex.escape(w) for w in window.split()) |
| 240 |
|
| 241 |
|
| 242 |
def _read_json(path: Path) -> dict[str, object]: |
| 243 |
"""Load the SPDX JSON file as an object, or exit on malformed input.""" |
| 244 |
raw = json.loads(path.read_text(encoding="utf-8")) |
| 245 |
if not isinstance(raw, dict): |
| 246 |
sys.exit(f"{path}: not a JSON object") |
| 247 |
return t.cast("dict[str, object]", raw) |
| 248 |
|
| 249 |
|
| 250 |
def _pick_template(data: dict[str, object], field: str, path: Path) -> str: |
| 251 |
"""Return the requested template field, or exit with a helpful message.""" |
| 252 |
template = data.get(field) |
| 253 |
if not isinstance(template, str) or not template: |
| 254 |
present = sorted(k for k in TEMPLATE_FIELDS if isinstance(data.get(k), str)) |
| 255 |
hint = f"; template fields present: {present}" if present else "" |
| 256 |
sys.exit(f"{path}: no usable {field!r}{hint}") |
| 257 |
return template |
| 258 |
|
| 259 |
|
| 260 |
def _validate(data: dict[str, object], field: str, regex_str: str) -> bool: |
| 261 |
"""Check the generated regex matches the corresponding text field.""" |
| 262 |
text_field = TEMPLATE_FIELDS[field] |
| 263 |
text = data.get(text_field) |
| 264 |
if not isinstance(text, str) or not text: |
| 265 |
print(f"validate: {text_field!r} absent; skipped", file=sys.stderr) |
| 266 |
return True |
| 267 |
pattern = rex.compile(regex_str, rex.IGNORECASE | rex.DOTALL) |
| 268 |
matched = bool(pattern.search(licenses.clean_comments(text))) |
| 269 |
status = "matches" if matched else "DOES NOT MATCH" |
| 270 |
print(f"validate: regex {status} {text_field}", file=sys.stderr) |
| 271 |
return matched |
| 272 |
|
| 273 |
|
| 274 |
def main() -> None: |
| 275 |
parser = argparse.ArgumentParser( |
| 276 |
description="Convert an SPDX template field into a clean_comments-aligned " |
| 277 |
"regex (seed for a hand-written matcher).", |
| 278 |
) |
| 279 |
parser.add_argument("file", type=Path, help="SPDX licence/exception JSON file") |
| 280 |
parser.add_argument( |
| 281 |
"--field", |
| 282 |
choices=sorted(TEMPLATE_FIELDS), |
| 283 |
default="standardLicenseTemplate", |
| 284 |
help="template field to convert (default: standardLicenseTemplate)", |
| 285 |
) |
| 286 |
parser.add_argument( |
| 287 |
"--validate", |
| 288 |
action="store_true", |
| 289 |
help="check the regex matches the file's corresponding text field", |
| 290 |
) |
| 291 |
args = parser.parse_args() |
| 292 |
|
| 293 |
data = _read_json(args.file) |
| 294 |
template = _pick_template(data, args.field, args.file) |
| 295 |
regex_str = template_to_regex(template) |
| 296 |
print(regex_str) |
| 297 |
|
| 298 |
if args.validate and not _validate(data, args.field, regex_str): |
| 299 |
sys.exit(1) |
| 300 |
|
| 301 |
|
| 302 |
if __name__ == "__main__": |
| 303 |
main() |