Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SP Boucher Development Standard7# File : payload/standards/lib/spstd/gitgov.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-git — SPB Git governance CLI: repository creation, incremental commits, verified pushes, releases."""42import argparse43import json44import os45import re46import shlex47import sys48import time4950from . import common as C51from . import header as H52from . import secscan as S5354SEMVER_RE = re.compile(r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$")555657def say(msg):58 print("sp-git: " + msg)596061def die(msg, code=1):62 C.eprint("sp-git: " + msg)63 sys.exit(code)646566# ----------------------------------------------------------------------------- SPB Git backend (SSH on the forge host)67class Backend(object):68 """SPB Git is a directory of bare repositories served by the forge; it is driven over SSH (existing keys/agent).6970 SP_GIT_LOCAL_BACKEND=<dir> replaces the forge host by a local directory (tests, offline rehearsal)."""7172 def __init__(self):73 cfg = C.git_config()74 self.r = cfg["remote"]75 self.web = cfg["repository"]["host"].rstrip("/")76 self.local = os.environ.get("SP_GIT_LOCAL_BACKEND")77 self.host = os.environ.get("SP_GIT_SSH_HOST") or self.r["ssh_host"]7879 def sh(self, script, timeout=25):80 if self.local:81 return C.run(["sh", "-c", script], cwd=self.local, timeout=timeout)82 return C.run(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", self.host, script], timeout=timeout)8384 def url(self, slug, private=False):85 root = self.r["private_root"] if private else self.r["public_root"]86 if self.local:87 return os.path.join(self.local, root, slug + ".git")88 return "%s:%s/%s.git" % (self.host, root, slug)8990 def exists(self, slug):91 """'' | 'public' | 'private' — raises RuntimeError when the forge cannot be reached."""92 q = shlex.quote(slug)93 rc, out, err = self.sh("if [ -d %s/%s.git ]; then echo public; elif [ -e %s/%s.git ]; then echo private; else echo none; fi"94 % (self.r["public_root"], q, self.r["private_root"], q))95 out = out.strip()96 if rc != 0 or out not in ("public", "private", "none"):97 raise RuntimeError((err or out).strip()[:200] or "forge unreachable (rc %d)" % rc)98 return "" if out == "none" else out99100 def create(self, slug, private=False):101 root = self.r["private_root"] if private else self.r["public_root"]102 q = shlex.quote(slug)103 script = ("set -e; mkdir -p %(root)s; d=%(root)s/%(q)s.git; [ -e \"$d\" ] && { echo exists; exit 3; }; "104 "git init -q --bare \"$d\"; git --git-dir=\"$d\" symbolic-ref HEAD refs/heads/main; "105 "for r in %(root)s/*.git; do if [ \"$r\" != \"$d\" ] && [ -x \"$r/hooks/post-receive\" ]; then "106 "cp -p \"$r/hooks/post-receive\" \"$d/hooks/post-receive\"; break; fi; done; echo created") % {"root": root, "q": q}107 rc, out, err = self.sh(script, 40)108 if rc != 0 or "created" not in out:109 raise RuntimeError((err or out).strip()[:300] or "creation failed (rc %d)" % rc)110111 def set_meta(self, slug, website, topics, description):112 tool = self.r.get("meta_tool")113 script = "[ -f %s ] && python3 %s %s %s %s %s" % (tool, tool, shlex.quote(slug), shlex.quote(website or ""),114 shlex.quote(topics or ""), shlex.quote(description or ""))115 rc, out, err = self.sh(script, 30)116 return rc == 0, (out or err).strip()117118 def web_status(self, slug):119 if self.local:120 return "n/a (local backend)"121 rc, out, _ = C.run(["curl", "-s", "-o", "/dev/null", "-m", "12", "-A", "Mozilla/5.0 (sp-git)", "-w", "%{http_code}",122 "%s/%s" % (self.web, slug)], timeout=20)123 return out.strip() if rc == 0 else "unreachable"124125126# ----------------------------------------------------------------------------- helpers127def slugify(name):128 s = re.sub(r"([a-z0-9])([A-Z])", r"\1-\2", name.strip())129 s = re.sub(r"[^A-Za-z0-9]+", "-", s).strip("-").lower()130 return s or "project"131132133def need_repo(path="."):134 root = C.git_root(os.path.abspath(path))135 if not root:136 die("not a git repository (run `sp-git init` to create and publish it)", 2)137 return root138139140def branch_of(root):141 return C.git_out(["symbolic-ref", "--short", "-q", "HEAD"], root, 10)142143144def has_head(root):145 return bool(C.git_out(["rev-parse", "--verify", "-q", "HEAD"], root, 10))146147148def upstream_of(root):149 return C.git_out(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], root, 10)150151152def unpushed_count(root):153 if not has_head(root):154 return 0155 n = C.git_out(["rev-list", "--count"] + S.unpushed_range(root), root, 30)156 return int(n) if n.isdigit() else 0157158159def dirty_files(root):160 return C.porcelain(root)161162163def validate_message(msg):164 types = "|".join(C.git_config()["commit_types"])165 first = msg.split("\n", 1)[0]166 if not re.match(r"^(%s)(\([A-Za-z0-9._/ -]+\))?!?: \S.*$" % types, first):167 return "commit subject must follow Conventional Commits: <type>(<scope>): <description> — types: %s" % types.replace("|", ", ")168 if len(first) > 100:169 return "commit subject longer than 100 characters"170 return ""171172173def publish_allowed(root):174 v2 = C.repo_policy(root)["v2"] or {}175 return v2.get("publish", True) is not False176177178GITIGNORE_COMMON = """# --- secrets and local configuration (never published) ---179.env180.env.*181!.env.example182!.env.sample183*.pem184*.p12185*.p8186*.key187*.jks188*.keystore189*.mobileprovision190secrets/191credentials.json192193# --- operating system and editors ---194.DS_Store195Thumbs.db196*.swp197.idea/198.vscode/199*.log200"""201GITIGNORE_STACKS = [202 (("package.json",), "# --- Node ---\nnode_modules/\ndist/\n.next/\n.nuxt/\n.turbo/\ncoverage/\n*.tsbuildinfo\n"),203 (("pyproject.toml", "setup.py", "requirements.txt"), "# --- Python ---\n__pycache__/\n*.py[cod]\n.venv/\nvenv/\n.pytest_cache/\n.mypy_cache/\n.ruff_cache/\n*.egg-info/\nbuild/\ndist/\n"),204 (("Package.swift", "*.xcodeproj", "*.xcworkspace"), "# --- Swift / Xcode ---\n.build/\n.swiftpm/\nDerivedData/\nxcuserdata/\n*.xcuserstate\n*.ipa\n*.dSYM.zip\n*.dSYM\n"),205 (("Cargo.toml",), "# --- Rust ---\ntarget/\n"),206 (("build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts"), "# --- Gradle / Android ---\n.gradle/\nbuild/\nlocal.properties\n*.apk\n*.aab\n"),207 (("go.mod",), "# --- Go ---\nbin/\n*.test\n*.out\n"),208 (("*.tex",), "# --- LaTeX ---\n*.aux\n*.bbl\n*.blg\n*.fdb_latexmk\n*.fls\n*.out\n*.synctex.gz\n*.toc\n"),209]210211212def make_gitignore(root):213 import fnmatch214 names = os.listdir(root)215 parts = [GITIGNORE_COMMON]216 for markers, block in GITIGNORE_STACKS:217 if any(fnmatch.filter(names, m) for m in markers):218 parts.append(block)219 return "\n".join(parts)220221222def make_readme(root, slug, description, private):223 meta = H.project_meta(root)224 idn = C.identity()225 i, c = idn["identity"], idn["contacts"]226 lic = H.detect_license(root, root)227 repo = "Private repository (SPB Git)" if private else "%s/%s" % (C.git_config()["repository"]["host"], slug)228 return """# %(name)s229230%(desc)s231232## Status233234Early development. Features, architecture, installation and usage are documented here as they are implemented.235236## Repository237238- Source: %(repo)s239- License: %(lic)s240241## Author242243**%(author)s** — %(position)s, %(inst)s244%(org)s · %(web)s · %(git)s245246- Contact: %(contact)s247- Development: %(dev)s248- Support: %(support)s249- Security: %(sec)s250""" % {"name": meta["project"], "desc": description or "_Description to be written._", "repo": repo, "lic": lic,251 "author": i["author"], "position": i["position"], "inst": i["institution"], "org": i["organization"], "web": i["website"],252 "git": i["git"], "contact": c["preferred"], "dev": c["development"], "support": c["support"], "sec": c["security"]}253254255def fix_headers(root, only=None):256 """Ensure headers on eligible files (all, or a list of repo-relative paths). Returns (changed, problems)."""257 own, _ = C.ownership(root)258 if own != "owned":259 return [], []260 files = [os.path.join(root, f) for f in only] if only is not None else C.list_files(root)261 changed, problems = [], []262 for p in files:263 if not os.path.isfile(p):264 continue265 r = H.process(p, "ensure")266 if r["status"] in ("added", "updated"):267 changed.append(r["rel"])268 elif r["status"] == "error":269 problems.append("%s: %s" % (r["rel"], r["reason"]))270 return changed, problems271272273def header_counts(root):274 return H.summarize(H.scan(root, "check"))275276277def security_gate(root, mode):278 findings, note = S.scan(root, mode)279 hi = S.high(findings)280 if findings:281 print(S.format_findings(findings))282 if hi:283 say("SECURITY: %d high-severity finding(s) in %s — publication blocked. Remove the secret (rotate it if it was "284 "committed); false positive → `%s` on the line or .sp-security-allow." % (len(hi), mode, S.ALLOW_MARK))285 return False286 return True287288289# ----------------------------------------------------------------------------- commands290def cmd_init(a):291 cwd = os.path.abspath(a.path)292 if not os.path.isdir(cwd):293 die("no such directory: %s" % cwd, 2)294 if os.path.realpath(cwd) in (os.path.realpath(C.HOME), "/"):295 die("refusing to initialise a repository in %s" % cwd, 2)296 root = C.git_root(cwd)297 if root and os.path.realpath(root) != os.path.realpath(cwd) and not a.here:298 say("using the enclosing repository %s" % root)299 if not root:300 rc, _, err = C.git(["init", "-q", "-b", "main"], cwd)301 if rc != 0:302 C.git(["init", "-q"], cwd)303 C.git(["symbolic-ref", "HEAD", "refs/heads/main"], cwd)304 C._cache.clear()305 root = C.git_root(cwd)306 if not root:307 die("git init failed: %s" % err.strip())308 say("git repository initialised (branch main)")309 else:310 say("git repository already initialised")311 v2 = C.repo_policy(root)["v2"] or {}312 private = a.private or str(v2.get("visibility", "")).lower() == "private"313 slug = slugify(a.name or v2.get("slug") or os.path.basename(root))314 if not os.path.exists(os.path.join(root, ".gitignore")):315 with open(os.path.join(root, ".gitignore"), "w", encoding="utf-8") as f:316 f.write(make_gitignore(root))317 say(".gitignore generated")318 if not any(os.path.exists(os.path.join(root, n)) for n in ("README.md", "Readme.md", "readme.md", "README")):319 with open(os.path.join(root, "README.md"), "w", encoding="utf-8") as f:320 f.write(make_readme(root, slug, a.description, private))321 say("README.md skeleton generated (complete it with the real features and usage)")322 blocker = ""323 o = C.origin_info(root)324 if o["kind"] != "none":325 say("origin already configured (%s) — kept as is" % o["raw"])326 elif a.no_remote or not publish_allowed(root):327 say("no remote created (%s)" % ("--no-remote" if a.no_remote else ".sp-standard.json: publish=false"))328 else:329 be = Backend()330 try:331 state = be.exists(slug)332 if state:333 url = be.url(slug, state == "private")334 rc, out, _ = C.git(["ls-remote", "--heads", url], root, 30)335 if out.strip() and not a.adopt:336 die("a %s repository named %r already exists on SPB Git with history. Use --name <other-slug>, or --adopt "337 "if this working tree is that project." % (state, slug), 3)338 say("remote repository %s already exists (%s)%s" % (slug, state, "" if out.strip() else ", empty"))339 private = state == "private"340 else:341 be.create(slug, private)342 say("remote repository created: %s (%s)" % (be.url(slug, private), "private" if private else "public"))343 C.git(["remote", "add", "origin", be.url(slug, private)], root)344 C._cache.clear()345 if a.description or a.topics:346 ok, msg = be.set_meta(slug, a.website or "", a.topics or "", a.description or "")347 say("forge metadata %s" % ("set" if ok else "NOT set (%s)" % msg[:120]))348 elif not private:349 say("reminder: set a description and topics → sp-git meta --description \"…\" --topics a,b,c")350 except RuntimeError as e:351 blocker = "SPB Git unreachable or creation failed: %s" % e352 say("BLOCKER: %s — local work is preserved; re-run `sp-git init` later." % blocker)353 changed, problems = fix_headers(root)354 if changed:355 say("source headers applied to %d file(s)" % len(changed))356 for p in problems:357 say("header problem: " + p)358 if a.no_commit:359 return 3 if blocker else 0360 if not security_gate(root, "tree"):361 return 1362 if not has_head(root):363 with C.RepoLock(root):364 C.git(["add", "-A"], root)365 rc, out, err = C.git(["commit", "-q", "-m", a.message or "chore: initialize repository"], root)366 if rc != 0:367 say("initial commit failed: %s" % (err or out).strip()[:300])368 return 1369 say("initial commit created (%s)" % C.git_out(["rev-parse", "--short", "HEAD"], root))370 elif dirty_files(root):371 say("%d uncommitted change(s) left for an explicit `sp-git commit`" % len(dirty_files(root)))372 if blocker or C.origin_info(root)["kind"] == "none":373 return 3 if blocker else 0374 return do_push(root, tags=False)375376377def cmd_status(a):378 root = need_repo(a.path)379 o = C.origin_info(root)380 own, why = C.ownership(root)381 br = branch_of(root)382 dirty = dirty_files(root)383 info = {"root": root, "project": H.project_meta(root)["project"], "branch": br, "origin": o["raw"] or None,384 "visibility": {"spbgit-public": "public", "spbgit-private": "private"}.get(o["kind"], o["kind"]),385 "web": o["web"] or None, "ownership": own, "ownership_basis": why, "uncommitted": len(dirty),386 "unpushed_commits": unpushed_count(root) if o["kind"] != "none" else None,387 "upstream": upstream_of(root) or None, "headers": header_counts(root) if own in ("owned", "unknown") else {},388 "head": C.git_out(["rev-parse", "--short", "HEAD"], root) or None}389 if a.json:390 print(json.dumps(info, indent=2, ensure_ascii=False))391 return 0392 print("Project : %s" % info["project"])393 print("Root : %s" % root)394 print("Branch : %s (HEAD %s)" % (br or "detached", info["head"]))395 print("Origin : %s" % (o["raw"] or "none — run `sp-git init`"))396 print("Visibility : %s%s" % (info["visibility"], (" " + o["web"]) if o["web"] else ""))397 print("Ownership : %s (%s)" % (own, why))398 print("Uncommitted : %d file(s)" % len(dirty))399 if o["kind"] != "none":400 print("Unpushed : %d commit(s)%s" % (info["unpushed_commits"], "" if info["upstream"] else " (no upstream yet)"))401 if info["headers"]:402 print("Headers : %s" % ", ".join("%s=%d" % kv for kv in sorted(info["headers"].items())))403 return 0404405406def cmd_commit(a):407 root = need_repo(a.path)408 if not a.message:409 die("a message is required: sp-git commit -m \"type(scope): description\" [files…]", 2)410 msg_err = validate_message(a.message[0])411 if msg_err:412 die(msg_err, 2)413 with C.RepoLock(root):414 if a.all:415 C.git(["add", "-A"], root)416 elif a.files:417 rc, _, err = C.git(["add", "--"] + [os.path.abspath(f) for f in a.files], root)418 if rc != 0:419 die("git add failed: %s" % err.strip())420 staged = [f for f in C.git_out(["diff", "--cached", "--name-only", "--diff-filter=ACMR", "-z"], root).split("\0") if f]421 if not staged and not C.git_out(["diff", "--cached", "--name-only"], root):422 die("nothing staged: name the files of this step (sp-git commit -m … file…) or use --all", 2)423 changed, problems = fix_headers(root, staged)424 if changed:425 C.git(["add", "--"] + changed, root)426 say("source headers applied/refreshed: %s" % ", ".join(changed[:8]) + (" …" if len(changed) > 8 else ""))427 for p in problems:428 say("header problem: " + p)429 if not security_gate(root, "staged"):430 return 1431 cmd = ["commit", "-q"]432 for m in a.message:433 cmd += ["-m", m]434 rc, out, err = C.git(cmd, root, 120)435 if rc != 0:436 say("commit failed: %s" % (err or out).strip()[:400])437 return 1438 say("committed %s — %s" % (C.git_out(["rev-parse", "--short", "HEAD"], root), a.message[0]))439 if a.push:440 return do_push(root, tags=False)441 if C.origin_info(root)["kind"] != "none":442 say("next: sp-git push")443 return 0444445446def do_push(root, tags=False):447 o = C.origin_info(root)448 if o["kind"] == "none":449 say("no origin: run `sp-git init` to create the SPB Git repository (public by default)")450 return 2451 if not publish_allowed(root):452 say("publication disabled for this repository (.sp-standard.json: publish=false) — nothing pushed")453 return 0454 br = branch_of(root)455 if not br:456 say("detached HEAD: check out a branch before pushing")457 return 2458 if not has_head(root):459 say("no commit yet")460 return 2461 if not security_gate(root, "unpushed"):462 return 1463 cmd = ["push"] + ([] if upstream_of(root) else ["-u"]) + ["origin", br] + (["--tags"] if tags else [])464 with C.RepoLock(root):465 for attempt in (1, 2, 3):466 rc, out, err = C.git(cmd, root, 300)467 text = (out + err)468 if rc == 0:469 break470 if re.search(r"non-fast-forward|fetch first|rejected", text):471 say("remote has new commits: fetching and rebasing local commits (non-destructive)")472 C.git(["fetch", "origin"], root, 120)473 if dirty_files(root):474 say("BLOCKER: working tree not clean, cannot rebase automatically. Commit your work, then `sp-git sync`.")475 return 4476 rc2, _, err2 = C.git(["rebase", "origin/" + br], root, 120)477 if rc2 != 0:478 C.git(["rebase", "--abort"], root)479 say("BLOCKER: conflict with origin/%s. Local commits are intact; resolve with `git pull --rebase` by hand "480 "(never force-push). %s" % (br, err2.strip()[:160]))481 return 4482 continue483 if attempt < 3 and re.search(r"Could not resolve|timed out|Connection (refused|reset|closed)|Network is unreachable|"484 r"unable to access|Could not read from remote", text):485 time.sleep(3 * attempt)486 continue487 say("BLOCKER: push failed (%s). Local commits are preserved; nothing was forced." % text.strip().split("\n")[-1][:200])488 return 4489 else:490 say("BLOCKER: push still failing after retries; local commits are preserved.")491 return 4492 return do_verify(root)493494495def do_verify(root, quiet=False):496 o = C.origin_info(root)497 br = branch_of(root)498 if o["kind"] == "none" or not br:499 say("nothing to verify (no origin or detached HEAD)")500 return 2501 local = C.git_out(["rev-parse", "HEAD"], root)502 rc, out, err = C.git(["ls-remote", "origin", "refs/heads/" + br], root, 60)503 if rc != 0:504 say("VERIFY FAILED: cannot read the remote (%s)" % err.strip()[:160])505 return 4506 remote = out.split()[0] if out.strip() else ""507 if remote != local:508 say("VERIFY FAILED: origin/%s is %s, local HEAD is %s" % (br, remote[:8] or "absent", local[:8]))509 return 4510 extra = ""511 if o["kind"] == "spbgit-public":512 code = Backend().web_status(o["slug"])513 extra = " — %s → HTTP %s" % (o["web"], code)514 if not quiet:515 say("verified: origin/%s = %s%s" % (br, local[:8], extra))516 return 0517518519def cmd_push(a):520 return do_push(need_repo(a.path), tags=a.tags)521522523def cmd_verify(a):524 return do_verify(need_repo(a.path))525526527def cmd_sync(a):528 root = need_repo(a.path)529 o = C.origin_info(root)530 if o["kind"] == "none":531 say("no origin: run `sp-git init`")532 return 2533 rc, _, err = C.git(["fetch", "origin", "--tags"], root, 180)534 if rc != 0:535 say("BLOCKER: fetch failed (%s)" % err.strip()[:160])536 return 4537 up = upstream_of(root)538 if up:539 behind = C.git_out(["rev-list", "--count", "HEAD..%s" % up], root)540 ahead = C.git_out(["rev-list", "--count", "%s..HEAD" % up], root)541 if behind and int(behind) > 0:542 if dirty_files(root):543 say("behind by %s commit(s) but the working tree is not clean: commit first, then sync again" % behind)544 return 4545 if int(ahead or 0) == 0:546 rc, _, err = C.git(["merge", "--ff-only", up], root, 120)547 else:548 rc, _, err = C.git(["rebase", up], root, 120)549 if rc != 0:550 C.git(["rebase", "--abort"], root)551 if rc != 0:552 say("BLOCKER: cannot integrate %s without conflict; local work intact (%s)" % (up, err.strip()[:120]))553 return 4554 say("integrated %s commit(s) from %s" % (behind, up))555 if unpushed_count(root) > 0 or not up:556 return do_push(root, tags=False)557 return do_verify(root)558559560def cmd_audit(a):561 root = need_repo(a.path)562 own, why = C.ownership(root)563 o = C.origin_info(root)564 issues, notes = [], []565 counts = header_counts(root) if own in ("owned", "unknown") else {}566 bad = counts.get("missing", 0) + counts.get("drift", 0) + counts.get("error", 0)567 if own == "owned" and bad:568 issues.append("%d eligible file(s) without a compliant header (sp-header fix %s)" % (bad, "."))569 findings, _ = S.scan(root, "tree")570 f2, _ = S.scan(root, "unpushed")571 findings = S.dedupe(findings + f2)572 if S.high(findings):573 issues.append("%d high-severity secret finding(s)" % len(S.high(findings)))574 if o["kind"] == "none":575 issues.append("no origin (sp-git init)")576 else:577 n = unpushed_count(root)578 if n:579 issues.append("%d unpushed commit(s)" % n)580 dirty = dirty_files(root)581 if dirty:582 notes.append("%d uncommitted file(s)" % len(dirty))583 if has_head(root):584 revs = S.unpushed_range(root) if o["kind"] != "none" else ["-20"]585 for line in C.git_out(["log", "--format=%h %s", "-50"] + (revs if o["kind"] != "none" else []), root).split("\n"):586 if line.strip() and validate_message(line.split(" ", 1)[1] if " " in line else ""):587 notes.append("non-conventional commit subject: %s" % line[:80])588 for n, label in (("README.md", "README"), (".gitignore", ".gitignore")):589 if not os.path.exists(os.path.join(root, n)):590 issues.append("%s missing" % label)591 lic = H.detect_license(root, root)592 rep = {"root": root, "ownership": own, "origin": o["raw"], "visibility": o["kind"], "headers": counts, "license": lic,593 "secrets": findings, "issues": issues, "notes": notes}594 if a.json:595 print(json.dumps(rep, indent=2, ensure_ascii=False))596 else:597 print("sp-git audit — %s" % H.project_meta(root)["project"])598 print(" ownership : %s (%s)" % (own, why))599 print(" origin : %s [%s]" % (o["raw"] or "none", o["kind"]))600 print(" license : %s" % lic)601 print(" headers : %s" % (", ".join("%s=%d" % kv for kv in sorted(counts.items())) or "not evaluated"))602 print(" secrets : %d high, %d medium" % (len(S.high(findings)), len(findings) - len(S.high(findings))))603 if findings:604 print(S.format_findings(findings, 15))605 for i in issues:606 print(" ISSUE : " + i)607 for n in notes[:12]:608 print(" note : " + n)609 print(" result : %s" % ("NOT COMPLIANT" if issues else "compliant"))610 return 1 if issues else 0611612613def cmd_release(a):614 root = need_repo(a.path)615 ver = a.version.lstrip("v")616 if not SEMVER_RE.match(ver):617 die("%r is not a Semantic Version (MAJOR.MINOR.PATCH)" % a.version, 2)618 tag = "v" + ver619 if C.git_out(["tag", "-l", tag], root):620 die("tag %s already exists" % tag, 2)621 cl = next((os.path.join(root, n) for n in ("CHANGELOG.md", "CHANGELOG", "Changelog.md") if os.path.isfile(os.path.join(root, n))), None)622 if not cl:623 die("CHANGELOG.md is required for a release", 2)624 with open(cl, encoding="utf-8", errors="replace") as f:625 if not re.search(r"^#+\s*\[?v?%s\b" % re.escape(ver), f.read(), re.M):626 die("CHANGELOG has no section for %s" % ver, 2)627 touched = []628 vf = os.path.join(root, "VERSION")629 if os.path.isfile(vf):630 with open(vf) as f:631 cur = f.read().strip()632 if cur != ver:633 with open(vf, "w") as f:634 f.write(ver + "\n")635 touched.append("VERSION")636 pj = os.path.join(root, "package.json")637 if os.path.isfile(pj):638 with open(pj, encoding="utf-8") as f:639 t = f.read()640 t2 = re.sub(r'("version"\s*:\s*")[^"]*(")', lambda m: m.group(1) + ver + m.group(2), t, count=1)641 if t2 != t:642 with open(pj, "w", encoding="utf-8") as f:643 f.write(t2)644 touched.append("package.json")645 other = [f for f in dirty_files(root) if f not in touched and os.path.basename(cl) != f]646 if other:647 die("working tree has unrelated uncommitted changes (%s…): commit them first" % ", ".join(other[:4]), 2)648 if a.test_cmd:649 say("running tests: %s" % a.test_cmd)650 rc, out, err = C.run(["sh", "-c", a.test_cmd], cwd=root, timeout=3600)651 if rc != 0:652 print((out + err)[-1500:])653 die("tests failed: the release is not declared", 1)654 else:655 say("no --test-cmd given: build and tests are NOT verified by sp-git for this release")656 own, _ = C.ownership(root)657 if own == "owned":658 c = header_counts(root)659 if c.get("missing", 0) + c.get("drift", 0) + c.get("error", 0):660 die("source headers are not compliant (sp-header fix .)", 1)661 if not security_gate(root, "tree") or not security_gate(root, "unpushed"):662 return 1663 with C.RepoLock(root):664 if dirty_files(root):665 C.git(["add", "--"] + touched + [os.path.basename(cl)], root)666 rc, out, err = C.git(["commit", "-q", "-m", "release: prepare version %s" % ver], root)667 if rc != 0:668 die("release commit failed: %s" % (err or out).strip()[:200])669 rc, _, err = C.git(["tag", "-a", tag, "-m", "Release %s" % tag], root)670 if rc != 0:671 die("tag failed: %s" % err.strip())672 say("tag %s created" % tag)673 if C.origin_info(root)["kind"] == "none" or not publish_allowed(root):674 say("no publication (no origin or publish=false): release is local only")675 return 0676 rc = do_push(root, tags=False)677 if rc != 0:678 return rc679 rc, out, err = C.git(["push", "origin", tag], root, 120)680 if rc != 0:681 say("BLOCKER: tag push failed (%s)" % err.strip()[:160])682 return 4683 remote = C.git_out(["ls-remote", "--tags", "origin", tag], root, 60)684 if not remote:685 say("VERIFY FAILED: tag %s not visible on origin" % tag)686 return 4687 say("release %s published and verified on origin. Binary assets, if any: `spbgit release upload <repo> %s <file>` (forge CLI)." % (tag, tag))688 return 0689690691def cmd_meta(a):692 root = need_repo(a.path)693 o = C.origin_info(root)694 if o["kind"] not in ("spbgit-public", "spbgit-private"):695 die("origin is not an SPB Git repository", 2)696 ok, msg = Backend().set_meta(o["slug"], a.website or "", a.topics or "", a.description or "")697 say("forge metadata %s" % ("set: " + msg if ok else "NOT set: " + msg[:200]))698 return 0 if ok else 4699700701def cmd_doctor(a):702 ok = True703 rc, out, _ = C.run(["git", "--version"])704 print(" [%s] %s" % ("ok" if rc == 0 else "FAIL", out.strip() or "git missing"))705 ok = ok and rc == 0706 for k in ("user.name", "user.email"):707 v = C.git_out(["config", "--global", k], C.HOME)708 print(" [%s] git %s = %s" % ("ok" if v else "warn", k, v or "(unset)"))709 be = Backend()710 try:711 be.exists("sp-git-doctor-probe")712 print(" [ok] SPB Git reachable over SSH (%s)" % (be.local or be.host))713 rc, out, _ = be.sh("[ -f %s ] && echo yes || echo no" % be.r["meta_tool"])714 print(" [%s] forge metadata tool %s" % ("ok" if "yes" in out else "warn", be.r["meta_tool"]))715 except RuntimeError as e:716 print(" [warn] SPB Git not reachable over SSH from this machine: %s" % e)717 print(" [info] forge web: %s → HTTP %s" % (be.web, be.web_status("")))718 return 0 if ok else 1719720721def main(argv=None):722 ap = argparse.ArgumentParser(prog="sp-git", description="SPB Git governance (SP Boucher development standard)")723 sub = ap.add_subparsers(dest="cmd")724725 def add(name, fn, help_=""):726 s = sub.add_parser(name, help=help_)727 s.set_defaults(fn=fn)728 s.add_argument("-C", dest="path", default=".")729 return s730 s = add("init", cmd_init, "git init + SPB Git repository (public by default) + headers + first commit + push")731 s.add_argument("--name", help="repository slug (kebab-case); default: directory name")732 s.add_argument("--private", action="store_true", help="confidential project: SSH-only repository, never listed on the forge")733 s.add_argument("--no-remote", action="store_true", help="local repository only")734 s.add_argument("--adopt", action="store_true", help="attach to an existing remote repository of the same name")735 s.add_argument("--no-commit", action="store_true")736 s.add_argument("--here", action="store_true")737 s.add_argument("--description")738 s.add_argument("--topics", help="comma-separated")739 s.add_argument("--website")740 s.add_argument("-m", "--message")741 s = add("status", cmd_status)742 s.add_argument("--json", action="store_true")743 s = add("commit", cmd_commit, "validated incremental commit (headers, secret scan, Conventional Commits)")744 s.add_argument("-m", "--message", action="append")745 s.add_argument("-a", "--all", action="store_true", help="stage every change (only when all of them belong to this step)")746 s.add_argument("--push", action="store_true")747 s.add_argument("files", nargs="*")748 s = add("push", cmd_push, "secret scan of unpushed commits, push (never forced), remote verification")749 s.add_argument("--tags", action="store_true")750 add("verify", cmd_verify, "prove that origin holds the local HEAD")751 add("sync", cmd_sync, "fetch, fast-forward or rebase local commits, push, verify")752 s = add("audit", cmd_audit)753 s.add_argument("--json", action="store_true")754 s = add("release", cmd_release, "SemVer release: changelog check, validations, commit, tag, push, verify")755 s.add_argument("version")756 s.add_argument("--test-cmd", help="command that must succeed before the release is declared")757 s = add("meta", cmd_meta, "description / topics / website on the forge")758 s.add_argument("--description")759 s.add_argument("--topics")760 s.add_argument("--website")761 add("doctor", cmd_doctor)762 sub.add_parser("version")763 a = ap.parse_args(argv)764 if a.cmd == "version":765 print("sp-git %s" % C.version())766 return 0767 if not getattr(a, "fn", None):768 ap.print_help()769 return 2770 return a.fn(a) or 0771772773if __name__ == "__main__":774 sys.exit(main())775