amont-runtime 1.48.0

The amont hook logic: registry, dispatchers, checks and the trust model
Documentation
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
405
406
407
408
409
410
411
412
413
414
415
//! The three Go hooks: `gofmt`, `go vet`, `go test` — the Rust lane's shape,
//! spoken in Go.
//!
//! Scoped like every other language hook: they fire only when the commit (or
//! push) touches Go, and only under a directory that actually has a `go.mod`.
//! A Python repo never invokes the Go toolchain.
//!
//! Split across the two dispatchers by COST, as the other languages are:
//! `gofmt` and `go vet` are pre-commit (as cargo-fmt and clippy are), `test`
//! is pre-push (as cargo-test and pytest are). Each is a separate check so
//! `hook.skip` can disable them individually.
//!
//! One deliberate difference from cargo: `gofmt` takes FILES, not a manifest
//! root — so the format check is handed exactly the staged `.go` list and
//! never wanders into files this commit did not touch. `vet` and `test` need
//! a module to make sense of imports, so they run per `go.mod` root like
//! cargo runs per `Cargo.toml`.

use super::common::{
    fail, fixing_enabled, hl, ok, repo_root, restage, run as run_tool, staged_files, warn, which,
    Restaged,
};
use crate::check::Outcome;
use crate::git;
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

/// Files that mean "this touches Go". `go.mod` and `go.sum` count: a
/// dependency bump compiles differently without a single `.go` edit, and that
/// is exactly when `go vet` and the test suite earn their keep.
///
/// Exported for the registry's drift guard, like `rust_tools::RUST_PATHS`.
pub const GO_PATHS: &[&str] = &[".go", "go.mod", "go.sum"];

/// What `gofmt` is handed. Exported so `registry.rs` declares the scope from
/// the same constant — see `lint_json_yaml::EXTS` for the drift this prevents.
pub const EXTS: &[&str] = &[".go"];

fn is_go_path(f: &str) -> bool {
    let name = f.rsplit('/').next().unwrap_or(f);
    GO_PATHS.iter().any(|pattern| {
        if pattern.starts_with('.') {
            name.ends_with(pattern)
        } else {
            name == *pattern
        }
    })
}

/// The nearest ancestor of `file` holding a `go.mod`, bounded by the repo —
/// the same walk as `rust_tools::cargo_root_for`, for the same reason: a Go
/// service can live in a subdirectory next to other languages, and the
/// toolchain must run where the module is. `./...` then covers every package
/// from that point.
fn module_root_for(root: &str, file: &str) -> Option<PathBuf> {
    let mut dir = Path::new(root).join(file);
    dir.pop();
    loop {
        if dir.join("go.mod").is_file() {
            return Some(dir);
        }
        if dir == Path::new(root) || !dir.starts_with(root) {
            return None;
        }
        if !dir.pop() {
            return None;
        }
    }
}

fn module_roots<'a>(root: &str, files: impl Iterator<Item = &'a str>) -> Vec<PathBuf> {
    let mut seen = BTreeSet::new();
    for f in files.filter(|f| is_go_path(f)) {
        if let Some(d) = module_root_for(root, f) {
            seen.insert(d);
        }
    }
    seen.into_iter().collect()
}

/// Does the module at `dir` hold a package `./...` would match? A tools
/// module (a `go.mod` with `tool` directives and nothing else) holds none,
/// and `go vet ./...` / `go test ./...` exit 1 there with "matched no
/// packages". The walk skips what `./...` skips: nested modules, `vendor/`,
/// `testdata/` and directories starting with `.` or `_`.
fn has_go_package(dir: &Path) -> bool {
    fn walk(dir: &Path, top: bool) -> bool {
        if !top && dir.join("go.mod").is_file() {
            return false;
        }
        let Ok(entries) = std::fs::read_dir(dir) else {
            return false;
        };
        let mut subdirs = Vec::new();
        for e in entries.flatten() {
            let name = e.file_name();
            let name = name.to_string_lossy();
            let Ok(kind) = e.file_type() else { continue };
            if kind.is_dir() {
                let skipped = name.starts_with('.')
                    || name.starts_with('_')
                    || name == "vendor"
                    || name == "testdata";
                if !skipped {
                    subdirs.push(e.path());
                }
            } else if name.ends_with(".go") {
                return true;
            }
        }
        subdirs.iter().any(|d| walk(d, false))
    }
    walk(dir, true)
}

/// The module roots `go vet` / `go test` can run in: those with a package.
fn package_roots<'a>(root: &str, files: impl Iterator<Item = &'a str>) -> Vec<PathBuf> {
    module_roots(root, files)
        .into_iter()
        .filter(|d| has_go_package(d))
        .collect()
}

/// Run one `go`/`gofmt` invocation in every module root. True when all
/// succeeded.
fn run_in_roots(
    settings: &crate::config::Settings,
    roots: &[PathBuf],
    argv: &[String],
    args: &[&str],
) -> bool {
    let extra: Vec<String> = args.iter().map(|s| (*s).to_string()).collect();
    let mut all_ok = true;
    for dir in roots {
        let d = dir.to_string_lossy().into_owned();
        if !run_tool(settings, &d, argv, &extra) {
            all_ok = false;
        }
    }
    all_ok
}

