Skip to main content

git_policy_cli/
forwarding.rs

1//! What:
2//!  Start real Git with the caller's exact arguments,
3//!  streams and environment.
4//! Why:
5//!  The wrapper adds policy around Git;
6//!  it must never change what Git receives
7//!      or what the caller observes from Git.
8//!
9//! In TS you'd write (pseudocode):
10//! ```ts
11//! // spawn(gitPath, args, { stdio: 'inherit', env }) and exit with the child's status.
12//! ```
13
14/// What:
15///  `OsString` is owned operating-system text of raw OS bytes (sibling `String`
16///       must be UTF-8).
17/// Why:
18///   Arguments are forwarded byte for byte;
19///  they are never decoded or re-quoted.
20///
21/// In TS you'd write (pseudocode):
22/// ```ts
23/// // process.argv entries, but without any UTF-8 decoding.
24/// ```
25use std::ffi::OsString;
26/// `Path` is a borrowed filesystem path of raw OS bytes.
27use std::path::Path;
28/// Starts that ride out a short shortage of processes.
29#[cfg(unix)]
30use super::start_retry::exec_retrying;
31/// Starts that ride out a short shortage of processes.
32use super::start_retry::RetryStart;
33/// `Command` builds a child process from a program and an argument list,
34///  with no shell.
35use std::process::Command;
36
37/// What:
38///  How a Git child ended.
39///       `i32` is a signed 32-bit integer,
40///  the type of exit codes and signal numbers
41///       (siblings `u8`,
42///  `i64`).
43/// Why:
44///   A child killed by a signal has no exit code;
45///  callers need both cases to
46///       report Git's result faithfully.
47///  `i32` is what the operating system returns.
48///
49/// In TS you'd write (pseudocode):
50/// ```ts
51/// type ChildOutcome = { exited: number } | { signaled: number };
52/// ```
53#[derive(Clone, Copy, Debug, Eq, PartialEq)]
54pub enum ChildOutcome {
55    /// The child called `exit` with this code.
56    Exited(i32),
57    /// The child was terminated by this signal number.
58    Signaled(i32),
59}
60
61/// What:
62///  Build the child command:
63///  program,
64///  unchanged arguments,
65///  added variables.
66///       `&[OsString]` borrows the argument list;
67///  `&[(OsString, OsString)]` borrows
68///       name/value pairs.
69/// Why:
70///   One builder guarantees every real-Git start,
71///  forwarded or queried,
72///  uses an
73///       argument array (no shell string) and inherits the caller's environment plus
74///       only the overlay.
75///
76/// In TS you'd write (pseudocode):
77/// ```ts
78/// function gitCommand(realGit: string, args: string[], overlay: [string, string][]): Command;
79/// ```
80pub fn git_command(
81    real_git: &Path,
82    arguments: &[OsString],
83    overlay: &[(OsString, OsString)],
84) -> Command {
85    // `mut` allows the builder to be configured step by step.
86    let mut command: Command = Command::new(real_git);
87    // `.args` appends each argument as its own array element, bytes unchanged.
88    command.args(arguments);
89    // `for (name, value) in overlay` destructures each borrowed pair.
90    for (name, value) in overlay {
91        command.env(name, value);
92    }
93    return command;
94}
95
96/// What:
97///  Translate a child's end into this process's exit code.
98/// Why:
99///   Git 2.56.0 `run-command.c` reports a child killed by signal N as `128 + N`,
100///       which is also what a POSIX shell reports;
101///  an exit code passes through.
102///
103/// In TS you'd write (pseudocode):
104/// ```ts
105/// function exitCode(outcome: ChildOutcome): number;
106/// ```
107pub fn exit_code(outcome: ChildOutcome) -> i32 {
108    // What: `match` picks by variant and binds the number inside it.
109    // Why:  The two cases are computed differently and both must be handled.
110    //
111    // In TS you'd write (pseudocode):
112    // ```ts
113    // return 'exited' in outcome ? outcome.exited : 128 + outcome.signaled;
114    // ```
115    match outcome {
116        ChildOutcome::Exited(code) => return code,
117        ChildOutcome::Signaled(signal) => return 128 + signal,
118    }
119}
120
121/// What:
122///  Read a finished child's status into a `ChildOutcome`.
123///       `#[cfg(unix)]` on the inner block compiles it only on Unix-like systems.
124/// Why:
125///   Unix reports either an exit code or a terminating signal,
126///  never both.
127///  Other
128///       systems report only an exit code.
129///  One function serves both,
130///  so the part every
131///       system shares is the part every test run exercises;
132///  a status that is neither
133///       cannot be reported faithfully and counts as a general failure.
134///
135/// In TS you'd write (pseudocode):
136/// ```ts
137/// function outcomeOf(status: { code: number | null; signal: number | null }): ChildOutcome;
138/// ```
139pub(crate) fn outcome_of(status: std::process::ExitStatus) -> ChildOutcome {
140    // `if let Some(code) = ...` runs only when the child exited normally.
141    if let Some(code) = status.code() {
142        return ChildOutcome::Exited(code);
143    }
144    #[cfg(unix)]
145    {
146        // The trait adds `.signal()` to exit statuses on Unix.
147        use std::os::unix::process::ExitStatusExt;
148        if let Some(signal) = status.signal() {
149            return ChildOutcome::Signaled(signal);
150        }
151    }
152    return ChildOutcome::Exited(1);
153}
154
155/// What:
156///  Run real Git as a child with inherited stdin,
157///  stdout and stderr,
158///  and wait.
159///       `std::io::Result<T>` is `Result<T, std::io::Error>`.
160/// Why:
161///   Callers that must do work after Git returns (post-commit policies,
162///  status
163///       notes) need the wrapper process to survive Git.
164///  The child shares the
165///       caller's terminal and streams directly;
166///  nothing is buffered or copied.
167///       This path installs no signal handlers:
168///  a signal sent to the wrapper alone
169///       does not reach Git,
170///  exactly as with the TypeScript wrapper.
171///
172/// In TS you'd write (pseudocode):
173/// ```ts
174/// async function runRealGit(realGit, args, overlay): Promise<ChildOutcome>;
175/// ```
176pub fn run_real_git(
177    real_git: &Path,
178    arguments: &[OsString],
179    overlay: &[(OsString, OsString)],
180) -> std::io::Result<ChildOutcome> {
181    // What: `.status()` starts the child with inherited streams and waits for it;
182    //       a trailing `?` returns a start failure to our caller.
183    // Why:  Inherited streams are the default for `.status()`, so Git reads the
184    //       caller's stdin and writes the caller's stdout and stderr itself.
185    //
186    // In TS you'd write (pseudocode):
187    // ```ts
188    // const status = await spawn(realGit, args, { stdio: 'inherit' });
189    // ```
190    let status: std::process::ExitStatus = git_command(real_git, arguments, overlay).status_retrying()?;
191    // `Ok(...)` is the success variant carrying how the child ended.
192    return Ok(outcome_of(status));
193}
194
195/// What:
196///  Become real Git;
197///  returns only when Git could not be started.
198///       The returned `std::io::Error` says why the operating system refused.
199///       `#[cfg(unix)]` and `#[cfg(not(unix))]` each compile one of the two inner blocks.
200/// Why:
201///   On Unix this process is replaced by Git,
202///  which is exact forwarding:
203///  same process
204///       ID,
205///  same streams,
206///  same signals,
207///  same exit status,
208///  and no wrapper process left
209///       between the caller and Git.
210///  Windows cannot replace a process image;
211///  the nearest
212///       faithful behaviour there is to wait for Git and exit with its status.
213///
214/// In TS you'd write (pseudocode):
215/// ```ts
216/// // Unix has no Node equivalent: process.execve(realGit, args, env) replaces the process image.
217/// // Elsewhere: process.exit(exitCode(await runRealGit(realGit, args, overlay)));
218/// ```
219pub fn replace_process_with_real_git(
220    real_git: &Path,
221    arguments: &[OsString],
222    overlay: &[(OsString, OsString)],
223) -> std::io::Error {
224    #[cfg(unix)]
225    {
226        // `exec_retrying` replaces this process like `.exec()` and tries again when the start is refused.
227        return exec_retrying(&mut git_command(real_git, arguments, overlay));
228    }
229    // UNTESTED ON WINDOWS: no gate compiles or runs this branch (the crate does not build for Windows; README, Requirements).
230    #[cfg(not(unix))]
231    {
232        // `match` unpacks the run: success exits this process with Git's code.
233        match run_real_git(real_git, arguments, overlay) {
234            Ok(outcome) => std::process::exit(exit_code(outcome)),
235            Err(error) => return error,
236        }
237    }
238}
239
240/// Real-Git process controls stay out of the release executable.
241#[cfg(test)]
242#[path = "forwarding_tests.rs"]
243mod tests;