agentmux_srv_core/identity/
github_hooks.rs1use std::path::{Path, PathBuf};
15use std::sync::OnceLock;
16
17pub const HOOK_NAMES: &[&str] = &[
19 "applypatch-msg",
20 "pre-applypatch",
21 "post-applypatch",
22 "pre-commit",
23 "pre-merge-commit",
24 "prepare-commit-msg",
25 "commit-msg",
26 "post-commit",
27 "pre-rebase",
28 "post-checkout",
29 "post-merge",
30 "pre-push",
31 "pre-auto-gc",
32 "post-rewrite",
33 "reference-transaction",
34 "post-index-change",
35 "sendemail-validate",
36];
37
38const DIR_NAME: &str = "github-hooks";
40
41pub fn hook_script(name: &str) -> String {
43 format!("#!/bin/sh\n# Written by AgentMux for agents whose GitHub access goes through it.\nexec agentmux-bashwrap git-hook {name} \"$@\"\n")
44}
45
46pub fn ensure_hooks_dir(root: &Path) -> std::io::Result<PathBuf> {
48 let dir = root.join(DIR_NAME);
49 std::fs::create_dir_all(&dir)?;
50 for name in HOOK_NAMES {
51 let path = dir.join(name);
52 let script = hook_script(name);
53 if std::fs::read_to_string(&path).ok().as_deref() != Some(script.as_str()) {
54 std::fs::write(&path, script)?;
55 }
56 #[cfg(unix)]
57 {
58 use std::os::unix::fs::PermissionsExt;
59 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))?;
60 }
61 }
62 Ok(dir)
63}
64
65pub fn hooks_dir() -> Option<PathBuf> {
67 static DIR: OnceLock<Option<PathBuf>> = OnceLock::new();
68 DIR.get_or_init(|| {
69 let root = agentmux_common::data_paths::agentmux_root().ok()?;
70 match ensure_hooks_dir(&root) {
71 Ok(dir) => Some(dir),
72 Err(e) => {
73 tracing::warn!(target: "identity", error = %e, "identity.github: couldn't write the agents' git hooks; pushes won't be scanned");
74 None
75 }
76 }
77 })
78 .clone()
79}
80
81#[cfg(test)]
82mod tests {
83 use super::*;
84
85 #[test]
86 fn the_hooks_are_written_once_and_start_bashwrap_with_their_own_name() {
87 for name in ["pre-commit", "commit-msg", "post-checkout", "post-merge", "post-commit", "pre-push", "prepare-commit-msg"] {
89 assert!(HOOK_NAMES.contains(&name), "{name}");
90 }
91 let root = tempfile::tempdir().unwrap();
92 let dir = ensure_hooks_dir(root.path()).unwrap();
93 for name in HOOK_NAMES {
94 let text = std::fs::read_to_string(dir.join(name)).unwrap();
95 assert!(text.starts_with("#!/bin/sh\n"));
96 assert!(text.contains(&format!("exec agentmux-bashwrap git-hook {name} \"$@\"")), "{name}");
97 }
98 let before = std::fs::metadata(dir.join("pre-push")).unwrap().modified().unwrap();
100 ensure_hooks_dir(root.path()).unwrap();
101 assert_eq!(std::fs::metadata(dir.join("pre-push")).unwrap().modified().unwrap(), before);
102 std::fs::write(dir.join("pre-push"), "#!/bin/sh\nexit 0\n").unwrap();
104 ensure_hooks_dir(root.path()).unwrap();
105 assert!(std::fs::read_to_string(dir.join("pre-push")).unwrap().contains("git-hook pre-push"));
106 }
107}