Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : SP Boucher Source Governance9# File : spbheader/repo.py10# Description : Repository-level logic: git facts, license and ownership11# analysis, classification, policy files, file eligibility12# and variant selection.13# Module : spbheader14# Repository : https://git.spboucher.ai/spb-source-governance15# Project Website : https://git.spboucher.ai16# Created : 2026-11-2117# Last Modified : 2026-11-2118#19# =============================================================================20# AUTHOR & PROFESSIONAL AFFILIATION21# =============================================================================22#23# Author : Simon-Pierre Boucher24# Position : Professor of Finance25# Institution : Université du Québec en Outaouais (UQO)26# Department : Département des sciences administratives27# Organization : SP Boucher28#29# Website : https://spboucher.ai30# Git : https://git.spboucher.ai31#32# =============================================================================33# OFFICIAL CONTACT DIRECTORY34# =============================================================================35#36# General : info@spboucher.ai37# Professional : contact@spboucher.ai38# Direct : simon@spboucher.ai39# Research : research@spboucher.ai40# Development : dev@spboucher.ai41# Support : support@spboucher.ai42# Security/Admin : admin@spboucher.ai43# Notifications : notifications@spboucher.ai44#45# Preferred Contact: dev@spboucher.ai46#47# =============================================================================48# COPYRIGHT & INTELLECTUAL PROPERTY49# =============================================================================50#51# Copyright (c) 202652# Simon-Pierre Boucher53#54# All rights reserved where applicable.55#56# This file is governed by the applicable project license,57# copyright notices, institutional agreements and relevant law.58#59# Unless expressly authorized by the applicable license or60# rights holder, copying, redistribution, sublicensing,61# publication and commercial exploitation are not permitted.62#63# Existing third-party rights and notices remain unaffected.64#65# =============================================================================66# CONFIDENTIALITY & SECURITY67# =============================================================================68#69# Classification : Public70# Distribution : Public repository; use is governed by the project license71# Security Contact : admin@spboucher.ai72#73# Access to this source does not independently grant permission74# to redistribute or disclose confidential materials.75#76# Do not embed credentials, private keys, access tokens,77# certificates or confidential personal information.78#79# =============================================================================80# LICENSE & MAINTENANCE81# =============================================================================82#83# License : None specified (no license file in this repository)84# Maintainer : Simon-Pierre Boucher85# Technical Contact: dev@spboucher.ai86#87# =============================================================================88# END OF SP BOUCHER SOURCE HEADER89# =============================================================================9091"""Repository-level logic: git facts, license and ownership analysis, classification,92policy files, file eligibility and variant selection."""93from __future__ import annotations9495import fnmatch96import json97import re98import subprocess99import tomllib100import unicodedata101from pathlib import Path102103from . import core104105POLICY_FILE = ".spb-source-governance.toml"106BRANCH = "chore/spb-source-governance"107108109def git(repo: Path, *args: str, check: bool = True) -> str:110 r = subprocess.run(["git", "-C", str(repo), *args], capture_output=True)111 if check and r.returncode != 0:112 raise RuntimeError(f"git {' '.join(args)} failed in {repo}: {r.stderr.decode(errors='replace')[:300]}")113 return r.stdout.decode("utf-8", errors="replace")114115116def git_bytes(repo: Path, *args: str) -> bytes | None:117 r = subprocess.run(["git", "-C", str(repo), *args], capture_output=True)118 return r.stdout if r.returncode == 0 else None119120121def tracked(repo: Path) -> list[tuple[str, str]]:122 """[(mode, path)] of tracked files; symlinks and submodules keep their mode for exclusion."""123 out = subprocess.run(["git", "-C", str(repo), "ls-files", "-s", "-z"], capture_output=True).stdout124 res = []125 for rec in out.split(b"\0"):126 if rec:127 meta, path = rec.split(b"\t", 1)128 res.append((meta.split()[0].decode(), path.decode("utf-8", errors="surrogateescape")))129 return res130131132def file_dates(repo: Path, ref: str = "HEAD") -> dict[str, tuple[str, str]]:133 """path -> (first commit date, last commit date) as recorded in version control."""134 out = git(repo, "log", ref, "--no-renames", "--name-only", "--date=short", "--format=@@%ad", check=False)135 dates: dict[str, list[str]] = {}136 cur = ""137 for ln in out.splitlines():138 if ln.startswith("@@"):139 cur = ln[2:]140 elif ln:141 d = dates.setdefault(ln, [cur, cur])142 d[0] = cur # log is newest first: keep overwriting => oldest143 return {k: (v[0], v[1]) for k, v in dates.items()}144145146# --------------------------------------------------------------------------- license analysis147148LICENSE_NAMES = re.compile(r"^(LICEN[SC]E|COPYING|UNLICENSE)([.-][\w.-]+)?$", re.I)149SIGNATURES = [150 ("MIT", "MIT License", r"Permission is hereby granted, free of charge, to any person obtaining a copy"),151 ("Apache-2.0", "Apache License 2.0", r"Apache License\s+Version 2\.0"),152 ("MPL-2.0", "Mozilla Public License 2.0", r"Mozilla Public License,? [Vv]ersion 2\.0"),153 ("BSD-3-Clause", "BSD 3-Clause License", r"Redistributions of source code must retain.*Neither the name"),154 ("BSD-2-Clause", "BSD 2-Clause License", r"Redistributions of source code must retain"),155 ("AGPL-3.0", "GNU Affero General Public License v3", r"GNU AFFERO GENERAL PUBLIC LICENSE\s+Version 3"),156 ("LGPL", "GNU Lesser General Public License", r"GNU LESSER GENERAL PUBLIC LICENSE"),157 ("GPL", "GNU General Public License", r"GNU GENERAL PUBLIC LICENSE"),158 ("CC-BY-4.0", "Creative Commons Attribution 4.0", r"Creative Commons Attribution 4\.0"),159 ("CC0-1.0", "CC0 1.0 Universal", r"CC0 1\.0 Universal"),160 ("Unlicense", "The Unlicense", r"This is free and unencumbered software released into the public domain"),161]162# SPDX identifiers that are exact for the detected text; the GPL family needs a human163# (only / or-later cannot be read from the licence text alone), so no identifier is emitted.164SPDX_EXACT = {"MIT", "Apache-2.0", "MPL-2.0", "BSD-3-Clause", "BSD-2-Clause", "CC-BY-4.0", "CC0-1.0", "Unlicense"}165COPY_RE = re.compile(r"Copyright\s*(?:\(c\)|©)?\s*((?:19|20)\d{2}(?:\s*[-–]\s*(?:19|20)\d{2})?)[,]?\s+([^\n|]+)", re.I)166167168def analyze_license(repo: Path) -> dict:169 """Read the license file of a working tree. Never infers a license that is not written down."""170 res = {"file": "", "name": "", "spdx": "", "kind": "none", "holder": "", "years": "", "extra_files": []}171 top = sorted(p.name for p in repo.iterdir() if p.is_file())172 files = [n for n in top if LICENSE_NAMES.match(n)]173 res["extra_files"] = [n for n in top if re.match(r"^(NOTICE|AUTHORS|CONTRIBUTORS|SECURITY|CITATION)(\.\w+)?$", n, re.I)]174 if not files:175 return res176 res["file"] = files[0]177 text = (repo / files[0]).read_text(encoding="utf-8", errors="replace")178 flat = re.sub(r"\s+", " ", text)179 for spdx, name, sig in SIGNATURES:180 if re.search(sig, flat, re.S):181 res.update(name=name, kind="open-source", spdx=spdx if spdx in SPDX_EXACT else "")182 break183 else:184 if re.search(r"all rights reserved|tous droits réservés|proprietary|propriétaire", flat, re.I):185 res.update(name="Proprietary, all rights reserved (see license file)", kind="proprietary")186 else:187 res.update(name="Custom license (see license file)", kind="custom")188 m = COPY_RE.search(text)189 if m:190 holder = re.sub(r"\s*<[^>]*>", "", m.group(2))191 holder = re.split(r"\.\s|\s+All rights|\s+Tous droits", holder)[0].strip(" .")192 res.update(years=re.sub(r"\s*[-–]\s*", "-", m.group(1)), holder=holder)193 return res194195196def declared_license_metadata(repo: Path) -> str:197 """License strings found in package metadata (evidence only; never used to populate headers)."""198 found = []199 pj = repo / "package.json"200 if pj.exists():201 try:202 lic = json.loads(pj.read_text(encoding="utf-8")).get("license")203 if lic:204 found.append(f"package.json:{lic}")205 except Exception:206 pass207 pp = repo / "pyproject.toml"208 if pp.exists():209 try:210 proj = tomllib.loads(pp.read_text(encoding="utf-8")).get("project", {})211 lic = proj.get("license")212 if lic:213 found.append("pyproject.toml:" + (lic if isinstance(lic, str) else str(lic.get("text") or lic.get("file"))))214 except Exception:215 pass216 return ", ".join(found)217218219def paper_authors(repo: Path, files: list[str]) -> list[str]:220 """Raw \\author{...} declarations of the LaTeX sources (scientific authorship evidence)."""221 out = []222 for f in files:223 if not f.endswith(".tex") or f.count("/") > 3:224 continue225 try:226 text = (repo / f).read_text(encoding="utf-8", errors="replace")227 except OSError:228 continue229 if "\\documentclass" not in text:230 continue231 for m in re.finditer(r"^[^%\n]*\\author(?:\[[^\]]*\])?\{", text, re.M):232 depth, k = 1, m.end()233 while k < len(text) and depth:234 depth += {"{": 1, "}": -1}.get(text[k], 0)235 k += 1236 a = re.sub(r"\s+", " ", text[m.end():k - 1]).strip()237 if a and a not in out:238 out.append(a[:300])239 return out[:8]240241242# --------------------------------------------------------------------------- classification243244NAME_RULES = [ # (regex on slug, category, status, note) — first match wins245 (r"^wp47_uqo$", "research", "review", "paper authored by another researcher (no SP Boucher authorship claim possible)"),246 (r"^(phd_thesis|gsf3100|gsf6053|gsf6053_h25)$", "teaching", "review", "Université Laval material: UQO affiliation line would be misleading"),247 (r"^(phi-conseil|hilmacorp|hilmacorp-ca)$", "web", "review", "client / third-party entity site: rights holder to confirm"),248 (r"^jellyfin$", "infra", "review", "wrapper around third-party software: ownership to confirm"),249 (r"^(crea-ka|trouve-ka|resto-ka|house-ka|rent-ka)$", "web", "deferred", "archived 2026-09-04"),250 (r"^(websensor|market-atlas|hfmarketdata|datacenterindex|cancerindex|company-atlas|satelliteindex|internetpressure|pdf2txt|sp-tv|htr-platform|htr|clip-spboucher-ai)$",251 "web", "deferred", "retired / replaced production, repository frozen"),252 (r"^(wp\d+|wpai\d+|firc\d+)_uqo$", "research", "in-scope", ""),253 (r"^(uqo-research-db|qwhpi|air|valoplex|localvm-research|autoscholar|findata|wp-spboucher-ai|maclustr-research)$", "research", "in-scope", ""),254 (r"^(uqo_cours|uqo_cours_public|uqo-imm\d+|traite-evaluation-qc|artificial-neural-networks-book|neural-networks|uqo-eval|uqo-chat)$", "teaching", "in-scope", ""),255 (r"^orix-", "orix-app", "in-scope", ""),256 (r"^sp-", "sp-app", "in-scope", ""),257 (r"^(maclustr-|cluster-skill$)", "maclustr", "in-scope", ""),258 (r"^(spbgit|spb-cloud|ka-guardian|ka2|ka4|ka6|os-vault)$", "infra", "in-scope", ""),259 (r"^(zyquo-|llm-|maclustr-llm|polyllm|llmindex|modelmap|agent-os|khaelor|claude-remote|local-chat|skills-spboucher-ai|ultra-sharp-agent-skills|immbot-ai|ai-atlas)", "ai", "in-scope", ""),260 (r"(-ka|-ka-ios|-ka-macos)$|^ka-", "web", "in-scope", ""),261]262263264def classify(slug: str, files: list[str]) -> tuple[str, str, str]:265 for rx, cat, status, note in NAME_RULES:266 if re.search(rx, slug):267 if cat in ("web", "ai", "sp-app") and _is_apple(files):268 cat = "apple-app" if cat != "sp-app" else "sp-app"269 return cat, status, note270 if _is_apple(files):271 return "apple-app", "in-scope", ""272 exts = [f.rsplit(".", 1)[-1].lower() for f in files if "." in f]273 n = lambda *e: sum(exts.count(x) for x in e)274 if "package.json" in files or n("ts", "tsx", "js", "jsx", "mjs") > 5:275 return "web", "in-scope", ""276 if n("tex") > n("py") and n("tex") > 3:277 return "research", "in-scope", "classified from content (LaTeX dominant)"278 if n("py", "go", "rs", "sh", "c", "cpp") > 0:279 return "tool", "in-scope", ""280 return "unknown", "review", "classification could not be determined from name or content"281282283def _is_apple(files: list[str]) -> bool:284 return any(f.endswith((".xcodeproj/project.pbxproj", "project.yml")) or f == "Package.swift" for f in files) \285 and sum(f.endswith(".swift") for f in files) >= 3286287288def display_name(slug: str) -> str:289 m = re.match(r"^wp(\d+)_uqo$", slug)290 if m:291 return f"UQO Working Paper {m.group(1)}"292 m = re.match(r"^wpai(\d+)_uqo$", slug)293 if m:294 return f"UQO Working Paper AI-{m.group(1)}"295 m = re.match(r"^firc(\d+)_uqo$", slug)296 if m:297 return f"FIRC-{m.group(1)}"298 words = re.split(r"[-_]", slug)299 up = {"sp": "SP", "orix": "ORIX", "ka": "Ka", "uqo": "UQO", "ios": "iOS", "macos": "macOS", "ai": "AI",300 "api": "API", "llm": "LLM", "mlx": "MLX", "dj": "DJ", "tv": "TV", "ui": "UI", "www": "WWW", "qc": "QC"}301 return " ".join(up.get(w.lower(), w[:1].upper() + w[1:]) for w in words if w)302303304def readme_title(repo: Path) -> str:305 """Project name as the repository states it (first heading of the README), if short and clean."""306 for name in ("README.md", "readme.md", "README.MD"):307 f = repo / name308 if f.exists():309 head = f.read_text(encoding="utf-8", errors="replace")[:6000]310 m = re.search(r"<h1[^>]*>(.*?)</h1>", head, re.S | re.I) or re.search(r"^#\s+(.+)$", head, re.M)311 if m:312 t = re.sub(r"<[^>]+>|!\[[^\]]*\]\([^)]*\)|[`*_]", "", m.group(1))313 t = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", t)314 t = re.sub(r"\s+", " ", t).strip(" -—:")315 t = re.split(r"\s[—–:|]\s", t)[0]316 t = "".join(ch for ch in t if unicodedata.category(ch) not in ("So", "Sk", "Cs", "Mn", "Cf")).strip()317 if re.fullmatch(r"[a-z0-9._-]+", t) and t != repo.name:318 return "" # a README copied from another repository319 if 2 <= len(t) <= 48 and not re.search(r"[<>{}]", t):320 return t321 return ""322323324def draft_policy(slug: str, repo: Path, visibility: str, cfg: dict, registry_domains: dict | None = None) -> dict:325 """First policy for a repository, from verifiable facts only. Hand-editable afterwards."""326 files = [p for _, p in tracked(repo)]327 cat, status, note = classify(slug, files)328 lic = analyze_license(repo)329 ident = cfg["identity"]330 authors = sorted({a.strip() for a in git(repo, "log", "--format=%an", check=False).splitlines() if a.strip()})331 humans = [a for a in authors if a.lower() not in ("simon-pierre boucher", "spb", "mld", "maclustr-agentd", "claude")]332 first_year = (git(repo, "log", "--reverse", "--date=format:%Y", "--format=%ad", check=False).splitlines() or [""])[0]333 last_year = (git(repo, "log", "-1", "--date=format:%Y", "--format=%ad", check=False).strip())334 years = first_year if first_year == last_year else f"{first_year}-{last_year}"335 papers = paper_authors(repo, files) if cat in ("research", "teaching") else []336 review: list[str] = [note] if note else []337 if humans:338 review.append("other commit authors: " + ", ".join(humans))339 status = "review" if status == "in-scope" else status340341 own_license = bool(lic["holder"]) and "boucher" in lic["holder"].lower()342 if lic["file"] and lic["holder"] and not own_license:343 review.append(f"license file names another rights holder: {lic['holder']}")344 status = "review" if status == "in-scope" else status345 if own_license:346 cline, holder, basis = f"Copyright (c) {lic['years']}", lic["holder"], f"stated in {lic['file']}"347 elif cat in ("research", "teaching"):348 cline = "Copyright (c) the author(s) of this work."349 holder = "Ownership is not asserted by this notice; see the repository records."350 basis = "research / teaching material without a license file: ownership left unasserted"351 review.append("no license file: rights holder of the research code to be confirmed by the author")352 else:353 cline, holder = f"Copyright (c) {years}", ident["author"]["name"]354 basis = "sole author in version-control history (no license file)"355 oneline = (f"(c) {lic['years']} {lic['holder']}" if own_license else356 "(c) the author(s) of this work; ownership not asserted here" if cat in ("research", "teaching")357 else f"(c) {years} {ident['author']['name']}")358 def _others(decl: str) -> str:359 d = re.sub(r"\\(thanks|footnote|inst|corref|fnref|affil|orcidlink|email|texttt|href)\s*(\[[^\]]*\])?\{[^{}]*\}", " ", decl)360 d = re.sub(r"\\[A-Za-z]+\*?|[{}\\$~&%]|\[[^\]]*\]", " ", d)361 d = re.sub(r"Simon-Pierre\s+Boucher|S\.-?P\.\s*Boucher|withheld for review|Author identity", " ", d, flags=re.I)362 d = re.sub(r"[^A-Za-zÀ-ÿ' -]", " ", d)363 return " ".join(w for w in d.split() if len(w) > 2 and w.lower() not in ("and", "the", "for", "small", "quad"))364 coauth = [o for o in (_others(a) for a in papers if "\\begin" not in a or True) if len(o) > 5]365 coauth = [o for o in coauth if not re.fullmatch(r"[A-Z0-9 -]{3,12}", o)]366 if coauth and cat == "research":367 review.append("paper names other authors or contributors (" + " | ".join(coauth)[:160] + "): maintainer header not applied")368 status = "review" if status == "in-scope" else status369 public = visibility == "public"370 return {371 "schema": 1, "engine": core.ENGINE_VERSION, "slug": slug, "project": readme_title(repo) or display_name(slug),372 "category": cat, "status": status, "visibility": visibility,373 "repository_url": f"{ident['author']['git']}/{slug}" if public else "",374 "project_url": (registry_domains or {}).get(slug, ""),375 "version": "",376 "contact": ident["routing"].get(cat, ident["routing"]["default"]),377 "classification": "Public" if public else "Internal",378 "distribution": ("Public repository; use is governed by the project license" if public379 else "Private repository; authorized collaborators only"),380 "copyright": {"line": cline, "holder": holder, "oneline": oneline, "basis": basis},381 "license": {"name": lic["name"] or "None specified (no license file in this repository)",382 "spdx": lic["spdx"], "file": lic["file"], "kind": lic["kind"],383 "declared_metadata": declared_license_metadata(repo)},384 "exclude": {"paths": []},385 "variant": {},386 "review": [r for r in review if r],387 "evidence": {"commit_authors": authors, "paper_authors": papers, "other_files": lic["extra_files"],388 "history_years": years},389 }390391392def _toml_value(v) -> str:393 if isinstance(v, bool):394 return "true" if v else "false"395 if isinstance(v, (int, float)):396 return str(v)397 if isinstance(v, list):398 return "[" + ", ".join(_toml_value(x) for x in v) + "]"399 return json.dumps(str(v), ensure_ascii=False)400401402def dump_toml(d: dict) -> str:403 head = ["# SP Boucher source governance — repository policy.",404 "# Read by `spb-header`; edit by hand, then run `spb-header apply`.",405 "# Canonical policy: SOURCE_HEADER_POLICY.md of the spb-source-governance repository.", ""]406 scal = [f"{k} = {_toml_value(v)}" for k, v in d.items() if not isinstance(v, dict)]407 tabs = []408 for k, v in d.items():409 if isinstance(v, dict):410 tabs += ["", f"[{k}]"] + [f"{kk} = {_toml_value(vv)}" for kk, vv in v.items()]411 return "\n".join(head + scal + tabs) + "\n"412413414def load_policy(path: Path) -> dict:415 with open(path, "rb") as fh:416 return tomllib.load(fh)417418419def repo_policy_view(policy: dict) -> dict:420 """The subset written into the repository itself (no audit evidence, no review notes)."""421 keep = ("schema", "engine", "slug", "project", "category", "status", "repository_url", "project_url",422 "version", "contact", "classification", "distribution", "copyright", "license", "exclude", "variant")423 out = {k: policy[k] for k in keep if k in policy}424 out["license"] = {k: v for k, v in policy["license"].items() if k in ("name", "spdx", "file")}425 out["copyright"] = {k: v for k, v in policy["copyright"].items() if k != "basis"}426 return out427428429# --------------------------------------------------------------------------- eligibility430431PUBLIC_DIRS = {"public", "static", "assets", "www", "wwwroot", "htdocs"}432433434def path_exclusion(path: str, syn_role: str, cfg: dict, policy: dict) -> str:435 ex = cfg["exclusions"]436 parts = path.split("/")437 dirs, name = [p for p in parts[:-1]], parts[-1]438 low = [d.lower() for d in dirs]439 for pat in policy.get("exclude", {}).get("paths", []):440 if fnmatch.fnmatch(path, pat) or fnmatch.fnmatch(path, pat.rstrip("/") + "/*"):441 return "excluded-by-repository-policy"442 for group, reason in (("third_party", "third-party-directory"), ("generated", "generated-or-build-directory"),443 ("checksummed", "checksummed-or-fixture-directory"),444 ("anonymous", "anonymous-submission-material")):445 hit = set(ex["dirs"][group])446 if any(d in hit or dd in hit for d, dd in zip(dirs, low)):447 return reason448 if any(d.endswith((".xcodeproj", ".xcworkspace", ".xcassets", ".lproj", ".framework", ".bundle", ".docc")) for d in dirs):449 return "apple-tool-managed-bundle"450 if syn_role in ("tex", "bib") and any(d in set(ex["dirs"]["research_output"]) for d in low):451 return "research-output-directory (computed tables / figures are never edited)"452 if name in ex["files"]["names"] or any(name.endswith(s) for s in ex["files"]["suffixes"]):453 return "generated-or-lock-file"454 if re.search(r"(anonym|blind)", name, re.I):455 return "anonymous-submission-material"456 return ""457458459def choose_variant(path: str, syn: core.Syntax, policy: dict) -> str:460 ext = path.rsplit(".", 1)[-1].lower() if "." in path else ""461 override = policy.get("variant", {}).get(ext)462 if override:463 return override464 cat = policy["category"]465 if syn.role == "tex":466 return "SPB-LATEX"467 if syn.role == "bib":468 return "SPB-BIB"469 if syn.role in ("config", "style") or syn.style == "html":470 return "SPB-MINIMAL"471 if ext in core.JS_EXT | {"css", "scss"} and PUBLIC_DIRS & set(path.lower().split("/")[:-1]):472 return "SPB-MINIMAL" # served to browsers as-is: compact public attribution only473 if cat in ("research", "teaching"):474 return "SPB-RESEARCH"475 if ext in ("swift", "m", "mm", "h") and syn.prefix == "//":476 return "SPB-APPLE"477 if cat in ("maclustr", "infra") or syn.role == "script":478 return "SPB-INFRA"479 if ext in core.JS_EXT:480 return "SPB-WEB"481 return "SPB-FULL"482483484def module_name(path: str) -> str:485 parts = path.split("/")486 for anchor in ("Sources", "Tests", "src", "packages", "apps", "lib"):487 if anchor in parts[:-1]:488 k = parts.index(anchor)489 if k + 1 < len(parts) - 1:490 return parts[k + 1]491 return parts[0] if len(parts) > 1 else ""492493494def header_values(path: str, policy: dict, cfg: dict, variant: str, dates: tuple[str, str] | None) -> dict:495 a, c = cfg["identity"]["author"], cfg["identity"]["contacts"]496 lic, cp = policy["license"], policy["copyright"]497 return {498 "SUBTITLE": cfg["identity"]["subtitle"][variant],499 "PROJECT_NAME": policy["project"], "FILE_PATH": path, "FILE_DESCRIPTION": "",500 "MODULE_NAME": module_name(path), "REPOSITORY_URL": policy.get("repository_url", ""),501 "PROJECT_URL": policy.get("project_url", ""), "PROJECT_VERSION": policy.get("version", ""),502 "CREATION_DATE": dates[0] if dates else "", "MODIFICATION_DATE": dates[1] if dates else "",503 "AUTHOR": a["name"], "POSITION": a["position"], "INSTITUTION": a["institution"],504 "DEPARTMENT": a["department"], "ORGANIZATION": a["organization"], "WEBSITE": a["website"], "GIT": a["git"],505 "C_GENERAL": c["general"], "C_PROFESSIONAL": c["professional"], "C_DIRECT": c["direct"],506 "C_RESEARCH": c["research"], "C_DEVELOPMENT": c["development"], "C_SUPPORT": c["support"],507 "C_SECURITY": c["security"], "C_NOTIFICATIONS": c["notifications"],508 "PRIMARY_PROJECT_CONTACT": policy["contact"],509 "COPYRIGHT_LINE": cp["line"], "COPYRIGHT_HOLDER": cp["holder"], "COPYRIGHT_ONELINE": cp["oneline"],510 "CLASSIFICATION": policy["classification"], "DISTRIBUTION_POLICY": policy["distribution"],511 "SPDX": lic.get("spdx", ""), "LICENSE": lic["name"], "LICENSE_FILE": lic.get("file", ""),512 }513514515ANON_NAME = re.compile(r"(anon|blind)", re.I)516ANON_TEXT = re.compile(r"identity withheld|withheld for review|anonymi[sz]ed for review", re.I)517518519def has_anonymous_variant(repo: Path, files: list[str]) -> bool:520 """True if the repository builds an anonymized manuscript (double-blind review).521 Its LaTeX sources are shared with the signed version, so none of them may carry identity."""522 for f in files:523 if f.endswith((".tex", ".sty", ".cls")):524 if ANON_NAME.search(f.rsplit("/", 1)[-1]):525 return True526 try:527 if ANON_TEXT.search((repo / f).read_text(encoding="utf-8", errors="replace")):528 return True529 except OSError:530 pass531 return False532533534def tex_listing_targets(repo: Path, files: list[str]) -> set[str]:535 """LaTeX files typeset verbatim by another file: a header would be printed in the PDF."""536 hits: set[str] = set()537 rx = re.compile(r"\\(?:lstinputlisting|verbatiminput|inputminted|VerbatimInput|pgfplotstableread|pgfplotstabletypeset)"538 r"(?:\[[^\]]*\])?(?:\{[^}]*\})?\{([^}]+)\}")539 for f in files:540 if f.endswith((".tex", ".sty", ".cls")):541 try:542 for m in rx.finditer((repo / f).read_text(encoding="utf-8", errors="replace")):543 hits.add(m.group(1).rsplit("/", 1)[-1])544 except OSError:545 pass546 return hits547