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| hooks::run_tests::run(ctx.settings, ctx.push.get(), ctx.manifest, ctx.name),
548 },
549 Builtin {
550 name: "pre-push-cargo-test",
551 stage: Stage::PrePush,
552 scope: Scope::new(hooks::rust_tools::RUST_PATHS, &["Cargo.toml"])
553 .not_during(&[GitState::Bisect, GitState::Rebase]),
554 severity: Severity::Block,
555 fix: Fix::None,
556 reach: Reach::Convention,
557 run: |ctx| hooks::rust_tools::test(ctx.settings, ctx.push.get(), ctx.name),
558 },
559 Builtin {
560 name: "pre-push-go-test",
561 stage: Stage::PrePush,
562 scope: Scope::new(hooks::go_tools::GO_PATHS, &["go.mod"])
563 .not_during(&[GitState::Bisect, GitState::Rebase]),
564 severity: Severity::Block,
565 fix: Fix::None,
566 reach: Reach::Convention,
567 run: |ctx| hooks::go_tools::test(ctx.settings, ctx.push.get(), ctx.name),
568 },
569 Builtin {
570 name: "pre-push-pytest",
571 stage: Stage::PrePush,
572 scope: Scope::new(hooks::python_tools::EXTS, &["pytest.ini", "conftest.py"])
573 .not_during(&[GitState::Bisect, GitState::Rebase]),
574 severity: Severity::Block,
575 fix: Fix::None,
576 reach: Reach::Convention,
577 run: |ctx| hooks::python_tools::pytest(ctx.settings, ctx.push.get(), ctx.name),
578 },
579];
580
581pub fn severity_of(settings: &crate::config::Settings, check: &dyn Check) -> Severity {
587 effective_override(settings, None, check.name()).unwrap_or_else(|| check.severity())
588}
589
590pub fn severity_key(check: &str) -> String {
592 format!("amont.severity.{check}")
593}
594
595#[derive(Debug, Default, Clone)]
606pub struct Overrides(std::collections::BTreeMap<String, (Severity, Source)>);
607
608#[derive(Debug, Clone, Copy, PartialEq, Eq)]
612pub enum Source {
613 Config,
614 Policy,
615}
616
617impl Source {
618 pub fn as_str(self) -> &'static str {
619 match self {
620 Source::Config => "config",
621 Source::Policy => "policy",
622 }
623 }
624}
625
626impl Overrides {
627 pub fn read(settings: &crate::config::Settings) -> Overrides {
634 let policy = settings.policy();
635 match crate::git::stdout(&[
636 "config",
637 "--show-scope",
638 "--get-regexp",
639 r"^amont\.severity\.",
640 ]) {
641 Some(scoped) => Overrides::from_scoped(&scoped, policy),
642 None => Overrides::from_plain_with_policy_below(
646 crate::git::stdout(&["config", "--get-regexp", r"^amont\.severity\."]),
647 policy,
648 ),
649 }
650 }
651
652 pub fn from_scoped(scoped: &str, policy: &crate::policy::Policy) -> Overrides {
659 let mut below = String::new();
660 let mut above = String::new();
661 for line in scoped.lines() {
662 let Some((scope, rest)) = line.split_once('\t') else {
663 continue;
664 };
665 match scope {
666 "system" | "global" => {
667 below.push_str(rest);
668 below.push('\n');
669 }
670 _ => {
671 above.push_str(rest);
672 above.push('\n');
673 }
674 }
675 }
676 let mut o = Overrides::default();
677 o.fold_plain(&below, Source::Config);
678 o.fold_policy(policy);
679 o.fold_plain(&above, Source::Config);
680 o
681 }
682
683 pub fn from_plain_with_policy_below(
688 plain: Option<String>,
689 policy: &crate::policy::Policy,
690 ) -> Overrides {
691 let mut o = Overrides::default();
692 o.fold_policy(policy);
693 o.fold_plain(plain.as_deref().unwrap_or_default(), Source::Config);
694 o
695 }
696
697 fn fold_policy(&mut self, policy: &crate::policy::Policy) {
700 for (target, severity) in &policy.severities {
701 self.0.insert(target.clone(), (*severity, Source::Policy));
702 }
703 }
704
705 fn fold_plain(&mut self, text: &str, source: Source) {
709 for line in text.lines() {
710 let Some((key, value)) = line.split_once(' ') else {
711 continue;
712 };
713 let Some(check) = key.strip_prefix("amont.severity.") else {
714 continue;
715 };
716 match Severity::parse(value.trim()) {
717 Some(sev) => {
718 self.0.insert(check.to_string(), (sev, source));
719 }
720 None => {
721 self.0.remove(check);
722 }
723 }
724 }
725 }
726
727 pub fn from_config(out: Option<String>) -> Overrides {
735 let mut o = Overrides::default();
736 o.fold_plain(out.as_deref().unwrap_or_default(), Source::Config);
737 o
738 }
739
740 pub fn applied_to(&self, check: &str) -> Option<(&str, Severity)> {
747 self.applied_with_source(check)
748 .map(|(pattern, severity, _)| (pattern, severity))
749 }
750
751 pub fn applied_with_source(&self, check: &str) -> Option<(&str, Severity, Source)> {
755 self.0
756 .iter()
757 .filter_map(|(pattern, (severity, source))| {
758 crate::names_check(check, pattern)
759 .map(|m| (m, pattern.as_str(), *severity, *source))
760 })
761 .max_by_key(|(m, _, _, _)| *m)
762 .map(|(_, pattern, severity, source)| (pattern, severity, source))
763 }
764
765 pub fn of(&self, check: &dyn Check) -> Severity {
767 self.applied_to(check.name())
768 .map(|(_, severity)| severity)
769 .unwrap_or_else(|| check.severity())
770 }
771}
772
773#[cfg(test)]
774mod precedence {
775 use super::{Overrides, Severity};
776
777 fn overrides(lines: &[&str]) -> Overrides {
778 let text = lines
779 .iter()
780 .map(|l| format!("amont.severity.{l}\n"))
781 .collect::<String>();
782 Overrides::from_config(Some(text))
783 }
784
785 #[test]
789 fn the_more_specific_key_wins() {
790 let both = overrides(&["pre-commit warn", "pre-commit-clippy block"]);
791 assert_eq!(
792 both.applied_to("pre-commit-clippy"),
793 Some(("pre-commit-clippy", Severity::Block)),
794 "a full id beats its trigger"
795 );
796 assert_eq!(
797 both.applied_to("pre-commit-shellcheck"),
798 Some(("pre-commit", Severity::Warn)),
799 "and the trigger still governs every check it did not exempt"
800 );
801 }
802
803 #[test]
806 fn the_three_ways_to_name_a_check_are_ranked() {
807 let all = overrides(&["pre-commit warn", "clippy block", "pre-commit-clippy warn"]);
808 assert_eq!(
809 all.applied_to("pre-commit-clippy"),
810 Some(("pre-commit-clippy", Severity::Warn))
811 );
812
813 let no_full = overrides(&["pre-commit warn", "clippy block"]);
814 assert_eq!(
815 no_full.applied_to("pre-commit-clippy"),
816 Some(("clippy", Severity::Block)),
817 "a short name beats a trigger"
818 );
819 }
820
821 #[test]
824 fn a_key_that_names_no_check_applies_to_nothing() {
825 let typo = overrides(&["clipy warn", "e warn", " warn"]);
826 assert_eq!(typo.applied_to("pre-commit-clippy"), None);
827 }
828}
829
830pub fn effective_override(
840 settings: &crate::config::Settings,
841 repo: Option<&Path>,
842 check: &str,
843) -> Option<Severity> {
844 overrides_in(settings, repo)
845 .applied_to(check)
846 .map(|(_, s)| s)
847}
848
849pub fn effective_key(
855 settings: &crate::config::Settings,
856 repo: Option<&Path>,
857 check: &str,
858) -> Option<String> {
859 overrides_in(settings, repo)
860 .applied_to(check)
861 .map(|(pattern, _)| pattern.to_string())
862}
863
864fn overrides_in(settings: &crate::config::Settings, repo: Option<&Path>) -> Overrides {
865 match repo {
866 None => Overrides::read(settings),
870 Some(dir) => Overrides::from_config(crate::git::stdout_in(
874 dir,
875 &["config", "--get-regexp", r"^amont\.severity\."],
876 )),
877 }
878}
879
880pub fn stage_checks(stage: Stage) -> impl Iterator<Item = &'static Builtin> {
882 CHECKS.iter().filter(move |check| check.stage == stage)
883}
884
885pub fn push_twin_scope(short: &str) -> Option<(&'static str, Scope)> {
892 let mut push = stage_checks(Stage::PrePush);
893 let twin = push
894 .find(|check| check.pairing_name() == short)
895 .or_else(|| {
896 hooks::run_tests::is_gate_script(short)
897 .then(|| stage_checks(Stage::PrePush).find(|c| c.name() == "pre-push-run-tests-js"))
898 .flatten()
899 });
900 twin.map(|check| (check.name(), check.scope()))
901}
902
903pub fn all_stage_checks<'a>(
910 stage: Stage,
911 manifest: &'a crate::manifest::Manifest,
912) -> Vec<&'a dyn Check> {
913 let mut out: Vec<&'a dyn Check> = stage_checks(stage)
914 .map(|check| check as &dyn Check)
915 .collect();
916 out.extend(
917 manifest
918 .externals
919 .iter()
920 .filter(|external| external.stage == stage)
921 .map(|external| external as &dyn Check),
922 );
923 out
924}
925
926pub fn lookup(name: &str, manifest: &crate::manifest::Manifest) -> Option<HookFn> {
927 if let Some((_, f)) = ENTRYPOINTS.iter().find(|(n, _)| *n == name) {
928 return Some(*f);
929 }
930 if CHECKS.iter().any(|check| check.name == name)
937 || manifest
938 .externals
939 .iter()
940 .any(|external| external.id == name)
941 {
942 return Some(|ctx: &Ctx| {
943 let check = one_named(ctx.name, ctx.manifest).expect("checked above");
944 let _slot = crate::host_slots::enter_check(check.name(), check.weight());
947 Verdict::blocking(matches!(
948 (check.run(ctx), severity_of(ctx.settings, check)),
949 (Outcome::Failed, Severity::Block)
950 ))
951 });
952 }
953 None
954}
955
956pub fn one_named<'a>(name: &str, manifest: &'a crate::manifest::Manifest) -> Option<&'a dyn Check> {
960 if let Some(builtin) = CHECKS.iter().find(|check| check.name == name) {
961 return Some(builtin);
962 }
963 manifest
964 .externals
965 .iter()
966 .find(|external| external.id == name)
967 .map(|external| external as &dyn Check)
968}
969
970#[cfg(test)]
971mod tests {
972 use super::{lookup, Overrides, Reach, Severity, Stage, CHECKS, ENTRYPOINTS};
973 use crate::names::BIN;
974 use std::collections::BTreeSet;
975
976 #[test]
983 fn the_batch_agrees_with_the_authority() {
984 let d = std::env::temp_dir().join(format!("ov-{}", std::process::id()));
985 let _ = std::fs::remove_dir_all(&d);
986 std::fs::create_dir_all(&d).unwrap();
987 let git = |args: &[&str]| {
988 std::process::Command::new("git")
989 .args(args)
990 .current_dir(&d)
991 .output()
992 .expect("git");
993 };
994 git(&["init", "-q", "--template=", "."]);
995 let key = "amont.severity.pre-commit-merge-conflict";
996 git(&["config", "--add", key, "warn"]);
997 git(&["config", "--add", key, "block"]);
998
999 let raw = std::process::Command::new("git")
1000 .args(["config", "--get-regexp", r"^amont\.severity\."])
1001 .current_dir(&d)
1002 .output()
1003 .expect("git");
1004 let batch = Overrides::from_config(Some(
1005 String::from_utf8_lossy(&raw.stdout).trim().to_string(),
1006 ));
1007 let authority =
1008 crate::git::stdout_in(&d, &["config", "--get", key]).and_then(|v| Severity::parse(&v));
1009 let _ = std::fs::remove_dir_all(&d);
1010
1011 assert_eq!(
1012 authority,
1013 Some(Severity::Block),
1014 "git applies the last entry"
1015 );
1016 assert_eq!(
1017 batch.0.get("pre-commit-merge-conflict").map(|(s, _)| *s),
1018 authority,
1019 "the batch reader disagreed with `--get`"
1020 );
1021 }
1022
1023 #[test]
1027 fn an_unrecognised_value_clears_rather_than_overrides() {
1028 let o = Overrides::from_config(Some(
1029 "amont.severity.a warn\namont.severity.a advisory\namont.severity.b warn".to_string(),
1030 ));
1031 assert_eq!(o.0.get("a"), None, "a typo must not leave `warn` standing");
1032 assert_eq!(o.0.get("b").map(|(s, _)| *s), Some(Severity::Warn));
1033 }
1034
1035 #[test]
1036 fn names_are_unique_across_entrypoints_and_checks() {
1037 let mut seen = BTreeSet::new();
1038 for n in ENTRYPOINTS
1039 .iter()
1040 .map(|(n, _)| *n)
1041 .chain(CHECKS.iter().map(|check| check.name))
1042 {
1043 assert!(seen.insert(n), "duplicate registration: {n}");
1044 }
1045 }
1046
1047 #[test]
1049 fn the_shipped_shims_are_exactly_the_git_invoked_hooks() {
1050 let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../templates/hooks");
1051 let mut shipped: Vec<String> = std::fs::read_dir(dir)
1052 .expect("templates/hooks")
1053 .flatten()
1054 .map(|entry| entry.file_name().to_string_lossy().into_owned())
1055 .collect();
1056 shipped.sort();
1057 assert_eq!(
1058 shipped,
1059 vec![
1060 "commit-msg",
1061 "post-commit",
1062 "post-rewrite",
1063 "pre-commit",
1064 "pre-push",
1065 "prepare-commit-msg"
1066 ]
1067 );
1068 let none = crate::manifest::Manifest::default();
1069 for name in &shipped {
1070 assert!(
1071 lookup(name, &none).is_some(),
1072 "shipped shim {name:?} has no handler"
1073 );
1074 }
1075 }
1076
1077 #[test]
1080 fn every_check_is_reachable_by_name() {
1081 let none = crate::manifest::Manifest::default();
1082 for check in CHECKS {
1083 assert!(
1084 lookup(check.name, &none).is_some(),
1085 "{} not reachable",
1086 check.name
1087 );
1088 }
1089 assert!(lookup("pre-commit-not-a-check", &none).is_none());
1090 }
1091
1092 #[test]
1094 fn pre_push_runs_cheapest_first() {
1095 let order: Vec<&str> = super::stage_checks(Stage::PrePush)
1096 .map(|check| check.name)
1097 .collect();
1098 assert_eq!(
1099 order,
1100 vec![
1101 "pre-push-branch-protect",
1102 "pre-push-branch-pattern",
1103 "pre-push-secrets",
1104 "pre-push-pull-rebase",
1105 "pre-push-audit-go",
1106 "pre-push-audit-js",
1107 "pre-push-audit-python",
1108 "pre-push-audit-rust",
1109 "pre-push-run-tests-js",
1110 "pre-push-cargo-test",
1111 "pre-push-go-test",
1112 "pre-push-pytest",
1113 ]
1114 );
1115 }
1116
1117 enum Consumes {
1123 All,
1124 Exts(&'static [&'static str]),
1125 }
1126
1127 const CONSUMED: &[(&str, Consumes)] = &[
1141 (
1142 "pre-commit-argo-lint",
1143 Consumes::Exts(crate::hooks::k8s::EXTS),
1144 ),
1145 (
1149 "pre-commit-ban-terms",
1150 Consumes::Exts(crate::hooks::ban_terms::EXTS),
1151 ),
1152 (
1153 "pre-commit-cargo-fmt",
1154 Consumes::Exts(crate::hooks::rust_tools::EXTS),
1155 ),
1156 (
1157 "pre-commit-clippy",
1158 Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
1159 ),
1160 (
1161 "pre-commit-go-vet",
1162 Consumes::Exts(crate::hooks::go_tools::GO_PATHS),
1163 ),
1164 (
1165 "pre-commit-gofmt",
1166 Consumes::Exts(crate::hooks::go_tools::EXTS),
1167 ),
1168 (
1169 "pre-commit-kube-linter",
1170 Consumes::Exts(crate::hooks::k8s::EXTS),
1171 ),
1172 (
1173 "pre-commit-kubeconform",
1174 Consumes::Exts(crate::hooks::k8s::EXTS),
1175 ),
1176 (
1177 "pre-commit-lint-js",
1178 Consumes::Exts(crate::hooks::lint_js::EXTS),
1179 ),
1180 (
1181 "pre-commit-lint-json-yaml",
1182 Consumes::Exts(crate::hooks::lint_json_yaml::EXTS),
1183 ),
1184 ("pre-commit-merge-conflict", Consumes::All),
1185 ("pre-commit-package-lock", Consumes::All),
1186 (
1190 "pre-commit-prettier",
1191 Consumes::Exts(crate::hooks::prettier::EXTS),
1192 ),
1193 (
1194 "pre-commit-pyright",
1195 Consumes::Exts(crate::hooks::python_tools::EXTS),
1196 ),
1197 (
1198 "pre-commit-ruff",
1199 Consumes::Exts(crate::hooks::python_tools::EXTS),
1200 ),
1201 ("pre-commit-usual-name", Consumes::All),
1202 (
1203 "pre-commit-yamllint",
1204 Consumes::Exts(crate::hooks::yamllint::EXTS),
1205 ),
1206 (
1207 "pre-commit-shellcheck",
1208 Consumes::Exts(crate::hooks::shellcheck::EXTS),
1209 ),
1210 (
1211 "pre-commit-hadolint",
1212 Consumes::Exts(crate::hooks::hadolint::NAMES),
1213 ),
1214 (
1215 "pre-commit-helm-lint",
1216 Consumes::Exts(crate::hooks::helm::EXTS),
1217 ),
1218 ("pre-commit-large-files", Consumes::All),
1219 ("pre-commit-secrets", Consumes::All),
1220 ("pre-push-secrets", Consumes::All),
1221 ("pre-push-branch-protect", Consumes::All),
1222 ("pre-push-branch-pattern", Consumes::All),
1223 ("pre-push-pull-rebase", Consumes::All),
1224 (
1225 "pre-push-run-tests-js",
1226 Consumes::Exts(crate::hooks::run_tests::JS_EXTS),
1227 ),
1228 (
1229 "pre-push-pytest",
1230 Consumes::Exts(crate::hooks::python_tools::EXTS),
1231 ),
1232 (
1233 "pre-push-cargo-test",
1234 Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
1235 ),
1236 (
1237 "pre-push-go-test",
1238 Consumes::Exts(crate::hooks::go_tools::GO_PATHS),
1239 ),
1240 (
1242 "pre-commit-tree-parity",
1243 Consumes::Exts(crate::hooks::k8s::EXTS),
1244 ),
1245 ];
1246
1247 #[test]
1258 fn no_check_declares_a_file_type_it_does_not_consume() {
1259 for (name, _) in CONSUMED {
1260 assert!(
1261 CHECKS.iter().any(|check| check.name == *name),
1262 "CONSUMED names {name:?}, which is not a check"
1263 );
1264 }
1265 for check in CHECKS {
1266 let entry = CONSUMED.iter().find(|(name, _)| *name == check.name);
1267 if check.scope.files.is_empty() && entry.is_none() {
1268 continue;
1269 }
1270 let Some((_, consumes)) = entry else {
1271 panic!(
1272 "{} declares scope.files {:?} but is missing from CONSUMED — \
1273 say what it actually reads",
1274 check.name, check.scope.files
1275 );
1276 };
1277 let Consumes::Exts(consumed) = consumes else {
1278 continue; };
1280 for ext in check.scope.files {
1281 assert!(
1282 consumed.contains(ext),
1283 "{} declares {ext:?} in its scope but never asks for it — \
1284 `{BIN} list` would report a coverage the check does not have",
1285 check.name
1286 );
1287 }
1288 }
1289 }
1290
1291 #[test]
1303 fn a_push_suite_declares_every_path_it_consumes() {
1304 for name in ["pre-push-cargo-test", "pre-push-go-test", "pre-push-pytest"] {
1305 let check = CHECKS.iter().find(|c| c.name == name).expect(name);
1306 let Some((_, Consumes::Exts(consumed))) = CONSUMED.iter().find(|(n, _)| *n == name)
1307 else {
1308 panic!("{name} must consume an explicit file set");
1309 };
1310 for path in *consumed {
1311 assert!(
1312 check.scope.files.contains(path),
1313 "{name} runs for {path:?} but does not declare it: a push \
1314 touching only {path:?} would be rehearsed as nothing to do, \
1315 run at push time, and never stamped"
1316 );
1317 }
1318 }
1319 }
1320
1321 const HAS_FIXING_CODE: &[(&str, bool)] = &[
1330 ("pre-commit-agents-md", true),
1331 ("pre-commit-argo-lint", false),
1332 ("pre-commit-ban-terms", false),
1333 ("pre-commit-branch-pattern", false),
1334 ("pre-commit-branch-protect", false),
1335 ("pre-commit-cargo-fmt", true),
1336 ("pre-commit-clippy", false),
1337 ("pre-commit-go-vet", false),
1338 ("pre-commit-gofmt", true),
1339 ("pre-commit-kube-linter", false),
1340 ("pre-commit-kubeconform", false),
1341 ("pre-commit-lint-js", false),
1342 ("pre-commit-lint-json-yaml", false),
1343 ("pre-commit-manifest-trust", false),
1344 ("pre-commit-merge-conflict", false),
1345 ("pre-commit-package-lock", false),
1346 ("pre-commit-prettier", true),
1347 ("pre-commit-pyright", false),
1348 ("pre-commit-ruff", true),
1349 ("pre-commit-tree-parity", false),
1350 ("pre-commit-usual-name", false),
1351 ("pre-commit-yamllint", false),
1352 ("pre-commit-shellcheck", false),
1353 ("pre-commit-hadolint", false),
1354 ("pre-commit-helm-lint", false),
1355 ("pre-commit-large-files", false),
1356 ("pre-commit-secrets", false),
1357 ("pre-push-secrets", false),
1358 ("pre-push-branch-protect", false),
1359 ("pre-push-branch-pattern", false),
1360 ("pre-push-pull-rebase", false),
1361 ("pre-push-audit-go", false),
1362 ("pre-push-audit-js", false),
1363 ("pre-push-audit-python", false),
1364 ("pre-push-audit-rust", false),
1365 ("pre-push-run-tests-js", false),
1366 ("pre-push-cargo-test", false),
1367 ("pre-push-go-test", false),
1368 ("pre-push-pytest", false),
1369 ];
1370
1371 #[test]
1374 fn every_rewrite_declaration_has_a_fixer() {
1375 let declared: BTreeSet<&str> = CHECKS
1376 .iter()
1377 .filter(|check| check.fix == super::Fix::Rewrite)
1378 .map(|check| check.name)
1379 .collect();
1380 let implemented: BTreeSet<&str> = HAS_FIXING_CODE
1381 .iter()
1382 .filter(|(_, has)| *has)
1383 .map(|(name, _)| *name)
1384 .collect();
1385 assert_eq!(
1386 declared, implemented,
1387 "a check declaring Fix::Rewrite with no fixer lies to `{BIN} list --json`, \
1388 and a check with a fixer that does not declare it can never be reached"
1389 );
1390
1391 let listed: BTreeSet<&str> = HAS_FIXING_CODE.iter().map(|(name, _)| *name).collect();
1394 let all: BTreeSet<&str> = CHECKS.iter().map(|check| check.name).collect();
1395 assert_eq!(listed, all, "HAS_FIXING_CODE does not cover CHECKS");
1396 }
1397
1398 #[test]
1409 fn the_safety_net_is_exactly_the_low_false_positive_set() {
1410 let safety: Vec<&str> = CHECKS
1411 .iter()
1412 .filter(|c| c.reach == Reach::Safety)
1413 .map(|c| c.name)
1414 .collect();
1415 assert_eq!(
1416 safety,
1417 vec![
1418 "pre-commit-ban-terms",
1419 "pre-commit-large-files",
1420 "pre-commit-manifest-trust",
1421 "pre-commit-merge-conflict",
1422 "pre-commit-secrets",
1423 "pre-push-secrets",
1424 ]
1425 );
1426 }
1427
1428 #[test]
1429 fn every_check_declares_a_stage_and_a_scope() {
1430 assert_eq!(CHECKS.len(), 39);
1431 let pre_commit = super::stage_checks(Stage::PreCommit).count();
1432 let pre_push = super::stage_checks(Stage::PrePush).count();
1433 assert_eq!(
1434 pre_commit + pre_push,
1435 CHECKS.len(),
1436 "every check has a stage"
1437 );
1438 }
1439}