Skip to main content

git_policy_cli/
hook_dispatch.rs

1//! What:
2//!  The hook dispatcher: a native entry started by a preparation hook name inside a transaction's
3//!  `hooks` directory, which runs the repository's hooks for that event under the hook lock.
4//! Why:
5//!  Git starts the entry through `core.hooksPath`; the start name selects the event.
6//!  The incumbent's `dispatch.mjs` (`src/hook-dispatch/hook-dispatch-program.ts`) does the same work,
7//!  and both take the hook lock at `<common>/cli-git/hook.lock`, so they serialize on one lock.
8//!  Any other start name, including `post-commit` or a hook name outside a transaction, behaves as `git`.
9//!
10//! In TS you'd write (pseudocode):
11//! ```ts
12//! await dispatch(event, process.argv.slice(2));
13//! ```
14
15/// Plan reading, the lock path and the plan's JSON spelling.
16use super::hook_dispatch_plan::{
17    ConfigParameters, CONFIG_PARAMETERS_VARIABLE, HookDispatchPlan, PLAN_FILENAME, PLAN_LIMIT,
18    PREPARATION_HOOK_EVENTS, WORK_TREE_VARIABLE, parse_hook_dispatch_plan,
19};
20/// The hook entry naming rule on Windows.
21use super::hook_dispatch_entries::{hook_entry_name, transaction_no_hooks_directory};
22/// Lock acquisition and release shared with the other owner locks.
23use super::live_lock::acquire_live_owner_lock;
24use super::owner_lock::OwnerLock;
25use super::start_retry::RetryStart;
26/// Bounded no-follow reads of the plan.
27use super::private_storage::read_regular_file;
28/// Preparation lease variable name.
29use super::transaction_lease::PREPARATION_LEASE_VARIABLE;
30/// Registry naming of transaction directories.
31use super::transaction_registry::{TRANSACTION_ROOT_NAME, is_transaction_id};
32/// The wrapper's ordinary path when the start name is not a dispatch.
33use super::entry::run_process;
34/// `OsStr`/`OsString` are operating-system text; `Command` starts Git.
35use std::ffi::{OsStr, OsString};
36/// `Path`/`PathBuf` are borrowed/owned filesystem paths.
37use std::path::{Path, PathBuf};
38/// Child process starting.
39use std::process::Command;
40
41/// What:
42///  One recognized dispatch: the event the entry is named after and its transaction's hooks directory.
43/// Why:
44///   The dispatcher needs both, and the start name is the only proof that Git started this entry.
45///
46/// In TS you'd write (pseudocode):
47/// ```ts
48/// type DispatchTarget = { event: CommitHookEvent; hooksDirectory: string };
49/// ```
50#[derive(Clone, Debug, Eq, PartialEq)]
51pub struct DispatchTarget {
52    /// Preparation event the entry is named after.
53    pub event: &'static str,
54    /// The transaction's `hooks` directory, holding `plan.json` beside the entry.
55    pub hooks_directory: PathBuf,
56}
57
58/// What:
59///  The event a start name names, if any.
60/// Why:
61///   Only the preparation events have entries; on Windows Git's `.exe` suffix is part of the lookup.
62///
63/// In TS you'd write (pseudocode):
64/// ```ts
65/// PREPARATION_HOOK_EVENTS.find((event) => name === hookEntryName(event));
66/// ```
67fn event_of_name(name: &str) -> Option<&'static str> {
68    for event in PREPARATION_HOOK_EVENTS {
69        if name == hook_entry_name(event) {
70            return Some(event);
71        }
72    }
73    return None;
74}
75
76/// What:
77///  Recognize a start name inside a transaction's `hooks` directory beside a `plan.json`.
78/// Why:
79///   The incumbent's dispatcher runs from `<transaction>/hooks`; recognizing any other name would
80///  turn ordinary Git invocations into dispatches.
81///  The name is read lexically, and the file system is touched only after every name matches.
82///
83/// In TS you'd write (pseudocode):
84/// ```ts
85/// // the dispatcher is the program written as <tx>/hooks/<event> beside <tx>/hooks/plan.json
86/// ```
87pub fn dispatch_target_for_start_name(start_name: &Path) -> Option<DispatchTarget> {
88    let name: &str = start_name.file_name()?.to_str()?;
89    let event: &'static str = event_of_name(name)?;
90    let hooks_directory: &Path = start_name.parent()?;
91    if hooks_directory.file_name()? != "hooks" {
92        return None;
93    }
94    let transaction: &Path = hooks_directory.parent()?;
95    if !is_transaction_id(transaction.file_name()?.to_str()?) {
96        return None;
97    }
98    if transaction.parent()?.file_name()? != TRANSACTION_ROOT_NAME {
99        return None;
100    }
101    if read_regular_file(hooks_directory.join(PLAN_FILENAME).as_path(), PLAN_LIMIT).is_err() {
102        return None;
103    }
104    return Some(DispatchTarget {
105        event,
106        hooks_directory: hooks_directory.to_path_buf(),
107    });
108}
109
110/// What:
111///  The environment the dispatched Git sees: the caller's variables with the plan's three overrides.
112/// Why:
113///   The incumbent's dispatcher restores `GIT_CONFIG_PARAMETERS` (or removes it), exports the worktree root
114///  and the preparation lease; nothing else changes.
115///
116/// In TS you'd write (pseudocode):
117/// ```ts
118/// environment.GIT_WORK_TREE = plan.worktreeRoot; environment.CLI_GIT_PREPARATION_LEASE = plan.lease;
119/// ```
120pub fn dispatch_environment(
121    environment: &[(OsString, OsString)],
122    plan: &HookDispatchPlan,
123) -> Vec<(OsString, OsString)> {
124    // `mut` lets the overrides replace the caller's values.
125    let mut result: Vec<(OsString, OsString)> = Vec::with_capacity(environment.len() + 3);
126    for (name, value) in environment {
127        let overridden: bool = name == CONFIG_PARAMETERS_VARIABLE
128            || name == WORK_TREE_VARIABLE
129            || name == PREPARATION_LEASE_VARIABLE;
130        if !overridden {
131            result.push((name.clone(), value.clone()));
132        }
133    }
134    if let ConfigParameters::Present(value) = &plan.config_parameters {
135        result.push((OsString::from(CONFIG_PARAMETERS_VARIABLE), OsString::from(value)));
136    }
137    result.push((
138        OsString::from(WORK_TREE_VARIABLE),
139        OsString::from(plan.worktree_root.as_str()),
140    ));
141    result.push((
142        OsString::from(PREPARATION_LEASE_VARIABLE),
143        OsString::from(plan.lease.as_str()),
144    ));
145    return result;
146}
147
148/// What:
149///  Print one dispatcher diagnostic and return exit status 1, as an uncaught error does in the incumbent.
150/// Why:
151///   Failures stop the hook with a message; the lock is released before this returns.
152///
153/// In TS you'd write (pseudocode):
154/// ```ts
155/// throw new Error('cli-git hook dispatcher: ' + message);
156/// ```
157fn dispatch_failure(message: &str) -> i32 {
158    eprintln!("cli-git hook dispatcher: {message}");
159    return 1;
160}
161
162/// What:
163///  Run the real Git hook runner for one event under the plan's lock, and return its status.
164/// Why:
165///   The incumbent's `dispatch`:
166///  a disabled event exits 0 untouched, the lock is taken unless the plan skips it,
167///  Git runs `hook run --ignore-missing <event>` with the repository's hooks path,
168///  a signal or a failure to report a status is exit 1, and the lock is released afterwards.
169///
170/// In TS you'd write (pseudocode):
171/// ```ts
172/// async function dispatch(event, args): Promise<void>;
173/// ```
174pub fn run_hook_dispatch(
175    target: &DispatchTarget,
176    arguments: &[OsString],
177    environment: &[(OsString, OsString)],
178) -> i32 {
179    let plan_path: PathBuf = target.hooks_directory.join(PLAN_FILENAME);
180    let Ok(bytes) = read_regular_file(plan_path.as_path(), PLAN_LIMIT) else {
181        return dispatch_failure(
182            format!("cannot read the plan {}", plan_path.display()).as_str(),
183        );
184    };
185    let Some(plan) = String::from_utf8(bytes)
186        .ok()
187        .and_then(|text| { return parse_hook_dispatch_plan(text.as_str()); })
188    else {
189        return dispatch_failure(
190            format!("the plan {} is malformed", plan_path.display()).as_str(),
191        );
192    };
193    if plan.disabled_events.iter().any(|name| { return name == target.event; }) {
194        return 0;
195    }
196    let child_environment: Vec<(OsString, OsString)> = dispatch_environment(environment, &plan);
197    let lock: Option<OwnerLock> = if plan.skip_hook_lock {
198        None
199    } else {
200        match acquire_live_owner_lock(Path::new(plan.hook_lock_path.as_str()), "the hook lock") {
201            Ok(acquired) => Some(acquired),
202            Err(error) => return dispatch_failure(error.to_string().as_str()),
203        }
204    };
205    // The transaction directory is the parent of the `hooks` directory the entry started from.
206    let no_hooks: PathBuf = match target.hooks_directory.parent() {
207        Some(transaction) => transaction_no_hooks_directory(transaction),
208        None => return dispatch_failure("the hooks directory has no transaction directory"),
209    };
210    let status: i32 = run_git_hook(&plan, target.event, no_hooks.as_path(), arguments, child_environment.as_slice());
211    if let Some(held) = lock
212        && let Err(error) = held.release()
213    {
214        return dispatch_failure(error.to_string().as_str());
215    }
216    return status;
217}
218
219/// What:
220///  Start Git's hook runner for one event with the plan's paths, and wait for it.
221/// Why:
222///   The incumbent's `spawn` with `stdio: 'inherit'`; a missing status (a signal or a failure to start) is 1.
223///  `core.hooksPath` names the absent directory, so Git runs only the hooks the configuration defines by name:
224///  traditional hooks are unsupported, and the transaction's own entries must not start themselves again.
225///
226/// In TS you'd write (pseudocode):
227/// ```ts
228/// spawn(plan.gitPath, ['-c', `hook.${event}.enabled=true`, '-c', `core.hooksPath=${noHooks}`, 'hook', 'run', '--ignore-missing', event, '--', ...args], { stdio: 'inherit', env });
229/// ```
230fn run_git_hook(
231    plan: &HookDispatchPlan,
232    event: &str,
233    no_hooks: &Path,
234    arguments: &[OsString],
235    environment: &[(OsString, OsString)],
236) -> i32 {
237    let enabled: String = format!("hook.{event}.enabled=true");
238    // Built from raw OS text, so a transaction directory that is not UTF-8 stays exact.
239    let mut hooks_path: OsString = OsString::from("core.hooksPath=");
240    hooks_path.push(no_hooks.as_os_str());
241    let status = Command::new(plan.git_path.as_str())
242        .args(["-c", enabled.as_str()])
243        .args([OsStr::new("-c"), hooks_path.as_os_str()])
244        .args(["hook", "run", "--ignore-missing", event, "--"])
245        .args(arguments)
246        .env_clear()
247        .envs(environment.iter().map(|(name, value)| { return (name.clone(), value.clone()); }))
248        .status_retrying();
249    let Ok(finished) = status else {
250        return dispatch_failure(
251            format!("cannot start {}", plan.git_path).as_str(),
252        );
253    };
254    return finished.code().unwrap_or(1);
255}
256
257/// What:
258///  Dispatch when the start name names a transaction's entry, otherwise run the wrapper.
259/// Why:
260///   The executable calls this with its own start name first; every other start name, and
261///  an absent one, reaches the ordinary path unchanged.
262///
263/// In TS you'd write (pseudocode):
264/// ```ts
265/// if (startName is a dispatch) await dispatch(event, args); else await runProcess(args, env);
266/// ```
267pub fn run_executable(
268    start_name: Option<&OsStr>,
269    arguments: &[OsString],
270    environment: &[(OsString, OsString)],
271) -> i32 {
272    if let Some(name) = start_name
273        && let Some(target) = dispatch_target_for_start_name(Path::new(name))
274    {
275        return run_hook_dispatch(&target, arguments, environment);
276    }
277    return run_process(arguments, environment);
278}
279
280#[cfg(test)]
281#[path = "hook_dispatch_tests.rs"]
282mod tests;