Skip to main content

git_policy_cli/
post_commit_hook.rs

1//! What:
2//!  The single `post-commit` run after a landing: its author environment, the hook lock around it,
3//!  and the real Git hook runner with inherited standard streams.
4//! Why:
5//!  The incumbent's `commit-landing-post-commit-hook.ts` runs it outside both landing locks,
6//!  under the hook lock unless `hooks.concurrentCommits` is `true` or an outer preparation lease is inherited.
7//!  Its exit status is ignored, as native Git ignores it, and the user sees the hook's output on the terminal.
8//!
9//! In TS you'd write (pseudocode):
10//! ```ts
11//! await runPostCommitHook({ gitPath, cwd, globalArgs, realIndexPath, landedOid, plan });
12//! ```
13
14use super::diagnostic_log::debug;
15use super::forwarding::git_command;
16use super::hook_dispatch_plan::HookDispatchPlan;
17use super::live_lock::acquire_live_owner_lock;
18use super::owner_lock::OwnerLock;
19use super::transaction_git::{GitContext, GitRequest, run_git};
20use std::ffi::OsString;
21use std::path::Path;
22use std::process::{Command, Stdio};
23
24/// What:
25///  A failure of the post-commit run: the author lookup, the hook lock, or the hook's start.
26/// Why:
27///   The caller reports the message and exits 1, as the incumbent reports a thrown error after a landing.
28///
29/// In TS you'd write (pseudocode):
30/// ```ts
31/// throw new CommitTransactionGitError(message);
32/// ```
33#[derive(Clone, Debug, Eq, PartialEq)]
34pub struct PostCommitHookError(pub String);
35
36/// What:
37///  Whether `post-commit` ran, and the status its hook returned when it did.
38/// Why:
39///   A disabled event runs nothing, and a non-zero status is recorded but never fails the landed commit.
40///
41/// In TS you'd write (pseudocode):
42/// ```ts
43/// type PostCommitHookOutcome = 'disabled' | { exitCode: number };
44/// ```
45#[derive(Clone, Copy, Debug, Eq, PartialEq)]
46pub enum PostCommitHookOutcome {
47    /// `hook.post-commit.enabled=false` disabled the event; nothing ran.
48    Disabled,
49    /// The hook runner's status, which the caller ignores.
50    Ran(i32),
51}
52
53/// What:
54///  The inputs of one post-commit run.
55/// Why:
56///   Named fields keep the paths apart, and the plan carries the disabled events and the hook lock.
57///
58/// In TS you'd write (pseudocode):
59/// ```ts
60/// { gitPath, cwd, globalArgs, realIndexPath, landedOid, plan }
61/// ```
62#[derive(Clone, Copy, Debug)]
63pub struct PostCommitHookRequest<'a> {
64    /// Real Git and the caller's global options.
65    pub context: &'a GitContext,
66    /// Owning worktree root, where the hook runs.
67    pub worktree: &'a Path,
68    /// Real index native Git names in `GIT_INDEX_FILE`.
69    pub real_index: &'a Path,
70    /// Landed commit whose author the hook sees.
71    pub landed_oid: &'a str,
72    /// Dispatch plan holding the disabled events and the hook lock.
73    pub plan: &'a HookDispatchPlan,
74}
75
76/// What:
77///  Run `post-commit` once for a landed commit.
78/// Why:
79///   The order matches the incumbent: disabled check, author lookup, hook lock, hook run, lock release.
80///
81/// In TS you'd write (pseudocode):
82/// ```ts
83/// if (plan.disabledEvents.includes('post-commit')) return; await using lock = plan.skipHookLock ? undefined : await acquireOwnerLock(...); await runTransactionGit(...);
84/// ```
85pub fn run_post_commit_hook(
86    request: PostCommitHookRequest,
87) -> Result<PostCommitHookOutcome, PostCommitHookError> {
88    if request.plan.disabled_events.iter().any(|name| {
89        return name.as_str() == "post-commit";
90    }) {
91        debug(
92            "runPostCommitHook",
93            "post-commit disabled by hook.post-commit.enabled=false",
94        );
95        return Ok(PostCommitHookOutcome::Disabled);
96    }
97    let mut environment: Vec<(OsString, OsString)> =
98        read_author_environment(request.context, request.worktree, request.landed_oid)?;
99    environment.push((
100        OsString::from("GIT_INDEX_FILE"),
101        request.real_index.as_os_str().to_os_string(),
102    ));
103    environment.push((OsString::from("GIT_EDITOR"), OsString::from(":")));
104    // Held until the end of this function, so an early return releases it through `Drop`.
105    let lock: Option<OwnerLock> = if request.plan.skip_hook_lock {
106        None
107    } else {
108        Some(acquire_hook_lock(request.plan.hook_lock_path.as_str())?)
109    };
110    let status: i32 = run_hook(request.context, request.worktree, environment.as_slice())?;
111    if let Some(held) = lock {
112        held.release()
113            .map_err(|error| return PostCommitHookError(error.to_string()))?;
114    }
115    return Ok(PostCommitHookOutcome::Ran(status));
116}
117
118/// What:
119///  Take the hook lock for the post-commit run, waiting silently while a live owner holds it.
120/// Why:
121///   The incumbent's `acquireOwnerLock` on `plan.hookLockPath`, shared with the preparation dispatchers.
122///
123/// In TS you'd write (pseudocode):
124/// ```ts
125/// await acquireOwnerLock({ lockDirectory: plan.hookLockPath });
126/// ```
127fn acquire_hook_lock(lock_path: &str) -> Result<OwnerLock, PostCommitHookError> {
128    let directory: &Path = Path::new(lock_path);
129    // The incumbent creates the lock's parents recursively; the native owner lock creates one level only.
130    if let Some(parent) = directory.parent() {
131        std::fs::create_dir_all(parent).map_err(|error| {
132            return PostCommitHookError(format!("creating {} failed: {error}", parent.display()));
133        })?;
134    }
135    return acquire_live_owner_lock(directory, "the hook lock")
136        .map_err(|error| return PostCommitHookError(error.to_string()));
137}
138
139/// What:
140///  Read the landed commit's author as `GIT_AUTHOR_*` variables, through a Git start without the global options.
141/// Why:
142///   The incumbent's `authorEnvironment` runs `show` with the bare command; a refusal fails the run before the hook starts.
143///
144/// In TS you'd write (pseudocode):
145/// ```ts
146/// await runTransactionGit({ gitPath, cwd, args: ['show', '--no-patch', '--date=raw', '--format=%an%x00%ae%x00%ad', landedOid] });
147/// ```
148fn read_author_environment(
149    context: &GitContext,
150    worktree: &Path,
151    landed_oid: &str,
152) -> Result<Vec<(OsString, OsString)>, PostCommitHookError> {
153    let request: GitRequest = GitRequest {
154        without_prefix: true,
155        ..GitRequest::new(
156            worktree,
157            &[
158                "show",
159                "--no-patch",
160                "--date=raw",
161                "--format=%an%x00%ae%x00%ad",
162                landed_oid,
163            ],
164        )
165    };
166    let output = run_git(context, &request).map_err(|error| {
167        return PostCommitHookError(format!("git show could not start: {error}"));
168    })?;
169    if !output.succeeded() {
170        return Err(PostCommitHookError(output.error_text()));
171    }
172    let text: String = String::from_utf8(output.stdout).map_err(|error| {
173        return PostCommitHookError(format!(
174            "the landed commit's author fields are not UTF-8: {error}"
175        ));
176    })?;
177    return Ok(author_environment(text.as_str())
178        .into_iter()
179        .map(|(name, value)| {
180            return (OsString::from(name), OsString::from(value));
181        })
182        .collect());
183}
184
185/// What:
186///  Start the real Git hook runner for `post-commit` with inherited standard streams, and return its status.
187/// Why:
188///   The user sees the hook's output on the terminal, as the incumbent's `stdio: 'inherit'` gives it;
189///  a missing status (a signal) is 1, which the caller ignores.
190///
191/// In TS you'd write (pseudocode):
192/// ```ts
193/// await runTransactionGit({ gitPath, cwd, args: [...globalArgs, 'hook', 'run', '--ignore-missing', 'post-commit'], environment, stdio: 'inherit', allowFailure: true });
194/// ```
195fn run_hook(
196    context: &GitContext,
197    worktree: &Path,
198    environment: &[(OsString, OsString)],
199) -> Result<i32, PostCommitHookError> {
200    let mut arguments: Vec<OsString> = context.global_prefix.clone();
201    arguments.extend(
202        ["hook", "run", "--ignore-missing", "post-commit"]
203            .into_iter()
204            .map(OsString::from),
205    );
206    let mut command: Command = git_command(
207        context.real_git.as_path(),
208        arguments.as_slice(),
209        context.overlay.as_slice(),
210    );
211    command
212        .current_dir(worktree)
213        .envs(environment.iter().cloned())
214        .stdin(Stdio::inherit())
215        .stdout(Stdio::inherit())
216        .stderr(Stdio::inherit());
217    let finished = command.status().map_err(|error| {
218        return PostCommitHookError(format!(
219            "{} could not start: {error}",
220            context.real_git.display()
221        ));
222    })?;
223    return Ok(finished.code().unwrap_or(1));
224}
225
226/// What:
227///  The environment native `git commit` gives the hook, from the landed commit's `%an`, `%ae` and raw `%ad`.
228/// Why:
229///   Hooks read `GIT_AUTHOR_*`; the incumbent takes the NUL-separated fields and drops one trailing newline.
230///
231/// In TS you'd write (pseudocode):
232/// ```ts
233/// const [name = '', email = '', date = ''] = output.replace(/\n$/, '').split('\0');
234/// ```
235pub fn author_environment(output: &str) -> Vec<(String, String)> {
236    let trimmed: &str = output.strip_suffix('\n').unwrap_or(output);
237    let mut fields = trimmed.split('\0');
238    let name: &str = fields.next().unwrap_or("");
239    let email: &str = fields.next().unwrap_or("");
240    let date: &str = fields.next().unwrap_or("");
241    return vec![
242        (String::from("GIT_AUTHOR_NAME"), String::from(name)),
243        (String::from("GIT_AUTHOR_EMAIL"), String::from(email)),
244        (String::from("GIT_AUTHOR_DATE"), format!("@{date}")),
245    ];
246}
247
248/// Post-commit controls stay out of the release executable.
249#[cfg(test)]
250#[path = "post_commit_hook_tests.rs"]
251mod tests;