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::commit_transaction::{CommitInvocation, TransactionResult, TransactionStop, run_commit_transaction};
17use super::config_schema::CliGitConfig;
18use super::command_commit::CommitRegion;
19use super::diagnostic_log::warn;
20use super::diagnostics::{EngineFailureCode, render_engine_failure};
21use super::git_version::check_git_version;
22use super::policy_checks::ShippedChecks;
23use super::policy_engine::StageRequest;
24use super::policy_events::{PolicyEvent, render_policy_events};
25use super::policy_trigger::Trigger;
26use super::post_commit::{PostCommitOutcome, PostCommitRequest, run_post_commit};
27use super::repository_facts::RepositoryFacts;
28use super::transaction_git::GitContext;
29use super::transaction_lease::has_valid_preparation_lease;
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 executable: PathBuf = match std::env::current_exe() {
168        Ok(found) => found,
169        Err(error) => {
170            write_stderr(format!("cli-git: cannot determine this executable: {error}\n").as_str());
171            return CommitEnding { code: 2 };
172        }
173    };
174    let invocation: CommitInvocation<'_> = CommitInvocation {
175        context: command.context,
176        environment: command.environment,
177        cwd: cwd.as_path(),
178        arguments: command.arguments,
179        subcommand_index: command.subcommand_index,
180        region: command.region,
181        config: command.config,
182        controls: command.controls,
183        inherited_lease_valid: has_valid_preparation_lease(command.environment),
184        executable: executable.as_path(),
185    };
186    let request: StageRequest = StageRequest {
187        trigger: Trigger::PreForward,
188        config: command.config.policies.clone(),
189        controls: command.controls.clone(),
190        selected: Vec::new(),
191    };
192    let result: TransactionResult = match run_commit_transaction(&invocation, checks, &request) {
193        Ok(found) => found,
194        Err(stop) => return report_stop(stop),
195    };
196    write_stderr(render_policy_events(0, result.events.as_slice()).as_str());
197    let Some(landed) = result.landed_oid else {
198        return CommitEnding { code: result.exit_code };
199    };
200    return post_commit(command, &invocation, landed.as_str());
201}
202
203/// What:
204///  The post-commit lifecycle of a landed commit: the gate over its changes, then the automatic backup.
205/// Why:
206///   A blocked gate keeps the commit local and exits 2; a passing gate lets the backup run.
207///
208/// In TS you'd write (pseudocode):
209/// ```ts
210/// const post = await runPostCommitLifecycle({ ... }); if (post.blocked) throw new PolicyDecisionError(2); await autoPush({ ... });
211/// ```
212fn post_commit(command: &CommitCommand<'_>, invocation: &CommitInvocation<'_>, landed: &str) -> CommitEnding {
213    let request: PostCommitRequest<'_> = PostCommitRequest {
214        real_git: command.context.real_git.as_path(),
215        landed_oid: landed,
216        arguments: command.arguments,
217        global_prefix: command.context.global_prefix.as_slice(),
218        overlay: command.context.overlay.as_slice(),
219        config: command.config.policies.clone(),
220        controls: command.controls.clone(),
221    };
222    let git: PushGit = PushGit {
223        real_git: command.context.real_git.clone(),
224        cwd: invocation.cwd.to_path_buf(),
225        environment: command.context.overlay.clone(),
226    };
227    let mut stderr = std::io::stderr();
228    match run_post_commit(&request, &git, &mut stderr) {
229        Ok(PostCommitOutcome { exit_code, .. }) => return CommitEnding { code: exit_code },
230        Err(error) => {
231            warn(TAG, format!("the post-commit lifecycle failed: {error:?}").as_str());
232            write_stderr(format!("{error:?}\n").as_str());
233            return CommitEnding { code: 1 };
234        }
235    }
236}
237
238/// Controls for this module stay out of the release executable.
239#[cfg(test)]
240#[path = "commit_command_tests.rs"]
241mod tests;