Skip to main content

grit_lib/
hooks.rs

1//! Hook execution utilities.
2//!
3//! Implements Git's multihook model: hooks from `hook.<name>.*` config plus the
4//! traditional script in the hooks directory (`core.hooksPath` or `.git/hooks/`).
5
6use crate::command_runner::{
7    git_for_windows_tool_dirs, prepend_to_child_path, system_command_runner, CommandEnvironment,
8    CommandRunner, CommandSpec, CommandStdin, CommandStdio, ConcurrentStdinFeed, RunningCommand,
9    ScriptInterpreter, ShellInvocation,
10};
11use crate::config::{parse_path, ConfigSet};
12use crate::environment::Environment;
13use crate::git_path::path_without_verbatim_prefix;
14use crate::git_path::CanonicalizeExt;
15use crate::objects::HashAlgo;
16use crate::objects::ObjectId;
17use crate::repo::Repository;
18use std::collections::{HashMap, HashSet, VecDeque};
19use std::ffi::OsString;
20use std::fs;
21#[cfg(unix)]
22use std::os::unix::fs::PermissionsExt;
23use std::path::{Path, PathBuf};
24use std::sync::Arc;
25use std::time::Duration;
26use thiserror::Error;
27
28use crate::progress::CancelToken;
29
30/// Whether `err` means the OS would not execute the file as a program, so it must be run
31/// through a shell (`ENOEXEC` on Unix, `ERROR_BAD_EXE_FORMAT` on Windows).
32fn is_not_an_executable(err: &std::io::Error) -> bool {
33    #[cfg(unix)]
34    const NOT_EXECUTABLE: i32 = 8;
35    #[cfg(windows)]
36    const NOT_EXECUTABLE: i32 = 193;
37    #[cfg(not(any(unix, windows)))]
38    const NOT_EXECUTABLE: i32 = -1;
39    err.raw_os_error() == Some(NOT_EXECUTABLE)
40}
41
42/// Where hook subprocesses send their stdout and stderr.
43///
44/// The library never writes hook output itself: it either hands the bytes back to the caller
45/// or lets the child write straight to this process's standard streams.
46#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
47pub enum HookStdio {
48    /// Pipe both streams and return them in [`HookResult`] and [`HookError::Failed`].
49    ///
50    /// The default, so an embedder (TUI, GUI, server) can show the output in its own way.
51    #[default]
52    Capture,
53    /// The child writes directly to this process's stderr, as Git does: live output, nothing
54    /// buffered. A hook's stdout goes to stderr too unless
55    /// [`RunHookOptions::stdout_to_stderr`] is false. Returned [`HookOutput`]s are empty.
56    Inherit,
57}
58
59/// Bytes the hooks of one event wrote while [`HookStdio::Capture`] was in effect.
60///
61/// When several hooks run for one event (configured `hook.<name>.*` entries, then the hooks
62/// directory script), their output is appended in run order.
63#[derive(Clone, Default, PartialEq, Eq)]
64pub struct HookOutput {
65    /// Everything the hooks wrote to stdout.
66    pub stdout: Vec<u8>,
67    /// Everything the hooks wrote to stderr.
68    pub stderr: Vec<u8>,
69}
70
71impl std::fmt::Debug for HookOutput {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        f.debug_struct("HookOutput")
74            .field("stdout", &String::from_utf8_lossy(&self.stdout))
75            .field("stderr", &String::from_utf8_lossy(&self.stderr))
76            .finish()
77    }
78}
79
80impl HookOutput {
81    /// Whether no output was captured on either stream.
82    #[must_use]
83    pub fn is_empty(&self) -> bool {
84        self.stdout.is_empty() && self.stderr.is_empty()
85    }
86}
87
88/// Hook subprocess failure (non-zero exit or spawn error).
89#[derive(Debug, Error)]
90#[non_exhaustive]
91pub enum HookError {
92    /// A hook ran and returned a non-zero exit status.
93    ///
94    /// The message is one line; the hook's own output is in `output`, never in `Display`.
95    #[error("hook {hook_name} failed with exit status {status}")]
96    Failed {
97        /// Basename of the hook script that failed.
98        hook_name: String,
99        /// Process exit code from the hook subprocess.
100        status: i32,
101        /// What the hooks wrote; empty under [`HookStdio::Inherit`].
102        output: HookOutput,
103    },
104    /// The hook (or the shell that runs it) could not be started.
105    #[error("failed to run hook {hook_name} ({})", path.display())]
106    Spawn {
107        /// Hook event name (`pre-commit`, `commit-msg`, …).
108        hook_name: String,
109        /// Program that failed to start: the hook script, or the interpreter chosen for it.
110        path: PathBuf,
111        /// Error returned by the [`CommandRunner`] when spawning.
112        #[source]
113        source: std::io::Error,
114        /// What earlier hooks for the same event wrote before this one could not start
115        /// (configured `hook.<name>.*` entries run before the hooks directory script); empty
116        /// under [`HookStdio::Inherit`].
117        output: HookOutput,
118    },
119
120    /// A configured hook event references `hook.<name>` without `hook.<name>.command`.
121    #[error(
122        "'hook.{hook_name}.command' must be configured or 'hook.{hook_name}.event' must be removed; aborting."
123    )]
124    MissingHookCommand {
125        /// Configured hook name (`hook.<name>.*`).
126        hook_name: String,
127    },
128}
129
130impl HookError {
131    /// Hook output captured before the failure, or `None` for configuration and repository errors.
132    #[must_use]
133    pub fn output(&self) -> Option<&HookOutput> {
134        match self {
135            HookError::Failed { output, .. } | HookError::Spawn { output, .. } => Some(output),
136            HookError::MissingHookCommand { .. } => None,
137        }
138    }
139}
140
141fn hook_command_env(git_dir: Option<&Path>, extra_env: &[(String, String)]) -> CommandEnvironment {
142    let mut env = CommandEnvironment::inherit_process_only();
143    if let Some(gd) = git_dir {
144        env.set
145            .push((OsString::from("GIT_DIR"), gd.as_os_str().to_os_string()));
146    }
147    for (k, v) in extra_env {
148        env.set
149            .push((OsString::from(k.as_str()), OsString::from(v.as_str())));
150    }
151    env
152}
153
154/// Environment for commit-style hooks (`GIT_INDEX_FILE`, `GIT_EDITOR`, `GIT_PREFIX`, and extra pairs).
155#[derive(Debug, Clone, Default)]
156pub struct CommitHookEnv<'a> {
157    /// Absolute or cwd-relative index path passed as `GIT_INDEX_FILE`.
158    pub index_file: Option<&'a Path>,
159    /// When set, overrides `GIT_EDITOR` for the hook subprocess (e.g. `":"` when no editor is used).
160    pub git_editor: Option<&'a str>,
161    /// When set, used as `GIT_PREFIX`; when unset, derived from the current directory and work tree.
162    pub git_prefix: Option<&'a str>,
163    /// Additional `KEY=value` pairs for the hook subprocess.
164    pub extra_env: &'a [(&'a str, &'a str)],
165}
166
167fn absolute_index_path(index_file: &Path, cwd: &Path) -> PathBuf {
168    if index_file.is_absolute() {
169        index_file.to_path_buf()
170    } else {
171        cwd.join(index_file)
172    }
173}
174
175/// `GIT_PREFIX` for the invoking cwd relative to the work tree (Git sets this from the user's
176/// `pwd`, not from the hook subprocess cwd, which is usually the work tree root).
177fn git_prefix_for_invocation(repo: &Repository, invocation_cwd: &Path) -> String {
178    let Some(wt) = repo.work_tree() else {
179        return String::new();
180    };
181    if invocation_cwd == repo.git_dir() {
182        return String::new();
183    }
184    let wt_canon = wt
185        .canonicalize_simplified()
186        .unwrap_or_else(|_| wt.to_path_buf());
187    let wd_canon = invocation_cwd
188        .canonicalize_simplified()
189        .unwrap_or_else(|_| invocation_cwd.to_path_buf());
190    let rel = wd_canon.strip_prefix(&wt_canon).ok();
191    let Some(rel) = rel else {
192        return String::new();
193    };
194    let Some(s) = rel.to_str() else {
195        return String::new();
196    };
197    if s.is_empty() {
198        return String::new();
199    }
200    let mut out = s.replace('\\', "/");
201    if !out.ends_with('/') {
202        out.push('/');
203    }
204    out
205}
206
207fn build_commit_hook_env(
208    repo: &Repository,
209    _work_dir: &Path,
210    opts: &CommitHookEnv<'_>,
211) -> Vec<(String, String)> {
212    let mut env: Vec<(String, String)> = Vec::new();
213    if let Some(p) = opts.index_file {
214        env.push((
215            "GIT_INDEX_FILE".to_string(),
216            absolute_index_path(p, &repo.environment().cwd)
217                .to_string_lossy()
218                .into_owned(),
219        ));
220    }
221    let invocation_cwd = repo.environment().discovery_cwd();
222    let prefix = opts
223        .git_prefix
224        .map(|s| s.to_string())
225        .unwrap_or_else(|| git_prefix_for_invocation(repo, &invocation_cwd));
226    env.push(("GIT_PREFIX".to_string(), prefix));
227    if let Some(ed) = opts.git_editor {
228        env.push(("GIT_EDITOR".to_string(), ed.to_string()));
229    }
230    for (k, v) in opts.extra_env {
231        env.push(((*k).to_string(), (*v).to_string()));
232    }
233    env
234}
235
236/// Git `git_parse_maybe_bool`: `Some(true/false)` or `None` if unrecognized.
237fn parse_maybe_bool(value: &str) -> Option<bool> {
238    let v = value.trim().to_ascii_lowercase();
239    match v.as_str() {
240        "true" | "yes" | "on" | "1" => Some(true),
241        "false" | "no" | "off" | "0" => Some(false),
242        _ => None,
243    }
244}
245
246/// Split `hook.<subsection>.<var>` into `(subsection, var)`.
247fn parse_hook_config_key(key: &str) -> Option<(&str, &str)> {
248    let rest = key.strip_prefix("hook.")?;
249    let (subsection, var) = rest.rsplit_once('.')?;
250    if subsection.is_empty() || var.is_empty() {
251        return None;
252    }
253    Some((subsection, var))
254}
255
256/// Parsed `hook.*` configuration in one pass (Git `hook_config_lookup_all` semantics).
257#[derive(Debug, Default)]
258struct HookConfigTables {
259    /// Friendly name → last-seen command string.
260    commands: HashMap<String, String>,
261    /// Event name → ordered friendly names (last duplicate wins position).
262    event_hooks: HashMap<String, VecDeque<String>>,
263    disabled: HashSet<String>,
264}
265
266impl HookConfigTables {
267    fn apply_entry(&mut self, key: &str, value: Option<&str>) {
268        let Some((hook_name, subkey)) = parse_hook_config_key(key) else {
269            return;
270        };
271        let Some(value) = value else {
272            return;
273        };
274        let hook_name = hook_name.to_string();
275
276        match subkey {
277            "event" => {
278                if value.is_empty() {
279                    for hooks in self.event_hooks.values_mut() {
280                        hooks.retain(|n| n != &hook_name);
281                    }
282                } else {
283                    let event = value.to_string();
284                    let hooks = self.event_hooks.entry(event).or_default();
285                    hooks.retain(|n| n != &hook_name);
286                    hooks.push_back(hook_name);
287                }
288            }
289            "command" => {
290                self.commands.insert(hook_name, value.to_string());
291            }
292            "enabled" => match parse_maybe_bool(value) {
293                Some(false) => {
294                    self.disabled.insert(hook_name);
295                }
296                Some(true) => {
297                    self.disabled.remove(&hook_name);
298                }
299                None => {}
300            },
301            _ => {}
302        }
303    }
304
305    fn from_config(config: &ConfigSet) -> Self {
306        let mut t = Self::default();
307        for e in config.entries() {
308            t.apply_entry(&e.key, e.value.as_deref());
309        }
310        t
311    }
312
313    /// Configured hooks for `event`, in order, excluding disabled entries without a command.
314    ///
315    /// Returns `Err` if a non-disabled hook lacks `hook.<name>.command` (Git dies here).
316    fn hooks_for_event(&self, event: &str) -> crate::error::Result<Vec<(String, String)>> {
317        let Some(names) = self.event_hooks.get(event) else {
318            return Ok(Vec::new());
319        };
320        let mut out = Vec::new();
321        for name in names {
322            if self.disabled.contains(name) {
323                continue;
324            }
325            let Some(cmd) = self.commands.get(name) else {
326                return Err(HookError::MissingHookCommand {
327                    hook_name: name.clone(),
328                }
329                .into());
330            };
331            out.push((name.clone(), cmd.clone()));
332        }
333        Ok(out)
334    }
335}
336
337/// One hook invocation resolved for an event.
338#[derive(Debug)]
339enum ResolvedHook {
340    Configured { command: String },
341    Traditional { path: PathBuf, argv0: PathBuf },
342}
343
344/// Resolve the hooks directory from config or fall back to `$GIT_DIR/hooks`.
345///
346/// A relative `core.hooksPath` is taken relative to the directory hooks run in: the top of
347/// the work tree, or `$GIT_DIR` in a bare repository. It does not depend on the directory
348/// the repository was opened from.
349///
350/// Never carries a Windows `\\?\` prefix, so the path can be shown to users and handed to
351/// hook interpreters such as Git for Windows' `sh`.
352pub(crate) fn resolve_hooks_dir(repo: &Repository) -> PathBuf {
353    resolve_hooks_dir_for_config(repo, repo.config().snapshot().ok().as_deref())
354}
355
356fn resolve_hooks_dir_for_config(repo: &Repository, config: Option<&ConfigSet>) -> PathBuf {
357    let dir = match config.and_then(|cfg| cfg.value("core.hooksPath")) {
358        Some(hooks_path) => {
359            let p = PathBuf::from(parse_path(repo.environment(), &hooks_path));
360            if p.is_absolute() {
361                p
362            } else {
363                hook_run_dir(repo).join(p)
364            }
365        }
366        None => crate::repo::common_git_dir_for_config(repo.git_dir()).join("hooks"),
367    };
368    path_without_verbatim_prefix(&dir).into_owned()
369}
370
371/// Directory hooks run in by default: the work tree top, or `$GIT_DIR` when bare.
372fn hook_run_dir(repo: &Repository) -> &Path {
373    repo.work_tree().unwrap_or(repo.git_dir())
374}
375
376fn hook_argv0(repo: &Repository, hooks_dir: &Path, hook_name: &str, cwd: &Path) -> PathBuf {
377    let default_hooks_dir = repo.git_dir().join("hooks");
378    if same_dir(hooks_dir, &default_hooks_dir) {
379        if cwd == repo.git_dir() {
380            return PathBuf::from("hooks").join(hook_name);
381        }
382        if let Some(work_tree) = repo.work_tree() {
383            // Only relativise to `.git/hooks/<name>` when the git dir is literally
384            // `<work_tree>/.git`. When `GIT_DIR` points elsewhere (e.g.
385            // `GIT_DIR=clone1/.git` run from the parent dir, which makes the work
386            // tree default to the process cwd), the relative path would resolve
387            // against the wrong directory. In that case fall through to the
388            // absolute hook path, mirroring upstream `hook.c`, which absolutises
389            // the hook path whenever it runs the hook in a specific directory.
390            if cwd == work_tree && same_dir(repo.git_dir(), &work_tree.join(".git")) {
391                return PathBuf::from(".git").join("hooks").join(hook_name);
392            }
393        }
394    }
395    hooks_dir.join(hook_name)
396}
397
398/// Compare two paths for pointing at the same directory, tolerating symlinks and
399/// non-canonical components by canonicalising both ends when possible.
400fn same_dir(a: &Path, b: &Path) -> bool {
401    if a == b {
402        return true;
403    }
404    match (a.canonicalize_simplified(), b.canonicalize_simplified()) {
405        (Ok(ca), Ok(cb)) => ca == cb,
406        _ => false,
407    }
408}
409
410// `repo`/`meta` are only read on Unix (executable-bit advice); Windows has no
411// POSIX permission bits, so the candidate is returned without that check.
412#[cfg_attr(not(unix), allow(unused_variables))]
413fn traditional_hook_candidate(
414    repo: &Repository,
415    hooks_dir: &Path,
416    hook_name: &str,
417) -> Option<PathBuf> {
418    let path = hooks_dir.join(hook_name);
419    if !path.exists() {
420        return None;
421    }
422    let meta = fs::metadata(&path).ok()?;
423    #[cfg(unix)]
424    if meta.permissions().mode() & 0o111 == 0 {
425        let config = repo.config().snapshot().ok();
426        let show_warning = config
427            .as_deref()
428            .and_then(|c| c.value("advice.ignoredHook"))
429            .map(|v| !matches!(v.to_lowercase().as_str(), "false" | "no" | "off" | "0"))
430            .unwrap_or(true);
431        if show_warning {
432            repo.warn(crate::diagnostics::Warning::NonExecutableHookIgnored {
433                hook_name: hook_name.to_string(),
434                hook_path: Some(path.clone()),
435            });
436        }
437        return None;
438    }
439    Some(path)
440}
441
442/// Configured hooks only (for out-of-repo `git hook run`).
443fn resolve_configured_hooks_only(
444    hook_name: &str,
445    config: &ConfigSet,
446) -> crate::error::Result<Vec<ResolvedHook>> {
447    let tables = HookConfigTables::from_config(config);
448    let mut seq = Vec::new();
449    for (_friendly, command) in tables.hooks_for_event(hook_name)? {
450        seq.push(ResolvedHook::Configured { command });
451    }
452    Ok(seq)
453}
454
455/// Build ordered hook list: configured hooks first, then the traditional hookdir script.
456fn resolve_hook_sequence(
457    repo: &Repository,
458    hook_name: &str,
459    config: &ConfigSet,
460) -> crate::error::Result<Vec<ResolvedHook>> {
461    let tables = HookConfigTables::from_config(config);
462    let mut seq = Vec::new();
463    for (_friendly, command) in tables.hooks_for_event(hook_name)? {
464        seq.push(ResolvedHook::Configured { command });
465    }
466    let hooks_dir = resolve_hooks_dir_for_config(repo, Some(config));
467    if let Some(path) = traditional_hook_candidate(repo, &hooks_dir, hook_name) {
468        let argv0 = hook_argv0(repo, &hooks_dir, hook_name, hook_run_dir(repo));
469        seq.push(ResolvedHook::Traditional { path, argv0 });
470    }
471    Ok(seq)
472}
473
474/// Interpreter basename named by a script's `#!` line, or `None` without one.
475///
476/// `#!/bin/sh -e` gives `sh` and `#!/usr/bin/env bash` gives `bash`. Options after the
477/// interpreter are dropped, as Git for Windows does when it runs scripts itself.
478#[cfg_attr(not(windows), allow(dead_code))]
479fn shebang_interpreter(head: &[u8]) -> Option<String> {
480    let rest = head.strip_prefix(b"#!")?;
481    let line_len = rest
482        .iter()
483        .position(|&b| b == b'\n' || b == b'\r')
484        .unwrap_or(rest.len());
485    let line = std::str::from_utf8(&rest[..line_len]).ok()?;
486    let basename = |word: &str| word.rsplit(['/', '\\']).next().map(str::to_owned);
487    let mut words = line.split_ascii_whitespace();
488    let mut name = basename(words.next()?)?;
489    if name == "env" {
490        name = basename(words.find(|w| !w.starts_with('-'))?)?;
491    }
492    (!name.is_empty()).then_some(name)
493}
494
495/// Strip Windows `\\?\` prefixes from the path-valued `GIT_*` variables in `set`.
496///
497/// Repository paths are canonicalized, which makes them verbatim on Windows, but Git for
498/// Windows does not open a verbatim `GIT_INDEX_FILE` (it reads an empty index instead) and
499/// MSYS tools cannot open such paths at all.
500fn strip_verbatim_prefix_from_path_vars(set: &mut [(OsString, OsString)]) {
501    crate::git_path::strip_verbatim_prefix_from_subprocess_path_vars(set);
502}
503
504/// Shell for `hook.<name>.command` entries and for scripts the OS will not execute directly.
505///
506/// See [`crate::command_runner::shell_program`]: `/bin/sh` on Unix, `sh` resolved against the
507/// hook's `PATH` on Windows.
508fn hook_shell(env: &CommandEnvironment) -> ScriptInterpreter {
509    crate::command_runner::shell_interpreter(env)
510}
511
512/// Interpreter from the `#!` line of `script` (Windows cannot execute scripts directly).
513#[cfg(windows)]
514fn script_shebang_interpreter(
515    script: &Path,
516    env: &CommandEnvironment,
517) -> Option<ScriptInterpreter> {
518    use std::io::Read;
519    let mut head = [0u8; 256];
520    let mut file = fs::File::open(script).ok()?;
521    let n = file.read(&mut head).ok()?;
522    let name = shebang_interpreter(&head[..n])?;
523    Some(crate::command_runner::resolve_script_interpreter(
524        &name,
525        crate::command_runner::child_path_var(env).as_deref(),
526    ))
527}
528
529/// Stdio and environment shared by every hook subprocess.
530struct HookSpawnContext<'a> {
531    runner: &'a dyn CommandRunner,
532    cwd: &'a Path,
533    env: &'a CommandEnvironment,
534    stdin_piped: bool,
535    stdout: CommandStdio,
536    stderr: CommandStdio,
537    server_receive_hook: bool,
538}
539
540impl HookSpawnContext<'_> {
541    fn spec(&self, program: PathBuf, shell: Option<ShellInvocation>, args: &[&str]) -> CommandSpec {
542        CommandSpec {
543            program,
544            args: if shell.is_some() {
545                Vec::new()
546            } else {
547                args.iter().map(OsString::from).collect()
548            },
549            shell,
550            cwd: Some(path_without_verbatim_prefix(self.cwd).into_owned()),
551            env: self.env.clone(),
552            stdin: if self.stdin_piped {
553                CommandStdin::Pipe(Vec::new())
554            } else {
555                CommandStdin::Inherit
556            },
557            stdout: self.stdout,
558            stderr: self.stderr,
559        }
560    }
561
562    /// Spec running `interpreter` with `invocation`; an interpreter from a Git for Windows
563    /// tree also gets that tree's tool directories in front of `PATH`, as Git gives hooks.
564    fn interpreter_spec(
565        &self,
566        interpreter: ScriptInterpreter,
567        invocation: ShellInvocation,
568        args: &[&str],
569    ) -> CommandSpec {
570        let mut spec = self.spec(interpreter.program, Some(invocation), args);
571        if let Some(root) = &interpreter.git_root {
572            prepend_to_child_path(&mut spec.env, &git_for_windows_tool_dirs(root));
573        }
574        spec
575    }
576
577    fn spawn(&self, spec: &CommandSpec, hook_name: &str) -> crate::error::Result<RunningCommand> {
578        let spawn = if self.server_receive_hook {
579            self.runner.spawn_server_receive_hook(spec)
580        } else {
581            self.runner.spawn(spec)
582        };
583        Ok(spawn.map_err(|source| HookError::Spawn {
584            hook_name: hook_name.to_owned(),
585            path: spec.program.clone(),
586            source,
587            output: HookOutput::default(),
588        })?)
589    }
590
591    /// Run `script` (spelled `argv0` for the child) directly, or through a shell when the OS
592    /// will not execute it. On Windows a script with a `#!` line goes straight to that
593    /// interpreter.
594    #[cfg_attr(not(windows), allow(unused_variables))]
595    fn spawn_traditional(
596        &self,
597        hook_name: &str,
598        script: &Path,
599        argv0: &Path,
600        args: &[&str],
601    ) -> crate::error::Result<RunningCommand> {
602        let argv0 = path_without_verbatim_prefix(argv0);
603        let via_shell = |shell: ScriptInterpreter| {
604            let invocation = ShellInvocation::ScriptPath {
605                script_path: argv0.to_path_buf(),
606                args: args.iter().map(OsString::from).collect(),
607            };
608            self.interpreter_spec(shell, invocation, args)
609        };
610        #[cfg(windows)]
611        if let Some(interpreter) = script_shebang_interpreter(script, self.env) {
612            return self.spawn(&via_shell(interpreter), hook_name);
613        }
614        let direct = self.spec(argv0.to_path_buf(), None, args);
615        match self.spawn(&direct, hook_name) {
616            Err(crate::error::Error::Hook(HookError::Spawn { source, .. }))
617                if is_not_an_executable(&source) =>
618            {
619                self.spawn(&via_shell(hook_shell(self.env)), hook_name)
620            }
621            other => other,
622        }
623    }
624
625    /// Run a `hook.<name>.command` entry as `sh -c <command> hook <args>…`.
626    fn spawn_configured(
627        &self,
628        hook_name: &str,
629        command: &str,
630        args: &[&str],
631    ) -> crate::error::Result<RunningCommand> {
632        let invocation = ShellInvocation::DashC {
633            script: command.to_owned(),
634            argv0: Some("hook".to_owned()),
635            args: args.iter().map(OsString::from).collect(),
636        };
637        self.spawn(
638            &self.interpreter_spec(hook_shell(self.env), invocation, args),
639            hook_name,
640        )
641    }
642}
643
644/// Well-known lifecycle hooks that porcelain operations run and report in their outcomes
645/// (for example [`crate::porcelain::commit::CommitOutcome::hooks_run`]).
646#[derive(Debug, Clone, Copy, PartialEq, Eq)]
647#[cfg_attr(feature = "serde-models", derive(serde::Serialize))]
648#[cfg_attr(feature = "serde-models", serde(rename_all = "kebab-case"))]
649pub enum HookName {
650    /// `.git/hooks/pre-commit` or `hook.pre-commit.*`.
651    PreCommit,
652    /// `.git/hooks/pre-merge-commit`, run before a clean merge records its commit.
653    PreMergeCommit,
654    /// `.git/hooks/prepare-commit-msg`, run on the message file before `commit-msg`; not skipped
655    /// by `--no-verify`.
656    PrepareCommitMsg,
657    /// `.git/hooks/commit-msg` or `hook.commit-msg.*`.
658    CommitMsg,
659    /// `.git/hooks/post-commit` or `hook.post-commit.*`.
660    PostCommit,
661    /// `.git/hooks/post-checkout`, run after `HEAD` moves to another commit or branch.
662    PostCheckout,
663    /// `.git/hooks/post-merge`, run after a merge or fast-forward updates the work tree.
664    PostMerge,
665    /// `.git/hooks/post-rewrite`, run after amend or a history rewrite replaces commits.
666    PostRewrite,
667    /// `.git/hooks/pre-rebase`, run before a rebase rewrites anything; a non-zero exit refuses
668    /// the rebase.
669    PreRebase,
670}
671
672impl HookName {
673    /// Git hook basename (`pre-commit`, `commit-msg`, `post-commit`, `post-checkout`, …).
674    #[must_use]
675    pub const fn as_str(self) -> &'static str {
676        match self {
677            Self::PreCommit => "pre-commit",
678            Self::PreMergeCommit => "pre-merge-commit",
679            Self::PrepareCommitMsg => "prepare-commit-msg",
680            Self::PreRebase => "pre-rebase",
681            Self::CommitMsg => "commit-msg",
682            Self::PostCommit => "post-commit",
683            Self::PostCheckout => "post-checkout",
684            Self::PostMerge => "post-merge",
685            Self::PostRewrite => "post-rewrite",
686        }
687    }
688}
689
690/// Whether an operation runs the hooks Git runs once it has completed (`post-checkout`,
691/// `post-merge`, `post-rewrite`).
692///
693/// These hooks are advisory: their exit status never changes the operation's result. Callers
694/// that compose several operations (or an embedder that does not want user scripts to run)
695/// pass [`PostOperationHooks::Skip`].
696#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
697pub enum PostOperationHooks {
698    /// Run the installed post-operation hooks (default, matching Git).
699    #[default]
700    Run,
701    /// Do not run post-operation hooks.
702    Skip,
703}
704
705impl PostOperationHooks {
706    /// Whether hooks should run.
707    #[must_use]
708    pub const fn enabled(self) -> bool {
709        matches!(self, Self::Run)
710    }
711}
712
713/// What kind of rewrite a `post-rewrite` hook is told about (its first argument).
714#[derive(Debug, Clone, Copy, PartialEq, Eq)]
715pub enum RewriteKind {
716    /// `commit --amend` replaced the tip commit.
717    Amend,
718    /// A rebase or history edit replayed commits.
719    Rebase,
720}
721
722impl RewriteKind {
723    /// Hook argument (`amend` or `rebase`).
724    #[must_use]
725    pub const fn as_str(self) -> &'static str {
726        match self {
727            Self::Amend => "amend",
728            Self::Rebase => "rebase",
729        }
730    }
731}
732
733/// Run an advisory hook whose outcome never fails the surrounding operation.
734///
735/// Returns whether a hook ran (a non-zero exit still counts as having run). A hook that cannot
736/// be started, or invalid `hook.*` configuration, is reported as [`Warning::HookNotRun`] on the
737/// repository's diagnostics sink and returns `false`.
738///
739/// [`Warning::HookNotRun`]: crate::diagnostics::Warning::HookNotRun
740pub(crate) fn run_advisory_hook(
741    repo: &Repository,
742    hook: HookName,
743    args: &[&str],
744    stdin_data: Option<&[u8]>,
745    commit_env: Option<&CommitHookEnv<'_>>,
746) -> bool {
747    let result = match commit_env {
748        Some(env) => run_commit_hook(repo, hook.as_str(), args, stdin_data, env),
749        None => run_hook(repo, hook.as_str(), args, stdin_data),
750    };
751    match result {
752        Ok(result) => result.was_executed(),
753        Err(err) => {
754            let mut detail = err.to_string();
755            let mut cause = std::error::Error::source(&err);
756            while let Some(c) = cause {
757                detail.push_str(": ");
758                detail.push_str(&c.to_string());
759                cause = c.source();
760            }
761            repo.warn(crate::diagnostics::Warning::HookNotRun {
762                hook_name: hook.as_str().to_owned(),
763                detail,
764            });
765            false
766        }
767    }
768}
769
770/// Run `post-checkout <old> <new> <flag>` after `HEAD` moved.
771///
772/// `old` is the commit `HEAD` pointed at before (`None` for an unborn branch, passed as the null
773/// object id). `branch_checkout` is `true` when `HEAD` itself moved to another branch or commit
774/// (switch, rebase) and `false` when only paths were checked out.
775///
776/// Returns whether a hook ran (a non-zero exit still counts). The hook's outcome is never an
777/// error: a hook that cannot be started is reported as
778/// [`Warning::HookNotRun`](crate::diagnostics::Warning::HookNotRun) and returns `false`.
779pub(crate) fn run_post_checkout(
780    repo: &Repository,
781    old: Option<ObjectId>,
782    new: ObjectId,
783    branch_checkout: bool,
784) -> bool {
785    let old_hex = old
786        .unwrap_or_else(|| ObjectId::null(repo.odb().hash_algo()))
787        .to_hex();
788    let new_hex = new.to_hex();
789    let flag = if branch_checkout { "1" } else { "0" };
790    run_advisory_hook(
791        repo,
792        HookName::PostCheckout,
793        &[old_hex.as_str(), new_hex.as_str(), flag],
794        None,
795        None,
796    )
797}
798
799/// Run `post-merge <flag>` after a merge or fast-forward updated the work tree; the flag is
800/// `1` for a squash merge and `0` otherwise.
801///
802/// Returns whether a hook ran; failures never become errors (see [`run_post_checkout`]).
803pub(crate) fn run_post_merge(repo: &Repository, squash: bool) -> bool {
804    run_advisory_hook(
805        repo,
806        HookName::PostMerge,
807        &[if squash { "1" } else { "0" }],
808        None,
809        None,
810    )
811}
812
813/// Run `pre-rebase <upstream>` before a rebase of the checked-out branch rewrites anything.
814///
815/// `upstream` is the upstream exactly as the user named it (Git passes the argument, not the
816/// resolved commit). `None` means the branch's configured upstream, which the hook receives as
817/// its full ref name (`refs/remotes/origin/main`), as Git does. The hook gets no second
818/// argument because the branch being rebased is the current one.
819///
820/// Returns whether a hook ran.
821///
822/// # Errors
823///
824/// [`HookError::Failed`] when the hook exits non-zero, which refuses the rebase;
825/// [`HookError::Spawn`], repository errors, or [`HookError::MissingHookCommand`] as for
826/// [`run_hook`].
827pub(crate) fn run_pre_rebase(
828    repo: &Repository,
829    upstream: Option<&str>,
830) -> crate::error::Result<bool> {
831    let configured;
832    let upstream_arg = match upstream {
833        Some(arg) => arg,
834        None => {
835            configured = crate::state::resolve_head_for_repository(repo)
836                .ok()
837                .and_then(|head| {
838                    head.branch_name().and_then(|branch| {
839                        crate::branch_tracking::upstream_tracking_full_ref(repo, branch)
840                    })
841                })
842                .unwrap_or_else(|| "@{upstream}".to_owned());
843            configured.as_str()
844        }
845    };
846    let name = HookName::PreRebase.as_str();
847    run_hook(repo, name, &[upstream_arg], None)?.check(name)
848}
849
850/// Bytes fed to `post-rewrite` on stdin: one `<old> <new>` line per rewritten commit.
851#[must_use]
852pub fn post_rewrite_stdin(pairs: &[(ObjectId, ObjectId)]) -> Vec<u8> {
853    let mut out = Vec::with_capacity(pairs.len() * 82);
854    for (old, new) in pairs {
855        out.extend_from_slice(old.to_hex().as_bytes());
856        out.push(b' ');
857        out.extend_from_slice(new.to_hex().as_bytes());
858        out.push(b'\n');
859    }
860    out
861}
862
863/// Run `post-rewrite <amend|rebase>` with `pairs` (`old new`, oldest first) on stdin.
864///
865/// Nothing runs when `pairs` is empty. Returns whether a hook ran; failures never become errors
866/// (see [`run_post_checkout`]).
867pub(crate) fn run_post_rewrite(
868    repo: &Repository,
869    kind: RewriteKind,
870    pairs: &[(ObjectId, ObjectId)],
871) -> bool {
872    if pairs.is_empty() {
873        return false;
874    }
875    let stdin = post_rewrite_stdin(pairs);
876    run_advisory_hook(
877        repo,
878        HookName::PostRewrite,
879        &[kind.as_str()],
880        Some(&stdin),
881        None,
882    )
883}
884
885/// Result of running the hooks for one event.
886#[derive(Debug, Clone, PartialEq, Eq)]
887pub enum HookResult {
888    /// Every hook ran and exited 0.
889    Success {
890        /// What the hooks wrote; empty under [`HookStdio::Inherit`].
891        output: HookOutput,
892    },
893    /// No hook is installed for the event (or it is not executable) — treated as success.
894    NotFound,
895    /// A hook exited non-zero; later hooks for the event did not run.
896    Failed {
897        /// Exit code of the failing hook (1 when it had none, e.g. killed by a signal).
898        status: i32,
899        /// What the hooks wrote up to and including the failing one; empty under
900        /// [`HookStdio::Inherit`].
901        output: HookOutput,
902    },
903}
904
905impl HookResult {
906    /// Returns true if the hook was successful or not found.
907    #[must_use]
908    pub fn is_ok(&self) -> bool {
909        matches!(self, HookResult::Success { .. } | HookResult::NotFound)
910    }
911
912    /// Returns true if the hook existed and ran (regardless of exit code).
913    #[must_use]
914    pub fn was_executed(&self) -> bool {
915        !matches!(self, HookResult::NotFound)
916    }
917
918    /// Exit code of the hook run: `Some(0)` on success, `None` when no hook ran.
919    #[must_use]
920    pub fn status(&self) -> Option<i32> {
921        match self {
922            HookResult::Success { .. } => Some(0),
923            HookResult::NotFound => None,
924            HookResult::Failed { status, .. } => Some(*status),
925        }
926    }
927
928    /// Captured output, or `None` when no hook ran.
929    #[must_use]
930    pub fn output(&self) -> Option<&HookOutput> {
931        match self {
932            HookResult::Success { output } | HookResult::Failed { output, .. } => Some(output),
933            HookResult::NotFound => None,
934        }
935    }
936
937    /// Turn a failed run into [`HookError::Failed`] for `hook_name`; returns whether a hook ran.
938    ///
939    /// # Errors
940    ///
941    /// [`HookError::Failed`] carrying the status and captured output when a hook exited non-zero.
942    pub fn check(self, hook_name: &str) -> crate::error::Result<bool> {
943        match self {
944            HookResult::Success { .. } => Ok(true),
945            HookResult::NotFound => Ok(false),
946            HookResult::Failed { status, output } => Err(HookError::Failed {
947                hook_name: hook_name.to_owned(),
948                status,
949                output,
950            }
951            .into()),
952        }
953    }
954}
955
956/// Options for [`run_hook_opts`].
957#[derive(Debug, Clone, Default)]
958pub struct RunHookOptions<'a> {
959    /// Capture hook output or let hooks write to this process's stderr (see [`HookStdio`]).
960    ///
961    /// The `run_*` helpers that take a [`Repository`] use [`Repository::hook_stdio`].
962    pub stdio: HookStdio,
963    /// Under [`HookStdio::Inherit`], send hook stdout to this process's stderr (Git does this
964    /// for every hook except `pre-push`). Captured stdout is always returned separately.
965    pub stdout_to_stderr: bool,
966    /// File path to open and pipe to each hook's stdin (reopened per hook).
967    pub path_to_stdin: Option<&'a Path>,
968    /// In-memory stdin (used when `path_to_stdin` is None).
969    pub stdin_data: Option<&'a [u8]>,
970    /// Extra environment variables for each hook subprocess.
971    pub env_vars: &'a [(&'a str, &'a str)],
972    /// Override the hook process working directory.
973    pub cwd: Option<&'a Path>,
974    /// Commit-style env (`GIT_INDEX_FILE`, `GIT_PREFIX`, author exports, …) merged after `env_vars`.
975    pub commit_env: Option<&'a CommitHookEnv<'a>>,
976}
977
978/// Run all hooks for `hook_name` in Git order; return first non-zero exit or success.
979///
980/// When `repo` is `None`, only configured hooks run (out-of-repo); cwd is the process cwd and
981/// `GIT_DIR` is not set for those hooks.
982///
983/// Hook output is handled per [`RunHookOptions::stdio`]: captured into the returned
984/// [`HookOutput`], or written by the child straight to this process's stderr. The library
985/// never re-emits what a hook (or an injected [`CommandRunner`]) produced.
986///
987const HOOK_WAIT_POLL: Duration = Duration::from_millis(50);
988
989fn kill_pid_sigkill(pid: u32, kill_process_group: bool) {
990    crate::command_runner::force_kill_process_pid(pid, kill_process_group);
991}
992
993fn wait_hook_command(
994    child: RunningCommand,
995    capture: bool,
996    cancel: &CancelToken,
997    output: &mut HookOutput,
998) -> crate::error::Result<crate::command_runner::CommandExit> {
999    use crate::command_runner::CommandOutput;
1000
1001    if cancel.is_cancelled() {
1002        return stop_hook_child(child, capture, output);
1003    }
1004
1005    if child.child_pid().is_none() {
1006        return finish_hook_wait(child, capture, output);
1007    }
1008
1009    let pid = child.child_pid();
1010    let kill_process_group = child.kill_process_group();
1011    let shared = std::sync::Arc::new(std::sync::Mutex::new(Some(child)));
1012    let shared_wait = std::sync::Arc::clone(&shared);
1013    let (tx, rx) = std::sync::mpsc::sync_channel(1);
1014    std::thread::spawn(move || {
1015        let child = shared_wait.lock().unwrap_or_else(|e| e.into_inner()).take();
1016        let Some(child) = child else {
1017            return;
1018        };
1019        let result = if capture {
1020            child.wait_with_output()
1021        } else {
1022            child.wait().map(|status| CommandOutput {
1023                status,
1024                stdout: Vec::new(),
1025                stderr: Vec::new(),
1026            })
1027        };
1028        let _ = tx.send(result);
1029    });
1030
1031    loop {
1032        if cancel.is_cancelled() {
1033            if let Some(mut child) = shared.lock().unwrap_or_else(|e| e.into_inner()).take() {
1034                let _ = child.kill();
1035                if capture {
1036                    if let Ok(out) = child.wait_with_output() {
1037                        output.stdout.extend_from_slice(&out.stdout);
1038                        output.stderr.extend_from_slice(&out.stderr);
1039                    }
1040                } else {
1041                    let _ = child.wait();
1042                }
1043            }
1044            if let Some(pid) = pid {
1045                kill_pid_sigkill(pid, kill_process_group);
1046            }
1047            if let Ok(Ok(out)) = rx.recv_timeout(HOOK_WAIT_POLL.saturating_mul(20)) {
1048                if capture {
1049                    output.stdout.extend_from_slice(&out.stdout);
1050                    output.stderr.extend_from_slice(&out.stderr);
1051                }
1052            }
1053            return Err(crate::error::Error::Cancelled);
1054        }
1055        match rx.try_recv() {
1056            Ok(Ok(out)) => {
1057                if capture {
1058                    output.stdout.extend_from_slice(&out.stdout);
1059                    output.stderr.extend_from_slice(&out.stderr);
1060                }
1061                return Ok(out.status);
1062            }
1063            Ok(Err(_)) => {
1064                return Ok(crate::command_runner::CommandExit {
1065                    success: false,
1066                    code: Some(1),
1067                });
1068            }
1069            Err(std::sync::mpsc::TryRecvError::Empty) => {
1070                std::thread::sleep(HOOK_WAIT_POLL);
1071            }
1072            Err(std::sync::mpsc::TryRecvError::Disconnected) => {
1073                return Ok(crate::command_runner::CommandExit {
1074                    success: false,
1075                    code: Some(1),
1076                });
1077            }
1078        }
1079    }
1080}
1081
1082fn stop_hook_child(
1083    child: RunningCommand,
1084    capture: bool,
1085    output: &mut HookOutput,
1086) -> crate::error::Result<crate::command_runner::CommandExit> {
1087    let pid = child.child_pid();
1088    let kill_process_group = child.kill_process_group();
1089    let mut child = child;
1090    let _ = child.kill();
1091    let _ = finish_hook_wait(child, capture, output);
1092    if let Some(pid) = pid {
1093        kill_pid_sigkill(pid, kill_process_group);
1094    }
1095    Err(crate::error::Error::Cancelled)
1096}
1097
1098fn finish_hook_wait(
1099    child: RunningCommand,
1100    capture: bool,
1101    output: &mut HookOutput,
1102) -> crate::error::Result<crate::command_runner::CommandExit> {
1103    if capture {
1104        match child.wait_with_output() {
1105            Ok(out) => {
1106                output.stdout.extend_from_slice(&out.stdout);
1107                output.stderr.extend_from_slice(&out.stderr);
1108                Ok(out.status)
1109            }
1110            Err(_) => Ok(crate::command_runner::CommandExit {
1111                success: false,
1112                code: Some(1),
1113            }),
1114        }
1115    } else {
1116        match child.wait() {
1117            Ok(status) => Ok(status),
1118            Err(_) => Ok(crate::command_runner::CommandExit {
1119                success: false,
1120                code: Some(1),
1121            }),
1122        }
1123    }
1124}
1125
1126/// # Errors
1127///
1128/// [`HookError::Spawn`] when a hook (or the shell that runs it) cannot be started, carrying the
1129/// output earlier hooks for the event already wrote, and [`HookError::MissingHookCommand`] for an
1130/// incomplete `hook.*` configuration. A hook that runs and exits non-zero is
1131/// `Ok(HookResult::Failed { .. })`.
1132pub(crate) fn run_hook_opts(
1133    repo: Option<&Repository>,
1134    hook_name: &str,
1135    args: &[&str],
1136    config: &ConfigSet,
1137    opts: RunHookOptions<'_>,
1138) -> crate::error::Result<HookResult> {
1139    run_hook_opts_with_cancel(
1140        repo,
1141        hook_name,
1142        args,
1143        config,
1144        opts,
1145        &CancelToken::never(),
1146        false,
1147    )
1148}
1149
1150fn run_hook_opts_with_cancel(
1151    repo: Option<&Repository>,
1152    hook_name: &str,
1153    args: &[&str],
1154    config: &ConfigSet,
1155    opts: RunHookOptions<'_>,
1156    cancel: &CancelToken,
1157    server_receive_hook: bool,
1158) -> crate::error::Result<HookResult> {
1159    let seq = match repo {
1160        Some(r) => resolve_hook_sequence(r, hook_name, config)?,
1161        None => resolve_configured_hooks_only(hook_name, config)?,
1162    };
1163    if seq.is_empty() {
1164        return Ok(HookResult::NotFound);
1165    }
1166
1167    let work_dir: PathBuf = opts.cwd.map_or_else(
1168        || match repo {
1169            Some(r) => hook_run_dir(r).to_path_buf(),
1170            None => PathBuf::from("."),
1171        },
1172        Path::to_path_buf,
1173    );
1174    let work_dir = work_dir.as_path();
1175    let git_dir_for_configured = repo.map(|r| r.git_dir());
1176    let runner: Arc<dyn CommandRunner> = match repo {
1177        Some(r) => r.command_runner(),
1178        None => system_command_runner(),
1179    };
1180
1181    let mut merged_env: Vec<(String, String)> = opts
1182        .env_vars
1183        .iter()
1184        .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
1185        .collect();
1186    if let Some(r) = repo {
1187        if let Some(ce) = opts.commit_env {
1188            merged_env.extend(build_commit_hook_env(r, work_dir, ce));
1189        }
1190    }
1191
1192    let mut hook_env = match repo {
1193        Some(r) => CommandEnvironment::from_repository_environment(r.environment(), &merged_env),
1194        None => hook_command_env(git_dir_for_configured, &merged_env),
1195    };
1196    if cfg!(windows) {
1197        strip_verbatim_prefix_from_path_vars(&mut hook_env.set);
1198    }
1199
1200    let capture = opts.stdio == HookStdio::Capture;
1201    let (stdout, stderr) = match opts.stdio {
1202        HookStdio::Capture => (CommandStdio::Pipe, CommandStdio::Pipe),
1203        HookStdio::Inherit if opts.stdout_to_stderr => {
1204            (CommandStdio::ParentStderr, CommandStdio::Inherit)
1205        }
1206        HookStdio::Inherit => (CommandStdio::Inherit, CommandStdio::Inherit),
1207    };
1208    let mut output = HookOutput::default();
1209
1210    for h in &seq {
1211        let (stdin_piped, stdin_file) = match opts.path_to_stdin {
1212            Some(p) => (true, Some(p.to_path_buf())),
1213            None => (opts.stdin_data.is_some(), None),
1214        };
1215
1216        let ctx = HookSpawnContext {
1217            runner: runner.as_ref(),
1218            cwd: work_dir,
1219            env: &hook_env,
1220            stdin_piped,
1221            stdout,
1222            stderr,
1223            server_receive_hook,
1224        };
1225        let spawned = match h {
1226            ResolvedHook::Traditional { path, argv0 } => {
1227                let Some(r) = repo else {
1228                    continue;
1229                };
1230                let effective_argv0 = path
1231                    .parent()
1232                    .map(|hooks_dir| hook_argv0(r, hooks_dir, hook_name, work_dir))
1233                    .unwrap_or_else(|| argv0.clone());
1234                ctx.spawn_traditional(hook_name, path, &effective_argv0, args)
1235            }
1236            ResolvedHook::Configured { command } => ctx.spawn_configured(hook_name, command, args),
1237        };
1238        let mut child = match spawned {
1239            Ok(child) => child,
1240            Err(crate::error::Error::Hook(HookError::Spawn {
1241                hook_name,
1242                path,
1243                source,
1244                ..
1245            })) => {
1246                return Err(HookError::Spawn {
1247                    hook_name,
1248                    path,
1249                    source,
1250                    output,
1251                }
1252                .into())
1253            }
1254            Err(other) => return Err(other),
1255        };
1256
1257        let exit = if capture && stdin_piped && (stdin_file.is_some() || opts.stdin_data.is_some())
1258        {
1259            if cancel.is_cancelled() {
1260                let pid = child.child_pid();
1261                let kill_process_group = child.kill_process_group();
1262                let mut child = child;
1263                let _ = child.kill();
1264                if let Some(pid) = pid {
1265                    kill_pid_sigkill(pid, kill_process_group);
1266                }
1267                return Err(crate::error::Error::Cancelled);
1268            }
1269            let output_result = if let Some(ref path) = stdin_file {
1270                let file = match fs::File::open(path) {
1271                    Ok(f) => f,
1272                    Err(_e) => {
1273                        return Ok(HookResult::Failed { status: 1, output });
1274                    }
1275                };
1276                child.feed_stdin_and_wait_with_output(Some(ConcurrentStdinFeed::File(file)))
1277            } else if let Some(data) = opts.stdin_data {
1278                child.feed_stdin_and_wait_with_output(Some(ConcurrentStdinFeed::Bytes(data)))
1279            } else {
1280                child.close_stdin();
1281                child.wait_with_output()
1282            };
1283            match output_result {
1284                Ok(o) => {
1285                    output.stdout.extend_from_slice(&o.stdout);
1286                    output.stderr.extend_from_slice(&o.stderr);
1287                    o.status
1288                }
1289                Err(_) => crate::command_runner::CommandExit {
1290                    success: false,
1291                    code: Some(1),
1292                },
1293            }
1294        } else {
1295            if let Some(ref path) = stdin_file {
1296                let file = match fs::File::open(path) {
1297                    Ok(f) => f,
1298                    Err(_e) => {
1299                        return Ok(HookResult::Failed { status: 1, output });
1300                    }
1301                };
1302                if let Some(stdin) = child.stdin_mut() {
1303                    let mut file = file;
1304                    let _ = crate::sigpipe::copy(&mut file, stdin);
1305                }
1306            } else if let Some(data) = opts.stdin_data {
1307                if let Some(stdin) = child.stdin_mut() {
1308                    let _ = crate::sigpipe::write_all(stdin, data);
1309                }
1310            }
1311            if stdin_piped {
1312                child.close_stdin();
1313            }
1314            match wait_hook_command(child, capture, cancel, &mut output) {
1315                Ok(exit) => exit,
1316                Err(crate::error::Error::Cancelled) => return Err(crate::error::Error::Cancelled),
1317                Err(other) => return Err(other),
1318            }
1319        };
1320
1321        if !exit.success {
1322            if let Some(r) = repo {
1323                let _ = r.reload_config();
1324            }
1325            return Ok(HookResult::Failed {
1326                status: exit.code.unwrap_or(1),
1327                output,
1328            });
1329        }
1330    }
1331
1332    if let Some(r) = repo {
1333        let _ = r.reload_config();
1334    }
1335
1336    Ok(HookResult::Success { output })
1337}
1338
1339/// Like [`run_commit_hook`] but a hook that exits non-zero is an error.
1340///
1341/// # Errors
1342///
1343/// [`HookError::Failed`] with the hook's exit status and captured output, or any error from
1344/// [`run_commit_hook`].
1345pub(crate) fn run_commit_hook_checked(
1346    repo: &Repository,
1347    hook_name: &str,
1348    args: &[&str],
1349    stdin_data: Option<&[u8]>,
1350    commit_env: &CommitHookEnv<'_>,
1351) -> crate::error::Result<()> {
1352    run_commit_hook(repo, hook_name, args, stdin_data, commit_env)?
1353        .check(hook_name)
1354        .map(drop)
1355}
1356
1357/// Run commit-style hooks with `GIT_INDEX_FILE`, `GIT_PREFIX`, and related env (Git `run_commit_hook`).
1358///
1359/// Output follows [`Repository::hook_stdio`].
1360///
1361/// # Errors
1362///
1363/// [`HookError::Spawn`] when a hook cannot be started, repository errors when repository
1364/// config cannot be loaded, or [`HookError::MissingHookCommand`] when a configured hook has no
1365/// command.
1366pub(crate) fn run_commit_hook(
1367    repo: &Repository,
1368    hook_name: &str,
1369    args: &[&str],
1370    stdin_data: Option<&[u8]>,
1371    commit_env: &CommitHookEnv<'_>,
1372) -> crate::error::Result<HookResult> {
1373    run_commit_hook_with_cancel(
1374        repo,
1375        hook_name,
1376        args,
1377        stdin_data,
1378        commit_env,
1379        &CancelToken::never(),
1380    )
1381}
1382
1383/// Like [`run_commit_hook`] but honours [`Cancel`] while hook subprocesses run.
1384pub(crate) fn run_commit_hook_with_cancel(
1385    repo: &Repository,
1386    hook_name: &str,
1387    args: &[&str],
1388    stdin_data: Option<&[u8]>,
1389    commit_env: &CommitHookEnv<'_>,
1390    cancel: &CancelToken,
1391) -> crate::error::Result<HookResult> {
1392    let config = repo.config().snapshot()?;
1393    run_hook_opts_with_cancel(
1394        Some(repo),
1395        hook_name,
1396        args,
1397        config.as_ref(),
1398        RunHookOptions {
1399            stdin_data,
1400            commit_env: Some(commit_env),
1401            ..repo_hook_options(repo, hook_name)
1402        },
1403        cancel,
1404        false,
1405    )
1406}
1407
1408/// Default [`RunHookOptions`] for `hook_name` on `repo`: [`Repository::hook_stdio`], and stdout
1409/// sent to stderr for every hook except `pre-push`, whose stdout is part of its protocol.
1410fn repo_hook_options<'a>(repo: &Repository, hook_name: &str) -> RunHookOptions<'a> {
1411    RunHookOptions {
1412        stdio: repo.hook_stdio(),
1413        stdout_to_stderr: hook_name != "pre-push",
1414        ..RunHookOptions::default()
1415    }
1416}
1417
1418/// Run a hook by name with the given arguments (Git-compatible multihooks).
1419///
1420/// Output follows [`Repository::hook_stdio`]; when inherited, `pre-push` keeps stdout
1421/// separate and other hooks send stdout to stderr.
1422///
1423/// # Errors
1424///
1425/// [`HookError::Spawn`] when a hook cannot be started, repository errors when repository
1426/// config cannot be loaded, or [`HookError::MissingHookCommand`] when a configured hook has no
1427/// command.
1428pub(crate) fn run_hook(
1429    repo: &Repository,
1430    hook_name: &str,
1431    args: &[&str],
1432    stdin_data: Option<&[u8]>,
1433) -> crate::error::Result<HookResult> {
1434    let config = repo.config().snapshot()?;
1435    run_hook_opts(
1436        Some(repo),
1437        hook_name,
1438        args,
1439        config.as_ref(),
1440        RunHookOptions {
1441            stdin_data,
1442            ..repo_hook_options(repo, hook_name)
1443        },
1444    )
1445}
1446
1447/// Run a server-side hook (`pre-receive`, `update`, …) with cwd = `GIT_DIR`.
1448///
1449/// The hook sees `GIT_DIR=.`, as Git's receive-pack hooks do, so scripts that run
1450/// `git` commands address the repository they were started in.
1451///
1452/// Output is always captured, whatever [`Repository::hook_stdio`] says, because the server
1453/// relays it to the client over the sideband. A hook that cannot be resolved or started is
1454/// reported as `Failed { status: 1 }` so the push is declined.
1455pub(crate) fn run_hook_in_git_dir(
1456    repo: &Repository,
1457    hook_name: &str,
1458    args: &[&str],
1459    stdin_data: Option<&[u8]>,
1460    env_vars: &[(&str, &str)],
1461) -> HookResult {
1462    run_hook_in_git_dir_with_cancel(
1463        repo,
1464        hook_name,
1465        args,
1466        stdin_data,
1467        env_vars,
1468        &CancelToken::never(),
1469    )
1470    .unwrap_or_else(|_| hook_declined())
1471}
1472
1473fn hook_declined() -> HookResult {
1474    HookResult::Failed {
1475        status: 1,
1476        output: HookOutput::default(),
1477    }
1478}
1479
1480/// Like [`run_hook_in_git_dir`], but honours [`CancelToken`](crate::progress::CancelToken) and can terminate the hook process group.
1481///
1482/// # Errors
1483///
1484/// [`Error::Cancelled`](crate::error::Error::Cancelled) when `cancel` is set while a hook subprocess runs.
1485pub(crate) fn run_hook_in_git_dir_with_cancel(
1486    repo: &Repository,
1487    hook_name: &str,
1488    args: &[&str],
1489    stdin_data: Option<&[u8]>,
1490    env_vars: &[(&str, &str)],
1491    cancel: &CancelToken,
1492) -> crate::error::Result<HookResult> {
1493    let env_vars: Vec<(&str, &str)> = std::iter::once(("GIT_DIR", "."))
1494        .chain(env_vars.iter().copied())
1495        .collect();
1496    let config = repo.config().snapshot()?;
1497    run_hook_opts_with_cancel(
1498        Some(repo),
1499        hook_name,
1500        args,
1501        config.as_ref(),
1502        RunHookOptions {
1503            stdio: HookStdio::Capture,
1504            stdout_to_stderr: true,
1505            stdin_data,
1506            env_vars: &env_vars,
1507            cwd: Some(repo.git_dir()),
1508            ..RunHookOptions::default()
1509        },
1510        cancel,
1511        true,
1512    )
1513}
1514
1515/// One ref update a push is about to make, as reported to the `pre-push` hook.
1516#[derive(Clone, Debug, PartialEq, Eq)]
1517pub struct PrePushRef {
1518    /// Local source as named by the push (`refs/heads/main`, `HEAD`, …). `None` when the
1519    /// source was a bare object id, or for a deletion.
1520    pub local_ref: Option<String>,
1521    /// Object the remote ref will point at; `None` for a deletion.
1522    pub local_oid: Option<ObjectId>,
1523    /// Destination ref on the remote (`refs/heads/main`).
1524    pub remote_ref: String,
1525    /// Current value of [`Self::remote_ref`] on the remote; `None` when it does not exist.
1526    pub remote_oid: Option<ObjectId>,
1527}
1528
1529impl PrePushRef {
1530    /// The hook's stdin line: `<local ref> SP <local oid> SP <remote ref> SP <remote oid> LF`.
1531    ///
1532    /// A missing object id is written as the all-zero id of width `algo`; a deletion's local
1533    /// ref is `(delete)` and a bare object id source repeats the id.
1534    fn stdin_line(&self, algo: crate::objects::HashAlgo) -> String {
1535        let zero = "0".repeat(algo.hex_len());
1536        let hex = |oid: Option<ObjectId>| oid.map_or_else(|| zero.clone(), |o| o.to_hex());
1537        let local_ref = match (&self.local_ref, self.local_oid) {
1538            (Some(name), _) => name.clone(),
1539            (None, Some(oid)) => oid.to_hex(),
1540            (None, None) => "(delete)".to_owned(),
1541        };
1542        format!(
1543            "{local_ref} {} {} {}\n",
1544            hex(self.local_oid),
1545            self.remote_ref,
1546            hex(self.remote_oid)
1547        )
1548    }
1549}
1550
1551/// Run the client-side `pre-push` hook before a push sends anything.
1552///
1553/// The hook receives `remote` (the remote's name, or its URL for an unnamed remote) and `url`
1554/// as arguments, and one [`PrePushRef`] line per update on stdin. It runs even when `refs` is
1555/// empty. Output follows [`Repository::hook_stdio`]; under [`HookStdio::Inherit`] the hook's
1556/// stdout goes to stderr with its stderr, so a caller's own stdout (for example JSON output)
1557/// stays clean.
1558///
1559/// Returns the hook's captured output (empty under [`HookStdio::Inherit`] or when no hook is
1560/// installed).
1561///
1562/// # Errors
1563///
1564/// [`HookError::Failed`] when the hook exits non-zero (the push must not proceed),
1565/// [`HookError::Spawn`] when it cannot be started, repository errors when configuration
1566/// cannot be loaded, and [`HookError::MissingHookCommand`] when a configured hook has no command.
1567pub(crate) fn run_pre_push_hook(
1568    repo: &Repository,
1569    remote: &str,
1570    url: &str,
1571    refs: &[PrePushRef],
1572) -> crate::error::Result<HookOutput> {
1573    let config = repo.config().snapshot()?;
1574    let algo = repo.odb().hash_algo();
1575    let stdin: String = refs.iter().map(|r| r.stdin_line(algo)).collect();
1576    let result = run_hook_opts(
1577        Some(repo),
1578        "pre-push",
1579        &[remote, url],
1580        config.as_ref(),
1581        RunHookOptions {
1582            stdout_to_stderr: true,
1583            stdin_data: Some(stdin.as_bytes()),
1584            ..repo_hook_options(repo, "pre-push")
1585        },
1586    )?;
1587    let output = match &result {
1588        HookResult::Success { output } => output.clone(),
1589        HookResult::NotFound | HookResult::Failed { .. } => HookOutput::default(),
1590    };
1591    result.check("pre-push")?;
1592    Ok(output)
1593}
1594
1595/// Phase argument for the [`reference-transaction`](https://git-scm.com/docs/githooks#_reference_transaction) hook.
1596#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1597pub(crate) enum ReferenceTransactionPhase {
1598    /// Before any ref write in the transaction; non-zero exit aborts the batch.
1599    Prepared,
1600    /// After refs were written successfully.
1601    Committed,
1602    /// After the transaction was aborted without writing (or after `prepared` refused).
1603    Aborted,
1604}
1605
1606impl ReferenceTransactionPhase {
1607    fn as_arg(self) -> &'static str {
1608        match self {
1609            Self::Prepared => "prepared",
1610            Self::Committed => "committed",
1611            Self::Aborted => "aborted",
1612        }
1613    }
1614}
1615
1616/// Cached hook execution context for ref-store transactions (no full [`Repository`] handle).
1617#[derive(Clone)]
1618pub struct RefHookContext {
1619    git_dir: PathBuf,
1620    work_tree: Option<PathBuf>,
1621    environment: Arc<Environment>,
1622    command_runner: Arc<dyn CommandRunner>,
1623    hook_stdio: HookStdio,
1624    #[cfg_attr(not(unix), allow(dead_code))]
1625    diagnostics: crate::diagnostics::DiagnosticsHandle,
1626    hash_algo: HashAlgo,
1627}
1628
1629impl RefHookContext {
1630    /// Build hook context for a repository being opened.
1631    #[allow(clippy::too_many_arguments)]
1632    pub(crate) fn new(
1633        git_dir: PathBuf,
1634        work_tree: Option<PathBuf>,
1635        environment: Arc<Environment>,
1636        command_runner: Arc<dyn CommandRunner>,
1637        hook_stdio: HookStdio,
1638        diagnostics: crate::diagnostics::DiagnosticsHandle,
1639        hash_algo: HashAlgo,
1640    ) -> Self {
1641        Self {
1642            git_dir,
1643            work_tree,
1644            environment,
1645            command_runner,
1646            hook_stdio,
1647            diagnostics,
1648            hash_algo,
1649        }
1650    }
1651
1652    /// Git directory this context was opened for (main or linked worktree admin dir).
1653    #[must_use]
1654    pub(crate) fn git_dir(&self) -> &Path {
1655        &self.git_dir
1656    }
1657
1658    /// Null object id for this repository's hash algorithm.
1659    #[must_use]
1660    pub(crate) fn null_oid(&self) -> ObjectId {
1661        ObjectId::null(self.hash_algo)
1662    }
1663
1664    fn hook_run_dir(&self) -> &Path {
1665        self.work_tree.as_deref().unwrap_or(&self.git_dir)
1666    }
1667
1668    fn load_config(&self) -> crate::error::Result<Arc<crate::config::ConfigSet>> {
1669        crate::config::ConfigSet::load(
1670            &self.environment,
1671            Some(&self.git_dir),
1672            &crate::config::LoadConfigOptions::standard(&self.environment, Some(&self.git_dir)),
1673        )
1674        .map(Arc::new)
1675    }
1676
1677    /// Run the `reference-transaction` hook for one phase and stdin payload.
1678    ///
1679    /// A failure on [`ReferenceTransactionPhase::Prepared`] is returned as [`HookError::Failed`]
1680    /// or [`HookError::Spawn`]; `committed` and `aborted` ignore hook failures.
1681    pub(crate) fn run_reference_transaction(
1682        &self,
1683        phase: ReferenceTransactionPhase,
1684        stdin: &[u8],
1685    ) -> crate::error::Result<()> {
1686        if stdin.is_empty() {
1687            return Ok(());
1688        }
1689        let config = self.load_config()?;
1690        let result = run_hook_opts_for_ref_context(
1691            self,
1692            "reference-transaction",
1693            &[phase.as_arg()],
1694            config.as_ref(),
1695            RunHookOptions {
1696                stdin_data: Some(stdin),
1697                stdout_to_stderr: true,
1698                stdio: self.hook_stdio,
1699                ..RunHookOptions::default()
1700            },
1701            &CancelToken::never(),
1702        )?;
1703        if phase == ReferenceTransactionPhase::Prepared {
1704            result.check("reference-transaction")?;
1705        }
1706        Ok(())
1707    }
1708}
1709
1710fn resolve_hooks_dir_for_ref(ctx: &RefHookContext, config: &ConfigSet) -> PathBuf {
1711    let dir = match config.value("core.hooksPath") {
1712        Some(hooks_path) => {
1713            let p = PathBuf::from(parse_path(ctx.environment.as_ref(), &hooks_path));
1714            if p.is_absolute() {
1715                p
1716            } else {
1717                ctx.hook_run_dir().join(p)
1718            }
1719        }
1720        None => crate::repo::common_git_dir_for_config(&ctx.git_dir).join("hooks"),
1721    };
1722    path_without_verbatim_prefix(&dir).into_owned()
1723}
1724
1725fn hook_argv0_for_ref(
1726    ctx: &RefHookContext,
1727    hooks_dir: &Path,
1728    hook_name: &str,
1729    cwd: &Path,
1730) -> PathBuf {
1731    let default_hooks_dir = ctx.git_dir.join("hooks");
1732    if same_dir(hooks_dir, &default_hooks_dir) {
1733        if cwd == ctx.git_dir.as_path() {
1734            return PathBuf::from("hooks").join(hook_name);
1735        }
1736        if let Some(work_tree) = &ctx.work_tree {
1737            if cwd == work_tree.as_path() && same_dir(&ctx.git_dir, &work_tree.join(".git")) {
1738                return PathBuf::from(".git").join("hooks").join(hook_name);
1739            }
1740        }
1741    }
1742    hooks_dir.join(hook_name)
1743}
1744
1745fn resolve_hook_sequence_for_ref(
1746    ctx: &RefHookContext,
1747    hook_name: &str,
1748    config: &ConfigSet,
1749) -> crate::error::Result<Vec<ResolvedHook>> {
1750    let tables = HookConfigTables::from_config(config);
1751    let mut seq = Vec::new();
1752    for (_friendly, command) in tables.hooks_for_event(hook_name)? {
1753        seq.push(ResolvedHook::Configured { command });
1754    }
1755    let hooks_dir = resolve_hooks_dir_for_ref(ctx, config);
1756    if let Some(path) = traditional_hook_candidate_for_ref(ctx, &hooks_dir, hook_name) {
1757        let argv0 = hook_argv0_for_ref(ctx, &hooks_dir, hook_name, ctx.hook_run_dir());
1758        seq.push(ResolvedHook::Traditional { path, argv0 });
1759    }
1760    Ok(seq)
1761}
1762
1763#[cfg_attr(not(unix), allow(unused_variables))]
1764fn traditional_hook_candidate_for_ref(
1765    ctx: &RefHookContext,
1766    hooks_dir: &Path,
1767    hook_name: &str,
1768) -> Option<PathBuf> {
1769    let path = hooks_dir.join(hook_name);
1770    if !path.exists() {
1771        return None;
1772    }
1773    let meta = fs::metadata(&path).ok()?;
1774    #[cfg(unix)]
1775    if meta.permissions().mode() & 0o111 == 0 {
1776        let show_warning = ctx
1777            .load_config()
1778            .ok()
1779            .and_then(|c| c.value("advice.ignoredHook"))
1780            .map(|v| !matches!(v.to_lowercase().as_str(), "false" | "no" | "off" | "0"))
1781            .unwrap_or(true);
1782        if show_warning {
1783            ctx.diagnostics
1784                .warn(crate::diagnostics::Warning::NonExecutableHookIgnored {
1785                    hook_name: hook_name.to_string(),
1786                    hook_path: Some(path.clone()),
1787                });
1788        }
1789        return None;
1790    }
1791    Some(path)
1792}
1793
1794fn run_hook_opts_for_ref_context(
1795    ctx: &RefHookContext,
1796    hook_name: &str,
1797    args: &[&str],
1798    config: &ConfigSet,
1799    opts: RunHookOptions<'_>,
1800    cancel: &CancelToken,
1801) -> crate::error::Result<HookResult> {
1802    let seq = resolve_hook_sequence_for_ref(ctx, hook_name, config)?;
1803    if seq.is_empty() {
1804        return Ok(HookResult::NotFound);
1805    }
1806
1807    let work_dir = opts
1808        .cwd
1809        .map(Path::to_path_buf)
1810        .unwrap_or_else(|| ctx.hook_run_dir().to_path_buf());
1811    let work_dir = work_dir.as_path();
1812    let runner = ctx.command_runner.as_ref();
1813
1814    let merged_env: Vec<(String, String)> = opts
1815        .env_vars
1816        .iter()
1817        .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
1818        .collect();
1819
1820    let mut hook_env =
1821        CommandEnvironment::from_repository_environment(ctx.environment.as_ref(), &merged_env);
1822    if cfg!(windows) {
1823        strip_verbatim_prefix_from_path_vars(&mut hook_env.set);
1824    }
1825    hook_env.set.push((
1826        OsString::from("GIT_DIR"),
1827        ctx.git_dir.as_os_str().to_os_string(),
1828    ));
1829
1830    let capture = opts.stdio == HookStdio::Capture;
1831    let (stdout, stderr) = match opts.stdio {
1832        HookStdio::Capture => (CommandStdio::Pipe, CommandStdio::Pipe),
1833        HookStdio::Inherit if opts.stdout_to_stderr => {
1834            (CommandStdio::ParentStderr, CommandStdio::Inherit)
1835        }
1836        HookStdio::Inherit => (CommandStdio::Inherit, CommandStdio::Inherit),
1837    };
1838    let mut output = HookOutput::default();
1839
1840    for h in &seq {
1841        let (stdin_piped, stdin_file) = match opts.path_to_stdin {
1842            Some(p) => (true, Some(p.to_path_buf())),
1843            None => (opts.stdin_data.is_some(), None),
1844        };
1845
1846        let hook_ctx = HookSpawnContext {
1847            runner,
1848            cwd: work_dir,
1849            env: &hook_env,
1850            stdin_piped,
1851            stdout,
1852            stderr,
1853            server_receive_hook: false,
1854        };
1855        let spawned = match h {
1856            ResolvedHook::Traditional { path, argv0 } => {
1857                let effective_argv0 = path
1858                    .parent()
1859                    .map(|hooks_dir| hook_argv0_for_ref(ctx, hooks_dir, hook_name, work_dir))
1860                    .unwrap_or_else(|| argv0.clone());
1861                hook_ctx.spawn_traditional(hook_name, path, &effective_argv0, args)
1862            }
1863            ResolvedHook::Configured { command } => {
1864                hook_ctx.spawn_configured(hook_name, command, args)
1865            }
1866        };
1867        let mut child = match spawned {
1868            Ok(child) => child,
1869            Err(crate::error::Error::Hook(HookError::Spawn {
1870                hook_name,
1871                path,
1872                source,
1873                ..
1874            })) => {
1875                return Err(HookError::Spawn {
1876                    hook_name,
1877                    path,
1878                    source,
1879                    output,
1880                }
1881                .into())
1882            }
1883            Err(other) => return Err(other),
1884        };
1885
1886        let exit = if capture && stdin_piped && (stdin_file.is_some() || opts.stdin_data.is_some())
1887        {
1888            if cancel.is_cancelled() {
1889                let pid = child.child_pid();
1890                let kill_process_group = child.kill_process_group();
1891                let mut child = child;
1892                let _ = child.kill();
1893                if let Some(pid) = pid {
1894                    kill_pid_sigkill(pid, kill_process_group);
1895                }
1896                return Err(crate::error::Error::Cancelled);
1897            }
1898            let output_result = if let Some(ref path) = stdin_file {
1899                let file = match fs::File::open(path) {
1900                    Ok(f) => f,
1901                    Err(_e) => {
1902                        return Ok(HookResult::Failed { status: 1, output });
1903                    }
1904                };
1905                child.feed_stdin_and_wait_with_output(Some(ConcurrentStdinFeed::File(file)))
1906            } else if let Some(data) = opts.stdin_data {
1907                child.feed_stdin_and_wait_with_output(Some(ConcurrentStdinFeed::Bytes(data)))
1908            } else {
1909                child.close_stdin();
1910                child.wait_with_output()
1911            };
1912            match output_result {
1913                Ok(o) => {
1914                    output.stdout.extend_from_slice(&o.stdout);
1915                    output.stderr.extend_from_slice(&o.stderr);
1916                    o.status
1917                }
1918                Err(_) => crate::command_runner::CommandExit {
1919                    success: false,
1920                    code: Some(1),
1921                },
1922            }
1923        } else {
1924            if let Some(ref path) = stdin_file {
1925                let file = match fs::File::open(path) {
1926                    Ok(f) => f,
1927                    Err(_e) => {
1928                        return Ok(HookResult::Failed { status: 1, output });
1929                    }
1930                };
1931                if let Some(stdin) = child.stdin_mut() {
1932                    let mut file = file;
1933                    let _ = crate::sigpipe::copy(&mut file, stdin);
1934                }
1935            } else if let Some(data) = opts.stdin_data {
1936                if let Some(stdin) = child.stdin_mut() {
1937                    let _ = crate::sigpipe::write_all(stdin, data);
1938                }
1939            }
1940            if stdin_piped {
1941                child.close_stdin();
1942            }
1943            match wait_hook_command(child, capture, cancel, &mut output) {
1944                Ok(exit) => exit,
1945                Err(crate::error::Error::Cancelled) => return Err(crate::error::Error::Cancelled),
1946                Err(other) => return Err(other),
1947            }
1948        };
1949
1950        if !exit.success {
1951            return Ok(HookResult::Failed {
1952                status: exit.code.unwrap_or(1),
1953                output,
1954            });
1955        }
1956    }
1957
1958    Ok(HookResult::Success { output })
1959}
1960
1961#[cfg(test)]
1962mod tests {
1963    use super::*;
1964
1965    fn touch(path: &Path) {
1966        fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
1967        fs::write(path, b"").expect("write");
1968    }
1969
1970    fn exe(name: &str) -> String {
1971        format!("{name}{}", std::env::consts::EXE_SUFFIX)
1972    }
1973
1974    #[test]
1975    fn hook_result_reports_status_output_and_checks() {
1976        let output = HookOutput {
1977            stdout: b"out".to_vec(),
1978            stderr: b"err".to_vec(),
1979        };
1980        assert!(!output.is_empty());
1981        assert!(HookOutput::default().is_empty());
1982        assert_eq!(
1983            HookError::MissingHookCommand {
1984                hook_name: "x".into()
1985            }
1986            .output(),
1987            None
1988        );
1989        assert_eq!(
1990            format!("{output:?}"),
1991            r#"HookOutput { stdout: "out", stderr: "err" }"#
1992        );
1993
1994        let success = HookResult::Success {
1995            output: output.clone(),
1996        };
1997        assert!(success.is_ok() && success.was_executed());
1998        assert_eq!(success.status(), Some(0));
1999        assert_eq!(success.output(), Some(&output));
2000        assert!(success.check("pre-commit").expect("success"));
2001
2002        let missing = HookResult::NotFound;
2003        assert!(missing.is_ok() && !missing.was_executed());
2004        assert_eq!((missing.status(), missing.output()), (None, None));
2005        assert!(!missing.check("pre-commit").expect("not found"));
2006
2007        let failed = HookResult::Failed {
2008            status: 3,
2009            output: output.clone(),
2010        };
2011        assert!(!failed.is_ok() && failed.was_executed());
2012        assert_eq!(failed.status(), Some(3));
2013        match failed.check("commit-msg") {
2014            Err(err @ crate::error::Error::Hook(HookError::Failed { .. })) => {
2015                assert_eq!(err.to_string(), "hook commit-msg failed with exit status 3");
2016                let crate::error::Error::Hook(HookError::Failed {
2017                    hook_name,
2018                    status,
2019                    output: got,
2020                }) = err
2021                else {
2022                    unreachable!()
2023                };
2024                assert_eq!((hook_name.as_str(), status), ("commit-msg", 3));
2025                assert_eq!(got, output);
2026            }
2027            other => panic!("expected HookError::Failed, got {other:?}"),
2028        }
2029    }
2030
2031    #[test]
2032    fn post_rewrite_stdin_is_one_old_new_line_per_pair() {
2033        let a = ObjectId::from_hex("1111111111111111111111111111111111111111").expect("a");
2034        let b = ObjectId::from_hex("2222222222222222222222222222222222222222").expect("b");
2035        assert_eq!(post_rewrite_stdin(&[]), b"");
2036        assert_eq!(
2037            post_rewrite_stdin(&[(a, b), (b, a)]),
2038            format!(
2039                "{} {}\n{} {}\n",
2040                a.to_hex(),
2041                b.to_hex(),
2042                b.to_hex(),
2043                a.to_hex()
2044            )
2045            .into_bytes()
2046        );
2047    }
2048
2049    #[test]
2050    fn post_operation_names_and_flags() {
2051        assert_eq!(HookName::PostCheckout.as_str(), "post-checkout");
2052        assert_eq!(HookName::PostMerge.as_str(), "post-merge");
2053        assert_eq!(HookName::PostRewrite.as_str(), "post-rewrite");
2054        assert_eq!(HookName::PreMergeCommit.as_str(), "pre-merge-commit");
2055        assert_eq!(HookName::PrepareCommitMsg.as_str(), "prepare-commit-msg");
2056        assert_eq!(HookName::PreRebase.as_str(), "pre-rebase");
2057        assert_eq!(RewriteKind::Amend.as_str(), "amend");
2058        assert_eq!(RewriteKind::Rebase.as_str(), "rebase");
2059        assert!(PostOperationHooks::default().enabled());
2060        assert!(!PostOperationHooks::Skip.enabled());
2061    }
2062
2063    #[test]
2064    fn shebang_interpreter_takes_the_interpreter_basename() {
2065        assert_eq!(
2066            shebang_interpreter(b"#!/bin/sh\nexit 0\n").as_deref(),
2067            Some("sh")
2068        );
2069        assert_eq!(
2070            shebang_interpreter(b"#!/bin/bash -e\n").as_deref(),
2071            Some("bash")
2072        );
2073        assert_eq!(shebang_interpreter(b"#! /bin/sh\n").as_deref(), Some("sh"));
2074        assert_eq!(
2075            shebang_interpreter(b"#!/bin/sh\r\nexit 0\r\n").as_deref(),
2076            Some("sh")
2077        );
2078        assert_eq!(shebang_interpreter(b"#!/bin/sh").as_deref(), Some("sh"));
2079        assert_eq!(
2080            shebang_interpreter(br"#!C:\tools\perl.exe").as_deref(),
2081            Some("perl.exe")
2082        );
2083    }
2084
2085    #[test]
2086    fn shebang_interpreter_looks_through_env() {
2087        assert_eq!(
2088            shebang_interpreter(b"#!/usr/bin/env bash\n").as_deref(),
2089            Some("bash")
2090        );
2091        assert_eq!(
2092            shebang_interpreter(b"#!/usr/bin/env -S python3 -u\n").as_deref(),
2093            Some("python3")
2094        );
2095        assert_eq!(shebang_interpreter(b"#!/usr/bin/env\n"), None);
2096    }
2097
2098    #[test]
2099    fn shebang_interpreter_rejects_non_scripts() {
2100        assert_eq!(shebang_interpreter(b"exit 0\n"), None);
2101        assert_eq!(shebang_interpreter(b""), None);
2102        assert_eq!(shebang_interpreter(b"#!\n"), None);
2103        assert_eq!(shebang_interpreter(b"#!/\n"), None);
2104        assert_eq!(shebang_interpreter(b"\x7fELF\x02\x01"), None);
2105    }
2106
2107    #[cfg(unix)]
2108    #[test]
2109    fn hook_shell_is_bin_sh_on_unix() {
2110        let mut env = CommandEnvironment::default();
2111        env.set.push(("PATH".into(), "/nonexistent".into()));
2112        assert_eq!(hook_shell(&env), ScriptInterpreter::bare("/bin/sh"));
2113    }
2114
2115    #[test]
2116    fn interpreter_from_git_tree_gets_its_tool_dirs_on_path() {
2117        let tmp = tempfile::tempdir().expect("tempdir");
2118        let root = tmp.path().join("Git");
2119        touch(&root.join("cmd").join(exe("git")));
2120        touch(&root.join("mingw64").join("bin").join(exe("git")));
2121        touch(&root.join("usr").join("bin").join(exe("sh")));
2122        let mut env = CommandEnvironment::default();
2123        env.set
2124            .push(("PATH".into(), root.join("cmd").into_os_string()));
2125        let runner = crate::command_runner::RecordingRunner::always_success();
2126        let ctx = HookSpawnContext {
2127            runner: runner.as_ref(),
2128            cwd: tmp.path(),
2129            env: &env,
2130            stdin_piped: false,
2131            stdout: CommandStdio::Inherit,
2132            stderr: CommandStdio::Inherit,
2133            server_receive_hook: false,
2134        };
2135        let dash_c = || ShellInvocation::DashC {
2136            script: "true".into(),
2137            argv0: Some("hook".into()),
2138            args: Vec::new(),
2139        };
2140        let interpreter = crate::command_runner::resolve_script_interpreter(
2141            "sh",
2142            Some(root.join("cmd").as_os_str()),
2143        );
2144        let spec = ctx.interpreter_spec(interpreter, dash_c(), &[]);
2145        assert_eq!(spec.program, root.join("usr").join("bin").join(exe("sh")));
2146        let expected = std::env::join_paths([
2147            root.join("mingw64").join("bin"),
2148            root.join("usr").join("bin"),
2149            root.join("cmd"),
2150        ])
2151        .expect("join");
2152        assert_eq!(
2153            crate::command_runner::child_path_var(&spec.env),
2154            Some(expected)
2155        );
2156
2157        let bare = ctx.interpreter_spec(ScriptInterpreter::bare("/bin/sh"), dash_c(), &[]);
2158        assert_eq!(
2159            crate::command_runner::child_path_var(&bare.env),
2160            Some(root.join("cmd").into_os_string()),
2161            "interpreters outside a Git tree keep PATH as is"
2162        );
2163    }
2164
2165    #[test]
2166    fn verbatim_prefixes_are_stripped_from_path_vars() {
2167        let mut set: Vec<(OsString, OsString)> = vec![
2168            ("GIT_INDEX_FILE".into(), r"\\?\C:\repo\.git\index".into()),
2169            ("GIT_DIR".into(), r"\\?\UNC\server\share\repo\.git".into()),
2170            ("GIT_WORK_TREE".into(), r"C:\repo".into()),
2171            (
2172                "GIT_OBJECT_DIRECTORY".into(),
2173                r"\\?\C:\repo\.git\objects".into(),
2174            ),
2175            ("GIT_PREFIX".into(), r"\\?\kept".into()),
2176        ];
2177        strip_verbatim_prefix_from_path_vars(&mut set);
2178        let value = |key: &str| {
2179            set.iter()
2180                .find(|(k, _)| k == key)
2181                .map(|(_, v)| v.clone())
2182                .expect("present")
2183        };
2184        assert_eq!(
2185            value("GIT_INDEX_FILE"),
2186            OsString::from(r"C:\repo\.git\index")
2187        );
2188        assert_eq!(
2189            value("GIT_DIR"),
2190            OsString::from(r"\\server\share\repo\.git")
2191        );
2192        assert_eq!(value("GIT_WORK_TREE"), OsString::from(r"C:\repo"));
2193        assert_eq!(
2194            value("GIT_OBJECT_DIRECTORY"),
2195            OsString::from(r"C:\repo\.git\objects")
2196        );
2197        assert_eq!(value("GIT_PREFIX"), OsString::from(r"\\?\kept"));
2198    }
2199
2200    #[cfg(unix)]
2201    #[test]
2202    fn run_hook_in_git_dir_drains_stderr_while_reading_large_stdin() {
2203        use crate::repo::{InitOptions, Repository};
2204
2205        let dir = tempfile::tempdir().expect("tempdir");
2206        let (repo, _) = Repository::init(dir.path(), &InitOptions::default()).expect("init");
2207        let hook = repo.git_dir().join("hooks").join("pre-receive");
2208        fs::write(
2209            &hook,
2210            b"#!/bin/sh\nwhile read old new ref; do echo \"checking $ref\" >&2; done\nexit 0\n",
2211        )
2212        .expect("write hook");
2213        let mut perms = fs::metadata(&hook).expect("meta").permissions();
2214        perms.set_mode(0o755);
2215        fs::set_permissions(&hook, perms).expect("chmod");
2216
2217        let stdin: Vec<u8> = (1..=3000)
2218            .map(|i| {
2219                format!(
2220                    "1111111111111111111111111111111111111111 \
2221                     2222222222222222222222222222222222222222 refs/heads/b{i}\n"
2222                )
2223            })
2224            .collect::<String>()
2225            .into_bytes();
2226
2227        let started = std::time::Instant::now();
2228        let result = run_hook_in_git_dir(&repo, "pre-receive", &[], Some(&stdin), &[]);
2229        assert!(
2230            started.elapsed() < std::time::Duration::from_secs(5),
2231            "pre-receive hook I/O took {:?}",
2232            started.elapsed()
2233        );
2234        assert!(result.is_ok());
2235        let output = result.output().expect("hook output");
2236        assert!(output.stderr.len() > 64 * 1024);
2237        assert!(output.stderr.starts_with(b"checking "));
2238    }
2239
2240    #[test]
2241    fn not_an_executable_matches_only_the_platform_code() {
2242        #[cfg(unix)]
2243        assert!(is_not_an_executable(&std::io::Error::from_raw_os_error(8)));
2244        #[cfg(windows)]
2245        assert!(is_not_an_executable(&std::io::Error::from_raw_os_error(
2246            193
2247        )));
2248        assert!(!is_not_an_executable(&std::io::Error::from(
2249            std::io::ErrorKind::NotFound
2250        )));
2251    }
2252}