Files

77 lines
2.9 KiB
Python

#!/usr/bin/env python3
"""Run one gate command and print its LeaseVibe gate-evidence comment (lawbook 5.8.2 / 5.8.3).
The first line is the sentinel `TWELVE-EIGHT-GATE-EVIDENCE v1 <GATE-ID> <ITEM-KEY>`; the labelled fields carry the
full argv, the working directory, the environment that matters, the scope, the exit code, the commit, the generation
time, the run position and the disposition. Nothing is invented: the exit code is the command's own and the commit is
`git rev-parse HEAD`.
Usage: scripts/dev/gate-evidence.py [--env NAME]... GATE-ID ITEM-KEY "scope text" -- command [args...]
(--env NAME, before the positionals, records an environment variable that the command saw)
Paste stdout into a comment on ITEM-KEY. Exit code of this script is the command's exit code.
"""
import argparse
import datetime
import os
import subprocess
import sys
def git_head():
return subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip()
def environment(names):
shown = [f"{name}={os.environ[name]}" for name in names if name in os.environ]
return ", ".join(shown) if shown else "none beyond the default shell environment"
def run_gate(argv):
try:
result = subprocess.run(argv, capture_output=True, text=True)
except FileNotFoundError as error:
return 127, [f"cannot run {argv[0]}: {error}"]
tail = (result.stdout + result.stderr).strip().splitlines()[-6:]
return result.returncode, tail
def render(args, code, tail):
when = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
lines = [
f"TWELVE-EIGHT-GATE-EVIDENCE v1 {args.gate} {args.item}",
f"**Gate:** {args.gate}",
f"**Command:** {' '.join(args.command)}",
f"**Working Directory:** {os.getcwd()}",
f"**Environment:** {environment(args.env)}",
f"**Scope:** {args.scope}",
f"**Exit Code:** {code}",
f"**Commit:** {git_head()}",
f"**Generated:** {when}",
"**Run Position:** the commit above is the commit carrying the change or a descendant of it",
f"**Disposition:** {'PASS' if code == 0 else 'FAIL'}",
"",
"Last output lines:",
*[f" {row}" for row in tail],
]
return "\n".join(lines)
def main(argv):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("gate")
parser.add_argument("item")
parser.add_argument("scope")
parser.add_argument("--env", action="append", default=[])
parser.add_argument("command", nargs=argparse.REMAINDER)
args = parser.parse_args(argv)
args.command = args.command[1:] if args.command[:1] == ["--"] else args.command
if not args.command:
parser.error("a command is required after --")
code, tail = run_gate(args.command)
print(render(args, code, tail))
return code
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))