Skip to main content

git_policy_cli/
commit_conclusion.rs

1//! What:
2//!  The conclusion of a settled commit transaction:
3//!  the normalization-only landing when the corrections removed every change, otherwise the hook dispatcher,
4//!  native preparation in the shadow, the prepared record, the landing loop and the post-landing completion.
5//! Why:
6//!  The incumbent's `commit-transaction-conclusion.ts` runs these steps in this order: the tree is written from the
7//!  stable private index, the dispatcher shim is shared by preparation and the post-landing `post-commit`, the
8//!  prepared record is durable before the preparation marker, and the transaction directory is removed only after
9//!  the worktree copies are installed.
10//!
11//! In TS you'd write (pseudocode):
12//! ```ts
13//! return await concludeCommitTransaction(settled);
14//! ```
15
16use super::capture_invocation::InvocationCapture;
17use super::commit_args::{resolve_private_commit_args, split_commit_invocation, without_all_flag};
18use super::commit_landing_loop::{LoopInput, LoopOutcome, land_with_replay};
19use super::commit_facts::PrivateIndexFacts;
20use super::commit_index::write_private_tree;
21use super::commit_no_change::{NoChangeInput, complete_no_change_transaction};
22use super::commit_preparation::{PREPARED_FILENAME, PreparationHooks, PreparationRequest, read_prepared_commit, run_native_commit};
23use super::commit_replay_options::{ReplayOptions, replay_options};
24use super::commit_transaction::{CommitInvocation, Selection, TransactionResult, TransactionStop, failed, write_journal_record};
25use super::commit_workspace::CommitWorkspace;
26use super::commit_worktree_records::{HookChanges, describe_hook_changes, selected_worktree_records};
27use super::diagnostic_log::debug;
28use super::global_arguments::global_layout;
29use super::hook_dispatch_entries::write_hook_dispatch;
30use super::hook_dispatch_plan::{HookDispatchPlan, HookPlanInputs, SILENCED_HOOK_EVENTS, compute_hook_dispatch_plan, new_preparation_lease};
31use super::policy_checks::ShippedChecks;
32use super::policy_engine::StageRequest;
33use super::policy_events::PolicyEvent;
34use super::policy_pass::PassResult;
35use super::post_landing::{LandedTransaction, PostLandingRequest, complete_landed_transaction};
36use super::repository_facts::RepositoryFacts;
37use super::transaction_git::GitContext;
38use super::transaction_journal::{AddedPath, PreparedRecord};
39use super::transaction_journal_encode::encode_prepared;
40use super::transaction_phase::{Phase, reach_transaction_phase};
41use std::ffi::OsString;
42use std::path::Path;
43
44/// Module tag for diagnostics.
45const TAG: &str = "concludeCommitTransaction";
46
47/// What:
48///  Everything the conclusion reads from the settled transaction.
49/// Why:
50///   The steps share the workspace, the capture, the policies' settled pass and the selection facts.
51///
52/// In TS you'd write (pseudocode):
53/// ```ts
54/// type SettledCommitTransaction = { workspace; capture; mode; pass; changedPasses; changedPaths; ... };
55/// ```
56pub struct ConclusionInput<'a, F: RepositoryFacts> {
57    /// The invocation's fixed facts.
58    pub invocation: &'a CommitInvocation<'a>,
59    /// The published workspace.
60    pub workspace: &'a mut CommitWorkspace,
61    /// The invocation capture.
62    pub capture: &'a InvocationCapture,
63    /// The selection facts.
64    pub selection: &'a Selection,
65    /// The request the policies run under.
66    pub request: &'a StageRequest,
67    /// The shipped checks over the private index.
68    pub checks: &'a mut ShippedChecks<PrivateIndexFacts<F>>,
69    /// The settled pass.
70    pub pass: PassResult,
71    /// How many passes changed content.
72    pub changed_passes: u64,
73    /// The paths the corrections wrote.
74    pub changed_paths: Vec<String>,
75    /// The paths the private index changes against the base.
76    pub committed_paths: Vec<String>,
77    /// The positional pathspec tokens.
78    pub pathspecs: &'a [String],
79}
80
81/// What:
82///  The settled pass's events with the fix summary the corrections earned.
83/// Why:
84///   The summary appears only after some pass changed candidate bytes, naming each changed path once in byte order.
85///
86/// In TS you'd write (pseudocode):
87/// ```ts
88/// withChangedFixSummary({ result: pass, trigger: 'pre-forward', passes, changedPaths });
89/// ```
90pub fn events_with_changed_summary(events: Vec<PolicyEvent>, passes: u64, changed_paths: &[String]) -> Vec<PolicyEvent> {
91    if passes == 0 {
92        return events;
93    }
94    return events_with_summary(events, passes, changed_paths);
95}
96
97/// What:
98///  The events with a fix summary appended whatever the pass count.
99/// Why:
100///   A normalization that removed every change always reports its summary.
101///
102/// In TS you'd write (pseudocode):
103/// ```ts
104/// withFixSummary({ result, trigger: 'pre-forward', passes, changedPaths });
105/// ```
106pub fn events_with_summary(mut events: Vec<PolicyEvent>, passes: u64, changed_paths: &[String]) -> Vec<PolicyEvent> {
107    let mut sorted: Vec<String> = changed_paths.to_vec();
108    sorted.sort_by(|left, right| { return left.as_bytes().cmp(right.as_bytes()); });
109    events.push(PolicyEvent::FixSummary {
110        trigger: super::policy_trigger::Trigger::PreForward,
111        passes,
112        changed_paths: sorted
113            .iter()
114            .map(|path| { return super::event_path::EventPath::from_git_bytes(path.as_bytes()); })
115            .collect(),
116    });
117    return events;
118}
119
120/// What:
121///  The kept global options and the commit region of the private arguments.
122/// Why:
123///   Native `git commit` runs in the shadow, so the options that would redirect it away are dropped.
124///
125/// In TS you'd write (pseudocode):
126/// ```ts
127/// splitCommitInvocation({ args: privateArgs, subcommandIndex });
128/// ```
129fn private_invocation(pass: &PassResult, pathspecs: &[String], selection: &Selection) -> (Vec<String>, Vec<String>) {
130    let text: Vec<String> = pass.arguments.iter().map(|token| { return token.to_string_lossy().into_owned(); }).collect();
131    let private_args: Vec<String> =
132        resolve_private_commit_args(text.as_slice(), pathspecs, selection.mode, selection.read_only);
133    let owned: Vec<OsString> = private_args.iter().map(OsString::from).collect();
134    let index: usize = global_layout(owned.as_slice()).prefix_len;
135    return split_commit_invocation(private_args.as_slice(), index);
136}
137
138/// What:
139///  Complete a settled policy pass through a landed commit or a normalization-only reconciliation.
140/// Why:
141///   This is the incumbent's `concludeCommitTransaction`.
142///
143/// In TS you'd write (pseudocode):
144/// ```ts
145/// return await concludeCommitTransaction(settled);
146/// ```
147pub fn conclude_commit_transaction<F: RepositoryFacts>(
148    input: ConclusionInput<'_, F>,
149) -> Result<TransactionResult, TransactionStop> {
150    let ConclusionInput {
151        invocation,
152        workspace,
153        capture,
154        selection,
155        request,
156        checks,
157        pass,
158        changed_passes,
159        changed_paths,
160        committed_paths,
161        pathspecs,
162    } = input;
163    let context: &GitContext = invocation.context;
164    let cwd: &Path = invocation.cwd;
165    let repository_root: &Path = capture.layout.repository_root.as_path();
166    let timeout_ms: u64 = invocation.config.concurrency.index_lock.unproven_owner_timeout_ms;
167    let intended_tree: String = write_private_tree(
168        context,
169        cwd,
170        workspace.landing.commit_index.as_path(),
171        workspace.object_directory.as_path(),
172    )?;
173    let changes = checks.content.install_changes();
174    let selected: Vec<AddedPath> = selected_worktree_records(
175        context,
176        cwd,
177        repository_root,
178        workspace.landing.commit_index.as_path(),
179        changes.as_slice(),
180    )?;
181    let eligible: bool = !changes.is_empty()
182        && !invocation.region.allow_empty
183        && !invocation.region.amend
184        && !selection.concludes_sequencer;
185    if let Some(result) = complete_no_change_transaction(NoChangeInput {
186        invocation,
187        workspace,
188        capture,
189        mode: selection.mode,
190        eligible,
191        intended_tree: intended_tree.as_str(),
192        committed_paths: committed_paths.as_slice(),
193        selected_worktree_paths: selected.as_slice(),
194        events: &pass.events,
195        changed_passes,
196        changed_paths: changed_paths.as_slice(),
197        index_lock_timeout_ms: timeout_ms,
198    })? {
199        return Ok(result);
200    }
201    let (global_args, commit_args): (Vec<String>, Vec<String>) = private_invocation(&pass, pathspecs, selection);
202    let global_os: Vec<OsString> = global_args.iter().map(OsString::from).collect();
203    let lease: String = new_preparation_lease(workspace.landing.directory.as_path())
204        .map_err(|error| { return failed(format!("{error:?}")); })?;
205    let plan: HookDispatchPlan = compute_hook_dispatch_plan(&HookPlanInputs {
206        context,
207        cwd,
208        global_arguments: global_os.as_slice(),
209        common_directory: capture.layout.common_dir.as_path(),
210        worktree_root: repository_root,
211        lease: lease.as_str(),
212        concurrent_commits: invocation.config.concurrency.hooks.concurrent_commits,
213        inherited_lease_valid: invocation.inherited_lease_valid,
214        environment: invocation.environment,
215    })
216    .map_err(|error| { return failed(format!("{error:?}")); })?;
217    write_hook_dispatch(workspace.hooks_directory.as_path(), &plan, invocation.executable)
218        .map_err(|error| { return failed(error.to_string()); })?;
219    let hooks: PreparationHooks = PreparationHooks {
220        directory: workspace.hooks_directory.clone(),
221        silenced_events: SILENCED_HOOK_EVENTS.iter().map(|event| { return String::from(*event); }).collect(),
222    };
223    let native_args: Vec<String> = if selection.staged_all {
224        without_all_flag(commit_args.as_slice())
225    } else {
226        commit_args.clone()
227    };
228    let preparation: PreparationRequest<'_> = PreparationRequest {
229        capture,
230        shadow: workspace.landing.shadow.as_path(),
231        hooks: &hooks,
232        commit_index: workspace.landing.commit_index.as_path(),
233        global_args: global_args.as_slice(),
234        commit_args: native_args.as_slice(),
235    };
236    let status: i32 = run_native_commit(context, cwd, &preparation).map_err(|error| { return TransactionStop::Message(error.to_string()); })?;
237    if status != 0 {
238        return Err(TransactionStop::NativeExit(status));
239    }
240    let prepared = read_prepared_commit(context, workspace.landing.shadow.as_path())?;
241    let hook_changes: HookChanges = describe_hook_changes(
242        context,
243        cwd,
244        workspace.object_directory.as_path(),
245        intended_tree.as_str(),
246        prepared.tree_oid.as_str(),
247    )?;
248    debug(
249        TAG,
250        format!("prepared {}; hooks changed {} paths", prepared.oid, hook_changes.paths.len()).as_str(),
251    );
252    let mut prepared_records: Vec<AddedPath> = selected.clone();
253    prepared_records.extend(hook_changes.worktree_records.iter().cloned());
254    write_journal_record(
255        workspace.landing.directory.as_path(),
256        PREPARED_FILENAME,
257        encode_prepared(&PreparedRecord {
258            shadow_path: workspace.landing.shadow.display().to_string(),
259            prepared_oid: prepared.oid.clone(),
260            signed: prepared.signed,
261            intended_tree_oid: intended_tree.clone(),
262            committed_paths: committed_paths.clone(),
263            added_paths: Vec::new(),
264            selected_worktree_paths: prepared_records.clone(),
265        })
266        .as_str(),
267    )?;
268    reach_transaction_phase(Phase::PreparationDone, None)?;
269    let settled_events: Vec<PolicyEvent> = events_with_changed_summary(pass.events.clone(), changed_passes, changed_paths.as_slice());
270    let options: ReplayOptions = replay_options(commit_args.as_slice());
271    let outcome: LoopOutcome = land_with_replay(LoopInput {
272        invocation,
273        workspace,
274        capture,
275        mode: selection.mode,
276        request,
277        checks,
278        prepared: &prepared,
279        settled_events: settled_events.clone(),
280        options: &options,
281        global_args: global_args.as_slice(),
282        read_only_selection: selection.read_only,
283        committed_paths: committed_paths.clone(),
284        added_paths: Vec::new(),
285        worktree_records: prepared_records.clone(),
286        hook_changes,
287        index_lock_timeout_ms: timeout_ms,
288        reserve_after_lost_races: invocation.config.concurrency.landing.reserve_after_lost_races,
289    })?;
290    let (oid, loop_events, final_worktree, final_added): (String, Vec<PolicyEvent>, Vec<AddedPath>, Vec<AddedPath>) =
291        match outcome {
292            LoopOutcome::Failed { events, exit_code } => {
293                return Ok(TransactionResult {
294                    events,
295                    exit_code,
296                    landed_oid: None,
297                });
298            }
299            LoopOutcome::Landed {
300                oid,
301                events,
302                worktree_records,
303                added_paths,
304            } => (oid, events, worktree_records, added_paths),
305        };
306    // Before cleanup, so an interruption leaves the journal for startup recovery to finish the worktree copies.
307    let landed: LandedTransaction = LandedTransaction {
308        landed_oid: oid.clone(),
309        branch: capture.layout.target_ref.clone(),
310        cwd: cwd.to_path_buf(),
311        repository_root: repository_root.to_path_buf(),
312        directory: workspace.landing.directory.clone(),
313        shadow: workspace.landing.shadow.clone(),
314        git_dir: capture.layout.git_dir.clone(),
315        registry_root: capture.layout.registry_root.clone(),
316        real_index: capture.layout.real_index_path.clone(),
317        added_paths: final_added,
318        worktree_records: final_worktree,
319    };
320    let completed = complete_landed_transaction(PostLandingRequest {
321        context,
322        plan: &plan,
323        landed: &landed,
324    });
325    if let Err(error) = completed {
326        return Err(TransactionStop::Message(error.to_string()));
327    }
328    // The completion removed the shadow and the directory, so the workspace has nothing left to dispose of; on a
329    // failure the landing's mark stays, and recovery finishes what the completion did not.
330    workspace.finish_transaction();
331    workspace.mark_disposed();
332    let mut events: Vec<PolicyEvent> = settled_events;
333    events.extend(loop_events);
334    return Ok(TransactionResult {
335        events,
336        exit_code: 0,
337        landed_oid: Some(oid),
338    });
339}
340
341/// Controls for this module stay out of the release executable.
342#[cfg(test)]
343#[path = "commit_conclusion_tests.rs"]
344mod tests;