/// `gofmt -l` over exactly the staged `.go` files: it PRINTS the unformatted
/// ones and exits 0 either way, so the listing decides, not the exit code.
/// A non-zero exit is a parse error in a staged file — the commit has bigger
/// problems, and hiding them behind "formatting is clean" would be a lie.
fn unformatted(
    settings: &crate::config::Settings,
    root: &str,
    gofmt: &str,
    files: &[String],
) -> Option<Vec<String>> {
    let mut cmd = std::process::Command::new(gofmt);
    cmd.arg("-l")
        .args(files)
        .current_dir(root)
        .stdin(std::process::Stdio::null());
    super::common::strip_git_env(&mut cmd);
    let (ran, out) = super::common::capture_within(settings, &mut cmd)?;
    match ran {
        super::common::Ran::TimedOut(budget) => {
            super::common::say_timed_out(gofmt, budget);
            None
        }
        super::common::Ran::Status(s) if !s.success() => {
            // gofmt refused to parse something; its own message says which.
            for line in out.lines() {
                crate::say!("{line}");
            }
            Some(files.to_vec())
        }
        super::common::Ran::Status(_) => Some(
            out.lines()
                .map(str::trim)
                .filter(|l| !l.is_empty())
                .map(String::from)
                .collect(),
        ),
    }
}

pub fn fmt(settings: &crate::config::Settings, _args: &[std::ffi::OsString]) -> Outcome {
    let files = staged_files(EXTS);
    if files.is_empty() {
        return Outcome::Passed;
    }
    let root = repo_root();
    if module_roots(&root, files.iter().map(String::as_str)).is_empty() {
        return Outcome::Passed;
    }
    let Some(gofmt) = which("gofmt") else {
        warn("Go staged but gofmt is not installed — install the Go toolchain.");
        return Outcome::Unavailable;
    };
    let Some(dirty) = unformatted(settings, &root, &gofmt, &files) else {
        return Outcome::Unavailable;
    };
    if dirty.is_empty() {
        ok(settings, "Go formatting is clean");
        return Outcome::Passed;
    }

    // `gofmt -w` rewrites only the files `-l` named — never the whole module,
    // so `restage` never stages anything the author did not stage.
    if fixing_enabled(settings) {
        let argv = vec![gofmt.clone()];
        let mut args: Vec<&str> = vec!["-w"];
        args.extend(dirty.iter().map(String::as_str));
        if run_in_roots(settings, &[PathBuf::from(&root)], &argv, &args) {
            match restage(&files) {
                Restaged::Staged => {
                    ok(settings, "Go reformatted and re-staged");
                    return Outcome::Fixed;
                }
                Restaged::Failed(stuck) => {
                    fail(&format!(
                        "gofmt rewrote these files but {} failed — the index still holds the \
                         UNFORMATTED content: {}",
                        hl("git add"),
                        stuck.join(", ")
                    ));
                    return Outcome::Failed;
                }
                Restaged::Nothing => {}
            }
        }
    }

    fail(&format!(
        "Unformatted Go: {}. Run {}.",
        dirty.join(", "),
        hl("gofmt -w .")
    ));
    Outcome::Failed
}

pub fn vet(settings: &crate::config::Settings, _args: &[std::ffi::OsString]) -> Outcome {
    // Basename-matched like `is_rust_path`, so `vendor/Notgo.mod` is not a
    // module marker.
    let files: Vec<String> = staged_files(&[])
        .into_iter()
        .filter(|f| is_go_path(f))
        .collect();
    if files.is_empty() {
        return Outcome::Passed;
    }
    let root = repo_root();
    let roots = package_roots(&root, files.iter().map(String::as_str));
    if roots.is_empty() {
        return Outcome::Passed;
    }
    let Some(go) = which("go") else {
        warn("Go staged but the go toolchain is not installed.");
        return Outcome::Unavailable;
    };
    if run_in_roots(settings, &roots, &[go], &["vet", "./..."]) {
        ok(settings, "go vet passed");
        Outcome::Passed
    } else {
        fail(&format!("{} found problems.", hl("go vet")));
        Outcome::Failed
    }
}

