Debian Codegraph @

scripts/rank-license-usage-codesearch.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 """Rank licence / exception usage across Debian via codesearch.debian.net.
18
19 An offline curation aid for deciding which short licences and which exceptions
20 are worth embedding as full text (TODO items 2 and 3). For each candidate it
21 asks Debian Code Search how many distinct source packages carry its
22 `SPDX-License-Identifier:` tag (licences) or `WITH <id>` exception, and prints a
23 ranked table flagging those at or above a package threshold (default 100).
24
25 It is NOT part of the test suite and must never run in CI (like
26 verify-anchors-codesearch.py / audit-license-coverage.py). Its human-reviewed
27 output guides the curated `_EMBEDDED_LICENSE_IDS` / exception list in
28 scripts/emit-license-data.py; the runtime itself never touches the network.
29
30 CAVEAT - the `SPDX-License-Identifier:` signal is biased and undercounts. It only
31 sees packages that write an SPDX tag, which skews heavily toward tag-adopting
32 ecosystems (Rust/Cargo, Go, modern JS) and misses traditional C/Perl projects
33 that ship a COPYING file with no tag. In practice ubiquitous licences like
34 ISC/Zlib/X11 score far below their real prevalence while MIT (tagged by most
35 Rust crates) is inflated.
36
37 `--text-mode` queries a different signal instead: a distinctive, non-template
38 substring of the licence's own text (via spdx_template_as_re.py), matched with
39 a whitespace-tolerant regex so re-wrapped copies still count. This recovers
40 usage the tag misses regardless of tagging. It is not strictly better
41 (a licence whose wording varies a lot in the wild, or whose text is largely
42 shared with a sibling licence, can score lower than the tag - MIT and
43 BSD-3-Clause commonly have no distinctive-enough window at all), so run both
44 modes and compare rather than trusting either alone.
45
46 Politeness (identical to verify-anchors-codesearch.py): one request at a time, a
47 sleep between live requests, an on-disk response cache, a descriptive
48 User-Agent, and honouring HTTP 429 / Retry-After. The v1 API needs an
49 `x-dcs-apikey` header (key from https://codesearch.debian.net/apikeys/ via Salsa
50 login) supplied via `$DCS_API_KEY` or `--key-file PATH` (never hardcoded).
51
52 CAUTION with `--all`: a few hundred requests at the default 1.3s spacing can
53 still be enough load that individual requests start stalling well before any
54 HTTP 429 comes back. The cache makes a run resumable, but prefer a larger
55 `--sleep`, a `--limit`-ed slice at a time, and spacing separate `--all` runs
56 out over time rather than back-to-back, out of consideration for the service.
57
58 Examples::
59
60 # rank a few licence ids by package count
61 scripts/rank-license-usage-codesearch.py --key-file KEY MIT Zlib ISC Unlicense
62
63 # rank every SPDX licence not already in common-licenses (long; cached)
64 scripts/rank-license-usage-codesearch.py --key-file KEY --all
65
66 # same, but the distinctive-text-window signal instead of the SPDX tag
67 scripts/rank-license-usage-codesearch.py --key-file KEY --text-mode --all
68
69 # rank exceptions
70 scripts/rank-license-usage-codesearch.py --key-file KEY --exceptions --all
71
72 # offline: show what would be queried, no network
73 scripts/rank-license-usage-codesearch.py --all --list
74 """
75
76 from __future__ import annotations
77
78 import argparse
79 import json
80 import sys
81 from collections.abc import Callable
82 from dataclasses import dataclass
83 from pathlib import Path
84 from typing import Literal
85
86 ROOT = Path(__file__).resolve().parent.parent
87 sys.path.insert(0, str(ROOT))
88 sys.path.insert(0, str(Path(__file__).resolve().parent))
89
90 from dcs_client import ( # noqa: E402
91 DEFAULT_SLEEP,
92 DcsClient,
93 DcsConfig,
94 SearchError,
95 SearchOutcome,
96 SearchState,
97 load_key,
98 )
99 from spdx_template_as_re import ( # noqa: E402
100 distinctive_window,
101 template_literal_spans,
102 window_to_regexp_query,
103 )
104
105 from decopy.licensing.data.common_licenses import COMMON_LICENSES # noqa: E402
106 from decopy.licensing.spdx import canonical_license_name # noqa: E402
107
108 LICENSES_DIR = ROOT / "tests" / "testdata" / "licenses"
109 EXCEPTIONS_DIR = ROOT / "tests" / "testdata" / "exceptions"
110
111 USER_AGENT = "decopy-usage-rank (+https://salsa.debian.org/debian/decopy)"
112 DEFAULT_CACHE = ROOT / ".cache" / "dcs-cache"
113 DEFAULT_THRESHOLD = 5 # distinct source packages, tag-mode; low on purpose -
114 # the tag can undercount real usage by orders of magnitude, so this flags
115 # "worth a --text-mode follow-up", not "definitely popular".
116
117
118 @dataclass
119 class Candidate:
120 label: str # decopy DEP-5 name, for the human-facing table
121 query: str
122 match_mode: Literal["literal", "regexp"] = "literal"
123
124
125 @dataclass
126 class Result:
127 candidate: Candidate
128 state: SearchState = SearchState.HITS
129 packages: int = 0 # only meaningful when state is HITS
130 hits: int = 0
131
132
133 def license_candidates(spdx_ids: list[str]) -> list[Candidate]:
134 return [
135 Candidate(
136 label=canonical_license_name(spdx_id),
137 query=f"SPDX-License-Identifier: {spdx_id}",
138 )
139 for spdx_id in spdx_ids
140 ]
141
142
143 def exception_candidates(exception_ids: list[str]) -> list[Candidate]:
144 return [
145 Candidate(label=exception_id, query=f"WITH {exception_id}")
146 for exception_id in exception_ids
147 ]
148
149
150 def all_license_ids(max_chars: int | None = None) -> list[str]:
151 """SPDX ids whose decopy name is not already a common-licences reference.
152
153 ``max_chars`` additionally drops ids whose ``licenseText`` is longer than
154 that (a long popular licence is a candidate for a common-licences
155 addition, not for embedding a copy in every debian/copyright).
156 """
157 ids = []
158 for path in LICENSES_DIR.glob("*.json"):
159 if canonical_license_name(path.stem) in COMMON_LICENSES:
160 continue
161 if max_chars is not None:
162 text = json.loads(path.read_text(encoding="utf-8")).get("licenseText", "")
163 if len(text) > max_chars:
164 continue
165 ids.append(path.stem)
166 return sorted(ids)
167
168
169 def all_exception_ids() -> list[str]:
170 return sorted(p.stem for p in EXCEPTIONS_DIR.glob("*.json"))
171
172
173 def common_license_ids() -> set[str]:
174 """SPDX ids already covered by a COMMON_LICENSES reference."""
175 return {
176 p.stem
177 for p in LICENSES_DIR.glob("*.json")
178 if canonical_license_name(p.stem) in COMMON_LICENSES
179 }
180
181
182 def _load_template(spdx_id: str) -> str:
183 path = LICENSES_DIR / f"{spdx_id}.json"
184 template = json.loads(path.read_text(encoding="utf-8")).get(
185 "standardLicenseTemplate", ""
186 )
187 return template if isinstance(template, str) else ""
188
189
190 def _text_corpus(ids: list[str]) -> dict[str, str]:
191 corpus: dict[str, str] = {}
192 for spdx_id in ids:
193 template = _load_template(spdx_id)
194 if template:
195 corpus[spdx_id] = " ".join(template_literal_spans(template))
196 return corpus
197
198
199 def text_license_candidates(
200 spdx_ids: list[str],
201 ) -> tuple[list[Candidate], list[str]]:
202 """(candidates, skipped) where each query is a distinctive text window.
203
204 Unlike license_candidates() (an SPDX-tag search), this searches for the
205 licence's own text so untagged copies count too. The collision corpus is
206 scoped to this ranking batch plus every COMMON_LICENSES-covered id, not
207 the whole SPDX corpus - see distinctive_window()'s docstring for why. Ids
208 with no distinctive-enough window are returned in the skipped list (a
209 query, not a print) for the caller to report.
210 """
211 corpus = _text_corpus(sorted(set(spdx_ids) | common_license_ids()))
212 candidates: list[Candidate] = []
213 skipped: list[str] = []
214 for spdx_id in spdx_ids:
215 spans = template_literal_spans(_load_template(spdx_id))
216 others = [text for other, text in corpus.items() if other != spdx_id]
217 window = distinctive_window(spans, others)
218 if window is None:
219 skipped.append(spdx_id)
220 continue
221 candidates.append(
222 Candidate(
223 label=canonical_license_name(spdx_id),
224 query=window_to_regexp_query(window),
225 match_mode="regexp",
226 )
227 )
228 return candidates, skipped
229
230
231 def count_packages(hits: list[dict]) -> int:
232 """Distinct source packages across the hits.
233
234 A hit without a ``package`` field is counted by its path instead, and a
235 note is printed so a path-count is never silently reported as a
236 package-count.
237 """
238 keys: set[str] = set()
239 fell_back = False
240 for hit in hits:
241 package = hit.get("package")
242 if package:
243 keys.add(package)
244 else:
245 keys.add(hit.get("path", ""))
246 fell_back = True
247 if fell_back:
248 note = " note: some hits had no package field; counted by path"
249 print(note, file=sys.stderr)
250 return len(keys)
251
252
253 def _result_for(candidate: Candidate, outcome: SearchOutcome) -> Result:
254 if outcome.state is SearchState.HITS:
255 return Result(
256 candidate,
257 state=SearchState.HITS,
258 packages=count_packages(outcome.hits),
259 hits=len(outcome.hits),
260 )
261 return Result(candidate, state=outcome.state)
262
263
264 Search = Callable[[str, str], SearchOutcome]
265
266
267 def fetch_results(
268 search: Search, candidates: list[Candidate], *, progress: bool
269 ) -> list[Result]:
270 results: list[Result] = []
271 for i, candidate in enumerate(candidates, 1):
272 if progress:
273 print(f" [{i}/{len(candidates)}] {candidate.label}", file=sys.stderr)
274 try:
275 outcome = search(candidate.query, candidate.match_mode)
276 except SearchError as exc:
277 # One candidate exhausting its retries should not discard every
278 # other already-fetched result; skip it and keep going. A fatal
279 # error (bad key/query) is SystemExit, which propagates and aborts.
280 print(f" giving up on {candidate.label}: {exc}", file=sys.stderr)
281 continue
282 results.append(_result_for(candidate, outcome))
283 return results
284
285
286 def _sort_key(result: Result) -> tuple[int, int, int]:
287 # Pending candidates sort last; broad ones first; then by package count.
288 return (
289 0 if result.state is SearchState.PENDING else 1,
290 1 if result.state is SearchState.BROAD else 0,
291 result.packages,
292 )
293
294
295 def _header(count: int, threshold: int) -> str:
296 return f"# {count} candidate(s); threshold={threshold} packages"
297
298
299 def _report_skips(skipped: list[str]) -> None:
300 for spdx_id in skipped:
301 print(f" no distinctive window for {spdx_id}; skipped", file=sys.stderr)
302
303
304 def report(results: list[Result], threshold: int) -> None:
305 print(_header(len(results), threshold))
306 ordered = sorted(results, key=_sort_key, reverse=True)
307 over = pending = 0
308 for result in ordered:
309 if result.state is SearchState.PENDING:
310 pending += 1
311 continue
312 broad = result.state is SearchState.BROAD
313 hit_threshold = broad or result.packages >= threshold
314 if hit_threshold:
315 over += 1
316 packages = "many" if broad else str(result.packages)
317 flag = "*" if hit_threshold else " "
318 print(
319 f"{flag} {result.candidate.label:32} packages={packages:>6} "
320 f"hits={result.hits:>6} q={result.candidate.query!r}"
321 )
322 done = len(results) - pending
323 print(f"\n# {over}/{done} queried at or above {threshold} packages (*)")
324 if pending:
325 print(f"# {pending} not yet queried (drop --offline-report to fetch them)")
326
327
328 def _selected_ids(
329 ids: list[str], *, exceptions: bool, all_: bool, max_chars: int | None
330 ) -> list[str]:
331 """Positional ids, or the full candidate set for the mode when --all."""
332 if ids:
333 return list(ids)
334 if not all_:
335 return []
336 return all_exception_ids() if exceptions else all_license_ids(max_chars)
337
338
339 def collect_candidates(
340 ids: list[str], *, exceptions: bool, text_mode: bool, limit: int = 0
341 ) -> tuple[list[Candidate], list[str]]:
342 """(candidates, skipped-ids). Only text mode can skip; others skip nothing.
343
344 ``limit`` (0 = no cap) trims the ids *before* building, so text mode does
345 not compute a distinctive window for ids that would be dropped anyway.
346 """
347 if limit:
348 ids = ids[:limit]
349 if exceptions:
350 return exception_candidates(ids), []
351 if text_mode:
352 return text_license_candidates(ids)
353 return license_candidates(ids), []
354
355
356 def build_parser() -> argparse.ArgumentParser:
357 parser = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0])
358 parser.add_argument("ids", nargs="*", help="SPDX licence/exception ids to rank")
359 parser.add_argument(
360 "--all", action="store_true", help="rank the full candidate set for the mode"
361 )
362 # --exceptions and --text-mode are alternate licence-search modes; argparse
363 # rejects passing both rather than a hand-rolled check inside main().
364 mode = parser.add_mutually_exclusive_group()
365 mode.add_argument(
366 "--exceptions", action="store_true", help="rank exception ids, not licences"
367 )
368 mode.add_argument(
369 "--text-mode",
370 action="store_true",
371 help="query a distinctive licence-text window instead of the SPDX tag",
372 )
373 parser.add_argument(
374 "--max-chars",
375 type=int,
376 default=None,
377 help="with --all, drop licences whose licenseText is longer than this",
378 )
379 parser.add_argument(
380 "--threshold", type=int, default=DEFAULT_THRESHOLD, help="package-count flag"
381 )
382 parser.add_argument(
383 "--limit", type=int, default=0, help="cap the candidate count (0 = no cap)"
384 )
385 parser.add_argument(
386 "--list", action="store_true", help="show queries; do not hit network"
387 )
388 parser.add_argument(
389 "--offline-report",
390 action="store_true",
391 help="report on cached results only (no network, no key needed); "
392 "candidates with no cache entry yet are counted as pending",
393 )
394 parser.add_argument("--refresh", action="store_true", help="ignore cache; re-query")
395 parser.add_argument("--sleep", type=float, default=DEFAULT_SLEEP)
396 parser.add_argument("--key-file", type=Path, default=None)
397 parser.add_argument("--cache-dir", type=Path, default=DEFAULT_CACHE)
398 return parser
399
400
401 def _print_query_list(candidates: list[Candidate], threshold: int) -> None:
402 print(_header(len(candidates), threshold))
403 for candidate in candidates:
404 print(f"{candidate.label:32} q={candidate.query!r}")
405
406
407 def _search_for(args: argparse.Namespace) -> Search:
408 """Build the client from parsed args and pick its cached/live search."""
409 key = "" if args.offline_report else load_key(args.key_file)
410 client = DcsClient(
411 DcsConfig(
412 key=key,
413 user_agent=USER_AGENT,
414 cache_dir=args.cache_dir,
415 sleep=args.sleep,
416 refresh=args.refresh,
417 cache_prefix="rank",
418 )
419 )
420 return client.search_cached if args.offline_report else client.search_live
421
422
423 def main() -> None:
424 args = build_parser().parse_args()
425 ids = _selected_ids(
426 args.ids, exceptions=args.exceptions, all_=args.all, max_chars=args.max_chars
427 )
428 candidates, skipped = collect_candidates(
429 ids, exceptions=args.exceptions, text_mode=args.text_mode, limit=args.limit
430 )
431 _report_skips(skipped)
432 if not candidates:
433 msg = "No candidates: pass ids, or --all (with --exceptions for those)."
434 raise SystemExit(msg)
435 if args.list:
436 _print_query_list(candidates, args.threshold)
437 return
438 results = fetch_results(
439 _search_for(args), candidates, progress=not args.offline_report
440 )
441 report(results, args.threshold)
442
443
444 if __name__ == "__main__":
445 main()