Skip to main content

git_policy_cli/
entry.rs

1//! What:
2//!  Decide what one `git` invocation of the native wrapper does,
3//!  and perform it.
4//! Why:
5//!  The executable stays thin:
6//!  it gathers process facts,
7//!  asks this module for an
8//!      action,
9//!  and performs it.
10//!  The decision itself is testable without replacing
11//!      the test process.
12//!
13//! In TS you'd write (pseudocode):
14//! ```ts
15//! // const action = planInvocation(args, env, inputs); perform(action);
16//! ```
17
18/// Import the sibling modules the decision combines.
19use super::action::{Action, ENGINE_FAILURE_EXIT_CODE, PushForward, failure};
20use super::announced_query::{WRAPPER_VERSION, announced_query, announcement, printable_after};
21use super::command_push::stackable_option_tokens;
22use super::external_hooks::external_hooks_warning;
23use super::lfs_pre_push::uses_lfs;
24use super::config_snapshot::{ConfigSnapshot, read_config_snapshot};
25use super::push_stacking::{STACKED_PUSH_MARKER, run_stacked_push};
26use super::command_push::parse_push_region;
27use super::child_environment::{
28    FORWARD_TARGET_VARIABLE, child_environment_overlay, environment_value,
29};
30use super::effective_target::default_allowed_worktree_dirs;
31use super::forwarding::{exit_code, replace_process_with_real_git, run_real_git};
32use super::index_writer_forward::{CoordinatedForward, CoordinatedRun, run_coordinated_forward};
33use super::index_writer_commands::is_index_writer;
34use super::forwarded_command::{ResolvedCommand, creates_or_moves_worktrees, resolve_forwarded_command};
35use super::invocation_config::{config_invalid_event, load_identity_config};
36use super::config_file::LoadedConfig;
37use super::repository_location::RepositoryLocation;
38use super::transaction_git::GitContext;
39use super::worktree_identity::WorktreeIdentity;
40use super::global_arguments::{GlobalLayout, GlobalOutcome, global_layout};
41use super::management::plan_management;
42/// The linter the executable gives the Markdown policy.
43use super::markdown_linter::executable_linter;
44/// The shipped checks and their constructor.
45use super::policy_checks::{ShippedChecks, shipped_checks};
46/// A forwarded command starts with no candidate content.
47use super::policy_content::LifecycleContent;
48use super::real_git::{ResolutionInputs, process_resolution_inputs, resolve_real_git};
49use super::real_git_candidate::same_file;
50use super::repository_facts::{GitFacts, RepositoryFacts, git_facts};
51use super::rule_require_root::{RequireRootDecision, decide_require_root};
52/// The variable that names the forbidden-strings rules list.
53use super::scanner_selection::RULES_VARIABLE;
54use super::wrapped_command::{WrappedOutcome, run_wrapped_command};
55use super::wrapper_controls::{Controls, no_controls, strip_global_controls};
56use super::worktree_copy_forward::{CopyFacts, ForwardedRun, copy_applies, run_forwarded_git};
57use super::wrapper_invocation::{StrippedInvocation, strip_wrapper_controls};
58/// What:
59///  `OsString` is owned operating-system text of raw OS bytes (sibling `String`
60///       must be UTF-8).
61/// Why:
62///   Arguments and environment values are never decoded.
63///
64/// In TS you'd write (pseudocode):
65/// ```ts
66/// // process.argv and process.env, but byte-preserving.
67/// ```
68use std::ffi::OsString;
69/// The trait that gives output streams `.write_all(..)`.
70use std::io::Write;
71/// `Path`/`PathBuf` are borrowed/owned filesystem paths of raw OS bytes.
72use std::path::{Path, PathBuf};
73
74/// The management namespace:
75///  `git cli-git ...` is handled by the wrapper,
76///  never by Git.
77pub const MANAGEMENT_COMMAND: &str = "cli-git";
78
79/// What:
80///  Explain that another cli-git wrapper selected this executable as real Git.
81///       `&Path` borrows this executable's path for the message.
82/// Why:
83///   Forwarding again would bounce between the two wrappers forever;
84///  stopping
85///       names this executable so the user can fix PATH.
86///
87/// In TS you'd write (pseudocode):
88/// ```ts
89/// function forwardedToSelf(ownExecutable: string): Action;
90/// ```
91fn forwarded_to_self(own_executable: &Path) -> Action {
92    // `format!` builds owned text; `.as_str()` lends it to the helper.
93    return failure(
94        format!(
95            "another cli-git wrapper selected this cli-git executable ({}) as real Git. \
96             Forwarding again would never reach Git. Remove the extra cli-git from PATH or \
97             place the real Git executable on PATH.",
98            own_executable.display()
99        )
100        .as_str(),
101    );
102}
103
104/// What:
105///  The caller's home directory from the environment,
106///  if it names one.
107///       `Option<PathBuf>` is "an owned path or nothing".
108/// Why:
109///   The tool caches exempt from linked-worktree enforcement live under the home
110///       directory;
111///  it comes from the injected environment,
112///  never from a fixed path.
113///
114/// In TS you'd write (pseudocode):
115/// ```ts
116/// const home = environment.HOME === undefined || environment.HOME === '' ? undefined : environment.HOME;
117/// ```
118fn home_directory(environment: &[(OsString, OsString)]) -> Option<PathBuf> {
119    // `if let Some(home) = ... && cond` runs only when the variable is set and not empty.
120    if let Some(home) = environment_value(environment, "HOME")
121        && !home.is_empty()
122    {
123        // `Some(...)` is the "present" case; `PathBuf::from` turns the text into a path.
124        return Some(PathBuf::from(home));
125    }
126    // `None` is the "absent" case.
127    return None;
128}
129
130/// What:
131///  Decide the action for one invocation from injected process facts.
132///       `&[OsString]` borrows the arguments after the program name;
133///       `&[(OsString, OsString)]` borrows the environment as name/value pairs.
134/// Why:
135///   Order matters.
136///  The recursion check runs before anything else.
137///  Wrapper controls
138///       written before the subcommand are removed first,
139///  because Git's own reading of
140///       the arguments stops at them and would hide the subcommand from every later
141///       decision.
142///  The management namespace is answered by the wrapper.
143///  Every other
144///       command goes through the wrapped-command lifecycle with real Git behind it.
145///
146/// In TS you'd write (pseudocode):
147/// ```ts
148/// function planInvocation(args: string[], environment: [string, string][], inputs: ResolutionInputs): Action;
149/// ```
150pub fn plan_invocation(
151    arguments: &[OsString],
152    environment: &[(OsString, OsString)],
153    inputs: &ResolutionInputs,
154) -> Action {
155    // `if let Some(target) = ... && cond` runs only when a forwarding wrapper left its
156    // marker and that marker names this executable.
157    if let Some(target) = environment_value(environment, FORWARD_TARGET_VARIABLE)
158        && same_file(Path::new(&target), inputs.own_executable.as_path())
159    {
160        return forwarded_to_self(inputs.own_executable.as_path());
161    }
162    // `mut` allows the scan to record what the removed controls asked for.
163    let mut global_controls: Controls = no_controls();
164    // `&mut global_controls` lends the record for writing.
165    let global_clean: Vec<OsString> = strip_global_controls(arguments, &mut global_controls);
166    // `.as_slice()` lends the owned list as a borrowed view.
167    let layout: GlobalLayout = global_layout(global_clean.as_slice());
168    if layout.outcome == GlobalOutcome::Command
169        && global_clean[layout.prefix_len] == MANAGEMENT_COMMAND
170    {
171        // `&list[a..]` borrows from index `a` on; `&list[..a]` borrows up to it.
172        return plan_management(
173            &global_clean[layout.prefix_len + 1..],
174            &global_clean[..layout.prefix_len],
175            &global_controls,
176            environment,
177            inputs,
178        );
179    }
180    // What: `match` on the resolver's `Result`: keep the path or stop with its message.
181    // Why:  Without real Git there is nothing to forward to.
182    //
183    // In TS you'd write (pseudocode):
184    // ```ts
185    // let realGit; try { realGit = resolveRealGit(inputs); } catch (e) { return failure(String(e)); }
186    // ```
187    let real_git: PathBuf = match resolve_real_git(inputs) {
188        Ok(found) => found,
189        Err(error) => return failure(error.to_string().as_str()),
190    };
191    let overlay: Vec<(OsString, OsString)> =
192        child_environment_overlay(environment, real_git.as_path());
193    // What: Top-level `--version`, `-v`, `--help` and `-h` run Git as a child and add the announcement.
194    // Why:  The layout is already known here, so every other invocation pays one enum comparison;
195    //       the other queries keep the exact process replacement below.
196    //
197    // In TS you'd write (pseudocode):
198    // ```ts
199    // const query = announcedQuery(args, layout); if (query) return { kind: 'forward-announced', ... };
200    // ```
201    if let Some(query) = announced_query(global_clean.as_slice(), &layout) {
202        return Action::ForwardAnnounced {
203            announcement: announcement(query, WRAPPER_VERSION, real_git.as_path()),
204            real_git,
205            arguments: global_clean,
206            overlay,
207            stderr: String::new(),
208        };
209    }
210    let stripped: StrippedInvocation = strip_wrapper_controls(arguments);
211    // The global options before the subcommand select the repository for every fact query.
212    let facts: GitFacts = git_facts(
213        real_git.as_path(),
214        &stripped.arguments[..stripped.layout.prefix_len],
215        overlay.as_slice(),
216    );
217    // `mut` lets the lifecycle cache facts and state what content policies can read.
218    let mut checks: ShippedChecks<GitFacts> = shipped_checks(
219        facts,
220        // `.clone()` copies the stripped arguments for the rule cores.
221        stripped.arguments.clone(),
222        LifecycleContent::None,
223        default_allowed_worktree_dirs(
224            environment,
225            // `.as_deref()` lends the optional owned path as an optional borrowed one.
226            home_directory(environment).as_deref(),
227        ),
228    );
229    // The forbidden-strings rules variable is read from this invocation's environment.
230    checks.scanner_settings.rules_variable = environment_value(environment, RULES_VARIABLE);
231    // The Markdown linter is found on, and runs with, this invocation's environment.
232    checks.markdown.linter = Box::new(executable_linter(environment));
233    // `match` picks by variant and binds the fields each ending carries.
234    match run_wrapped_command(&stripped, environment, &mut checks) {
235        // `arguments: forwarded` binds the field under a new name.
236        WrappedOutcome::Forward {
237            arguments: forwarded,
238            stderr,
239        } => {
240            // The opt-out, Git's other query forms (`--exec-path` and so on), and the commands that need no repository
241            // (`version`, `help`, `init`, `clone`, user-level `config`) never settle a copy.
242            let copy_bypassed: bool = stripped.controls.skip_worktree_copy
243                || stripped.layout.outcome != GlobalOutcome::Command
244                || decide_require_root(forwarded.as_slice(), &[])
245                    != RequireRootDecision::NeedsRepositoryRoot;
246            return stack_if_push(
247                forward_action(
248                    real_git,
249                    forwarded,
250                    overlay,
251                    stderr,
252                    environment,
253                    copy_bypassed,
254                    &mut checks,
255                ),
256                environment,
257            );
258        }
259        WrappedOutcome::Exit { code, stderr } => {
260            return Action::Exit {
261                code,
262                // `String::new()` is empty owned text: wrapped commands report on standard error.
263                stdout: String::new(),
264                stderr,
265            };
266        }
267    }
268}
269
270/// What:
271///  Run one invocation with the real process facts and return its exit code.
272///       `i32` is a signed 32-bit integer,
273///  the type of process exit codes.
274///       Returns only when Git was not started;
275///  a forwarded command never returns.
276/// Why:
277///   This is everything the executable's `main` does;
278///  keeping it in the library
279///       lets the same code be measured by tests and mutation runs.
280///
281/// In TS you'd write (pseudocode):
282/// ```ts
283/// function runProcess(args: string[], environment: [string, string][]): number;
284/// ```
285pub fn run_process(arguments: &[OsString], environment: &[(OsString, OsString)]) -> i32 {
286    // From here on every real-Git start of this process runs with traditional hooks off.
287    super::hooks_off::activate();
288    let action: Action = match process_resolution_inputs(environment) {
289        Ok(inputs) => plan_invocation(arguments, environment, &inputs),
290        Err(error) => failure(
291            format!(
292                "cannot determine this executable or the current directory, so real Git \
293                 cannot be selected safely: {error}"
294            )
295            .as_str(),
296        ),
297    };
298    // `match` picks by variant and binds the fields each one carries.
299    match action {
300        Action::Forward {
301            real_git,
302            arguments: forwarded,
303            overlay,
304            stderr,
305        } => {
306            // Warning events reach the caller before Git's own output.
307            write_stream(&mut std::io::stderr(), stderr.as_str());
308            let error: std::io::Error = replace_process_with_real_git(
309                real_git.as_path(),
310                forwarded.as_slice(),
311                overlay.as_slice(),
312            );
313            write_stream(
314                &mut std::io::stderr(),
315                format!(
316                    "cli-git: cannot start {}: {error}. Hint: if you moved or upgraded Git, check that the file exists and is executable with `ls -l {}`, \
317                     then reinstall Git or the wrapper; no Git command ran.\n",
318                    real_git.display(),
319                    real_git.display()
320                )
321                .as_str(),
322            );
323            return ENGINE_FAILURE_EXIT_CODE;
324        }
325        Action::ForwardCoordinated { forward, stderr } => {
326            write_stream(&mut std::io::stderr(), stderr.as_str());
327            return run_coordinated_action(&forward);
328        }
329        Action::ForwardAnnounced {
330            real_git,
331            arguments: forwarded,
332            overlay,
333            announcement,
334            stderr,
335        } => {
336            write_stream(&mut std::io::stderr(), stderr.as_str());
337            return run_announced(
338                real_git.as_path(),
339                forwarded.as_slice(),
340                overlay.as_slice(),
341                announcement.as_str(),
342            );
343        }
344        Action::ForwardSettled {
345            real_git,
346            arguments: forwarded,
347            overlay,
348            copy,
349            stderr,
350        } => {
351            write_stream(&mut std::io::stderr(), stderr.as_str());
352            return finish_forwarded(run_forwarded_git(
353                real_git.as_path(),
354                forwarded.as_slice(),
355                overlay.as_slice(),
356                Some(&*copy),
357            ));
358        }
359        Action::ForwardPush { forward, stderr } => {
360            write_stream(&mut std::io::stderr(), stderr.as_str());
361            return run_stacked_push(&forward);
362        }
363        Action::Exit {
364            code,
365            stdout,
366            stderr,
367        } => {
368            // `&mut` lends each stream for writing.
369            write_stream(&mut std::io::stdout(), stdout.as_str());
370            write_stream(&mut std::io::stderr(), stderr.as_str());
371            return code;
372        }
373    }
374}
375
376/// What:
377///  Run Git as a child for an announced query,
378///  print the announcement when Git exited with status 0,
379///  and return Git's status.
380/// Why:
381///   The child shares the caller's streams, so Git's own answer is untouched and comes first;
382///  the announcement follows it only when Git answered.
383///
384/// In TS you'd write (pseudocode):
385/// ```ts
386/// const outcome = await runRealGit(realGit, args, overlay); if (outcome.exited === 0) print(text); return exitCode(outcome);
387/// ```
388fn run_announced(
389    real_git: &Path,
390    arguments: &[OsString],
391    overlay: &[(OsString, OsString)],
392    text: &str,
393) -> i32 {
394    match run_real_git(real_git, arguments, overlay) {
395        Ok(outcome) => {
396            write_stream(&mut std::io::stdout(), printable_after(outcome, text));
397            return exit_code(outcome);
398        }
399        Err(error) => {
400            write_stream(
401                &mut std::io::stderr(),
402                format!(
403                    "cli-git: cannot start {}: {error}. Hint: if you moved or upgraded Git, check that the file exists and is executable with `ls -l {}`, \
404                     then reinstall Git or the wrapper; no Git command ran.\n",
405                    real_git.display(),
406                    real_git.display()
407                )
408                .as_str(),
409            );
410            return ENGINE_FAILURE_EXIT_CODE;
411        }
412    }
413}
414
415/// What:
416///  The exit code of a forwarded run, after printing the text of a run that failed.
417/// Why:
418///   A settled run keeps the wrapper alive around Git, so the exit code returns here instead of replacing the process.
419///
420/// In TS you'd write (pseudocode):
421/// ```ts
422/// process.exitCode = outcome.exitCode;
423/// ```
424fn finish_forwarded(run: ForwardedRun) -> i32 {
425    // `match` on the ending: a status, or a failure with its own text.
426    match run {
427        ForwardedRun::Ran(code) => return code,
428        ForwardedRun::Failed { stderr, code } => {
429            write_stream(&mut std::io::stderr(), stderr.as_str());
430            return code;
431        }
432    }
433}
434
435/// What:
436///  Run a coordinated forward:
437///  print its failure,
438///  run Git under the landing lock,
439///  or replace the process when no coordination applies after all.
440/// Why:
441///   The lock must outlive Git,
442///  so only a run that takes no lock may replace the process.
443///
444/// In TS you'd write (pseudocode):
445/// ```ts
446/// const outcome = await forwardToRealGit({ ... }); process.exitCode = outcome.exitCode;
447/// ```
448fn run_coordinated_action(forward: &CoordinatedForward) -> i32 {
449    match run_coordinated_forward(forward) {
450        CoordinatedRun::Ran(code) => return code,
451        CoordinatedRun::Failed { stderr, code } => {
452            write_stream(&mut std::io::stderr(), stderr.as_str());
453            return code;
454        }
455        CoordinatedRun::NotCoordinated => {
456            let error: std::io::Error = replace_process_with_real_git(
457                forward.real_git.as_path(),
458                forward.arguments.as_slice(),
459                forward.overlay.as_slice(),
460            );
461            write_stream(
462                &mut std::io::stderr(),
463                format!("cli-git: cannot start {}: {error}\n", forward.real_git.display()).as_str(),
464            );
465            return ENGINE_FAILURE_EXIT_CODE;
466        }
467    }
468}
469
470/// What:
471///  Choose how a forwarded command runs:
472///  plainly,
473///  under the landing lock when it writes the real index,
474///  and settled by the linked-worktree copy when it runs from a linked worktree or a bare repository
475///  (or creates a worktree from a main checkout whose configuration names the rules file).
476///  `copy_bypassed` is true for the wrapper's opt-out and for Git's query forms.
477/// Why:
478///   Only these commands need the wrapper to outlive Git or to hold a lock around it;
479///  everything else keeps the exact process replacement.
480///
481/// In TS you'd write (pseudocode):
482/// ```ts
483/// if (!isIndexWriter(command) && !copyApplies) forward(args); else await forwardToRealGit({ ..., unprovenOwnerTimeoutMs });
484/// ```
485fn forward_action(
486    real_git: PathBuf,
487    arguments: Vec<OsString>,
488    overlay: Vec<(OsString, OsString)>,
489    stderr: String,
490    environment: &[(OsString, OsString)],
491    copy_bypassed: bool,
492    checks: &mut ShippedChecks<GitFacts>,
493) -> Action {
494    let context: GitContext = GitContext {
495        real_git: real_git.clone(),
496        overlay: overlay.clone(),
497        global_prefix: Vec::new(),
498        // These queries send no input, so no scratch directory is needed.
499        common_dir: None,
500    };
501    let command: ResolvedCommand = resolve_forwarded_command(&context, arguments.as_slice());
502    let writes_index: bool = is_index_writer(&command);
503    if !writes_index && copy_bypassed {
504        return Action::Forward {
505            real_git,
506            arguments,
507            overlay,
508            stderr,
509        };
510    }
511    let location: RepositoryLocation = match checks.facts.location() {
512        Ok(found) => found,
513        Err(message) => return failure(message.as_str()),
514    };
515    if location.identity == WorktreeIdentity::OutsideWorktree {
516        return Action::Forward {
517            real_git,
518            arguments,
519            overlay,
520            stderr,
521        };
522    }
523    let loaded: Option<LoadedConfig> = match configuration_needed(&location.identity, &command, writes_index) {
524        false => None,
525        true => match load_identity_config(&location.identity) {
526            Ok(found) => Some(found),
527            Err(error) => {
528                return Action::Exit {
529                    code: ENGINE_FAILURE_EXIT_CODE,
530                    stdout: String::new(),
531                    stderr: config_invalid_event(&error),
532                };
533            }
534        },
535    };
536    let creates_or_moves: bool = creates_or_moves_worktrees(&command);
537    // Only a main checkout hands over the configured rules files; `copy_applies` limits it to a creating command.
538    let main_checkout_paths: Vec<String> = match (&location.identity, &loaded) {
539        // Every configured file, required or optional: the copier skips a file Git does not ignore or that is absent.
540        (WorktreeIdentity::MainWorktree { .. }, Some(found)) => found
541            .config
542            .policies
543            .forbidden_strings
544            .rules_files
545            .iter()
546            .flatten()
547            .map(|file| return file.path.clone())
548            .collect(),
549        _ => Vec::new(),
550    };
551    let copy: Option<CopyFacts> =
552        if !copy_bypassed && copy_applies(&location.identity, creates_or_moves, main_checkout_paths.as_slice()) {
553            Some(CopyFacts {
554                identity: location.identity.clone(),
555                creates_or_moves,
556                main_checkout_paths,
557                global_prefix: checks.facts.transaction_context().global_prefix,
558                environment: environment.to_vec(),
559            })
560        } else {
561            None
562        };
563    if !writes_index {
564        let Some(facts) = copy else {
565            return Action::Forward {
566                real_git,
567                arguments,
568                overlay,
569                stderr,
570            };
571        };
572        return Action::ForwardSettled {
573            real_git,
574            arguments,
575            overlay,
576            copy: Box::new(facts),
577            stderr,
578        };
579    }
580    let Some(found) = loaded else {
581        return failure("the repository configuration was not loaded for an index writer");
582    };
583    return Action::ForwardCoordinated {
584        forward: Box::new(CoordinatedForward {
585            real_git,
586            arguments,
587            overlay,
588            identity: location.identity,
589            command,
590            environment: environment.to_vec(),
591            timeout_ms: found.config.concurrency.index_lock.unproven_owner_timeout_ms,
592            copy,
593        }),
594        stderr,
595    };
596}
597
598/// What:
599///  Whether `command` is a push that must upload LFS objects first, and the configuration warning for configured
600///  external hooks, when the same read shows any, as empty text otherwise.
601///  A dry-run push reads the configuration too, for the warning, but uploads nothing.
602/// Why:
603///   A push that sends nothing (`--dry-run`) needs no upload, and a repository without LFS keys needs none either.
604///  One configuration read answers it, made with the invocation's own global options; when Git cannot list its
605///  configuration the hook is added anyway, because it then decides with Git's own answers.
606///  The warning costs no read of its own: a push is the one forwarded command that already holds the snapshot.
607///
608/// In TS you'd write (pseudocode):
609/// ```ts
610/// function needsLfsUpload(command, realGit, overlay): [boolean, string];
611/// ```
612fn needs_lfs_upload(
613    command: &ResolvedCommand,
614    real_git: &Path,
615    overlay: &[(OsString, OsString)],
616) -> (bool, String) {
617    if command.word() != b"push" {
618        return (false, String::new());
619    }
620    let dry_run: bool = parse_push_region(command.region(), &[]).is_ok_and(|region| {
621        return region.dry_run;
622    });
623    let context: GitContext = GitContext {
624        real_git: real_git.to_path_buf(),
625        overlay: overlay.to_vec(),
626        global_prefix: command.arguments[..command.subcommand_index].to_vec(),
627        common_dir: None,
628    };
629    let snapshot: Option<ConfigSnapshot> = match std::env::current_dir() {
630        Ok(directory) => read_config_snapshot(&context, directory.as_path()),
631        Err(_) => None,
632    };
633    let warning: String = external_hooks_warning(snapshot.as_ref()).unwrap_or_default();
634    if dry_run {
635        return (false, warning);
636    }
637    return match snapshot {
638        Some(found) => (uses_lfs(&found), warning),
639        None => (true, warning),
640    };
641}
642
643/// What:
644///  Turn the forward of a plain push that may be integrated into a run that can integrate it,
645///  and put the Git LFS upload in front of every push that publishes.
646/// Why:
647///   A push that lost a race to another session cannot succeed again, and the wrapper can only look at its status
648///  while it is alive;
649///  the stacked push itself carries `STACKED_PUSH_MARKER`, so it is forwarded as it is and never stacks again.
650///   A real push in a repository with LFS keys also runs as a child that the Git LFS upload (`lfs_upload`) precedes,
651///  the stacked push too, so the parent can explain a failed upload;
652///  the integration step's own dry-run queries never upload.
653///   Every other action is returned unchanged.
654///
655/// In TS you'd write (pseudocode):
656/// ```ts
657/// function stackIfPush(action: Action, environment): Action;
658/// ```
659fn stack_if_push(action: Action, environment: &[(OsString, OsString)]) -> Action {
660    let (real_git, arguments, overlay, copy, stderr) = match action {
661        Action::Forward {
662            real_git,
663            arguments,
664            overlay,
665            stderr,
666        } => (real_git, arguments, overlay, None, stderr),
667        Action::ForwardSettled {
668            real_git,
669            arguments,
670            overlay,
671            copy,
672            stderr,
673        } => (real_git, arguments, overlay, Some(copy), stderr),
674        other => return other,
675    };
676    let context: GitContext = GitContext {
677        real_git: real_git.clone(),
678        overlay: overlay.clone(),
679        global_prefix: Vec::new(),
680        // These queries send no input, so no scratch directory is needed.
681        common_dir: None,
682    };
683    let command: ResolvedCommand = resolve_forwarded_command(&context, arguments.as_slice());
684    let (lfs, hook_warning): (bool, String) = needs_lfs_upload(&command, real_git.as_path(), overlay.as_slice());
685    let stderr_with_warning: String = format!("{stderr}{hook_warning}");
686    let stacked_already: bool = environment_value(environment, STACKED_PUSH_MARKER).is_some();
687    let stack: bool =
688        !stacked_already && command.word() == b"push" && stackable_option_tokens(command.region()).is_some();
689    // A push that uploads LFS objects runs as a child like a stackable one: the parent that owns the push is the one
690    // that explains a failed upload, and no wrapper is started for it.
691    if stack || lfs {
692        return Action::ForwardPush {
693            forward: Box::new(PushForward {
694                real_git,
695                subcommand_index: command.subcommand_index,
696                arguments: command.arguments,
697                overlay,
698                copy,
699                environment: environment.to_vec(),
700                lfs,
701                stack,
702            }),
703            stderr: stderr_with_warning,
704        };
705    }
706    let forwarded: Vec<OsString> = arguments;
707    return match copy {
708        Some(facts) => Action::ForwardSettled {
709            real_git,
710            arguments: forwarded,
711            overlay,
712            copy: facts,
713            stderr: stderr_with_warning,
714        },
715        None => Action::Forward {
716            real_git,
717            arguments: forwarded,
718            overlay,
719            stderr: stderr_with_warning,
720        },
721    };
722}
723
724/// What:
725///  Whether the forwarded command needs the repository configuration.
726/// Why:
727///   An index writer reads its patience from it, and a main checkout reads the rules file name from it;
728///  linked worktrees and bare repositories need no configuration for the copy, so their commands load nothing new.
729///
730/// In TS you'd write (pseudocode):
731/// ```ts
732/// isIndexWriter(command) || (identity.kind === 'main-worktree' && createsOrMovesWorktrees(command))
733/// ```
734fn configuration_needed(identity: &WorktreeIdentity, command: &ResolvedCommand, writes_index: bool) -> bool {
735    return writes_index
736        || (matches!(identity, WorktreeIdentity::MainWorktree { .. })
737            && creates_or_moves_worktrees(command));
738}
739
740/// What:
741///  Write text to an output stream,
742///  ignoring a closed stream.
743///       `&mut dyn Write` lends "any writable stream" (`dyn` means the concrete type is
744///       chosen at run time,
745///  like a TS interface value).
746/// Why:
747///   The exit code already carries the result;
748///  a reader that went away must not
749///       turn a diagnostic into a panic.
750///
751/// In TS you'd write (pseudocode):
752/// ```ts
753/// function writeStream(stream: Writable, text: string): void { try { stream.write(text); } catch {} }
754/// ```
755fn write_stream(stream: &mut dyn Write, text: &str) {
756    // What: `let _ = ...` deliberately discards the write's `Result`.
757    // Why:  There is nowhere left to report a failure to write a diagnostic.
758    //
759    // In TS you'd write (pseudocode):
760    // ```ts
761    // try { stream.write(text); } catch { /* reader closed */ }
762    // ```
763    let _ = stream.write_all(text.as_bytes());
764}
765
766/// Plans of the announced queries,
767///  `--version`, `-v`, `--help` and `-h`, against the queries that stay exact.
768#[cfg(test)]
769#[path = "entry_announced_tests.rs"]
770mod announced_tests;
771
772/// Stop controls for a looping,
773///  missing or uninterpretable real Git.
774#[cfg(test)]
775#[path = "entry_stop_tests.rs"]
776mod stop_tests;
777
778/// Decision controls and the shared fixtures stay out of the release executable.
779#[cfg(test)]
780#[path = "entry_tests.rs"]
781mod tests;