/// pre-push. Mirrors `cargo-test`: the range actually being pushed decides
/// whether the suite runs, per ref, against the pushed tree — a docs-only
/// push costs nothing, and a multi-ref push tests each tip in its own
/// worktree.
pub fn test(
    settings: &crate::config::Settings,
    refs: &[crate::pushrefs::PushRef],
    gate: &str,
) -> Outcome {
    let Some(root) = git::stdout(&["rev-parse", "--show-toplevel"]) else {
        warn("go-test: git would not answer — the gate did NOT run");
        return Outcome::Unavailable;
    };
    let zero = git::stdout(&["hash-object", "--stdin"])
        .map(|h| "0".repeat(h.len()))
        .unwrap_or_else(|| "0".repeat(40));
    let mut ran_any = false;
    for r in refs {
        let changed = crate::pushrefs::changed_files_for(r, &zero);
        let roots = package_roots(&root, changed.iter().map(String::as_str));
        if roots.is_empty() {
            continue;
        }
        let Some(go) = which("go") else {
            warn("Go changed but the go toolchain is not installed — the gate did NOT run");
            return Outcome::Unavailable;
        };
        // Where THIS ref's suite runs decides what it is answering about —
        // the pushed commits, not whatever is open in the editor.
        let (where_, _guard) =
            crate::pushed_tree::where_to_run(settings, &r.local_oid, &root, gate);
        let roots: Vec<PathBuf> = roots
            .iter()
            .map(|rt| {
                rt.strip_prefix(&root)
                    .map(|rel| where_.join(rel))
                    .unwrap_or_else(|_| rt.clone())
            })
            .collect();
        if !run_in_roots(
            settings,
            &roots,
            std::slice::from_ref(&go),
            &["test", "./..."],
        ) {
            fail("Go tests failed. Push aborted.");
            return Outcome::Failed;
        }
        ran_any = true;
    }
    if ran_any {
        ok(settings, "Go tests passed");
    }
    Outcome::Passed
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn recognises_go_paths() {
        assert!(is_go_path("cmd/api/main.go"));
        assert!(is_go_path("go.mod"));
        assert!(is_go_path("services/auth/go.sum"));
        assert!(!is_go_path("README.md"));
        assert!(!is_go_path("main.gone"));
        // A file merely CONTAINING the name is not the module file.
        assert!(!is_go_path("docs/go.mod.md"));
        assert!(!is_go_path("vendor/Notgo.mod"));
    }

    #[test]
    fn finds_the_nearest_module_not_the_repo_root() {
        let tmp = std::env::temp_dir().join("amont-go-roots");
        let _ = std::fs::remove_dir_all(&tmp);
        let nested = tmp.join("services/api");
        std::fs::create_dir_all(nested.join("cmd")).unwrap();
        std::fs::write(nested.join("go.mod"), "module api\n").unwrap();
        let root = tmp.to_string_lossy().into_owned();

        let got = module_roots(&root, ["services/api/cmd/main.go"].into_iter());
        assert_eq!(got, vec![nested.clone()], "should find the nested module");

        // A Go file with no go.mod anywhere above it is not a module.
        std::fs::create_dir_all(tmp.join("scripts")).unwrap();
        let none = module_roots(&root, ["scripts/loose.go"].into_iter());
        assert!(none.is_empty(), "no module above it: {none:?}");
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn several_files_in_one_module_yield_one_root() {
        let tmp = std::env::temp_dir().join("amont-go-dedupe");
        let _ = std::fs::remove_dir_all(&tmp);
        std::fs::create_dir_all(tmp.join("pkg")).unwrap();
        std::fs::write(tmp.join("go.mod"), "module x\n").unwrap();
        let root = tmp.to_string_lossy().into_owned();
        let got = module_roots(&root, ["pkg/a.go", "pkg/b.go", "go.mod"].into_iter());
        assert_eq!(got.len(), 1, "one go invocation, not three: {got:?}");
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn a_tools_module_without_packages_is_not_vetted_or_tested() {
        let tmp = std::env::temp_dir().join("amont-go-tools-module");
        let _ = std::fs::remove_dir_all(&tmp);
        let w = |rel: &str, text: &str| {
            let p = tmp.join(rel);
            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
            std::fs::write(p, text).unwrap();
        };
        w("go.mod", "module op\n");
        w("internal/x/x.go", "package x\n");
        w(
            "tools/go.mod",
            "module tools\n\ntool golang.org/x/tools/gopls\n",
        );
        w("tools/go.sum", "");
        // What `./...` skips does not count as a package of `tools`.
        w("tools/vendor/v/v.go", "package v\n");
        w("tools/testdata/t.go", "package t\n");
        w("tools/_ignored/i.go", "package i\n");
        w("tools/.hidden/h.go", "package h\n");
        // Nor does a nested module's code.
        w("tools/nested/go.mod", "module nested\n");
        w("tools/nested/n.go", "package nested\n");
        let root = tmp.to_string_lossy().into_owned();
        let files = ["tools/go.mod", "tools/go.sum", "internal/x/x.go"];
        assert_eq!(
            module_roots(&root, files.into_iter()),
            vec![tmp.clone(), tmp.join("tools")],
            "both are modules"
        );
        assert_eq!(
            package_roots(&root, files.into_iter()),
            vec![tmp.clone()],
            "only the module with a package is vetted and tested"
        );
        // A package in any ordinary subdirectory keeps the module.
        w("tools/gen/main.go", "package main\n");
        assert_eq!(package_roots(&root, files.into_iter()).len(), 2);
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn non_go_files_select_nothing() {
        let got = module_roots("/tmp", ["README.md", "a.rs"].into_iter());
        assert!(got.is_empty());
    }
}