1use std::ffi::OsString;
15use std::path::Path;
16
17use crate::check::{
18 Builtin, Check, Fix, GitState, Outcome, Reach, Scope, Severity, Stage, Verdict,
19};
20use crate::pushrefs::PushRefs;
21use crate::{dispatch, hooks};
22
23pub struct Ctx<'a> {
27 pub name: &'a str,
29 pub args: &'a [OsString],
31 pub hooks_dir: &'a Path,
34 pub push: &'a PushRefs,
37 pub manifest: &'a crate::manifest::Manifest,
41 pub settings: &'a crate::config::Settings,
46 pub handed_to_cluster: &'a [String],
50 pub land: &'a crate::rehearsal::LandEnv,
53 pub audits: &'a crate::hooks::audit::Ledger,
56 pub source_worktree: Option<&'a std::path::Path>,
59}
60
61pub type HookFn = fn(&Ctx) -> Verdict;
62
63pub const ENTRYPOINTS: &[(&str, HookFn)] = &[
66 ("pre-commit", dispatch::pre_commit),
67 ("pre-push", dispatch::pre_push),
68 ("commit-msg", |ctx| {
75 if !dispatch::conventions_apply(ctx.settings, ctx.manifest) {
76 return Verdict::Proceed;
77 }
78 hooks::commit_msg::run(ctx.settings, ctx.args)
79 }),
80 ("prepare-commit-msg", |ctx| {
81 if !dispatch::conventions_apply(ctx.settings, ctx.manifest) {
82 return Verdict::Proceed;
83 }
84 hooks::prepare_commit_msg::run(ctx.args)
85 }),
86 ("post-commit", |ctx| {
87 hooks::post_commit::run(ctx.settings, ctx)
88 }),
89 ("post-rewrite", |ctx| {
92 hooks::post_rewrite::run(ctx.settings, ctx)
93 }),
94];
95
96const MID_OPERATION: &[GitState] = &[
115 GitState::Merge,
116 GitState::Rebase,
117 GitState::CherryPick,
118 GitState::Revert,
119];
120
121pub const CHECKS: &[Builtin] = &[
122 Builtin {
127 name: "pre-commit-agents-md",
128 stage: Stage::PreCommit,
129 scope: Scope::ALWAYS.not_during(MID_OPERATION),
130 severity: Severity::Warn,
131 fix: Fix::Rewrite,
132 reach: Reach::Convention,
133 run: |ctx| hooks::agents_md_drift::run(ctx.settings),
134 },
135 Builtin {
136 name: "pre-commit-argo-lint",
137 stage: Stage::PreCommit,
138 scope: Scope::new(
139 hooks::k8s::EXTS,
140 &["kustomization.yaml", "kustomization.yml"],
141 )
142 .not_during(MID_OPERATION),
143 severity: Severity::Block,
144 fix: Fix::None,
145 reach: Reach::Convention,
146 run: |ctx| hooks::k8s::argo_lint(ctx.settings, ctx.args),
147 },
148 Builtin {
149 name: "pre-commit-ban-terms",
150 stage: Stage::PreCommit,
151 scope: Scope::files(hooks::ban_terms::EXTS),
152 severity: Severity::Block,
153 fix: Fix::None,
154 reach: Reach::Safety,
155 run: |ctx| hooks::ban_terms::run(ctx.settings, ctx.name, ctx.args),
156 },
157 Builtin {
162 name: "pre-commit-branch-pattern",
163 stage: Stage::PreCommit,
164 scope: Scope::ALWAYS,
165 severity: Severity::Warn,
166 fix: Fix::None,
167 reach: Reach::Convention,
168 run: |ctx| hooks::branch_pattern::early(ctx.settings),
169 },
170 Builtin {
175 name: "pre-commit-branch-protect",
176 stage: Stage::PreCommit,
177 scope: Scope::ALWAYS,
178 severity: Severity::Warn,
179 fix: Fix::None,
180 reach: Reach::Convention,
181 run: |ctx| hooks::branch_protect::early(ctx.settings),
182 },
183 Builtin {
184 name: "pre-commit-cargo-fmt",
185 stage: Stage::PreCommit,
186 scope: Scope::new(hooks::rust_tools::EXTS, &["Cargo.toml"]).not_during(MID_OPERATION),
187 severity: Severity::Block,
188 fix: Fix::Rewrite,
189 reach: Reach::Convention,
190 run: |ctx| hooks::rust_tools::fmt(ctx.settings, ctx.args),
191 },
192 Builtin {
193 name: "pre-commit-clippy",
194 stage: Stage::PreCommit,
195 scope: Scope::new(hooks::rust_tools::EXTS, &["Cargo.toml"]).not_during(MID_OPERATION),
200 severity: Severity::Block,
201 fix: Fix::None,
202 reach: Reach::Convention,
203 run: |ctx| hooks::rust_tools::clippy(ctx.settings, ctx.args),
204 },
205 Builtin {
206 name: "pre-commit-go-vet",
207 stage: Stage::PreCommit,
208 scope: Scope::new(hooks::go_tools::EXTS, &["go.mod"]).not_during(MID_OPERATION),
209 severity: Severity::Block,
210 fix: Fix::None,
211 reach: Reach::Convention,
212 run: |ctx| hooks::go_tools::vet(ctx.settings, ctx.args),
213 },
214 Builtin {
215 name: "pre-commit-gofmt",
216 stage: Stage::PreCommit,
217 scope: Scope::new(hooks::go_tools::EXTS, &["go.mod"]).not_during(MID_OPERATION),
218 severity: Severity::Block,
219 fix: Fix::Rewrite,
220 reach: Reach::Convention,
221 run: |ctx| hooks::go_tools::fmt(ctx.settings, ctx.args),
222 },
223 Builtin {
224 name: "pre-commit-kube-linter",
225 stage: Stage::PreCommit,
226 scope: Scope::new(
227 hooks::k8s::EXTS,
228 &[".kube-linter*.yaml", ".kube-linter*.yml"],
229 )
230 .not_during(MID_OPERATION),
231 severity: Severity::Block,
232 fix: Fix::None,
233 reach: Reach::Convention,
234 run: |ctx| hooks::k8s::kube_linter(ctx.settings, ctx.args),
235 },
236 Builtin {
237 name: "pre-commit-kubeconform",
238 stage: Stage::PreCommit,
239 scope: Scope::new(
240 hooks::k8s::EXTS,
241 &["kustomization.yaml", "kustomization.yml"],
242 )
243 .not_during(MID_OPERATION),
244 severity: Severity::Block,
245 fix: Fix::None,
246 reach: Reach::Convention,
247 run: |ctx| hooks::k8s::kubeconform(ctx.settings, ctx.args),
248 },
249 Builtin {
250 name: "pre-commit-large-files",
251 stage: Stage::PreCommit,
252 scope: Scope::ALWAYS,
253 severity: Severity::Block,
254 fix: Fix::None,
255 reach: Reach::Safety,
256 run: |ctx| hooks::large_files::staged(ctx.settings),
257 },
258 Builtin {
259 name: "pre-commit-lint-js",
260 stage: Stage::PreCommit,
261 scope: Scope::new(hooks::lint_js::EXTS, &["package.json"]).not_during(MID_OPERATION),
262 severity: Severity::Block,
263 fix: Fix::None,
264 reach: Reach::Convention,
265 run: |ctx| hooks::lint_js::run(ctx.settings, ctx.args),
266 },
267 Builtin {
268 name: "pre-commit-lint-json-yaml",
269 stage: Stage::PreCommit,
270 scope: Scope::files(hooks::lint_json_yaml::EXTS).not_during(MID_OPERATION),
271 severity: Severity::Block,
272 fix: Fix::None,
273 reach: Reach::Convention,
274 run: |ctx| hooks::lint_json_yaml::run(ctx.settings, ctx.args),
275 },
276 Builtin {
282 name: "pre-commit-manifest-trust",
283 stage: Stage::PreCommit,
284 scope: Scope::named(&[crate::manifest::MANIFEST]).not_during(MID_OPERATION),
285 severity: Severity::Block,
286 fix: Fix::None,
287 reach: Reach::Safety,
288 run: |ctx| hooks::manifest_trust::run(ctx.settings, ctx.manifest),
289 },
290 Builtin {
291 name: "pre-commit-merge-conflict",
292 stage: Stage::PreCommit,
293 scope: Scope::ALWAYS,
294 severity: Severity::Block,
295 fix: Fix::None,
296 reach: Reach::Safety,
297 run: |ctx| hooks::merge_conflict::run(ctx.settings, ctx.name, ctx.args),
298 },
299 Builtin {
300 name: "pre-commit-package-lock",
301 stage: Stage::PreCommit,
302 scope: Scope::new(&[], &["package.json"]),
303 severity: Severity::Block,
304 fix: Fix::None,
305 reach: Reach::Convention,
306 run: |ctx| hooks::package_lock::run(ctx.settings, ctx.args),
307 },
308 Builtin {
309 name: "pre-commit-prettier",
310 stage: Stage::PreCommit,
311 scope: Scope::new(
312 &[],
313 &[
316 ".prettierrc",
317 ".prettierrc.json",
318 ".prettierrc.yml",
319 ".prettierrc.yaml",
320 ".prettierrc.js",
321 ".prettierrc.cjs",
322 ".prettierrc.mjs",
323 ".prettierrc.toml",
324 "prettier.config.js",
325 "prettier.config.mjs",
326 "prettier.config.cjs",
327 ],
328 )
329 .not_during(MID_OPERATION),
330 severity: Severity::Block,
331 fix: Fix::Rewrite,
332 reach: Reach::Convention,
333 run: |ctx| hooks::prettier::run(ctx.settings, ctx.args),
334 },
335 Builtin {
336 name: "pre-commit-pyright",
337 stage: Stage::PreCommit,
338 scope: Scope::new(
339 hooks::python_tools::EXTS,
340 &[
341 "pyrightconfig.json",
342 "pyrightconfig.jsonc",
343 "pyproject.toml",
344 ],
345 )
346 .not_during(MID_OPERATION),
347 severity: Severity::Block,
348 fix: Fix::None,
349 reach: Reach::Convention,
350 run: |ctx| hooks::python_tools::pyright(ctx.settings, ctx.args),
351 },
352 Builtin {
353 name: "pre-commit-ruff",
354 stage: Stage::PreCommit,
355 scope: Scope::new(
356 hooks::python_tools::EXTS,
357 &["ruff.toml", ".ruff.toml", "pyproject.toml"],
358 )
359 .not_during(MID_OPERATION),
360 severity: Severity::Block,
361 fix: Fix::Rewrite,
362 reach: Reach::Convention,
363 run: |ctx| hooks::python_tools::ruff(ctx.settings, ctx.args),
364 },
365 Builtin {
369 name: "pre-commit-secrets",
370 stage: Stage::PreCommit,
371 scope: Scope::ALWAYS,
372 severity: Severity::Block,
373 fix: Fix::None,
374 reach: Reach::Safety,
375 run: |ctx| hooks::secrets::staged(ctx.settings),
376 },
377 Builtin {
383 name: "pre-commit-tree-parity",
384 stage: Stage::PreCommit,
385 scope: Scope {
386 files: hooks::k8s::EXTS,
387 names: &[crate::manifest::MANIFEST],
388 dirs: &[],
389 opt_in: &[crate::manifest::MANIFEST],
390 not_during: MID_OPERATION,
391 },
392 severity: Severity::Block,
393 fix: Fix::None,
394 reach: Reach::Convention,
395 run: |ctx| hooks::tree_parity::run(ctx.settings),
396 },
397 Builtin {
398 name: "pre-commit-usual-name",
399 stage: Stage::PreCommit,
400 scope: Scope::ALWAYS,
401 severity: Severity::Block,
402 fix: Fix::None,
403 reach: Reach::Convention,
404 run: |ctx| hooks::usual_name::run(ctx.args),
405 },
406 Builtin {
407 name: "pre-commit-shellcheck",
408 stage: Stage::PreCommit,
409 scope: Scope::files(hooks::shellcheck::EXTS).not_during(MID_OPERATION),
412 severity: Severity::Block,
413 fix: Fix::None,
414 reach: Reach::Convention,
415 run: |ctx| hooks::shellcheck::run(ctx.settings, ctx.args),
416 },
417 Builtin {
418 name: "pre-commit-hadolint",
419 stage: Stage::PreCommit,
420 scope: Scope::named(hooks::hadolint::NAMES).not_during(MID_OPERATION),
424 severity: Severity::Block,
425 fix: Fix::None,
426 reach: Reach::Convention,
427 run: |ctx| hooks::hadolint::run(ctx.settings, ctx.args),
428 },
429 Builtin {
430 name: "pre-commit-helm-lint",
431 stage: Stage::PreCommit,
432 scope: Scope::new(hooks::helm::EXTS, hooks::helm::MARKERS).not_during(MID_OPERATION),
435 severity: Severity::Block,
436 fix: Fix::None,
437 reach: Reach::Convention,
438 run: |ctx| hooks::helm::run(ctx.settings, ctx.args),
439 },
440 Builtin {
441 name: "pre-commit-yamllint",
442 stage: Stage::PreCommit,
443 scope: Scope::new(
444 hooks::yamllint::EXTS,
445 &[".yamllint.yaml", ".yamllint.yml", ".yamllint"],
446 )
447 .not_during(MID_OPERATION),
448 severity: Severity::Block,
449 fix: Fix::None,
450 reach: Reach::Convention,
451 run: |ctx| hooks::yamllint::run(ctx.settings, ctx.args),
452 },
453 Builtin {
455 name: "pre-push-branch-protect",
456 stage: Stage::PrePush,
457 scope: Scope::ALWAYS,
458 severity: Severity::Block,
459 fix: Fix::None,
460 reach: Reach::Convention,
461 run: |ctx| hooks::branch_protect::run(ctx.settings, ctx.push.get()),
462 },
463 Builtin {
464 name: "pre-push-branch-pattern",
465 stage: Stage::PrePush,
466 scope: Scope::ALWAYS,
467 severity: Severity::Block,
468 fix: Fix::None,
469 reach: Reach::Convention,
470 run: |ctx| hooks::branch_pattern::run(ctx.settings, ctx.push.get(), ctx.args),
471 },
472 Builtin {
473 name: "pre-push-secrets",
474 stage: Stage::PrePush,
475 scope: Scope::ALWAYS,
476 severity: Severity::Block,
477 fix: Fix::None,
478 reach: Reach::Safety,
479 run: |ctx| hooks::secrets::pushed(ctx.settings, ctx.push.get()),
480 },
481 Builtin {
482 name: "pre-push-pull-rebase",
483 stage: Stage::PrePush,
484 scope: Scope::ALWAYS.not_during(&[GitState::Rebase, GitState::Merge]),
485 severity: Severity::Block,
486 fix: Fix::None,
487 reach: Reach::Convention,
488 run: |ctx| hooks::pull_rebase::run(ctx.settings, ctx.push.get(), ctx.args),
489 },
490 Builtin {
497 name: "pre-push-audit-go",
498 stage: Stage::PrePush,
499 scope: Scope::new(&[], &["go.sum"]),
500 severity: Severity::Block,
501 fix: Fix::None,
502 reach: Reach::Convention,
503 run: |ctx| hooks::audit::go(ctx),
504 },
505 Builtin {
509 name: "pre-push-audit-js",
510 stage: Stage::PrePush,
511 scope: Scope::new(&[], &["package-lock.json", "pnpm-lock.yaml"]),
512 severity: Severity::Block,
513 fix: Fix::None,
514 reach: Reach::Convention,
515 run: |ctx| hooks::audit::js(ctx),
516 },
517 Builtin {
522 name: "pre-push-audit-python",
523 stage: Stage::PrePush,
524 scope: Scope::new(&[], &["requirements.txt", "pyproject.toml"]),
525 severity: Severity::Block,
526 fix: Fix::None,
527 reach: Reach::Convention,
528 run: |ctx| hooks::audit::python(ctx),
529 },
530 Builtin {
531 name: "pre-push-audit-rust",
532 stage: Stage::PrePush,
533 scope: Scope::new(&[], &["Cargo.lock"]),
534 severity: Severity::Block,
535 fix: Fix::None,
536 reach: Reach::Convention,
537 run: |ctx| hooks::audit::rust(ctx),
538 },
539 Builtin {
540 name: "pre-push-run-tests-js",
541 stage: Stage::PrePush,
542 scope: Scope::new(hooks::run_tests::JS_EXTS, &["package.json"])
543 .not_during(&[GitState::Bisect, GitState::Rebase]),
544 severity: Severity::Block,
545 fix: Fix::None,
546 reach: Reach::Convention,
547 run: |ctx| {
548 hooks::run_tests::run(
549 ctx.settings,
550 ctx.push.get(),
551 &ctx.manifest.externals,
552 ctx.name,
553 )
554 },
555 },
556 Builtin {
557 name: "pre-push-cargo-test",
558 stage: Stage::PrePush,
559 scope: Scope::new(hooks::rust_tools::RUST_PATHS, &["Cargo.toml"])
560 .not_during(&[GitState::Bisect, GitState::Rebase]),
561 severity: Severity::Block,
562 fix: Fix::None,
563 reach: Reach::Convention,
564 run: |ctx| hooks::rust_tools::test(ctx.settings, ctx.push.get(), ctx.name),
565 },
566 Builtin {
567 name: "pre-push-go-test",
568 stage: Stage::PrePush,
569 scope: Scope::new(hooks::go_tools::GO_PATHS, &["go.mod"])
570 .not_during(&[GitState::Bisect, GitState::Rebase]),
571 severity: Severity::Block,
572 fix: Fix::None,
573 reach: Reach::Convention,
574 run: |ctx| hooks::go_tools::test(ctx.settings, ctx.push.get(), ctx.name),
575 },
576 Builtin {
577 name: "pre-push-pytest",
578 stage: Stage::PrePush,
579 scope: Scope::new(hooks::python_tools::EXTS, &["pytest.ini", "conftest.py"])
580 .not_during(&[GitState::Bisect, GitState::Rebase]),
581 severity: Severity::Block,
582 fix: Fix::None,
583 reach: Reach::Convention,
584 run: |ctx| hooks::python_tools::pytest(ctx.settings, ctx.push.get(), ctx.name),
585 },
586];
587
588pub fn severity_of(settings: &crate::config::Settings, check: &dyn Check) -> Severity {
594 effective_override(settings, None, check.name()).unwrap_or_else(|| check.severity())
595}
596
597pub fn severity_key(check: &str) -> String {
599 format!("amont.severity.{check}")
600}
601
602#[derive(Debug, Default, Clone)]
613pub struct Overrides(std::collections::BTreeMap<String, (Severity, Source)>);
614
615#[derive(Debug, Clone, Copy, PartialEq, Eq)]
619pub enum Source {
620 Config,
621 Policy,
622}
623
624impl Source {
625 pub fn as_str(self) -> &'static str {
626 match self {
627 Source::Config => "config",
628 Source::Policy => "policy",
629 }
630 }
631}
632
633impl Overrides {
634 pub fn read(settings: &crate::config::Settings) -> Overrides {
641 let policy = settings.policy();
642 match crate::git::stdout(&[
643 "config",
644 "--show-scope",
645 "--get-regexp",
646 r"^amont\.severity\.",
647 ]) {
648 Some(scoped) => Overrides::from_scoped(&scoped, policy),
649 None => Overrides::from_plain_with_policy_below(
653 crate::git::stdout(&["config", "--get-regexp", r"^amont\.severity\."]),
654 policy,
655 ),
656 }
657 }
658
659 pub fn from_scoped(scoped: &str, policy: &crate::policy::Policy) -> Overrides {
666 let mut below = String::new();
667 let mut above = String::new();
668 for line in scoped.lines() {
669 let Some((scope, rest)) = line.split_once('\t') else {
670 continue;
671 };
672 match scope {
673 "system" | "global" => {
674 below.push_str(rest);
675 below.push('\n');
676 }
677 _ => {
678 above.push_str(rest);
679 above.push('\n');
680 }
681 }
682 }
683 let mut o = Overrides::default();
684 o.fold_plain(&below, Source::Config);
685 o.fold_policy(policy);
686 o.fold_plain(&above, Source::Config);
687 o
688 }
689
690 pub fn from_plain_with_policy_below(
695 plain: Option<String>,
696 policy: &crate::policy::Policy,
697 ) -> Overrides {
698 let mut o = Overrides::default();
699 o.fold_policy(policy);
700 o.fold_plain(plain.as_deref().unwrap_or_default(), Source::Config);
701 o
702 }
703
704 fn fold_policy(&mut self, policy: &crate::policy::Policy) {
707 for (target, severity) in &policy.severities {
708 self.0.insert(target.clone(), (*severity, Source::Policy));
709 }
710 }
711
712 fn fold_plain(&mut self, text: &str, source: Source) {
716 for line in text.lines() {
717 let Some((key, value)) = line.split_once(' ') else {
718 continue;
719 };
720 let Some(check) = key.strip_prefix("amont.severity.") else {
721 continue;
722 };
723 match Severity::parse(value.trim()) {
724 Some(sev) => {
725 self.0.insert(check.to_string(), (sev, source));
726 }
727 None => {
728 self.0.remove(check);
729 }
730 }
731 }
732 }
733
734 pub fn from_config(out: Option<String>) -> Overrides {
742 let mut o = Overrides::default();
743 o.fold_plain(out.as_deref().unwrap_or_default(), Source::Config);
744 o
745 }
746
747 pub fn applied_to(&self, check: &str) -> Option<(&str, Severity)> {
754 self.applied_with_source(check)
755 .map(|(pattern, severity, _)| (pattern, severity))
756 }
757
758 pub fn applied_with_source(&self, check: &str) -> Option<(&str, Severity, Source)> {
762 self.0
763 .iter()
764 .filter_map(|(pattern, (severity, source))| {
765 crate::names_check(check, pattern)
766 .map(|m| (m, pattern.as_str(), *severity, *source))
767 })
768 .max_by_key(|(m, _, _, _)| *m)
769 .map(|(_, pattern, severity, source)| (pattern, severity, source))
770 }
771
772 pub fn of(&self, check: &dyn Check) -> Severity {
774 self.applied_to(check.name())
775 .map(|(_, severity)| severity)
776 .unwrap_or_else(|| check.severity())
777 }
778}
779
780#[cfg(test)]
781mod precedence {
782 use super::{Overrides, Severity};
783
784 fn overrides(lines: &[&str]) -> Overrides {
785 let text = lines
786 .iter()
787 .map(|l| format!("amont.severity.{l}\n"))
788 .collect::<String>();
789 Overrides::from_config(Some(text))
790 }
791
792 #[test]
796 fn the_more_specific_key_wins() {
797 let both = overrides(&["pre-commit warn", "pre-commit-clippy block"]);
798 assert_eq!(
799 both.applied_to("pre-commit-clippy"),
800 Some(("pre-commit-clippy", Severity::Block)),
801 "a full id beats its trigger"
802 );
803 assert_eq!(
804 both.applied_to("pre-commit-shellcheck"),
805 Some(("pre-commit", Severity::Warn)),
806 "and the trigger still governs every check it did not exempt"
807 );
808 }
809
810 #[test]
813 fn the_three_ways_to_name_a_check_are_ranked() {
814 let all = overrides(&["pre-commit warn", "clippy block", "pre-commit-clippy warn"]);
815 assert_eq!(
816 all.applied_to("pre-commit-clippy"),
817 Some(("pre-commit-clippy", Severity::Warn))
818 );
819
820 let no_full = overrides(&["pre-commit warn", "clippy block"]);
821 assert_eq!(
822 no_full.applied_to("pre-commit-clippy"),
823 Some(("clippy", Severity::Block)),
824 "a short name beats a trigger"
825 );
826 }
827
828 #[test]
831 fn a_key_that_names_no_check_applies_to_nothing() {
832 let typo = overrides(&["clipy warn", "e warn", " warn"]);
833 assert_eq!(typo.applied_to("pre-commit-clippy"), None);
834 }
835}
836
837pub fn effective_override(
847 settings: &crate::config::Settings,
848 repo: Option<&Path>,
849 check: &str,
850) -> Option<Severity> {
851 overrides_in(settings, repo)
852 .applied_to(check)
853 .map(|(_, s)| s)
854}
855
856pub fn effective_key(
862 settings: &crate::config::Settings,
863 repo: Option<&Path>,
864 check: &str,
865) -> Option<String> {
866 overrides_in(settings, repo)
867 .applied_to(check)
868 .map(|(pattern, _)| pattern.to_string())
869}
870
871fn overrides_in(settings: &crate::config::Settings, repo: Option<&Path>) -> Overrides {
872 match repo {
873 None => Overrides::read(settings),
877 Some(dir) => Overrides::from_config(crate::git::stdout_in(
881 dir,
882 &["config", "--get-regexp", r"^amont\.severity\."],
883 )),
884 }
885}
886
887pub fn stage_checks(stage: Stage) -> impl Iterator<Item = &'static Builtin> {
889 CHECKS.iter().filter(move |check| check.stage == stage)
890}
891
892pub fn all_stage_checks<'a>(
899 stage: Stage,
900 manifest: &'a crate::manifest::Manifest,
901) -> Vec<&'a dyn Check> {
902 let mut out: Vec<&'a dyn Check> = stage_checks(stage)
903 .map(|check| check as &dyn Check)
904 .collect();
905 out.extend(
906 manifest
907 .externals
908 .iter()
909 .filter(|external| external.stage == stage)
910 .map(|external| external as &dyn Check),
911 );
912 out
913}
914
915pub fn lookup(name: &str, manifest: &crate::manifest::Manifest) -> Option<HookFn> {
916 if let Some((_, f)) = ENTRYPOINTS.iter().find(|(n, _)| *n == name) {
917 return Some(*f);
918 }
919 if CHECKS.iter().any(|check| check.name == name)
926 || manifest
927 .externals
928 .iter()
929 .any(|external| external.id == name)
930 {
931 return Some(|ctx: &Ctx| {
932 let check = one_named(ctx.name, ctx.manifest).expect("checked above");
933 let _slot = crate::host_slots::enter_check(check.name(), check.weight());
936 Verdict::blocking(matches!(
937 (check.run(ctx), severity_of(ctx.settings, check)),
938 (Outcome::Failed, Severity::Block)
939 ))
940 });
941 }
942 None
943}
944
945pub fn one_named<'a>(name: &str, manifest: &'a crate::manifest::Manifest) -> Option<&'a dyn Check> {
949 if let Some(builtin) = CHECKS.iter().find(|check| check.name == name) {
950 return Some(builtin);
951 }
952 manifest
953 .externals
954 .iter()
955 .find(|external| external.id == name)
956 .map(|external| external as &dyn Check)
957}
958
959#[cfg(test)]
960mod tests {
961 use super::{lookup, Overrides, Reach, Severity, Stage, CHECKS, ENTRYPOINTS};
962 use crate::names::BIN;
963 use std::collections::BTreeSet;
964
965 #[test]
972 fn the_batch_agrees_with_the_authority() {
973 let d = std::env::temp_dir().join(format!("ov-{}", std::process::id()));
974 let _ = std::fs::remove_dir_all(&d);
975 std::fs::create_dir_all(&d).unwrap();
976 let git = |args: &[&str]| {
977 std::process::Command::new("git")
978 .args(args)
979 .current_dir(&d)
980 .output()
981 .expect("git");
982 };
983 git(&["init", "-q", "--template=", "."]);
984 let key = "amont.severity.pre-commit-merge-conflict";
985 git(&["config", "--add", key, "warn"]);
986 git(&["config", "--add", key, "block"]);
987
988 let raw = std::process::Command::new("git")
989 .args(["config", "--get-regexp", r"^amont\.severity\."])
990 .current_dir(&d)
991 .output()
992 .expect("git");
993 let batch = Overrides::from_config(Some(
994 String::from_utf8_lossy(&raw.stdout).trim().to_string(),
995 ));
996 let authority =
997 crate::git::stdout_in(&d, &["config", "--get", key]).and_then(|v| Severity::parse(&v));
998 let _ = std::fs::remove_dir_all(&d);
999
1000 assert_eq!(
1001 authority,
1002 Some(Severity::Block),
1003 "git applies the last entry"
1004 );
1005 assert_eq!(
1006 batch.0.get("pre-commit-merge-conflict").map(|(s, _)| *s),
1007 authority,
1008 "the batch reader disagreed with `--get`"
1009 );
1010 }
1011
1012 #[test]
1016 fn an_unrecognised_value_clears_rather_than_overrides() {
1017 let o = Overrides::from_config(Some(
1018 "amont.severity.a warn\namont.severity.a advisory\namont.severity.b warn".to_string(),
1019 ));
1020 assert_eq!(o.0.get("a"), None, "a typo must not leave `warn` standing");
1021 assert_eq!(o.0.get("b").map(|(s, _)| *s), Some(Severity::Warn));
1022 }
1023
1024 #[test]
1025 fn names_are_unique_across_entrypoints_and_checks() {
1026 let mut seen = BTreeSet::new();
1027 for n in ENTRYPOINTS
1028 .iter()
1029 .map(|(n, _)| *n)
1030 .chain(CHECKS.iter().map(|check| check.name))
1031 {
1032 assert!(seen.insert(n), "duplicate registration: {n}");
1033 }
1034 }
1035
1036 #[test]
1038 fn the_shipped_shims_are_exactly_the_git_invoked_hooks() {
1039 let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../templates/hooks");
1040 let mut shipped: Vec<String> = std::fs::read_dir(dir)
1041 .expect("templates/hooks")
1042 .flatten()
1043 .map(|entry| entry.file_name().to_string_lossy().into_owned())
1044 .collect();
1045 shipped.sort();
1046 assert_eq!(
1047 shipped,
1048 vec![
1049 "commit-msg",
1050 "post-commit",
1051 "post-rewrite",
1052 "pre-commit",
1053 "pre-push",
1054 "prepare-commit-msg"
1055 ]
1056 );
1057 let none = crate::manifest::Manifest::default();
1058 for name in &shipped {
1059 assert!(
1060 lookup(name, &none).is_some(),
1061 "shipped shim {name:?} has no handler"
1062 );
1063 }
1064 }
1065
1066 #[test]
1069 fn every_check_is_reachable_by_name() {
1070 let none = crate::manifest::Manifest::default();
1071 for check in CHECKS {
1072 assert!(
1073 lookup(check.name, &none).is_some(),
1074 "{} not reachable",
1075 check.name
1076 );
1077 }
1078 assert!(lookup("pre-commit-not-a-check", &none).is_none());
1079 }
1080
1081 #[test]
1083 fn pre_push_runs_cheapest_first() {
1084 let order: Vec<&str> = super::stage_checks(Stage::PrePush)
1085 .map(|check| check.name)
1086 .collect();
1087 assert_eq!(
1088 order,
1089 vec![
1090 "pre-push-branch-protect",
1091 "pre-push-branch-pattern",
1092 "pre-push-secrets",
1093 "pre-push-pull-rebase",
1094 "pre-push-audit-go",
1095 "pre-push-audit-js",
1096 "pre-push-audit-python",
1097 "pre-push-audit-rust",
1098 "pre-push-run-tests-js",
1099 "pre-push-cargo-test",
1100 "pre-push-go-test",
1101 "pre-push-pytest",
1102 ]
1103 );
1104 }
1105
1106 enum Consumes {
1112 All,
1113 Exts(&'static [&'static str]),
1114 }
1115
1116 const CONSUMED: &[(&str, Consumes)] = &[
1130 (
1131 "pre-commit-argo-lint",
1132 Consumes::Exts(crate::hooks::k8s::EXTS),
1133 ),
1134 (
1138 "pre-commit-ban-terms",
1139 Consumes::Exts(crate::hooks::ban_terms::EXTS),
1140 ),
1141 (
1142 "pre-commit-cargo-fmt",
1143 Consumes::Exts(crate::hooks::rust_tools::EXTS),
1144 ),
1145 (
1146 "pre-commit-clippy",
1147 Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
1148 ),
1149 (
1150 "pre-commit-go-vet",
1151 Consumes::Exts(crate::hooks::go_tools::GO_PATHS),
1152 ),
1153 (
1154 "pre-commit-gofmt",
1155 Consumes::Exts(crate::hooks::go_tools::EXTS),
1156 ),
1157 (
1158 "pre-commit-kube-linter",
1159 Consumes::Exts(crate::hooks::k8s::EXTS),
1160 ),
1161 (
1162 "pre-commit-kubeconform",
1163 Consumes::Exts(crate::hooks::k8s::EXTS),
1164 ),
1165 (
1166 "pre-commit-lint-js",
1167 Consumes::Exts(crate::hooks::lint_js::EXTS),
1168 ),
1169 (
1170 "pre-commit-lint-json-yaml",
1171 Consumes::Exts(crate::hooks::lint_json_yaml::EXTS),
1172 ),
1173 ("pre-commit-merge-conflict", Consumes::All),
1174 ("pre-commit-package-lock", Consumes::All),
1175 (
1179 "pre-commit-prettier",
1180 Consumes::Exts(crate::hooks::prettier::EXTS),
1181 ),
1182 (
1183 "pre-commit-pyright",
1184 Consumes::Exts(crate::hooks::python_tools::EXTS),
1185 ),
1186 (
1187 "pre-commit-ruff",
1188 Consumes::Exts(crate::hooks::python_tools::EXTS),
1189 ),
1190 ("pre-commit-usual-name", Consumes::All),
1191 (
1192 "pre-commit-yamllint",
1193 Consumes::Exts(crate::hooks::yamllint::EXTS),
1194 ),
1195 (
1196 "pre-commit-shellcheck",
1197 Consumes::Exts(crate::hooks::shellcheck::EXTS),
1198 ),
1199 (
1200 "pre-commit-hadolint",
1201 Consumes::Exts(crate::hooks::hadolint::NAMES),
1202 ),
1203 (
1204 "pre-commit-helm-lint",
1205 Consumes::Exts(crate::hooks::helm::EXTS),
1206 ),
1207 ("pre-commit-large-files", Consumes::All),
1208 ("pre-commit-secrets", Consumes::All),
1209 ("pre-push-secrets", Consumes::All),
1210 ("pre-push-branch-protect", Consumes::All),
1211 ("pre-push-branch-pattern", Consumes::All),
1212 ("pre-push-pull-rebase", Consumes::All),
1213 (
1214 "pre-push-run-tests-js",
1215 Consumes::Exts(crate::hooks::run_tests::JS_EXTS),
1216 ),
1217 (
1218 "pre-push-pytest",
1219 Consumes::Exts(crate::hooks::python_tools::EXTS),
1220 ),
1221 (
1222 "pre-push-cargo-test",
1223 Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
1224 ),
1225 (
1226 "pre-push-go-test",
1227 Consumes::Exts(crate::hooks::go_tools::GO_PATHS),
1228 ),
1229 (
1231 "pre-commit-tree-parity",
1232 Consumes::Exts(crate::hooks::k8s::EXTS),
1233 ),
1234 ];
1235
1236 #[test]
1247 fn no_check_declares_a_file_type_it_does_not_consume() {
1248 for (name, _) in CONSUMED {
1249 assert!(
1250 CHECKS.iter().any(|check| check.name == *name),
1251 "CONSUMED names {name:?}, which is not a check"
1252 );
1253 }
1254 for check in CHECKS {
1255 let entry = CONSUMED.iter().find(|(name, _)| *name == check.name);
1256 if check.scope.files.is_empty() && entry.is_none() {
1257 continue;
1258 }
1259 let Some((_, consumes)) = entry else {
1260 panic!(
1261 "{} declares scope.files {:?} but is missing from CONSUMED — \
1262 say what it actually reads",
1263 check.name, check.scope.files
1264 );
1265 };
1266 let Consumes::Exts(consumed) = consumes else {
1267 continue; };
1269 for ext in check.scope.files {
1270 assert!(
1271 consumed.contains(ext),
1272 "{} declares {ext:?} in its scope but never asks for it — \
1273 `{BIN} list` would report a coverage the check does not have",
1274 check.name
1275 );
1276 }
1277 }
1278 }
1279
1280 #[test]
1292 fn a_push_suite_declares_every_path_it_consumes() {
1293 for name in ["pre-push-cargo-test", "pre-push-go-test", "pre-push-pytest"] {
1294 let check = CHECKS.iter().find(|c| c.name == name).expect(name);
1295 let Some((_, Consumes::Exts(consumed))) = CONSUMED.iter().find(|(n, _)| *n == name)
1296 else {
1297 panic!("{name} must consume an explicit file set");
1298 };
1299 for path in *consumed {
1300 assert!(
1301 check.scope.files.contains(path),
1302 "{name} runs for {path:?} but does not declare it: a push \
1303 touching only {path:?} would be rehearsed as nothing to do, \
1304 run at push time, and never stamped"
1305 );
1306 }
1307 }
1308 }
1309
1310 const HAS_FIXING_CODE: &[(&str, bool)] = &[
1319 ("pre-commit-agents-md", true),
1320 ("pre-commit-argo-lint", false),
1321 ("pre-commit-ban-terms", false),
1322 ("pre-commit-branch-pattern", false),
1323 ("pre-commit-branch-protect", false),
1324 ("pre-commit-cargo-fmt", true),
1325 ("pre-commit-clippy", false),
1326 ("pre-commit-go-vet", false),
1327 ("pre-commit-gofmt", true),
1328 ("pre-commit-kube-linter", false),
1329 ("pre-commit-kubeconform", false),
1330 ("pre-commit-lint-js", false),
1331 ("pre-commit-lint-json-yaml", false),
1332 ("pre-commit-manifest-trust", false),
1333 ("pre-commit-merge-conflict", false),
1334 ("pre-commit-package-lock", false),
1335 ("pre-commit-prettier", true),
1336 ("pre-commit-pyright", false),
1337 ("pre-commit-ruff", true),
1338 ("pre-commit-tree-parity", false),
1339 ("pre-commit-usual-name", false),
1340 ("pre-commit-yamllint", false),
1341 ("pre-commit-shellcheck", false),
1342 ("pre-commit-hadolint", false),
1343 ("pre-commit-helm-lint", false),
1344 ("pre-commit-large-files", false),
1345 ("pre-commit-secrets", false),
1346 ("pre-push-secrets", false),
1347 ("pre-push-branch-protect", false),
1348 ("pre-push-branch-pattern", false),
1349 ("pre-push-pull-rebase", false),
1350 ("pre-push-audit-go", false),
1351 ("pre-push-audit-js", false),
1352 ("pre-push-audit-python", false),
1353 ("pre-push-audit-rust", false),
1354 ("pre-push-run-tests-js", false),
1355 ("pre-push-cargo-test", false),
1356 ("pre-push-go-test", false),
1357 ("pre-push-pytest", false),
1358 ];
1359
1360 #[test]
1363 fn every_rewrite_declaration_has_a_fixer() {
1364 let declared: BTreeSet<&str> = CHECKS
1365 .iter()
1366 .filter(|check| check.fix == super::Fix::Rewrite)
1367 .map(|check| check.name)
1368 .collect();
1369 let implemented: BTreeSet<&str> = HAS_FIXING_CODE
1370 .iter()
1371 .filter(|(_, has)| *has)
1372 .map(|(name, _)| *name)
1373 .collect();
1374 assert_eq!(
1375 declared, implemented,
1376 "a check declaring Fix::Rewrite with no fixer lies to `{BIN} list --json`, \
1377 and a check with a fixer that does not declare it can never be reached"
1378 );
1379
1380 let listed: BTreeSet<&str> = HAS_FIXING_CODE.iter().map(|(name, _)| *name).collect();
1383 let all: BTreeSet<&str> = CHECKS.iter().map(|check| check.name).collect();
1384 assert_eq!(listed, all, "HAS_FIXING_CODE does not cover CHECKS");
1385 }
1386
1387 #[test]
1398 fn the_safety_net_is_exactly_the_low_false_positive_set() {
1399 let safety: Vec<&str> = CHECKS
1400 .iter()
1401 .filter(|c| c.reach == Reach::Safety)
1402 .map(|c| c.name)
1403 .collect();
1404 assert_eq!(
1405 safety,
1406 vec![
1407 "pre-commit-ban-terms",
1408 "pre-commit-large-files",
1409 "pre-commit-manifest-trust",
1410 "pre-commit-merge-conflict",
1411 "pre-commit-secrets",
1412 "pre-push-secrets",
1413 ]
1414 );
1415 }
1416
1417 #[test]
1418 fn every_check_declares_a_stage_and_a_scope() {
1419 assert_eq!(CHECKS.len(), 39);
1420 let pre_commit = super::stage_checks(Stage::PreCommit).count();
1421 let pre_push = super::stage_checks(Stage::PrePush).count();
1422 assert_eq!(
1423 pre_commit + pre_push,
1424 CHECKS.len(),
1425 "every check has a stage"
1426 );
1427 }
1428}