Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SP Boucher Development Standard7# File : payload/standards/lib/spstd/header.py8# Module : Engine9# Repository : https://git.spboucher.ai/sp-development-standard10# Project Website : https://git.spboucher.ai/sp-development-standard11# Created : 2026-12-0212# Last Modified : 2026-12-0213#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""SP Boucher Source Header Engine — local, deterministic, idempotent (Python 3.8+, stdlib only)."""42import argparse43import ast44import datetime45import json46import os47import re48import sys4950from . import common as C5152END_MARK = "END OF SP BOUCHER SOURCE HEADER"53TITLE_MARK = "SP BOUCHER |"54RULE = "=" * 7755RULE_RE = re.compile(r"={40,}")56V2_LABELS = ["Project", "File", "Module", "Repository", "Project Website", "Created", "Last Modified", "Author",57 "Position", "Institution", "Organization", "Website", "Git", "Preferred Contact", "Development",58 "Support", "Security/Admin", "License"]59FIELD_RE = re.compile(r"^(Project Website|Last Modified|Preferred Contact|Security/Admin|[A-Z][A-Za-z ]{2,17}?)\s*:\s?(.*)$")60NOT_SPECIFIED = "Not specified"61NO_LICENSE = "None specified (no license file in this repository)"6263PREAMBLE_RES = [re.compile(p, re.I) for p in (64 r"^<\?php\s*$", r"^<\?xml\b", r"^<!DOCTYPE\b", r"^#version\b", r"^// swift-tools-version", r"^#\s*(syntax|escape|check)\s*=",65 r"^@charset\b", r"^%\s*!TEX", r"^%YAML\b", r"^#.*-\*-.*-\*-", r"^#\s*vim:", r"^#\s*frozen_string_literal",66 r"^//go:build\b", r"^// \+build\b", r"^(//|#|--|%|;|/\*)\s*SPDX-License-Identifier", r"^#\s*typed:", r"^#!(?!\[)",67 r"^[ \t\f]*#.*?coding[:=]\s*[-\w.]+")]686970# ----------------------------------------------------------------------------- language71def language_of(path, text):72 cfg = C.load_json("source-header/languages.json")73 name = os.path.basename(path)74 ext = os.path.splitext(name)[1]75 hit = cfg["filenames"].get(name)76 if not hit and (name.startswith("Dockerfile.") or name.startswith("Makefile.")):77 hit = cfg["filenames"][name.split(".")[0]]78 if not hit:79 hit = cfg["extensions"].get(ext) or cfg["extensions"].get(ext.lower())80 if not hit and not ext and text.startswith("#!"):81 first = text.split("\n", 1)[0]82 for key, val in cfg["shebangs"].items():83 if re.search(r"[/ ]%s[0-9.]*\b" % re.escape(key), first):84 hit = val85 break86 if not hit:87 return None88 lang, style = hit89 if style == "auto-m":90 if re.search(r"^\s*(#import|@interface|@implementation|@protocol|@import|#include)\b", text, re.M):91 lang, style = "Objective-C", "block"92 else:93 lang, style = "MATLAB", "percent"94 return lang, style959697# ----------------------------------------------------------------------------- eligibility98def classify(path, root=None, automatic=False):99 """Decide whether a file may carry the header. Returns dict(eligible, reason, language, style, text, ...)."""100 res = {"path": path, "eligible": False, "reason": "", "language": None, "style": None}101 ex = C.load_json("source-header/exclusions.json")102 name = os.path.basename(path)103 if os.path.islink(path) or not os.path.isfile(path):104 res["reason"] = "not a regular file"105 return res106 root = root or C.project_root(path)107 res["root"] = root108 rel = C.rel_to(path, root) if root else name109 res["rel"] = rel110 parts = rel.split("/")[:-1]111 for group, names in ex["dirs"].items():112 for part in parts:113 if part in names:114 res["reason"] = "excluded directory (%s: %s)" % (group, part)115 return res116 for part in parts:117 if any(part.endswith(s) for s in ex.get("dir_suffixes", [])):118 res["reason"] = "excluded directory (%s)" % part119 return res120 ext = os.path.splitext(name)[1].lower()121 if name in ex["files"]["names"] or any(name.endswith(s) for s in ex["files"]["suffixes"]):122 res["reason"] = "excluded file (lock, generated or tool-owned)"123 return res124 if ext in ex["files"]["never_extensions"] or name.startswith(".env"):125 res["reason"] = "format never stamped (%s)" % (ext or name)126 return res127 if root:128 pol = C.repo_policy(root)129 pats = list((pol["v2"] or {}).get("exclude", [])) + list(((pol["v1"] or {}).get("exclude") or {}).get("paths", []))130 if C.glob_match(rel, pats):131 res["reason"] = "excluded by the repository policy"132 return res133 try:134 size = os.path.getsize(path)135 with open(path, "rb") as f:136 raw = f.read()137 except OSError as e:138 res["reason"] = "unreadable (%s)" % e139 return res140 if size > ex["files"]["max_bytes"]:141 res["reason"] = "file too large"142 return res143 if b"\0" in raw[:8192]:144 res["reason"] = "binary file"145 return res146 bom = raw.startswith(b"\xef\xbb\xbf")147 try:148 text = raw[3:].decode("utf-8") if bom else raw.decode("utf-8")149 except UnicodeDecodeError:150 res["reason"] = "not UTF-8 (encoding preserved, file untouched)"151 return res152 res.update(raw=raw, bom=bom, text=text)153 hit = language_of(path, text)154 if not hit:155 res["reason"] = "unsupported language or format"156 return res157 res["language"], res["style"] = hit158 lines = text.split("\n")159 if lines and len(text) / max(1, len(lines)) > ex["files"]["max_avg_line"]:160 res["reason"] = "minified or machine-written (very long lines)"161 return res162 found = find_header(lines)163 res["header"] = found164 if not found:165 head = text[:2048]166 for m in ex["markers"]["generated"]:167 if m in head:168 res["reason"] = "generated file (%r)" % m169 return res170 own = C.identity()["own_names"]171 for line in leading_comment(lines):172 if any(m in line for m in ex["markers"]["foreign"]) and not any(o.lower() in line.lower() for o in own):173 if re.search(r"copyright|©|\(c\)\s*(19|20)\d\d|licen[cs]e|permission is hereby|redistribution", line, re.I):174 res["reason"] = "third-party notice present (%s)" % line.strip()[:60]175 res["third_party"] = True176 return res177 if res["language"] == "PHP":178 body = [l for l in lines if not l.startswith("#!")]179 if not body or not re.match(r"^<\?php\s*$", body[0]):180 res["reason"] = "PHP file does not start with a bare <?php line"181 return res182 if res["style"] == "html" and not found:183 first = next((l.strip() for l in lines if l.strip()), "")184 if first.startswith(("{%", "{{", "<%", "@extends", "---", "{#")):185 res["reason"] = "template directive must remain first"186 return res187 if automatic and ext in C.load_json("source-header/languages.json")["manual_only_extensions"]:188 res["reason"] = "manual-only format (run `sp-header apply` explicitly when attribution is verified)"189 res["manual"] = True190 return res191 res["eligible"] = True192 return res193194195def leading_comment(lines):196 out = []197 for l in lines[:60]:198 s = l.strip()199 if not s:200 if out:201 continue202 continue203 if s.startswith(("#", "//", "/*", "*", "--", "%", ";", "<!--", '"""', "'''")) or (out and out[-1].lstrip().startswith(("/*", "*", "<!--")) and "*/" not in out[-1] and "-->" not in out[-1]):204 out.append(l)205 else:206 break207 return out208209210# ----------------------------------------------------------------------------- metadata211def _readme_title(root):212 for n in ("README.md", "Readme.md", "readme.md", "README"):213 p = os.path.join(root, n)214 if os.path.isfile(p):215 try:216 with open(p, encoding="utf-8", errors="replace") as f:217 head = f.read(6000)218 except OSError:219 return ""220 m = re.search(r"<h1[^>]*>(.*?)</h1>", head, re.S | re.I) or re.search(r"^#\s+(.+)$", head, re.M)221 if m:222 t = re.sub(r"<[^>]+>|!\[[^\]]*\]\([^)]*\)|\[([^\]]*)\]\([^)]*\)", r"\1", m.group(1))223 t = re.sub(r"[`*_]|:[a-z_]+:", "", t)224 t = re.sub(r"\s+", " ", t).strip(" -–—|")225 if 1 < len(t) <= 60 and re.search(r"[A-Za-z]", t):226 return t227 return ""228229230def _manifest(root):231 """(name, homepage, license) from the project manifests, whichever exist."""232 name = home = lic = ""233234 def read(n):235 try:236 with open(os.path.join(root, n), encoding="utf-8", errors="replace") as f:237 return f.read(200000)238 except OSError:239 return ""240 t = read("package.json")241 if t:242 try:243 j = json.loads(t)244 name, home = j.get("name", "") or "", j.get("homepage", "") or ""245 lic = j.get("license", "") if isinstance(j.get("license"), str) else ""246 except ValueError:247 pass248 for fn, sect in (("Cargo.toml", "package"), ("pyproject.toml", "project")):249 t = read(fn)250 if t:251 m = re.search(r"^\[%s\](.*?)(^\[|\Z)" % sect, t, re.M | re.S)252 body = m.group(1) if m else ""253 n = re.search(r'^name\s*=\s*"([^"]+)"', body, re.M)254 name = name or (n.group(1) if n else "")255 h = re.search(r'^(?:homepage|Homepage)\s*=\s*"([^"]+)"', t, re.M)256 home = home or (h.group(1) if h else "")257 li = re.search(r'^license\s*=\s*"([^"]+)"', body, re.M) or re.search(r'^license\s*=\s*\{\s*text\s*=\s*"([^"]+)"', body, re.M)258 lic = lic or (li.group(1) if li else "")259 t = read("Package.swift")260 if t and not name:261 m = re.search(r'Package\(\s*name:\s*"([^"]+)"', t)262 name = m.group(1) if m else ""263 for fn in ("settings.gradle", "settings.gradle.kts"):264 t = read(fn)265 if t and not name:266 m = re.search(r'rootProject\.name\s*=\s*["\']([^"\']+)', t)267 name = m.group(1) if m else ""268 if not name:269 try:270 xs = [n for n in os.listdir(root) if n.endswith(".xcodeproj")]271 except OSError:272 xs = []273 if len(xs) == 1:274 name = xs[0][:-len(".xcodeproj")]275 if home and not re.match(r"https?://", home):276 home = ""277 return name, home, lic278279280LICENSE_SIGNATURES = [281 ("AGPL-3.0", r"GNU AFFERO GENERAL PUBLIC LICENSE\s+Version 3"), ("LGPL-3.0", r"GNU LESSER GENERAL PUBLIC LICENSE\s+Version 3"),282 ("LGPL-2.1", r"GNU LESSER GENERAL PUBLIC LICENSE\s+Version 2\.1"), ("GPL-3.0", r"GNU GENERAL PUBLIC LICENSE\s+Version 3"),283 ("GPL-2.0", r"GNU GENERAL PUBLIC LICENSE\s+Version 2"), ("Apache-2.0", r"Apache License\s+Version 2\.0"),284 ("MPL-2.0", r"Mozilla Public License,? [Vv]ersion 2\.0"), ("MIT", r"Permission is hereby granted, free of charge"),285 ("BSD-3-Clause", r"Redistribution and use in source and binary forms.*Neither the name"),286 ("BSD-2-Clause", r"Redistribution and use in source and binary forms"),287 ("ISC", r"Permission to use, copy, modify, and/or distribute this software"), ("Unlicense", r"This is free and unencumbered software"),288 ("CC-BY-4.0", r"Creative Commons Attribution 4\.0"), ("CC0-1.0", r"CC0 1\.0 Universal"),289 ("Proprietary", r"(?i)proprietary|all rights reserved"),290]291292293def detect_license(path, root):294 """Nearest LICENSE/COPYING from the file's directory up to the project root, then manifest metadata."""295 d = os.path.dirname(os.path.realpath(path)) if not os.path.isdir(path) else os.path.realpath(path)296 root_r = os.path.realpath(root) if root else d297 while True:298 key = ("lic", d)299 if key not in C._cache:300 found = ""301 try:302 names = sorted(os.listdir(d))303 except OSError:304 names = []305 for n in names:306 if re.match(r"^(LICEN[CS]E|COPYING|UNLICENSE)(\.(md|txt|rst))?$", n, re.I) and os.path.isfile(os.path.join(d, n)):307 try:308 with open(os.path.join(d, n), encoding="utf-8", errors="replace") as f:309 t = f.read(20000)310 except OSError:311 continue312 m = re.search(r"SPDX-License-Identifier:\s*([\w.+-]+)", t)313 if m:314 found = m.group(1)315 else:316 tt = re.sub(r"\s+", " ", t)317 for spdx, sig in LICENSE_SIGNATURES:318 if re.search(sig.replace(r"\s+", " "), tt, re.S):319 found = spdx320 if spdx.startswith(("GPL", "AGPL", "LGPL")):321 found += "-or-later" if re.search(r"or \(at your option\) any later version", tt) else "-only"322 break323 else:324 found = "See %s" % n325 break326 C._cache[key] = found327 if C._cache[key]:328 return C._cache[key]329 if d == root_r or os.path.dirname(d) == d or not d.startswith(root_r):330 break331 d = os.path.dirname(d)332 if root:333 v1 = C.repo_policy(root)["v1"] or {}334 declared = (v1.get("license") or {}).get("spdx") or ""335 lic = declared or _manifest(root)[2]336 if lic and lic.upper() not in ("UNLICENSED", "NONE"):337 return lic338 if lic.upper() == "UNLICENSED":339 return "Proprietary"340 return NO_LICENSE341342343MODULE_KEYWORDS = [344 (r"^(tests?|__tests__|spec|specs|uitests|.*tests)$", "Tests"), (r"^(scripts?|bin|tools?|tooling)$", "Scripts"),345 (r"^(api|routes?|endpoints?|handlers?)$", "API"), (r"^(auth|authentication|identity|login)$", "Authentication"),346 (r"^(net|network|networking|http|transport)$", "Networking"), (r"^(db|database|sql|persistence|prisma|schema)$", "Database"),347 (r"^(security|crypto|cryptography)$", "Security"), (r"^(inference|llm|mlx)$", "Inference"),348 (r"^(distributed|cluster|fabric)$", "Distributed Computing"), (r"^(analytics|metrics|telemetry|stats)$", "Analytics"),349 (r"^(ui|components?|widgets?|screens?|pages?|styles?|theme)$", "User Interface"), (r"^(render|rendering|renderer|graphics)$", "Rendering"),350 (r"^(metal|shaders?)$", "Metal"), (r"^(storage|store|cache|files)$", "Storage"), (r"^(services?)$", "Services"),351 (r"^(models?|entities|domain)$", "Models"), (r"^(views?)$", "Views"), (r"^(controllers?)$", "Controllers"),352 (r"^(core|kernel|engine)$", "Core"), (r"^(utils?|utilities|helpers?|common|shared|support)$", "Utilities"),353 (r"^(config|configs|configuration|settings)$", "Configuration"), (r"^(deploy|deployment|infra|infrastructure|ops|docker|k8s)$", "Deployment"),354 (r"^(hooks?)$", "Hooks"), (r"^(docs?|documentation)$", "Documentation"), (r"^(cli|cmd|commands?)$", "CLI"),355 (r"^(\.github|ci|workflows)$", "CI"), (r"^(middleware)$", "Middleware"), (r"^(agents?)$", "Agents"),356]357CONTAINERS = {"src", "source", "sources", "lib", "libs", "app", "apps", "backend", "frontend", "server", "client", "internal",358 "pkg", "packages", "main", "java", "kotlin", "python", "web", "mobile", "ios", "macos", "android", "payload", "standards"}359360361def detect_module(rel):362 parts = rel.split("/")363 dirs, name = parts[:-1], parts[-1]364 for d in dirs:365 if re.match(MODULE_KEYWORDS[0][0], d, re.I):366 return "Tests"367 meaningful = [d for d in dirs if d.lower() not in CONTAINERS]368 cand = meaningful[0] if meaningful else (dirs[-1] if dirs else "")369 if cand:370 for pat, label in MODULE_KEYWORDS:371 if re.match(pat, cand, re.I):372 return label373 words = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", cand.lstrip(".")).replace("_", " ").replace("-", " ").split()374 return " ".join(w if w.isupper() else w[:1].upper() + w[1:] for w in words) or "Core"375 low = name.lower()376 if re.match(r"^(test_|.*[._-]test\.|.*\.spec\.)", low):377 return "Tests"378 if low.startswith(("dockerfile", "makefile")) or low.endswith((".mk", ".cmake", ".gradle", ".gradle.kts")) or low in ("package.swift", "cmakelists.txt", "justfile"):379 return "Build"380 if low.endswith((".yaml", ".yml", ".toml")) or ".config." in low or low.startswith("."):381 return "Configuration"382 if low.endswith((".sh", ".bash", ".zsh", ".fish", ".ps1")):383 return "Scripts"384 return "Core"385386387def project_meta(root):388 key = ("meta", root)389 if key in C._cache:390 return C._cache[key]391 pol = C.repo_policy(root)392 v1, v2 = pol["v1"] or {}, pol["v2"] or {}393 mname, mhome, _ = _manifest(root)394 o = C.origin_info(root)395 project = v2.get("project") or v1.get("project") or _readme_title(root) or mname or o["slug"] or os.path.basename(root)396 website = v2.get("website") or v1.get("project_url") or mhome or NOT_SPECIFIED397 repository = v2.get("repository") or o["web"] or v1.get("repository_url") or NOT_SPECIFIED398 meta = {"project": project.strip(), "website": website.strip(), "repository": C.sanitize_url(repository)}399 C._cache[key] = meta400 return meta401402403def git_dates(path, root):404 """(first-add date following renames, last-commit date, is_dirty_or_untracked)."""405 if not root or not C.git_root(root):406 return "", "", True407 rel = C.rel_to(path, root)408 adds = C.git_out(["log", "--follow", "--diff-filter=A", "--format=%ad", "--date=short", "--", rel], root, 20).split()409 last = C.git_out(["log", "-1", "--format=%ad", "--date=short", "--", rel], root, 20)410 dirty = bool(C.git_out(["status", "--porcelain", "--", rel], root, 20)) or not last411 return (adds[-1] if adds else ""), last, dirty412413414def file_dates(path, root, is_new=False):415 first, last, dirty = git_dates(path, root)416 st = os.stat(path)417 mtime = datetime.date.fromtimestamp(st.st_mtime).isoformat()418 if first:419 created = first420 elif is_new:421 created = C.today()422 elif hasattr(st, "st_birthtime"):423 created = datetime.date.fromtimestamp(st.st_birthtime).isoformat()424 else:425 created = "Unknown"426 modified = C.today() if is_new else (last if (last and not dirty) else mtime)427 return created, modified428429430def years(created, modified):431 y1 = created[:4] if re.match(r"^\d{4}", created or "") else ""432 y2 = modified[:4] if re.match(r"^\d{4}", modified or "") else ""433 if y1 and y2 and y1 < y2:434 return "%s-%s" % (y1, y2)435 return y1 or y2 or str(datetime.date.today().year)436437438# ----------------------------------------------------------------------------- rendering / parsing439def body_lines(f):440 idn = C.identity()441 i, c, b = idn["identity"], idn["contacts"], idn["branding"]442 return [443 RULE, " " * 17 + b["title"], " " * 12 + b["subtitle"], RULE, "",444 "Project : " + f["project"], "File : " + f["file"], "Module : " + f["module"],445 "Repository : " + f["repository"], "Project Website : " + f["website"], "Created : " + f["created"],446 "Last Modified : " + f["modified"], "",447 "Author : " + i["author"], "Position : " + i["position"], "Institution : " + i["institution"],448 "Organization : " + i["organization"], "Website : " + i["website"], "Git : " + i["git"], "",449 "Preferred Contact: " + c["preferred"], "Development : " + c["development"], "Support : " + c["support"],450 "Security/Admin : " + c["security"], "",451 "Copyright (c) " + f["years"], i["author"],452 "All rights reserved where applicable. This file is governed by the",453 "applicable project license, copyright notices and relevant law.",454 "Existing third-party rights and notices remain unaffected.", "",455 "License : " + f["license"], "",456 "Do not embed credentials, private keys, access tokens,",457 "certificates or confidential personal information.", "",458 RULE, END_MARK, RULE,459 ]460461462def render(fields, style):463 st = C.load_json("source-header/languages.json")["styles"][style]464 out = []465 if st.get("open"):466 out.append(st["open"])467 for l in body_lines(fields):468 out.append((st["prefix"] + l).rstrip() if l else st["prefix"].rstrip())469 if st.get("close"):470 out.append(st["close"])471 return out472473474def find_header(lines):475 title = None476 for i, l in enumerate(lines[:40]):477 if TITLE_MARK in l:478 title = i479 break480 if title is None:481 return None482 endm = None483 for j in range(title, min(len(lines), title + 170)):484 if END_MARK in lines[j]:485 endm = j486 break487 if endm is None:488 return None489 start = title490 if title > 0 and RULE_RE.search(lines[title - 1]):491 start = title - 1492 if start > 0 and lines[start - 1].strip() in ("/**", "/*", "<!--"):493 start -= 1494 end = endm495 if end + 1 < len(lines) and RULE_RE.search(lines[end + 1]):496 end += 1497 if end + 1 < len(lines) and lines[end + 1].strip() in ("*/", "-->"):498 end += 1499 if start > 8:500 return None501 return start, end502503504def parse_fields(block):505 f, labels = {}, []506 for l in block:507 s = re.sub(r"^\s*(/\*\*?|\*/|\*|//|#|--|%|;|<!--|-->)?\s?", "", l.rstrip()).strip()508 m = FIELD_RE.match(s)509 if m:510 labels.append(m.group(1).strip())511 f.setdefault(m.group(1).strip(), m.group(2).strip())512 m = re.match(r"^Copyright \(c\)\s*(.+)$", s)513 if m:514 f.setdefault("years", m.group(1).strip())515 return f, labels516517518def fields_from_parsed(p):519 return {"project": p.get("Project", ""), "file": p.get("File", ""), "module": p.get("Module", ""),520 "repository": p.get("Repository", ""), "website": p.get("Project Website", ""), "created": p.get("Created", ""),521 "modified": p.get("Last Modified", ""), "license": p.get("License", ""), "years": p.get("years", "")}522523524def header_kind(lines, found, style):525 """v2 (exact), v2-drift (same fields, formatting differs) or legacy (an earlier SP Boucher variant)."""526 block = lines[found[0]:found[1] + 1]527 parsed, labels = parse_fields(block)528 if [l.rstrip() for l in block] == render(fields_from_parsed(parsed), style):529 return "v2", parsed530 if set(V2_LABELS) <= set(labels) and not (set(labels) - set(V2_LABELS)):531 return "v2-drift", parsed532 return "legacy", parsed533534535def split_preamble(lines):536 n = 0537 while n < min(len(lines), 4) and any(r.search(lines[n]) for r in PREAMBLE_RES):538 if n > 0 and re.match(r"^#!(?!\[)", lines[n]):539 break540 n += 1541 return n542543544# ----------------------------------------------------------------------------- core operation545def expected_fields(path, root, parsed=None, touch=False, is_new=False):546 meta = project_meta(root) if root else {"project": os.path.basename(os.path.dirname(os.path.abspath(path))),547 "website": NOT_SPECIFIED, "repository": NOT_SPECIFIED}548 rel = C.rel_to(path, root) if root else os.path.basename(path)549 old = fields_from_parsed(parsed) if parsed else {}550 created = old.get("created") or ""551 modified = old.get("modified") or ""552 if not created or (not modified and not touch):553 c2, m2 = file_dates(path, root, is_new)554 created = created or c2555 modified = modified or m2556 if touch:557 modified = C.today()558 module = detect_module(rel)559 if root: # .sp-standard.json: {"modules": {"path/prefix": "Name"}}560 best = ""561 for prefix, label in ((C.repo_policy(root)["v2"] or {}).get("modules") or {}).items():562 pre = prefix.strip("/")563 if (rel == pre or rel.startswith(pre + "/")) and len(pre) >= len(best):564 best, module = pre, label565 return {"project": meta["project"], "file": rel, "module": module, "repository": meta["repository"],566 "website": meta["website"], "created": created, "modified": modified, "license": detect_license(path, root),567 "years": years(created, modified)}568569570def validate_syntax(path, language, old_text, new_text):571 """Cheap proof that inserting the comment block did not change the program. Returns error string or ''."""572 if language in ("Python", "Python stub"):573 try:574 a = ast.dump(ast.parse(old_text))575 except SyntaxError:576 return "" # was already invalid: nothing to compare577 try:578 if ast.dump(ast.parse(new_text)) != a:579 return "Python AST changed"580 except SyntaxError as e:581 return "Python syntax error after header (%s)" % e582 elif language in ("Shell", "Bash", "Zsh"):583 sh = "zsh" if language == "Zsh" else "bash"584 rc0, _, _ = C.run([sh, "-n"], stdin=old_text.encode("utf-8"), timeout=10)585 rc1, _, err = C.run([sh, "-n"], stdin=new_text.encode("utf-8"), timeout=10)586 if rc0 == 0 and rc1 not in (0, 124, 127):587 return "%s -n failed after header (%s)" % (sh, err.strip()[:80])588 return ""589590591def process(path, action="ensure", dry_run=False, is_new=False, automatic=False, upgrade=False, force_owner=False):592 """action: check | ensure | touch. Returns dict(path, status, reason).593594 status: ok | legacy | added | updated | would-add | would-update | missing | drift | skipped | error"""595 path = os.path.abspath(path)596 root = C.project_root(path)597 info = classify(path, root, automatic=automatic)598 out = {"path": path, "rel": info.get("rel", os.path.basename(path)), "language": info.get("language"), "status": "skipped",599 "reason": info["reason"]}600 if not info["eligible"]:601 return out602 own, why = C.ownership(root)603 out["ownership"] = own604 if own in ("foreign", "restricted") and not force_owner:605 out["reason"] = "ownership %s: %s" % (own, why)606 return out607 if automatic and own != "owned":608 out["status"], out["reason"] = "deferred", "ownership not established yet: %s" % why609 return out610 text, lines, style = info["text"], info["text"].split("\n"), info["style"]611 eol = "\r\n" if lines and lines[0].endswith("\r") else "\n"612 if eol == "\r\n":613 lines = [l[:-1] if l.endswith("\r") else l for l in lines]614 found = info["header"]615 if found:616 kind, parsed = header_kind(lines, found, style)617 if kind == "legacy" and not upgrade:618 out["status"], out["reason"] = "legacy", "earlier SP Boucher header variant kept as is (use --upgrade to convert)"619 return out620 keep = parsed if kind != "legacy" else {"Created": parsed.get("Created", "")}621 fields = expected_fields(path, root, keep, touch=(action == "touch"))622 new_block = render(fields, style)623 if [l.rstrip() for l in lines[found[0]:found[1] + 1]] == new_block:624 out["status"], out["reason"] = "ok", ""625 return out626 if action == "check":627 out["status"], out["reason"] = "drift", "header metadata out of date"628 return out629 new_lines = lines[:found[0]] + new_block + lines[found[1] + 1:]630 verb = "update"631 else:632 if action == "check":633 out["status"], out["reason"] = "missing", "no SP Boucher header"634 return out635 fields = expected_fields(path, root, None, touch=(action == "touch"), is_new=is_new)636 n = split_preamble(lines)637 block = render(fields, style)638 pre = lines[:n]639 if pre and re.match(r"^//(go:build| \+build)", pre[-1]):640 pre = pre + [""]641 rest = lines[n:]642 if rest and rest[0].strip() == "" and len(rest) > 1:643 rest = rest[1:]644 new_lines = pre + block + ([""] if rest != [""] and rest else []) + (rest if rest else [""])645 verb = "add"646 new_text = "\n".join(new_lines)647 err = validate_syntax(path, info["language"], text if eol == "\n" else text.replace("\r\n", "\n"), new_text)648 if err:649 out["status"], out["reason"] = "error", err650 return out651 if dry_run:652 out["status"], out["reason"] = "would-" + verb, ""653 return out654 data = (new_text.replace("\n", "\r\n") if eol == "\r\n" else new_text).encode("utf-8")655 if info["bom"]:656 data = b"\xef\xbb\xbf" + data657 try:658 with open(path, "r+b") as f: # in place: mode, owner and inode preserved659 f.seek(0)660 f.write(data)661 f.truncate()662 except OSError as e:663 out["status"], out["reason"] = "error", str(e)664 return out665 out["status"], out["reason"] = ("added" if verb == "add" else "updated"), ""666 return out667668669def strip_header(text):670 """Text without its SP Boucher header (used by tests to prove the change is comment-only)."""671 lines = text.split("\n")672 f = find_header(lines)673 if not f:674 return text675 rest = lines[f[1] + 1:]676 if rest and rest[0].strip() == "":677 rest = rest[1:]678 return "\n".join(lines[:f[0]] + rest)679680681# ----------------------------------------------------------------------------- directory operations682def scan(directory, action, dry_run=False, upgrade=False, force_owner=False):683 results = []684 for p in sorted(C.list_files(directory)):685 results.append(process(p, action=action, dry_run=dry_run, upgrade=upgrade, force_owner=force_owner))686 return results687688689def summarize(results):690 counts = {}691 for r in results:692 counts[r["status"]] = counts.get(r["status"], 0) + 1693 return counts694695696def print_results(results, show=("missing", "drift", "error", "added", "updated", "would-add", "would-update"), verbose=False):697 for r in results:698 if verbose or r["status"] in show:699 print("%-13s %s%s" % (r["status"], r["rel"], (" — " + r["reason"]) if r["reason"] else ""))700701702def markdown_report(directory, results):703 root = C.project_root(directory) or directory704 meta = project_meta(root)705 own, why = C.ownership(root)706 c = summarize(results)707 eligible = sum(c.get(k, 0) for k in ("ok", "legacy", "missing", "drift", "error"))708 compliant = c.get("ok", 0) + c.get("legacy", 0)709 lines = ["# SP Boucher source header report", "",710 "- Standard version: %s" % C.version(), "- Date: %s" % C.today(), "- Project: %s" % meta["project"],711 "- Root: `%s`" % os.path.basename(root), "- Repository: %s" % meta["repository"],712 "- Ownership: %s (%s)" % (own, why), "- License: %s" % detect_license(root, root), "",713 "| Status | Files |", "|---|---|"]714 for k in sorted(c):715 lines.append("| %s | %d |" % (k, c[k]))716 lines += ["", "Eligible files: %d — compliant: %d (%s)" % (eligible, compliant, ("%.1f %%" % (100.0 * compliant / eligible)) if eligible else "n/a"), ""]717 bad = [r for r in results if r["status"] in ("missing", "drift", "error")]718 if bad:719 lines += ["## Files needing attention", ""] + ["- `%s` — %s: %s" % (r["rel"], r["status"], r["reason"]) for r in bad] + [""]720 reasons = {}721 for r in results:722 if r["status"] == "skipped":723 k = re.sub(r"\(.*", "", r["reason"]).strip()724 reasons[k] = reasons.get(k, 0) + 1725 if reasons:726 lines += ["## Skipped, by reason", ""] + ["- %s: %d" % kv for kv in sorted(reasons.items(), key=lambda kv: -kv[1])] + [""]727 return "\n".join(lines)728729730def doctor():731 ok = True732 print("sp-header %s — standards directory: %s" % (C.version(), C.STD_DIR))733 for rel in ("identity.json", "source-header/languages.json", "source-header/exclusions.json", "source-header/TEMPLATE.md",734 "source-header/POLICY.md"):735 present = os.path.isfile(os.path.join(C.STD_DIR, rel))736 ok = ok and present737 print(" [%s] %s" % ("ok" if present else "FAIL", rel))738 import tempfile739 d = tempfile.mkdtemp(prefix="sp-header-doctor-")740 try:741 p = os.path.join(d, "probe.py")742 with open(p, "w") as f:743 f.write("#!/usr/bin/env python3\nprint('x')\n")744 os.chmod(p, 0o755)745 r1 = process(p, "ensure", is_new=True)746 r2 = process(p, "ensure")747 with open(p) as f:748 t = f.read()749 good = (r1["status"] == "added" and r2["status"] == "ok" and t.startswith("#!/usr/bin/env python3\n# ====")750 and strip_header(t) == "#!/usr/bin/env python3\nprint('x')\n" and os.stat(p).st_mode & 0o777 == 0o755)751 ok = ok and good752 print(" [%s] self-test: add, idempotence, shebang, permissions" % ("ok" if good else "FAIL"))753 finally:754 import shutil755 shutil.rmtree(d, ignore_errors=True)756 langs = sorted(set(v[0] for v in C.load_json("source-header/languages.json")["extensions"].values()))757 print(" languages: %d (%s…)" % (len(langs), ", ".join(langs[:12])))758 return 0 if ok else 1759760761def main(argv=None):762 ap = argparse.ArgumentParser(prog="sp-header", description="SP Boucher Source Header Engine")763 sub = ap.add_subparsers(dest="cmd")764 for name in ("inspect", "generate"):765 s = sub.add_parser(name)766 s.add_argument("file")767 s = sub.add_parser("apply", help="add or refresh the header of files")768 s.add_argument("files", nargs="+")769 s.add_argument("--touch", action="store_true", help="set Last Modified to today (substantive edit)")770 s.add_argument("--new", action="store_true", help="the file was created today")771 s.add_argument("--upgrade", action="store_true", help="convert an earlier SP Boucher header variant")772 s.add_argument("--force-owner", action="store_true", help="ownership was verified by a human")773 s.add_argument("--dry-run", action="store_true")774 for name in ("check", "fix", "audit", "report"):775 s = sub.add_parser(name)776 s.add_argument("directory", nargs="?", default=".")777 s.add_argument("--json", action="store_true")778 s.add_argument("--force-owner", action="store_true")779 if name == "fix":780 s.add_argument("--dry-run", action="store_true")781 s.add_argument("--upgrade", action="store_true")782 if name == "report":783 s.add_argument("--out")784 sub.add_parser("doctor")785 sub.add_parser("version")786 a = ap.parse_args(argv)787 if a.cmd == "version":788 print("sp-header %s" % C.version())789 return 0790 if a.cmd == "doctor":791 return doctor()792 if a.cmd in ("inspect", "generate"):793 path = os.path.abspath(a.file)794 root = C.project_root(path)795 info = classify(path, root)796 if a.cmd == "generate":797 if not info.get("style"):798 C.eprint("sp-header: %s" % info["reason"])799 return 2800 lines = info["text"].split("\n")801 parsed = header_kind(lines, info["header"], info["style"])[1] if info.get("header") else None802 print("\n".join(render(expected_fields(path, root, parsed, is_new=not os.path.getsize(path)), info["style"])))803 return 0804 own, why = C.ownership(root)805 rep = {"file": path, "project_root": root, "language": info.get("language"), "comment_style": info.get("style"),806 "eligible": info["eligible"], "reason": info["reason"], "ownership": own, "ownership_basis": why}807 if info.get("text") is not None and info.get("style"):808 lines = info["text"].split("\n")809 if info.get("header"):810 kind, parsed = header_kind(lines, info["header"], info["style"])811 rep["header"] = {"kind": kind, "lines": [info["header"][0] + 1, info["header"][1] + 1], "fields": fields_from_parsed(parsed)}812 else:813 rep["header"] = None814 rep["expected"] = expected_fields(path, root, None)815 rep["check"] = process(path, "check")["status"]816 print(json.dumps(rep, indent=2, ensure_ascii=False))817 return 0818 if a.cmd == "apply":819 results = [process(f, "touch" if a.touch else "ensure", dry_run=a.dry_run, is_new=a.new, upgrade=a.upgrade,820 force_owner=a.force_owner) for f in a.files]821 print_results(results, verbose=True)822 return 1 if any(r["status"] == "error" for r in results) else 0823 directory = os.path.abspath(a.directory)824 if not os.path.exists(directory):825 C.eprint("sp-header: no such path: %s" % directory)826 return 2827 if os.path.isfile(directory):828 files_mode = [directory]829 else:830 files_mode = None831 action = "check" if a.cmd in ("check", "audit", "report") else "ensure"832 kw = dict(force_owner=a.force_owner)833 if a.cmd == "fix":834 kw.update(dry_run=a.dry_run, upgrade=a.upgrade)835 results = [process(f, action, **kw) for f in files_mode] if files_mode else scan(directory, action, **kw)836 counts = summarize(results)837 bad = counts.get("missing", 0) + counts.get("drift", 0) + counts.get("error", 0)838 if getattr(a, "json", False):839 print(json.dumps({"version": C.version(), "directory": directory, "counts": counts,840 "files": [{k: r[k] for k in ("rel", "status", "reason", "language")} for r in results]}, indent=2, ensure_ascii=False))841 elif a.cmd == "report":842 md = markdown_report(directory, results)843 if a.out:844 with open(a.out, "w", encoding="utf-8") as f:845 f.write(md + "\n")846 print("report written to %s" % a.out)847 else:848 print(md)849 else:850 print_results(results, verbose=(a.cmd == "audit"))851 own, why = C.ownership(C.project_root(directory))852 print("sp-header %s: %s — ownership %s (%s)" % (a.cmd, ", ".join("%s=%d" % kv for kv in sorted(counts.items())) or "no files", own, why))853 if a.cmd == "check":854 return 1 if bad else 0855 return 1 if counts.get("error", 0) else 0856857858if __name__ == "__main__":859 sys.exit(main())860