Skip to main content

git_policy_cli/
commit_command.rs

1//! What:
2//!  The `git commit` command of the native wrapper: the transaction, the settled events, the post-commit gate and
3//!  the automatic backup, in the incumbent's order.
4//! Why:
5//!  The incumbent (`src/bin.ts`) runs the commit transaction instead of forwarding the commit, prints the
6//!  pre-forward events only after the transaction returned, then runs the post-commit lifecycle for a landed commit
7//!  and, when the gate passes, the automatic push. A commit that landed nothing exits with the transaction's status.
8//!
9//! In TS you'd write (pseudocode):
10//! ```ts
11//! const transaction = await runCommitTransactionBoundary({ args, gitPath, policyOptions, concurrency });
12//! renderPolicyEvents(transaction.policyResult.events);
13//! const post = await runPostCommitLifecycle({ ... }); await autoPush({ ... });
14//! ```
15use super::auto_push_single_flight::PushGit;
16use super::child_environment::environment_with_overlay;
17use super::commit_transaction::{CommitInvocation, TransactionResult, TransactionStop, run_commit_transaction};
18use super::config_schema::CliGitConfig;
19use super::command_commit::CommitRegion;
20use super::diagnostic_log::warn;
21use super::diagnostics::{EngineFailureCode, render_engine_failure};
22use super::git_version::check_git_version;
23use super::policy_checks::ShippedChecks;
24use super::policy_engine::StageRequest;
25use super::policy_events::{PolicyEvent, render_policy_events};
26use super::policy_trigger::Trigger;
27use super::post_commit::{PostCommitOutcome, PostCommitRequest, run_post_commit};
28use super::repository_facts::RepositoryFacts;
29use super::transaction_git::GitContext;
30use super::wrapper_controls::Controls;
31use std::ffi::OsString;
32use std::io::Write;
33use std::path::{Path, PathBuf};
34
35/// Module tag for diagnostics.
36const TAG: &str = "runCommitCommand";
37
38/// What:
39///  The effective invocation directory: the process directory moved by every `-C` of the global options.
40/// Why:
41///   Relative pathspecs and the transaction's Git queries resolve from where Git itself would run.
42///
43/// In TS you'd write (pseudocode):
44/// ```ts
45/// parseGlobalOptions(args).effectiveCwd
46/// ```
47pub fn effective_directory(start: &Path, global_prefix: &[OsString]) -> PathBuf {
48    let mut directory: PathBuf = start.to_path_buf();
49    let mut index: usize = 0;
50    while index < global_prefix.len() {
51        if global_prefix[index] == "-C"
52            && let Some(value) = global_prefix.get(index + 1)
53        {
54            directory = directory.join(value);
55            index += 2;
56            continue;
57        }
58        index += 1;
59    }
60    return directory;
61}
62
63/// What:
64///  The ending of one commit command.
65/// Why:
66///   Everything the command wrote it wrote itself and in order, so only the exit status is left to the caller.
67///
68/// In TS you'd write (pseudocode):
69/// ```ts
70/// process.exitCode = code;
71/// ```
72#[derive(Clone, Copy, Debug, Eq, PartialEq)]
73pub struct CommitEnding {
74    /// The process exit status.
75    pub code: i32,
76}
77
78/// What:
79///  Write text to standard error, ignoring a closed stream.
80/// Why:
81///   The exit status already carries the result.
82///
83/// In TS you'd write (pseudocode):
84/// ```ts
85/// process.stderr.write(text);
86/// ```
87fn write_stderr(text: &str) {
88    let mut stream = std::io::stderr();
89    let _ = stream.write_all(text.as_bytes());
90    let _ = stream.flush();
91}
92
93/// What:
94///  Print what the transaction stopped with and name the exit status.
95/// Why:
96///   Each stop ends differently: Git's own status with nothing printed, a message with status 1, or a finding with
97///   status 2.
98///
99/// In TS you'd write (pseudocode):
100/// ```ts
101/// catch (error) { ... process.exitCode = ... }
102/// ```
103fn report_stop(stop: TransactionStop) -> CommitEnding {
104    match stop {
105        TransactionStop::NativeExit(code) => return CommitEnding { code },
106        TransactionStop::Message(message) => {
107            write_stderr(format!("{message}\n").as_str());
108            return CommitEnding { code: 1 };
109        }
110        TransactionStop::Failed { code, message } => {
111            let event: PolicyEvent = PolicyEvent::EngineFailure {
112                code,
113                message,
114                trigger: Some(Trigger::PreForward),
115                policy: None,
116                path: None,
117            };
118            write_stderr(render_policy_events(0, std::slice::from_ref(&event)).as_str());
119            return CommitEnding { code: 2 };
120        }
121    }
122}
123
124/// What:
125///  Everything the commit command reads from the wrapped invocation.
126/// Why:
127///   The command needs the identity and the loaded configuration the lifecycle already resolved.
128///
129/// In TS you'd write (pseudocode):
130/// ```ts
131/// { rawArgs, gitPath, runtimeResolution, ... }
132/// ```
133pub struct CommitCommand<'a> {
134    /// Real Git, its overlay and the global options.
135    pub context: &'a GitContext,
136    /// The invocation's environment.
137    pub environment: &'a [(OsString, OsString)],
138    /// The arguments with the wrapper's controls removed.
139    pub arguments: &'a [OsString],
140    /// The index of `commit` within the arguments.
141    pub subcommand_index: usize,
142    /// The commit options Git's table read.
143    pub region: &'a CommitRegion,
144    /// The loaded configuration.
145    pub config: &'a CliGitConfig,
146    /// The wrapper controls given on the command line.
147    pub controls: &'a Controls,
148}
149
150/// What:
151///  Run one `git commit` through the transaction and its lifecycle.
152/// Why:
153///   Startup recovery ran before configuration loaded, so the transaction starts from a clean registry unless a live
154///   transaction belongs to another invocation, which does not stop it.
155///
156/// In TS you'd write (pseudocode):
157/// ```ts
158/// await runCommitCommand({ ... });
159/// ```
160pub fn run_commit_command<F: RepositoryFacts>(command: &CommitCommand<'_>, checks: &mut ShippedChecks<F>) -> CommitEnding {
161    if let Err(reason) = check_git_version(command.context) {
162        write_stderr(render_engine_failure(0, EngineFailureCode::ContentUnavailable, reason.as_str()).as_str());
163        return CommitEnding { code: 2 };
164    }
165    let start: PathBuf = std::env::current_dir().unwrap_or_else(|_| { return PathBuf::from("."); });
166    let cwd: PathBuf = effective_directory(start.as_path(), command.context.global_prefix.as_slice());
167    let invocation: CommitInvocation<'_> = CommitInvocation {
168        context: command.context,
169        environment: command.environment,
170        cwd: cwd.as_path(),
171        arguments: command.arguments,
172        subcommand_index: command.subcommand_index,
173        region: command.region,
174        config: command.config,
175        controls: command.controls,
176    };
177    let request: StageRequest = StageRequest {
178        trigger: Trigger::PreForward,
179        config: command.config.policies.clone(),
180        controls: command.controls.clone(),
181        selected: Vec::new(),
182    };
183    let result: TransactionResult = match run_commit_transaction(&invocation, checks, &request) {
184        Ok(found) => found,
185        Err(stop) => return report_stop(stop),
186    };
187    write_stderr(render_policy_events(0, result.events.as_slice()).as_str());
188    let Some(landed) = result.landed_oid else {
189        return CommitEnding { code: result.exit_code };
190    };
191    return post_commit(command, &invocation, landed.as_str(), result.uses_lfs);
192}
193
194/// What:
195///  The post-commit lifecycle of a landed commit: the gate over its changes, then the automatic backup.
196/// Why:
197///   A blocked gate keeps the commit local and exits 2; a passing gate lets the backup run.
198///
199/// In TS you'd write (pseudocode):
200/// ```ts
201/// const post = await runPostCommitLifecycle({ ... }); if (post.blocked) throw new PolicyDecisionError(2); await autoPush({ ... });
202/// ```
203fn post_commit(command: &CommitCommand<'_>, invocation: &CommitInvocation<'_>, landed: &str, uses_lfs: bool) -> CommitEnding {
204    let request: PostCommitRequest<'_> = PostCommitRequest {
205        real_git: command.context.real_git.as_path(),
206        landed_oid: landed,
207        arguments: command.arguments,
208        global_prefix: command.context.global_prefix.as_slice(),
209        overlay: command.context.overlay.as_slice(),
210        environment: command.environment,
211        config: command.config.policies.clone(),
212        controls: command.controls.clone(),
213    };
214    let git: PushGit = PushGit {
215        real_git: command.context.real_git.clone(),
216        cwd: invocation.cwd.to_path_buf(),
217        environment: environment_with_overlay(command.environment, command.context.overlay.as_slice()),
218        lfs: uses_lfs,
219    };
220    let mut stderr = std::io::stderr();
221    match run_post_commit(&request, &git, &mut stderr) {
222        Ok(PostCommitOutcome { exit_code, .. }) => return CommitEnding { code: exit_code },
223        Err(error) => {
224            warn(TAG, format!("the post-commit lifecycle failed: {error:?}").as_str());
225            write_stderr(format!("{error:?}\n").as_str());
226            return CommitEnding { code: 1 };
227        }
228    }
229}
230
231/// Controls for this module stay out of the release executable.
232#[cfg(test)]
233#[path = "commit_command_tests.rs"]
234mod tests;