greengate 4.10.0

Opinionated git hooks that judge what you are committing, not what is on disk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! What the binary does with its argument list, driven through the real binary.
//!
//! The parse is unit-tested next to itself in `src/main.rs`, and that test
//! proves the ARGV maps to the right `Invocation`. This file proves the other
//! half, which a unit test structurally cannot: that dispatching on a hook
//! argument does not actually run the installer. The failure being guarded
//! against is not a wrong enum value — it is `git push` copying a binary into
//! `~/.local/bin`, populating a template directory, and baking shims, because
//! somebody's remote is called `install`.
//!
//! So every assertion here is about the FILESYSTEM and the exit code, with HOME
//! and XDG_CONFIG_HOME inside the sandbox: if a subcommand ran, it left
//! evidence, and the evidence is what is checked.

use std::path::{Path, PathBuf};
use std::process::Command;

/// Same shape as `tests/it/install.rs`'s sandbox, and for the same reason: a bug
/// in the code under test must not be able to reach the developer's real
/// configuration. Duplicated rather than shared because a `tests/common` module
/// that two files pull different halves of is how helpers grow parameters
/// nobody uses.
struct Sandbox(PathBuf);

impl Sandbox {
    fn new(name: &str) -> Self {
        let d = std::env::temp_dir().join(format!("gh-cli-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).expect("mkdir");
        Sandbox(d)
    }
    /// Joined component by component, NOT `join("a/b")` — see tests/it/install.rs.
    fn path(&self, rel: &str) -> PathBuf {
        rel.split('/').fold(self.0.clone(), |p, c| p.join(c))
    }
    fn run(&self, cwd: &Path, args: &[&str]) -> (i32, String) {
        let out = crate::common::amont_cmd()
            .args(args)
            .current_dir(cwd)
            .env("HOME", &self.0)
            .env("USERPROFILE", &self.0)
            .env("XDG_CONFIG_HOME", self.path(".config"))
            .output()
            .expect("run amont");
        (
            out.status.code().unwrap_or(-1),
            format!(
                "{}{}",
                String::from_utf8_lossy(&out.stdout),
                String::from_utf8_lossy(&out.stderr)
            ),
        )
    }
    /// Nothing a subcommand would have left behind.
    fn assert_nothing_was_installed(&self, repo: &Path, context: &str) {
        for n in ["amont", "amont.exe"] {
            assert!(
                !self.path(".local/bin").join(n).exists(),
                "{context}: the INSTALLER RAN — a binary appeared in ~/.local/bin"
            );
        }
        let tpl = self.path(".config/git/git-templates/templates/hooks");
        for name in DISPATCHERS {
            assert!(
                !tpl.join(name).exists(),
                "{context}: a template shim was written"
            );
            assert!(
                !repo.join(".git/hooks").join(name).exists(),
                "{context}: a repo shim was baked"
            );
        }
        assert!(
            !repo.join("AGENTS.md").exists(),
            "{context}: agents-md ran and wrote AGENTS.md"
        );
    }
}

impl Drop for Sandbox {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

const DISPATCHERS: [&str; 6] = [
    "commit-msg",
    "post-commit",
    "post-rewrite",
    "pre-commit",
    "pre-push",
    "prepare-commit-msg",
];

/// Every verb the dispatch table holds. Spelled out here on purpose: this file
/// is the outside view, and it should fail if the binary quietly grows a verb
/// that is not covered.
const VERBS: [&str; 7] = [
    "list",
    "install",
    "uninstall",
    "run",
    "trust",
    "restore",
    "agents-md",
];

fn git(dir: &Path, args: &[&str]) {
    Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .output()
        .expect("git");
}

fn init_repo(dir: &Path) {
    std::fs::create_dir_all(dir).expect("mkdir");
    git(dir, &["init", "-q", "--template=", "."]);
    git(dir, &["config", "user.email", "t@t.test"]);
    git(dir, &["config", "user.name", "t"]);
}

/// The verified bug: `amont --hooks-dir <d> pre-push <remote> <url>` is what
/// the pre-push shim execs, and dispatch was reading `<remote>`. A remote named
/// `install` ran the FULL INSTALLER mid-push; a remote named `run`, `list`,
/// `trust`, `restore` or `uninstall` made the hook a no-op that exited 0 — a
/// push with zero checks, reported as a pass.
///
/// Asserted on the filesystem rather than on the exit code, because "exited 0"
/// is precisely what the broken version did.
#[test]
fn a_remote_named_like_a_subcommand_still_runs_the_hook() {
    for verb in VERBS {
        let s = Sandbox::new(&format!("remote-{}", verb.replace('-', "")));
        let repo = s.path("repo");
        init_repo(&repo);
        let hooks = repo.join(".git/hooks");
        std::fs::create_dir_all(&hooks).expect("mkdir");

        let (_, out) = s.run(
            &repo,
            &[
                "--hooks-dir",
                hooks.to_str().expect("utf8"),
                "pre-push",
                verb,
                "https://example.test/r.git",
            ],
        );
        s.assert_nothing_was_installed(&repo, &format!("remote named {verb:?}, output:\n{out}"));
    }
}

/// The same for the first argument of a `commit-msg` hook, which git hands a
/// PATH. A repository whose commit-message template lives at a file called
/// `install` is not a thing anybody plans, but it is a thing `git commit`
/// would have run the installer over.
#[test]
fn a_hook_argument_that_is_a_file_named_install_reaches_the_hook_verbatim() {
    let s = Sandbox::new("literal-install");
    let repo = s.path("repo");
    init_repo(&repo);
    let hooks = repo.join(".git/hooks");
    std::fs::create_dir_all(&hooks).expect("mkdir");

    // A commit message file literally named `install`, with a subject the
    // commit-msg check will reject — so we can tell the hook actually READ this
    // file rather than dispatching on its name.
    let msg = repo.join("install");
    std::fs::write(
        &msg,
        "not a conventional subject at all, and far too long to pass\n",
    )
    .expect("write");

    let (code, out) = s.run(
        &repo,
        &[
            "--hooks-dir",
            hooks.to_str().expect("utf8"),
            "commit-msg",
            msg.to_str().expect("utf8"),
        ],
    );
    s.assert_nothing_was_installed(&repo, &format!("output:\n{out}"));
    assert_eq!(
        code, 1,
        "the commit-msg check did not read the file it was handed:\n{out}"
    );
    assert!(
        std::fs::read_to_string(&msg)
            .expect("read")
            .starts_with("not a conventional"),
        "the hook argument was treated as something other than a path"
    );
}

/// A subcommand's own arguments are passed through verbatim, including ones
/// spelled like other subcommands.
#[test]
fn a_subcommand_argument_spelled_like_a_verb_is_just_a_value() {
    let s = Sandbox::new("verb-value");
    let repo = s.path("repo");
    init_repo(&repo);

    // `--path install` must write AGENTS.md content to a file called `install`,
    // not run the installer.
    let (code, out) = s.run(&repo, &["agents-md", "--path", "install"]);
    assert_eq!(code, 0, "{out}");
    assert!(
        repo.join("install").is_file(),
        "--path was not honoured:\n{out}"
    );
    for n in ["amont", "amont.exe"] {
        assert!(
            !s.path(".local/bin").join(n).exists(),
            "THE INSTALLER RAN from an argument value:\n{out}"
        );
    }
}

/// Asking a program what it does must not be answered with "you used it
/// wrong". `--help` exited 2 with a single line naming `--hooks-dir` and none
/// of the seven verbs.
#[test]
fn help_exits_zero_and_describes_the_program() {
    let s = Sandbox::new("help");
    let plain = s.path("plain");
    std::fs::create_dir_all(&plain).expect("mkdir");

    for flag in ["--help", "-h"] {
        let (code, out) = s.run(&plain, &[flag]);
        assert_eq!(code, 0, "{flag} exited {code}:\n{out}");
        for verb in VERBS {
            assert!(out.contains(verb), "{flag} never mentions {verb}:\n{out}");
        }
        assert!(out.contains("--hooks-dir"), "{out}");
        assert!(out.contains("--stage"), "{out}");
        // The repository moved to greenharness/greengate (2026-11-08); the old
        // fredericrous.github.io manual does not redirect.
        assert!(
            out.contains("https://greenharness.github.io/greengate/"),
            "{flag} does not name the manual's new home:\n{out}"
        );
    }
}

/// No arguments is a usage error, and a usage error says why AND shows the
/// same block `--help` shows.
#[test]
fn no_arguments_is_a_usage_error_that_still_explains_itself() {
    let s = Sandbox::new("noargs");
    let plain = s.path("plain");
    std::fs::create_dir_all(&plain).expect("mkdir");

    let (code, out) = s.run(&plain, &[]);
    assert_eq!(code, 2, "{out}");
    assert!(out.contains("agents-md"), "{out}");
    assert!(out.contains("--hooks-dir"), "{out}");
}

/// A help request is inert in ANY position. `amont install --help` used to
/// run the full installer — copy the binary, populate the template dir —
/// because `--help` was only recognized as argv[0].
#[test]
fn help_after_a_verb_mutates_nothing() {
    let s = Sandbox::new("help-inert");
    let repo = s.path("repo");
    std::fs::create_dir_all(&repo).expect("mkdir");
    for verb in ["install", "init", "uninstall", "trust", "run", "setup"] {
        let (code, out) = s.run(&repo, &[verb, "--help"]);
        assert_eq!(code, 0, "{verb} --help must exit 0:\n{out}");
        assert!(
            out.contains("usage:"),
            "{verb} --help must print usage:\n{out}"
        );
    }
    s.assert_nothing_was_installed(&repo, "after --help on every verb");
}

/// A six-channel-distributed binary must answer what version it is.
#[test]
fn version_prints_the_crate_version() {
    let s = Sandbox::new("version");
    let repo = s.path("repo");
    std::fs::create_dir_all(&repo).expect("mkdir");
    for args in [&["--version"][..], &["-V"][..], &["list", "--version"][..]] {
        let (code, out) = s.run(&repo, args);
        assert_eq!(code, 0, "{args:?}:\n{out}");
        assert!(
            out.trim() == format!("greengate {}", env!("CARGO_PKG_VERSION")),
            "{args:?} must name the version:\n{out}"
        );
    }
    s.assert_nothing_was_installed(&repo, "after --version");
}

/// A typo'd flag is a hard usage error, not a silent no-op. `amont trust
/// --revok` used to fall through the `--revoke` test and GRANT trust.
#[test]
fn an_unknown_flag_is_a_usage_error_not_a_no_op() {
    let s = Sandbox::new("strict-flags");
    let repo = s.path("repo");
    std::fs::create_dir_all(&repo).expect("mkdir");
    for (args, bad) in [
        (&["trust", "--revok"][..], "--revok"),
        (&["install", "--frce"][..], "--frce"),
        (&["list", "--jsn"][..], "--jsn"),
        (&["uninstall", "--binray"][..], "--binray"),
        (&["run", "--all-file"][..], "--all-file"),
    ] {
        let (code, out) = s.run(&repo, args);
        assert_eq!(code, 2, "{args:?} must be a usage error:\n{out}");
        assert!(out.contains(bad), "{args:?} must name the flag:\n{out}");
    }
    s.assert_nothing_was_installed(&repo, "after typo'd flags");
}

/// A hook name this binary has never heard, arriving through hook mode, is
/// a shim from a NEWER template — age, not misuse. It must absorb (exit 0,
/// git ignores hooks that do not exist), warn exactly once per binary
/// version per repository, and leave a versioned marker `uninstall` cleans.
/// Before this, the day a new shim shipped, every machine with an older
/// binary printed `unknown hook` at exit 2 on every commit.
#[test]
fn a_hook_from_a_newer_template_is_absorbed_not_erred() {
    let s = Sandbox::new("newer-shim");
    let repo = s.path("repo");
    init_repo(&repo);
    let hooks = repo.join(".git/hooks");
    std::fs::create_dir_all(&hooks).expect("mkdir");
    let hooks_dir = hooks.to_str().expect("utf8").to_string();

    // First encounter: exit 0, one clear warning naming the fix.
    let (code, out) = s.run(
        &repo,
        &["--hooks-dir", &hooks_dir, "post-merge-from-the-future"],
    );
    assert_eq!(code, 0, "a newer shim must not fail the commit: {out}");
    assert!(
        out.contains("newer than this binary"),
        "the first encounter explains itself: {out}"
    );
    assert!(
        repo.join(".git/greengate-skew").is_file(),
        "the warning leaves its once-per-version marker"
    );

    // Second encounter, same version: silent. Even for a DIFFERENT unknown
    // hook — the message is about the binary's age, not about one name.
    let (code, out) = s.run(&repo, &["--hooks-dir", &hooks_dir, "another-future-hook"]);
    assert_eq!(code, 0, "{out}");
    assert!(
        out.trim().is_empty(),
        "once per binary version means once: {out:?}"
    );
}

/// The same unknown token WITHOUT --hooks-dir is still a loud usage error —
/// a person typed it, and silence would strand them.
#[test]
fn an_unknown_verb_stays_a_loud_usage_error() {
    let s = Sandbox::new("unknown-verb");
    let repo = s.path("repo");
    init_repo(&repo);
    let (code, out) = s.run(&repo, &["post-merge-from-the-future"]);
    assert_ne!(code, 0, "an interactive typo must not pass silently: {out}");
    assert!(!out.trim().is_empty(), "and it must say something");
}

/// `uninstall` forgets the skew marker with the rest of our bookkeeping.
#[test]
fn uninstall_forgets_the_skew_marker() {
    let s = Sandbox::new("skew-forget");
    let repo = s.path("repo");
    init_repo(&repo);
    let hooks = repo.join(".git/hooks");
    std::fs::create_dir_all(&hooks).expect("mkdir");
    let hooks_dir = hooks.to_str().expect("utf8").to_string();
    let (_, _) = s.run(
        &repo,
        &["--hooks-dir", &hooks_dir, "post-merge-from-the-future"],
    );
    assert!(repo.join(".git/greengate-skew").is_file());
    let (code, out) = s.run(&repo, &["uninstall"]);
    assert_eq!(code, 0, "{out}");
    assert!(
        !repo.join(".git/greengate-skew").exists(),
        "the marker is OUR bookkeeping — gone with the hooks"
    );
}

/// Every message names the program by the name it ships under.
#[test]
fn an_unknown_subcommand_error_starts_with_the_shipped_name() {
    let s = Sandbox::new("unknown-subcommand");
    let repo = s.path("repo");
    std::fs::create_dir_all(&repo).expect("mkdir");
    let (code, out) = s.run(&repo, &["frobnicate"]);
    assert_eq!(code, 2, "{out}");
    assert!(out.starts_with("greengate: "), "{out}");
    s.assert_nothing_was_installed(&repo, "after an unknown subcommand");
}