Skip to main content

git_policy_cli/
post_commit.rs

1//! What:
2//!  The post-commit policy gate over a landed commit's own changes, and the backup that follows it.
3//! Why:
4//!  The incumbent (`src/policy-engine/post-commit-lifecycle.ts`) checks the committed bytes of
5//!  every path a landed commit changed, and only a gate that passes lets the commit reach auto-push.
6//!  A blocked gate keeps the commit local and names it in a `commit-landed` event; the command exits `2`.
7//!  The landed commit is an input, so the integrator can call this after any landing.
8//!
9//! In TS you'd write (pseudocode):
10//! ```ts
11//! const result = await runPostCommitLifecycle({ rawArgs, transformedArgs, gitPath, cwd, landedOid, ... });
12//! if (!result.blocked) await autoPush({ gitPath, cwd, landedOid: result.oid });
13//! ```
14
15/// The auto-push a clean gate hands the landed commit to, and the Git request it runs with.
16use super::auto_push::{AutoPushResult, auto_push};
17use super::auto_push_single_flight::{PushGit, SingleFlightError};
18/// The landed-commit object name and the candidate layer's landed-delta source.
19use super::candidate_object::parse_object_id;
20use super::candidate_prediction::CandidateRequest;
21/// The policy configuration the gate runs with.
22use super::config_schema::PolicyConfig;
23/// The reading of the invocation's environment.
24use super::child_environment::environment_value;
25/// The failure code and the event kinds the gate emits.
26use super::diagnostics::EngineFailureCode;
27/// The linter the Markdown policy finds on, and runs with, the invocation's environment.
28use super::policy_checks::shipped_checks;
29use super::policy_content::LifecycleContent;
30use super::policy_engine::{StageEnd, StageRequest, pass_exit_code};
31use super::policy_events::{PolicyEvent, render_policy_events};
32use super::policy_pass::run_policy_pass;
33use super::policy_trigger::Trigger;
34use super::repository_facts::git_facts;
35/// The variable naming the forbidden-strings rules file.
36use super::scanner_selection::RULES_VARIABLE;
37use super::wrapper_controls::Controls;
38/// Owned OS strings for the replayed global options and the child environment.
39use std::ffi::OsString;
40/// `Write` is the stderr sink the gate's JSONL lines go to.
41use std::io::Write;
42/// `Path` is a borrowed filesystem path.
43use std::path::Path;
44
45/// Exit status the command returns when the gate blocks the backup, as the incumbent's `PolicyDecisionError(2)`.
46pub const POST_COMMIT_BLOCKED_EXIT_CODE: i32 = 2;
47
48/// What:
49///  The inputs of one post-commit gate.
50/// Why:
51///   The landed commit names the delta; the global prefix and the environment make every query read
52///  the repository the commit landed in.
53///
54/// In TS you'd write (pseudocode):
55/// ```ts
56/// type PostCommitInput = { gitPath; cwd; landedOid; arguments; environment; policySeverities; policyOptions };
57/// ```
58#[derive(Clone, Debug)]
59pub struct PostCommitRequest<'request> {
60    /// Absolute real Git executable.
61    pub real_git: &'request Path,
62    /// The landed commit object name, as Git printed it.
63    pub landed_oid: &'request str,
64    /// The arguments the command forwarded to Git.
65    pub arguments: &'request [OsString],
66    /// The global options of the invocation, kept before every query (`-C`, `--git-dir`, `-c`).
67    pub global_prefix: &'request [OsString],
68    /// Variables added to every query.
69    pub overlay: &'request [(OsString, OsString)],
70    /// The invocation's whole environment:
71    ///  the Markdown linter is found on its `PATH` and runs with it,
72    ///  and the forbidden-strings rules variable is read from it.
73    pub environment: &'request [(OsString, OsString)],
74    /// The policy severities and options the gate runs with.
75    pub config: PolicyConfig,
76    /// Escapes and flags the invocation carries.
77    pub controls: Controls,
78}
79
80/// What:
81///  The settled gate:
82///  the landed commit, every event it produced, and whether the backup must not run.
83/// Why:
84///   `events` already carries the `commit-landed` event when `blocked` is true,
85///  so the caller renders one list.
86///
87/// In TS you'd write (pseudocode):
88/// ```ts
89/// type PostCommitLifecycleResult = { oid: string; events: PolicyEvent[]; blocked: boolean };
90/// ```
91#[derive(Clone, Debug, Eq, PartialEq)]
92pub struct PostCommitGate {
93    /// The landed commit object name, as given.
94    pub oid: String,
95    /// Every event the gate produced, in order.
96    pub events: Vec<PolicyEvent>,
97    /// Whether the backup must not run.
98    pub blocked: bool,
99}
100
101/// What:
102///  Run the post-commit policies over the landed commit's delta.
103/// Why:
104///   Only a gate with no blocking event, no failure and no pending correction lets the backup run;
105///  a warning-only result is allowed, as in the incumbent.
106///   A landed name that is not an object name is an engine failure, so the commit is kept and reported.
107///
108/// In TS you'd write (pseudocode):
109/// ```ts
110/// async function runPostCommitLifecycle(input): Promise<PostCommitLifecycleResult>;
111/// ```
112pub fn run_post_commit_gate(request: &PostCommitRequest) -> PostCommitGate {
113    let oid = request.landed_oid.to_owned();
114    let (mut events, end): (Vec<PolicyEvent>, StageEnd) =
115        match parse_object_id(request.landed_oid.as_bytes()) {
116            Some(commit) => run_staged_gate(request, commit),
117            None => (
118                vec![PolicyEvent::EngineFailure {
119                    code: EngineFailureCode::ContentUnavailable,
120                    message: format!("landed commit {} is not an object name", request.landed_oid),
121                    trigger: Some(Trigger::PostCommit),
122                    policy: None,
123                    path: None,
124                }],
125                StageEnd::Failed,
126            ),
127        };
128    let blocked = pass_exit_code(events.as_slice(), end) != 0;
129    if blocked {
130        events.push(PolicyEvent::CommitLanded { oid: oid.clone() });
131    }
132    return PostCommitGate {
133        oid,
134        events,
135        blocked,
136    };
137}
138
139/// Run the post-commit stage over the landed delta of a parsed commit name.
140///
141/// In TS you'd write (pseudocode):
142/// ```ts
143/// await dependencies.runPolicyEngine({ trigger: 'post-commit', gitFacts: createPostCommitGitFacts(...) })
144/// ```
145fn run_staged_gate(
146    request: &PostCommitRequest,
147    commit: super::candidate_object::ObjectId,
148) -> (Vec<PolicyEvent>, StageEnd) {
149    let facts = git_facts(request.real_git, request.global_prefix, request.overlay);
150    let mut checks = shipped_checks(
151        facts,
152        request.arguments.to_vec(),
153        LifecycleContent::Requested(CandidateRequest::Landed(commit)),
154        Vec::new(),
155    );
156    // The scanner and Markdown options are the configuration's, as the pre-commit stage's checks hold them.
157    checks.scanner_settings.options = request.config.forbidden_strings.clone();
158    checks.markdown.options = request.config.markdown_autofix.clone();
159    // The forbidden-strings rules variable is read from this invocation's environment.
160    checks.scanner_settings.rules_variable = environment_value(request.environment, RULES_VARIABLE);
161    let stage: StageRequest = StageRequest {
162        trigger: Trigger::PostCommit,
163        config: request.config.clone(),
164        controls: request.controls.clone(),
165        selected: Vec::new(),
166    };
167    let pass = run_policy_pass(&stage, &mut checks);
168    return (pass.events, pass.end);
169}
170
171/// What:
172///  The result of the gate and the backup it allowed or prevented.
173/// Why:
174///   The exit status and the auto-push result come from one place, so the caller only reports them.
175///
176/// In TS you'd write (pseudocode):
177/// ```ts
178/// { gate: PostCommitLifecycleResult; autoPush?: AutoPushResult }
179/// ```
180#[derive(Clone, Debug, Eq, PartialEq)]
181pub struct PostCommitOutcome {
182    /// The gate result, including the `commit-landed` event when blocked.
183    pub gate: PostCommitGate,
184    /// `0` after a backup or a warning-only gate; `2` when the gate blocked the backup.
185    pub exit_code: i32,
186    /// The auto-push result, absent when the gate blocked the backup.
187    pub auto_push: Option<AutoPushResult>,
188}
189
190/// What:
191///  Run the gate, print its events, and back up the landed commit only when the gate allows it.
192/// Why:
193///   The incumbent prints the events before the backup and never backs up a blocked commit;
194///  a failed backup is reported by `auto_push` and never changes the outcome's exit code.
195///
196/// In TS you'd write (pseudocode):
197/// ```ts
198/// const result = await runPostCommitLifecycle(input);
199/// process.stderr.write(renderPolicyEvents(result.events));
200/// if (!result.blocked) await autoPush({ gitPath, cwd, landedOid: result.oid });
201/// ```
202pub fn run_post_commit(
203    request: &PostCommitRequest,
204    git: &PushGit,
205    err: &mut dyn Write,
206) -> Result<PostCommitOutcome, SingleFlightError> {
207    let gate = run_post_commit_gate(request);
208    let rendered = render_policy_events(0, gate.events.as_slice());
209    if !rendered.is_empty() {
210        err.write_all(rendered.as_bytes())
211            .map_err(SingleFlightError::Io)?;
212    }
213    if gate.blocked {
214        return Ok(PostCommitOutcome {
215            gate,
216            exit_code: POST_COMMIT_BLOCKED_EXIT_CODE,
217            auto_push: None,
218        });
219    }
220    let landed = gate.oid.clone();
221    let pushed = auto_push(git, landed.as_str(), err)?;
222    return Ok(PostCommitOutcome {
223        gate,
224        exit_code: 0,
225        auto_push: Some(pushed),
226    });
227}
228
229/// Post-commit gate behavior is controlled in the test module.
230#[cfg(test)]
231#[path = "post_commit_tests.rs"]
232mod tests;