use std::ffi::OsString;
use std::path::{Path, PathBuf};
use greengate_runtime::check::Stage;
use greengate_runtime::names::BIN;
use greengate_runtime::{pushrefs, registry, ListOptions};
const USAGE: &str = concat!(
"usage: ",
greengate_runtime::bin!(),
" <subcommand> | ",
greengate_runtime::bin!(),
" --hooks-dir <dir> <hook-name> [args…]\n",
"\n",
" list what would run in this repository, and why not\n",
" [--json] [--stage pre-commit|pre-push] [--pushed]\n",
" [--all: the inert checks too, one row each]\n",
" install turn hooks on here: copy the binary if needed, bake the shims\n",
" [--force] replaces a hook that is not ours\n",
" init wire up THIS repository only — the verb a package manager\n",
" calls from `prepare`; never copies a binary, never prompts,\n",
" never re-bakes from inside a push snapshot\n",
" uninstall remove OUR six shims and nothing else [--binary: the binary too]\n",
" [--repo: this repository only; the template dir is left as is;\n",
" it forgets attestations and revokes greengate.conf trust]\n",
" setup the commit-style questions, current values as defaults\n",
" [--local|--global] [--dry-run]\n",
" trust show what greengate.conf declares, and accept it\n",
" [--show: what is trusted] [--revoke: forget it]\n",
" run rehearse checks without committing: the pre-commit stage,\n",
" `run pre-push` for the push gate, or one check by name\n",
" [--all-files] [--hooks-dir <dir>]\n",
" `run --stamp [<gate>…]` — run the gates on HEAD of a clean\n",
" worktree and stamp the tree, as the commit and push hooks\n",
" do, so a later commit or push of that tree skips them\n",
" (default: every gate the hooks honour a stamp for). Exits 0\n",
" stamped, 1 a gate failed, 2 refused (dirty tree, unknown\n",
" gate), 4 a gate was deferred or could not be judged\n",
" [--quiet | --raw: a captured check's output to a log, one\n",
" line on a pass (the default when not at a terminal), or\n",
" the tool's own output as it comes]\n",
" rehearse run the push gate on a snapshot of HEAD in the background\n",
" and stamp the tree, so `git push` skips the suite\n",
" (`git config greengate.rehearseOnCommit true` does this after\n",
" every commit) [--wait: follow it, or run it here if none]\n",
" [--status] [--stop] [--cluster: send the gates the cluster\n",
" may run to an Argo Workflow that outlives this machine;\n",
" the next commit or push collects them]\n",
" cluster collect turn the finished detached Workflows of this repository\n",
" into cluster tokens now (every commit and push does it)\n",
" cluster sign in the cluster: sign the finished detached Workflows'\n",
" passing gates into ConfigMaps (key: GREENGATE_SIGNER_KEY)\n",
" [--watch: a pass every 30 s until SIGTERM or SIGINT]\n",
" restore bring back unstaged changes a killed pre-commit left parked\n",
" migrate move greengate 3.x's state and amont.* keys in this\n",
" repository, and the machine's global keys, to greengate's\n",
" names (every command does it once by itself)\n",
" [--global: read the machine's keys again]\n",
" [--reverse: back to 3.x's names, before a downgrade; 4.0\n",
" then leaves the repository alone until `migrate`]\n",
" [--tracked: rename the committed names instead —\n",
" amont.conf, amont.pack, the AGENTS.md markers — and\n",
" stage them for you to commit]\n",
" doctor list greengate 3.x names still set here: AMONT_*\n",
" variables, amont.* keys, state left in .git; exits 1 when\n",
" any is left (not an error), 0 when none, 2 when it\n",
" could not look (git failed)\n",
" agents-md write the agent-guidance block into AGENTS.md, plus the\n",
" CLAUDE.md signpost pointing at it (both generated, both\n",
" checked) [--check: report drift only] [--path <file>]\n",
" enroll the machine-level standing grant: every future clone gets\n",
" the hooks [--conventions declared|everywhere]\n",
" attest `attest covered` — print the gate names a VALID signed\n",
" attestation covers for the tree checked out here (CI's\n",
" one-liner; prints nothing and exits 0 on any failure)\n",
" [--signers <file>] [--principal <id>]\n",
" [--platform <arch-os>|any: which leg is asking; defaults\n",
" to this machine's, so a matrix leg only skips work that\n",
" really ran on ITS platform]\n",
" [--strict: exit 3 when an attestation for this tree was\n",
" found but its signature did not verify, rather than 0;\n",
" the rejection is named on stderr either way]\n",
" `attest check-inputs --require <gate>...` — prove the\n",
" named gates declare, in .github/attest-inputs, every file\n",
" the tree tracks (exit 1 uncovered, 2 no usable spec)\n",
" [--tree <rev>, default HEAD]\n",
"\n",
" check what is wrong with these FILES — no index, no staging, no\n",
" commit. The content checks only (ban-terms, secrets,\n",
" merge-conflict, large-files), reported as\n",
" `file:line:col: severity: message [check]`, which every\n",
" editor's error parser and every modern terminal already\n",
" understand. Reads a path list, or one unsaved buffer on\n",
" stdin. Exits 1 if anything blocking was found.\n",
" [<path>…] [--stdin-filename <path>] [--format text|json]\n",
"\n",
" land run the push gates on a snapshot of this branch with no\n",
" connection open, push it, then read the remote back to prove\n",
" the ref moved. Exits 0 landed, 1 refused (a gate failed, or\n",
" the push was refused), 3 unreachable or unverified, 4 accepted\n",
" but the expected tip was not observed (2 is usage)\n",
" [--force: lease on the tip it just read] [--json: stdout]\n",
" [--dry-run: resolve the target only; no network, no push]\n",
" [--tag <name>: land that existing tag instead, never moving\n",
" one already on the remote; a v* tag gets release audits]\n",
" slot run run a heavy command in a host slot, queued with every other\n",
" one on this machine; exits 75 without running it when no\n",
" slot frees in time [--weight N] [--max-wait S, default 90]\n",
" [--on-timeout run|exit] -- <command…>\n",
" slots who holds the host slots, and how many wait [--json]\n",
" stamps which gates the tree carries a verdict for: stamped (a local\n",
" token for the gate as it is declared now), attested (a signed\n",
" note for this platform), deferred, or absent\n",
" [--json] [--tree <rev>, default HEAD] [<gate>…]\n",
" warm fill the cache of every cold `tree` gate, so the next commit\n",
" can prove it within its slack (after a cold commit this\n",
" runs in the background by itself) [--worker]\n",
" tree-parity compare each `tree` gate in greengate.conf with the workflow\n",
" steps skipped on it; exits 1 on any drift (CI runs it,\n",
" never skipped)\n",
"\n",
" add vendor a pack's declarations into greengate.conf — a pack is a\n",
" git repository carrying a `greengate.pack` of manifest rows.\n",
" Resolves the revision to a commit id, refuses anything that\n",
" is not a check, and records the id beside the lines. Nothing\n",
" is trusted by adding it: the manifest changes, so `",
greengate_runtime::bin!(),
" trust`\n",
" must read the commands before any of them can run.\n",
" <source>[@<rev>]… [--dry-run]\n",
" github:owner/repo forgejo:host/owner/repo <git-url>\n",
"\n",
" --help this text --version the binary's version\n",
"\n",
"Hook mode (what the shims call): ",
greengate_runtime::bin!(),
" --hooks-dir <dir> <hook-name> [args…]\n",
"Formerly amont: `amont` runs this binary. greengate 4.0 reads greengate.*\n",
"keys and GREENGATE_* variables only; its first run in a repository moves\n",
"greengate 3.x's state and keys there (`migrate`).\n",
"The full manual: https://greenharness.github.io/greengate/\n",
);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Sub {
List,
Setup,
Install,
Init,
Uninstall,
Run,
Trust,
Restore,
AgentsMd,
Enroll,
Attest,
Check,
Add,
Rehearse,
TreeParity,
Warm,
Land,
Slot,
Slots,
Stamps,
Cluster,
Migrate,
Doctor,
}
impl Sub {
#[cfg(test)]
const fn index(self) -> usize {
match self {
Sub::List => 0,
Sub::Setup => 1,
Sub::Install => 2,
Sub::Init => 3,
Sub::Uninstall => 4,
Sub::Run => 5,
Sub::Trust => 6,
Sub::Restore => 7,
Sub::AgentsMd => 8,
Sub::Enroll => 9,
Sub::Attest => 10,
Sub::Check => 11,
Sub::Add => 12,
Sub::Rehearse => 13,
Sub::TreeParity => 14,
Sub::Warm => 15,
Sub::Land => 16,
Sub::Slot => 17,
Sub::Slots => 18,
Sub::Stamps => 19,
Sub::Cluster => 20,
Sub::Migrate => 21,
Sub::Doctor => 22,
}
}
}
const SUBCOMMANDS: [(&str, Sub); 23] = [
("list", Sub::List),
("setup", Sub::Setup),
("install", Sub::Install),
("init", Sub::Init),
("uninstall", Sub::Uninstall),
("run", Sub::Run),
("trust", Sub::Trust),
("restore", Sub::Restore),
("agents-md", Sub::AgentsMd),
("enroll", Sub::Enroll),
("attest", Sub::Attest),
("check", Sub::Check),
("add", Sub::Add),
("rehearse", Sub::Rehearse),
("tree-parity", Sub::TreeParity),
("warm", Sub::Warm),
("land", Sub::Land),
("slot", Sub::Slot),
("slots", Sub::Slots),
("stamps", Sub::Stamps),
("cluster", Sub::Cluster),
("migrate", Sub::Migrate),
("doctor", Sub::Doctor),
];
fn subcommand(arg: &str) -> Option<Sub> {
SUBCOMMANDS
.iter()
.find(|(name, _)| *name == arg)
.map(|(_, sub)| *sub)
}
#[derive(Debug, PartialEq, Eq)]
enum Invocation {
Sub {
name: Sub,
args: Vec<OsString>,
},
Hook {
hooks_dir: PathBuf,
name: String,
args: Vec<OsString>,
},
Help,
Version,
Usage(String),
}
fn parse(argv: Vec<OsString>) -> Invocation {
let Some(first) = argv.first() else {
return Invocation::Usage("no arguments".to_string());
};
if first == "--help" || first == "-h" {
return Invocation::Help;
}
if first == "--version" || first == "-V" {
return Invocation::Version;
}
if let Some(sub) = first.to_str().and_then(subcommand) {
return Invocation::Sub {
name: sub,
args: argv[1..].to_vec(),
};
}
let wants_help = argv.iter().any(|a| a == "--help" || a == "-h");
let mut hooks_dir: Option<PathBuf> = None;
let mut name: Option<String> = None;
let mut args: Vec<OsString> = Vec::new();
let mut it = argv.into_iter();
while let Some(a) = it.next() {
if name.is_some() {
args.push(a);
continue;
}
if a == "--hooks-dir" {
let Some(v) = it.next() else {
return Invocation::Usage("--hooks-dir requires a value".to_string());
};
hooks_dir = Some(PathBuf::from(v));
continue;
}
let Some(s) = a.to_str() else {
return Invocation::Usage(format!("hook name is not valid UTF-8: {a:?}"));
};
name = Some(s.to_owned());
}
match (hooks_dir, name) {
(Some(hooks_dir), Some(name)) => Invocation::Hook {
hooks_dir,
name,
args,
},
_ if wants_help => Invocation::Help,
(None, Some(name)) => Invocation::Usage(format!(
"{name:?} is not a subcommand, and hook mode needs --hooks-dir <dir> before the hook name"
)),
_ => Invocation::Usage("no hook name".to_string()),
}
}
#[cfg(unix)]
fn die_on_sigpipe() {
extern "C" {
fn signal(signum: i32, handler: usize) -> usize;
}
const SIGPIPE: i32 = 13;
const SIG_DFL: usize = 0;
unsafe {
signal(SIGPIPE, SIG_DFL);
}
}
#[cfg(not(unix))]
fn die_on_sigpipe() {}
fn main() {
die_on_sigpipe();
let _ = greengate_runtime::rehearsal::in_snapshot();
greengate_runtime::rehearsal::land_env();
greengate_runtime::rehearsal::prestage();
greengate_runtime::rehearsal::source_worktree();
match parse(std::env::args_os().skip(1).collect()) {
Invocation::Help => {
print!("{USAGE}");
std::process::exit(0);
}
Invocation::Version => {
println!("{BIN} {}", env!("CARGO_PKG_VERSION"));
std::process::exit(0);
}
Invocation::Usage(why) => {
eprintln!("{BIN}: {why}");
eprint!("{USAGE}");
std::process::exit(2);
}
Invocation::Sub { name, args } => std::process::exit(run_sub(name, &args)),
Invocation::Hook {
hooks_dir,
name,
args,
} => {
migrate_first();
std::process::exit(run_hook(&hooks_dir, &name, &args))
}
}
}
fn migrate_first() {
let cwd = std::env::current_dir().unwrap_or_default();
if let Err(why) = greengate_runtime::migrate::ensure(
&cwd,
&greengate_runtime::migrate::system_git,
now_secs(),
) {
eprintln!("{BIN}: {}", sanitize_lines(&why.to_string()));
eprintln!("{BIN}: {MIGRATE_HINT}");
std::process::exit(1);
}
}
fn now_secs() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |since| since.as_secs())
}
const MIGRATE_HINT: &str = concat!(
"the move to greengate's names stopped; what it did not reach keeps\n",
"its old name, and `",
greengate_runtime::bin!(),
" doctor` lists it."
);
fn sanitize_lines(text: &str) -> String {
text.lines()
.map(greengate_runtime::ui::sanitize)
.collect::<Vec<_>>()
.join("\n")
}
fn migrate_tracked(cwd: &Path) -> Result<(), String> {
use greengate_runtime::migrate::{system_git, tracked};
use greengate_runtime::names::old;
let root = greengate_runtime::git::stdout_in(cwd, &["rev-parse", "--show-toplevel"])
.ok_or("not inside a git work tree")?;
let root = Path::new(root.trim());
let staged = tracked::migrate_tracked(root, &system_git).map_err(|e| {
if e.staged_nothing() {
e.to_string()
} else {
format!(
"{e}\n`git status` shows what the rename staged, if anything, before it stopped"
)
}
})?;
for (old_name, new_name) in &staged.renamed {
eprintln!("renamed {old_name} to {new_name}");
}
for name in &staged.markers {
eprintln!("respelled the generated-block markers in {name}");
}
if staged.attest_inputs {
eprintln!("renamed the manifest in .github/attest-inputs");
}
if staged.changed() {
eprintln!("staged; review with `git diff --cached`, then commit");
} else {
eprintln!("nothing committed here carries greengate 3.x's names");
}
if staged.leftover_count > 0 {
eprintln!(
"{} tracked line(s) still name {}, {} or an {}* variable; \
these need reading, not a substitution:",
staged.leftover_count,
old::MANIFEST,
old::PACK_FILE,
old::ENV_PREFIX
);
for line in &staged.leftovers {
eprintln!(" {}", greengate_runtime::ui::sanitize(line));
}
if staged.leftover_count > staged.leftovers.len() {
eprintln!(
" … and {} more (`git grep -n -F -e {} -e {} -e {}`)",
staged.leftover_count - staged.leftovers.len(),
old::MANIFEST,
old::PACK_FILE,
old::ENV_PREFIX
);
}
}
Ok(())
}
fn migrate_command(args: &[OsString]) -> i32 {
let has = |flag: &str| args.iter().any(|a| a == flag);
if !has("--tracked") {
return report(
migrate_verb(args)
.map_err(|why| format!("{BIN}: {}\n{BIN}: {MIGRATE_HINT}", sanitize_lines(&why))),
);
}
if has("--reverse") || has("--global") {
eprintln!("{BIN}: `--tracked` stands alone: run `{BIN} migrate --tracked` by itself");
return 2;
}
let tracked = std::env::current_dir()
.map_err(|e| e.to_string())
.and_then(|cwd| migrate_tracked(&cwd));
report(tracked.map_err(|why| {
sanitize_lines(&why)
.lines()
.map(|line| format!("{BIN}: {line}"))
.collect::<Vec<_>>()
.join("\n")
}))
}
fn migrate_verb(args: &[OsString]) -> Result<(), String> {
use greengate_runtime::migrate::{self, Direction, Repo};
let git = &migrate::system_git;
let reverse = args.iter().any(|a| a == "--reverse");
let global = args.iter().any(|a| a == "--global");
let cwd = std::env::current_dir().map_err(|e| e.to_string())?;
let repo = Repo::locate(&cwd);
if reverse {
let mut moved = migrate::Moved::default();
if let Some(repo) = &repo {
moved = migrate::migrate_repo(repo, Direction::Reverse, git, now_secs())
.map_err(|e| e.to_string())?;
} else if !global {
return Err(
"not inside a git repository (`--global` moves the machine's keys alone)".into(),
);
}
if global {
moved.keys += migrate::reverse_global(git)
.map_err(|e| e.to_string())?
.keys;
}
eprintln!(
"moved {} names and {} keys back to greengate 3.x's; greengate 4.0 leaves {} alone \
until `{BIN} migrate` is run there",
moved.state,
moved.keys,
if repo.is_some() {
"this repository"
} else {
"them"
}
);
return Ok(());
}
if let Some(repo) = &repo {
for marker in [
repo.marker(),
repo.common.join(greengate_runtime::names::REVERSED_MARKER),
] {
match std::fs::remove_file(&marker) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
return Err(format!("could not remove {}: {e}", marker.display()));
}
_ => {}
}
}
}
if global {
migrate::forget_global().map_err(|e| e.to_string())?;
}
let moved = migrate::ensure(&cwd, git, now_secs()).map_err(|e| e.to_string())?;
if moved.state + moved.keys == 0 {
eprintln!("nothing of greengate 3.x's to move here");
} else {
eprintln!(
"moved {} names and {} keys to greengate's",
moved.state, moved.keys
);
}
Ok(())
}
fn known_flags(sub: Sub) -> (&'static [&'static str], &'static [&'static str]) {
match sub {
Sub::List => (&["--json", "--pushed", "--all"], &["--stage"]),
Sub::Setup => (&["--local", "--global", "--dry-run"], &[]),
Sub::Install => (&["--force"], &[]),
Sub::Init | Sub::Restore => (&[], &[]),
Sub::Uninstall => (&["--binary", "--repo"], &[]),
Sub::Run => (
&["--all-files", "--quiet", "--raw", "--stamp"],
&["--hooks-dir"],
),
Sub::Trust => (&["--show", "--revoke"], &[]),
Sub::AgentsMd => (&["--check"], &["--path"]),
Sub::Enroll => (&[], &["--conventions"]),
Sub::Attest => (
&["--require", "--strict"],
&["--signers", "--principal", "--platform", "--tree"],
),
Sub::Check => (&[], &["--stdin-filename", "--format"]),
Sub::Add => (&["--dry-run"], &[]),
Sub::Rehearse => (
&["--wait", "--status", "--stop", "--worker", "--cluster"],
&[],
),
Sub::TreeParity => (&[], &[]),
Sub::Warm => (&["--worker"], &[]),
Sub::Land => (&["--force", "--json", "--dry-run"], &["--tag"]),
Sub::Slot => (&[], &["--weight", "--max-wait", "--on-timeout"]),
Sub::Slots => (&["--json"], &[]),
Sub::Stamps => (&["--json"], &["--tree"]),
Sub::Cluster => (&["--watch"], &[]),
Sub::Migrate => (&["--reverse", "--global", "--tracked"], &[]),
Sub::Doctor => (&[], &[]),
}
}
fn unknown_flag(args: &[OsString], flags: &[&str], valued: &[&str]) -> Option<String> {
let mut skip_value = false;
for a in args {
if skip_value {
skip_value = false;
continue;
}
let Some(a) = a.to_str() else { continue };
if !a.starts_with('-') {
continue;
}
if let Some((name, _)) = a.split_once('=') {
if valued.contains(&name) {
continue;
}
}
if valued.contains(&a) {
skip_value = true;
continue;
}
if !flags.contains(&a) {
return Some(a.to_string());
}
}
None
}
fn verb_name(sub: Sub) -> &'static str {
SUBCOMMANDS
.iter()
.find(|(_, s)| *s == sub)
.map(|(n, _)| *n)
.unwrap_or("?")
}
fn run_sub(sub: Sub, args: &[OsString]) -> i32 {
let settings = greengate_runtime::config::Settings::default();
let own = if sub == Sub::Slot {
greengate_runtime::slot_cmd::split_at_dashes(args).0
} else {
args
};
if sub == Sub::Cluster
&& own.first().is_some_and(|a| a == "sign")
&& !own.iter().any(|a| a == "--version" || a == "-V")
{
return greengate_runtime::cluster::cluster_command(args);
}
if own.iter().any(|a| a == "--help" || a == "-h") {
print!("{USAGE}");
return 0;
}
if own.iter().any(|a| a == "--version" || a == "-V") {
println!("{BIN} {}", env!("CARGO_PKG_VERSION"));
return 0;
}
let (flags, valued) = known_flags(sub);
if let Some(bad) = unknown_flag(own, flags, valued) {
eprintln!("{BIN}: unknown flag {bad:?} for `{}`", verb_name(sub));
eprint!("{USAGE}");
if sub == Sub::Land && args.iter().any(|a| a == "--json") {
println!("{}", greengate_runtime::land::usage_json());
}
return 2;
}
let exempt = matches!(
sub,
Sub::Restore | Sub::Uninstall | Sub::Migrate | Sub::Doctor
) || own.iter().any(|a| a == "--dry-run");
if !exempt {
migrate_first();
}
match sub {
Sub::List => {
let stage = match stage_flag(args) {
Ok(s) => s,
Err(msg) => {
eprintln!("{BIN}: {msg}");
return 2;
}
};
if let Some(line) = greengate_runtime::attest_inputs::deprecated_opt_out() {
eprintln!("{BIN}: {line}");
}
greengate_runtime::list_checks(ListOptions {
json: args.iter().any(|a| a == "--json"),
stage,
pushed: args.iter().any(|a| a == "--pushed"),
all: args.iter().any(|a| a == "--all"),
})
}
Sub::Install => report(greengate_runtime::install::run(
&settings,
args.iter().any(|a| a == "--force"),
)),
Sub::Init => report(greengate_runtime::install::init()),
Sub::Uninstall => {
let binary = args.iter().any(|a| a == "--binary");
if args.iter().any(|a| a == "--repo") {
if binary {
eprintln!("{BIN}: uninstall --repo and --binary are mutually exclusive");
return 2;
}
report(greengate_runtime::install::uninstall_repo())
} else {
report(greengate_runtime::install::uninstall(binary))
}
}
Sub::Setup => report(greengate_runtime::setup::command(args)),
Sub::Restore => report(greengate_runtime::staged_only::restore_command(&settings)),
Sub::Trust => report(greengate_runtime::trust::command(args)),
Sub::Run => run_mode(args),
Sub::AgentsMd => agents_md(args),
Sub::Rehearse => {
greengate_runtime::rehearsal::command(args, greengate_runtime::rehearsal::prestage())
}
Sub::TreeParity => {
let root = greengate_runtime::hooks::common::repo_root();
let root = std::path::Path::new(&root);
let problems = greengate_runtime::hooks::tree_parity::check_repo(root);
for p in &problems {
println!("{}", greengate_runtime::ui::sanitize(&p.to_string()));
}
for p in greengate_runtime::hooks::tree_parity::builtin_drift(root) {
eprintln!(
"warning: {}",
greengate_runtime::ui::sanitize(&p.to_string())
);
}
i32::from(!problems.is_empty())
}
Sub::Warm => {
let root = greengate_runtime::hooks::common::repo_root();
greengate_runtime::tree_lint::warm(std::path::Path::new(&root))
}
Sub::Land => greengate_runtime::land::command(args),
Sub::Slot => greengate_runtime::slot_cmd::slot_command(args),
Sub::Slots => greengate_runtime::slot_cmd::slots_command(args),
Sub::Stamps => stamps_mode(args),
Sub::Cluster => greengate_runtime::cluster::cluster_command(args),
Sub::Migrate => migrate_command(args),
Sub::Doctor => {
let cwd = std::env::current_dir().unwrap_or_default();
let found = match greengate_runtime::migrate::leftovers(
&cwd,
&greengate_runtime::migrate::system_git,
) {
Ok(found) => found,
Err(why) => {
eprintln!("{BIN}: doctor could not look: {why}");
return 2;
}
};
for line in &found {
println!("{}", greengate_runtime::ui::sanitize(line));
}
if found.is_empty() {
eprintln!("no greengate 3.x names left here");
}
eprintln!("{}", greengate_runtime::slot_cmd::doctor_line());
i32::from(!found.is_empty())
}
Sub::Enroll => {
let conventions = match flag_value(args, "--conventions") {
Ok(v) => v,
Err(msg) => {
eprintln!("{BIN}: {msg}");
return 2;
}
};
report(greengate_runtime::install::enroll(conventions.as_deref()))
}
Sub::Add => {
use greengate_runtime::pack;
let dry_run = args.iter().any(|a| a == "--dry-run");
let specs: Vec<&str> = args
.iter()
.filter_map(|a| a.to_str())
.filter(|a| !a.starts_with("--"))
.collect();
if specs.is_empty() {
eprintln!("{BIN}: add needs a source (github:owner/repo, forgejo:host/owner/repo, or a git URL)");
eprint!("{USAGE}");
return 2;
}
let scratch =
std::env::temp_dir().join(format!("greengate-pack-{}", std::process::id()));
let mut fetched: Vec<(String, String, Vec<String>)> = Vec::new();
for (i, spec) in specs.iter().enumerate() {
let outcome = pack::parse_source(spec).and_then(|source| {
let id = pack::resolve(&source)?;
let text = pack::fetch(&source, &id, &scratch.join(i.to_string()))?;
let rows = pack::rows(&text)?;
Ok((source.label, id, rows))
});
match outcome {
Ok(got) => fetched.push(got),
Err(msg) => {
let _ = std::fs::remove_dir_all(&scratch);
eprintln!("{BIN}: {msg}");
return 1;
}
}
}
let _ = std::fs::remove_dir_all(&scratch);
for (label, id, rows) in &fetched {
println!("{label} @ {} declares:", &id[..7.min(id.len())]);
for r in rows {
println!(" {}", greengate_runtime::ui::sanitize(r));
}
}
if dry_run {
println!("--dry-run: nothing written");
return 0;
}
let root = greengate_runtime::hooks::common::repo_root();
let root = std::path::Path::new(&root);
let manifest_file = greengate_runtime::manifest::manifest_name(root);
let path = root.join(manifest_file);
let before = std::fs::read_to_string(&path).unwrap_or_default();
let mut after = before.clone();
for (label, id, rows) in &fetched {
match pack::splice(&after, label, id, rows) {
Ok(next) => after = next,
Err(msg) => {
eprintln!("{BIN}: {msg}");
return 1;
}
}
}
if after == before {
eprintln!("{} already carries exactly this", manifest_file);
return 0;
}
if let Err(e) = std::fs::write(&path, &after) {
eprintln!("{BIN}: cannot write {}: {e}", path.display());
return 1;
}
println!(
"\n{} changed — these commands cannot run until you review them:\n {BIN} trust",
manifest_file
);
0
}
Sub::Check => {
let format = match flag_value(args, "--format") {
Ok(f) => f,
Err(msg) => {
eprintln!("{BIN}: {msg}");
return 2;
}
};
let json = match format.as_deref() {
None | Some("text") => false,
Some("json") => true,
Some(other) => {
eprintln!("{BIN}: unknown --format {other:?} (text or json)");
return 2;
}
};
let stdin_name = match flag_value(args, "--stdin-filename") {
Ok(n) => n,
Err(msg) => {
eprintln!("{BIN}: {msg}");
return 2;
}
};
let mut paths: Vec<String> = Vec::new();
let mut skip = false;
for a in args {
if skip {
skip = false;
continue;
}
let Some(a) = a.to_str() else { continue };
if a == "--format" || a == "--stdin-filename" {
skip = true;
continue;
}
if !a.starts_with("--") {
paths.push(a.to_string());
}
}
let mut findings = Vec::new();
if let Some(name) = &stdin_name {
use std::io::Read;
let mut buf = Vec::new();
if std::io::stdin().read_to_end(&mut buf).is_err() {
eprintln!("{BIN}: could not read stdin");
return 2;
}
findings.extend(greengate_runtime::content::scan(&settings, name, &buf));
} else if paths.is_empty() {
eprintln!("{BIN}: check needs a path, or --stdin-filename <path>");
eprint!("{USAGE}");
return 2;
}
for p in &paths {
match std::fs::read(p) {
Ok(bytes) => {
findings.extend(greengate_runtime::content::scan(&settings, p, &bytes))
}
Err(e) => eprintln!("{BIN}: {p}: {e}"),
}
}
if json {
println!("{}", greengate_runtime::finding::to_json(&findings));
} else {
for f in &findings {
println!("{}", f.render());
}
}
i32::from(
findings
.iter()
.any(|f| f.severity == greengate_runtime::check::Severity::Block),
)
}
Sub::Attest => {
match args.first().and_then(|a| a.to_str()) {
Some("covered") => {}
Some("check-inputs") => return attest_check_inputs(&args[1..]),
_ => {
eprintln!("{BIN}: attest takes the subactions `covered` and `check-inputs`");
eprint!("{USAGE}");
return 2;
}
}
let (signers, principal, platform) = match (
flag_value(args, "--signers"),
flag_value(args, "--principal"),
flag_value(args, "--platform"),
) {
(Ok(s), Ok(p), Ok(pl)) => (s, p, pl),
(Err(msg), _, _) | (_, Err(msg), _) | (_, _, Err(msg)) => {
eprintln!("{BIN}: {msg}");
return 2;
}
};
let Some(signers) = signers
.map(PathBuf::from)
.or_else(greengate_runtime::attest::default_signers)
else {
return 0; };
let want = match platform.as_deref() {
Some("any") => None,
Some(explicit) => Some(explicit.to_string()),
None => Some(greengate_runtime::attest::platform()),
};
let report = greengate_runtime::attest::covered_report(
std::path::Path::new("."),
&signers,
principal.as_deref(),
want.as_deref(),
&[],
);
if let Some(gates) = &report.gates {
println!("{gates}");
}
let strict = args.iter().any(|a| a == "--strict");
if strict && report.gates.is_none() && !report.rejected.is_empty() {
3
} else {
0
}
}
}
}
fn attest_check_inputs(rest: &[OsString]) -> i32 {
let tree = match flag_value(rest, "--tree") {
Ok(t) => t.unwrap_or_else(|| "HEAD".to_string()),
Err(msg) => {
eprintln!("{BIN}: {msg}");
return 2;
}
};
let required: Vec<String> = rest
.iter()
.skip_while(|a| *a != "--require")
.skip(1)
.map_while(|a| a.to_str().filter(|s| !s.starts_with("--")))
.map(String::from)
.collect();
if required.is_empty() {
eprintln!("{BIN}: attest check-inputs needs --require <gate>...");
return 2;
}
match greengate_runtime::attest_inputs::check(&tree, &required) {
Err(e) => {
eprintln!("{}", e.render(&tree));
2
}
Ok(f) if f.is_empty() => {
println!("check-attest-inputs: ok");
0
}
Ok(f) => {
eprint!("{}", f.render());
1
}
}
}
fn flag_value(rest: &[OsString], flag: &str) -> Result<Option<String>, String> {
let mut iter = rest.iter();
while let Some(a) = iter.next() {
if a == flag {
return iter
.next()
.and_then(|v| v.to_str())
.map(|v| Some(v.to_string()))
.ok_or_else(|| format!("{flag} requires a value"));
}
}
Ok(None)
}
fn report(r: Result<(), String>) -> i32 {
match r {
Ok(()) => 0,
Err(e) => {
eprintln!("{e}");
1
}
}
}
fn run_mode(args: &[OsString]) -> i32 {
if args.iter().any(|a| a == "--stamp") {
return stamp_mode(args);
}
let all_files = args.iter().any(|a| a == "--all-files");
let named = args
.iter()
.filter_map(|a| a.to_str())
.find(|a| !a.starts_with("--"))
.map(str::to_owned);
let (manifest, settings) = greengate_runtime::manifest::load_resolved(std::path::Path::new(
&greengate_runtime::hooks::common::repo_root(),
));
if let Some(flag) = args.iter().rev().find(|a| *a == "--quiet" || *a == "--raw") {
settings.override_quiet(if flag == "--quiet" {
greengate_runtime::config::QuietOverride::Quiet
} else {
greengate_runtime::config::QuietOverride::Raw
});
}
let named = match named {
Some(n) if greengate_runtime::registry::lookup(&n, &manifest).is_none() => {
match greengate_runtime::dispatch::resolve_check_name(&n, &manifest) {
greengate_runtime::dispatch::Named2::Resolved(id) => Some(id),
greengate_runtime::dispatch::Named2::Unknown => {
eprintln!("{BIN}: unknown check {n:?} — try `{BIN} list`");
return 2;
}
greengate_runtime::dispatch::Named2::Ambiguous(ids) => {
eprintln!(
"{BIN}: {n:?} names more than one check — pick one: {}",
ids.join(", ")
);
return 2;
}
}
}
other => other,
};
let audits = greengate_runtime::hooks::audit::Ledger::default();
let push = if named
.as_deref()
.is_some_and(|n| needs_synthetic_push_refs(n, &manifest))
{
match pushrefs::synthetic_from_upstream() {
Ok(r) => pushrefs::PushRefs::preloaded(vec![r]),
Err(e) => {
eprintln!("{BIN}: {e}");
return 2;
}
}
} else {
pushrefs::PushRefs::default()
};
let hooks_dir = match hooks_dir_flag(args) {
Ok(Some(d)) => d,
Ok(None) => PathBuf::from(".git/hooks"),
Err(e) => {
eprintln!("{BIN}: {e}");
return 2;
}
};
let name = named.clone().unwrap_or_else(|| "pre-commit".to_string());
let ctx = registry::Ctx {
name: &name,
args: &[],
hooks_dir: &hooks_dir,
push: &push,
manifest: &manifest,
settings: &settings,
handed_to_cluster: greengate_runtime::rehearsal::handed_to_cluster(),
land: greengate_runtime::rehearsal::land_env(),
audits: &audits,
source_worktree: greengate_runtime::rehearsal::source_worktree(),
};
let verdict = match named {
Some(check) => match greengate_runtime::dispatch::run_named(&ctx, &check, all_files) {
greengate_runtime::dispatch::Named::Ran(v) => v,
greengate_runtime::dispatch::Named::Unknown => {
eprintln!("{BIN}: unknown check {check:?} — try `{BIN} list`");
return 2;
}
greengate_runtime::dispatch::Named::Ambiguous(ids) => {
eprintln!(
"{BIN}: {check:?} names more than one check — pick one: {}",
ids.join(", ")
);
return 2;
}
},
None => greengate_runtime::dispatch::run_all(&ctx, all_files),
};
verdict.exit_code()
}
fn positionals(args: &[OsString], valued: &[&str]) -> Vec<String> {
let mut out = Vec::new();
let mut skip = false;
for a in args {
if skip {
skip = false;
continue;
}
let Some(a) = a.to_str() else { continue };
if valued.contains(&a) {
skip = true;
continue;
}
if !a.starts_with('-') {
out.push(a.to_string());
}
}
out
}
fn load_here() -> (
greengate_runtime::manifest::Manifest,
greengate_runtime::config::Settings,
) {
greengate_runtime::manifest::load_resolved(std::path::Path::new(
&greengate_runtime::hooks::common::repo_root(),
))
}
fn stamp_mode(args: &[OsString]) -> i32 {
for (flag, why) in [
("--all-files", "--stamp always judges the whole tree"),
("--quiet", "--stamp prints its own report"),
("--raw", "--stamp prints its own report"),
] {
if args.iter().any(|a| a == flag) {
eprintln!("{BIN}: {why}; drop {flag}");
return 2;
}
}
if args
.iter()
.filter_map(|a| a.to_str())
.any(|a| a == "--hooks-dir" || a.starts_with("--hooks-dir="))
{
eprintln!("{BIN}: --stamp runs the gates itself, not through hooks; drop --hooks-dir");
return 2;
}
let (manifest, settings) = load_here();
let names = positionals(args, &["--hooks-dir"]);
greengate_runtime::run_stamp::stamp(&settings, &manifest, &names)
}
fn stamps_mode(args: &[OsString]) -> i32 {
let tree = match flag_value(args, "--tree") {
Ok(v) => v,
Err(msg) => {
eprintln!("{BIN}: {msg}");
return 2;
}
};
let (manifest, settings) = load_here();
let names = positionals(args, &["--tree"]);
greengate_runtime::run_stamp::stamps_command(
&settings,
&manifest,
if args.iter().any(|a| a == "--json") {
greengate_runtime::run_stamp::Output::Json
} else {
greengate_runtime::run_stamp::Output::Text
},
tree.as_deref(),
&names,
)
}
fn agents_md(args: &[OsString]) -> i32 {
let settings = greengate_runtime::config::Settings::default();
let check_only = args.iter().any(|a| a == "--check");
let path = match path_flag(args) {
Ok(Some(p)) => p,
Ok(None) => match greengate_runtime::hooks::common::repo_root_checked() {
Ok(root) => PathBuf::from(root).join("AGENTS.md"),
Err(e) => {
eprintln!("{BIN}: {e}");
return 2;
}
},
Err(e) => {
eprintln!("{BIN}: {e}");
return 2;
}
};
if check_only {
let pointer_code = pointer_path(&path).map_or(0, |p| {
match greengate_runtime::agents_md::check_pointer(&p) {
Ok(greengate_runtime::agents_md::CheckResult::Drifted) => {
eprintln!(
"{}: signpost drifted from the generated one — run `{BIN} agents-md`",
p.display()
);
1
}
Err(e) => {
eprintln!("{e}");
1
}
Ok(_) => 0,
}
});
let block_code = match greengate_runtime::agents_md::check(&settings, &path) {
Ok(greengate_runtime::agents_md::CheckResult::NotPresent) => {
println!(
"{}: not present (opt-in — run without --check to add it)",
path.display()
);
0
}
Ok(greengate_runtime::agents_md::CheckResult::MatchesGenerated) => {
println!("{}: up to date", path.display());
0
}
Ok(greengate_runtime::agents_md::CheckResult::Drifted) => {
eprintln!(
"{}: drifted from the generated block — run `{BIN} agents-md`",
path.display()
);
1
}
Err(e) => {
eprintln!("{e}");
1
}
};
block_code.max(pointer_code)
} else {
match greengate_runtime::agents_md::write(&settings, &path) {
Ok(()) => {
println!("wrote {}", path.display());
pointer_path(&path).map_or(
0,
|p| match greengate_runtime::agents_md::write_pointer(&p) {
Ok(()) => {
println!("wrote {} (signpost)", p.display());
0
}
Err(e) => {
eprintln!("{e}");
1
}
},
)
}
Err(e) => {
eprintln!("{e}");
1
}
}
}
}
fn pointer_path(block: &std::path::Path) -> Option<PathBuf> {
if block.file_name()? == "CLAUDE.md" {
return None;
}
Some(block.with_file_name("CLAUDE.md"))
}
fn run_hook(hooks_dir: &std::path::Path, hook: &str, args: &[OsString]) -> i32 {
let push = pushrefs::PushRefs::default();
let audits = greengate_runtime::hooks::audit::Ledger::default();
let (manifest, settings) = greengate_runtime::manifest::load_resolved(std::path::Path::new(
&greengate_runtime::hooks::common::repo_root(),
));
let ctx = registry::Ctx {
name: hook,
args,
hooks_dir,
push: &push,
manifest: &manifest,
settings: &settings,
handed_to_cluster: greengate_runtime::rehearsal::handed_to_cluster(),
land: greengate_runtime::rehearsal::land_env(),
audits: &audits,
source_worktree: greengate_runtime::rehearsal::source_worktree(),
};
match registry::lookup(hook, &manifest) {
Some(run_hook) => run_hook(&ctx).exit_code(),
None => greengate_runtime::skew::absorb_newer_hook(hook),
}
}
fn stage_flag(rest: &[OsString]) -> Result<Option<Stage>, String> {
let mut iter = rest.iter();
while let Some(a) = iter.next() {
if a == "--stage" {
let v = iter
.next()
.and_then(|v| v.to_str())
.ok_or_else(|| "--stage requires a value".to_string())?;
return match v {
"pre-commit" => Ok(Some(Stage::PreCommit)),
"pre-push" => Ok(Some(Stage::PrePush)),
other => Err(format!(
"--stage must be `pre-commit` or `pre-push`, got {other:?}"
)),
};
}
}
Ok(None)
}
fn path_flag(rest: &[OsString]) -> Result<Option<PathBuf>, String> {
value_flag(rest, "--path")
}
fn hooks_dir_flag(rest: &[OsString]) -> Result<Option<PathBuf>, String> {
value_flag(rest, "--hooks-dir")
}
fn value_flag(rest: &[OsString], flag: &str) -> Result<Option<PathBuf>, String> {
let mut iter = rest.iter();
while let Some(a) = iter.next() {
if a == flag {
let v = iter
.next()
.ok_or_else(|| format!("{flag} requires a value"))?;
return Ok(Some(PathBuf::from(v)));
}
}
Ok(None)
}
fn needs_synthetic_push_refs(name: &str, manifest: &greengate_runtime::manifest::Manifest) -> bool {
if name == "pre-push" {
return true;
}
if let Some(c) = registry::one_named(name, manifest) {
return c.stage() == Stage::PrePush;
}
registry::CHECKS
.iter()
.any(|c| c.stage == Stage::PrePush && greengate_runtime::skip_suppresses(c.name, name))
}
#[cfg(test)]
mod tests {
use super::*;
fn argv(items: &[&str]) -> Vec<OsString> {
items.iter().map(OsString::from).collect()
}
#[test]
fn a_hook_argument_never_names_a_subcommand() {
for (spelling, _) in SUBCOMMANDS {
let got = parse(argv(&[
"--hooks-dir",
"/d",
"pre-push",
spelling,
"https://example.test/r.git",
]));
assert_eq!(
got,
Invocation::Hook {
hooks_dir: PathBuf::from("/d"),
name: "pre-push".to_string(),
args: argv(&[spelling, "https://example.test/r.git"]),
},
"a remote named {spelling:?} hijacked dispatch"
);
let got = parse(argv(&["--hooks-dir", "/d", "commit-msg", spelling]));
assert_eq!(
got,
Invocation::Hook {
hooks_dir: PathBuf::from("/d"),
name: "commit-msg".to_string(),
args: argv(&[spelling]),
},
"a commit-message file named {spelling:?} hijacked dispatch"
);
}
}
#[test]
fn the_subcommand_table_is_exhaustive() {
for (i, (spelling, sub)) in SUBCOMMANDS.iter().enumerate() {
assert_eq!(sub.index(), i, "{spelling} is at the wrong position");
assert_eq!(
subcommand(spelling),
Some(*sub),
"{spelling} does not round-trip"
);
}
let mut names: Vec<&str> = SUBCOMMANDS.iter().map(|(n, _)| *n).collect();
names.sort_unstable();
let before = names.len();
names.dedup();
assert_eq!(before, names.len(), "a spelling appears twice");
}
#[test]
fn a_subcommand_passes_its_arguments_through_untouched() {
assert_eq!(
parse(argv(&["run", "pre-commit-prettier", "--all-files"])),
Invocation::Sub {
name: Sub::Run,
args: argv(&["pre-commit-prettier", "--all-files"]),
}
);
assert_eq!(
parse(argv(&["agents-md", "--path", "install"])),
Invocation::Sub {
name: Sub::AgentsMd,
args: argv(&["--path", "install"]),
}
);
}
#[test]
fn hooks_dir_after_the_hook_name_is_an_argument_not_a_flag() {
assert_eq!(
parse(argv(&[
"--hooks-dir",
"/d",
"pre-push",
"--hooks-dir",
"origin"
])),
Invocation::Hook {
hooks_dir: PathBuf::from("/d"),
name: "pre-push".to_string(),
args: argv(&["--hooks-dir", "origin"]),
}
);
}
#[test]
fn help_and_emptiness_are_their_own_answers() {
assert_eq!(parse(argv(&["--help"])), Invocation::Help);
assert_eq!(parse(argv(&["-h"])), Invocation::Help);
assert!(matches!(parse(argv(&[])), Invocation::Usage(_)));
assert!(matches!(
parse(argv(&["--hooks-dir"])),
Invocation::Usage(_)
));
assert!(matches!(parse(argv(&["pre-push"])), Invocation::Usage(_)));
}
#[test]
fn help_wins_over_an_unknown_word_but_not_over_a_hook() {
assert_eq!(parse(argv(&["--bogus", "--help"])), Invocation::Help);
assert_eq!(parse(argv(&["--bogus", "-h"])), Invocation::Help);
assert!(matches!(
parse(argv(&["--bogus-flag-for-probe"])),
Invocation::Usage(_)
));
assert!(matches!(
parse(argv(&["--hooks-dir", "/h", "pre-push", "--help"])),
Invocation::Hook { .. }
));
}
#[test]
fn the_usage_block_names_every_subcommand() {
for (spelling, _) in SUBCOMMANDS {
assert!(USAGE.contains(spelling), "usage never mentions {spelling}");
}
assert!(USAGE.contains("--hooks-dir"));
assert!(USAGE.contains("--stage"));
}
}