1use anyhow::Result;
2use std::process::Command;
3
4use crate::opener::augmented_path;
5
6pub struct HookContext {
8 pub owner: String,
10 pub repo: String,
12 pub issue: String,
14 pub branch: String,
16 pub worktree_path: String,
18}
19
20impl HookContext {
21 #[must_use]
24 pub fn render(&self, template: &str) -> String {
25 template
26 .replace("{{owner}}", &self.owner)
27 .replace("{{repo}}", &self.repo)
28 .replace("{{issue}}", &self.issue)
29 .replace("{{branch}}", &self.branch)
30 .replace("{{worktree_path}}", &self.worktree_path)
31 }
32}
33
34pub fn run_hook(script: &str, ctx: &HookContext) -> Result<()> {
43 let rendered = ctx.render(script);
44
45 let tmp_path = std::env::temp_dir().join(format!("worktree-hook-{}.sh", uuid::Uuid::new_v4()));
46 std::fs::write(&tmp_path, rendered.as_bytes())?;
47
48 #[cfg(unix)]
49 {
50 use std::os::unix::fs::PermissionsExt;
51 std::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o755))?;
52 }
53
54 let result = Command::new("sh")
55 .arg(&tmp_path)
56 .env("PATH", augmented_path())
57 .status();
58 let _ = std::fs::remove_file(&tmp_path);
59
60 match result {
61 Ok(status) if !status.success() => {
62 eprintln!("Warning: hook exited with status {:?}", status.code());
63 }
64 Err(e) => {
66 eprintln!("Warning: failed to run hook: {e}");
67 }
68 _ => {}
70 }
71
72 Ok(())
73}
74
75#[cfg(test)]
76#[path = "hooks_tests.rs"]
77mod tests;