Skip to main content

git_policy_cli/
lfs_bounded_push.rs

1//! What:
2//!  Run one bounded `git push` of the auto-push, preceded by the Git LFS upload when the repository has one.
3//! Why:
4//!  The auto-push and its reconcile pushes publish refs, so they upload the LFS objects the pushed commits point to
5//!  exactly as a typed `git push` does. The wrapper is the parent of both children and captures their output, so it
6//!  owns the explanation: a missing `git-lfs` is refused before anything starts, a failed upload ends the attempt with
7//!  the full explanation after the program's own output, and the push is not started. The push carries no hook, and no
8//!  process other than Git and `git-lfs` is started for this, none of them the wrapper.
9//!
10//! In TS you'd write (pseudocode):
11//! ```ts
12//! const failed = plan && await uploadBounded(plan); if (failed) return failed; return await runBoundedPush(pushCommand(git, args));
13//! ```
14
15/// The attempt record, the coordinator's Git and its error type.
16use super::auto_push_single_flight::{PushAttempt, PushGit, SingleFlightError, git_command, run_query};
17/// The deadline, the grace, the low-speed abort and the push itself.
18use super::bounded_push::{STOP_GRACE, apply_low_speed_defaults, push_deadline, run_bounded_push, strip_one_line_break};
19/// The check that the program can start.
20use super::lfs_push_precheck::lfs_refusal;
21/// Narrows the plan to the objects the push introduces.
22use super::lfs_object_plan::narrow_plan;
23/// What to upload and the bounded run of it.
24use super::lfs_upload::run_upload_bounded;
25/// The repository found from the files.
26use super::git_system_config::with_real_git;
27use super::repo_read_layout::read_layout_after_success;
28use super::lfs_pre_push::plan_failed_message;
29use super::lfs_upload_plan::{Query, plan_upload, read_settings};
30/// Owned OS strings for Git arguments.
31use std::ffi::OsString;
32
33/// Exit status of a push the wrapper refused before anything started.
34const REFUSED_EXIT_CODE: i64 = 1;
35
36/// What:
37///  Run `git <arguments>` (a `push`) as a bounded child, after the upload when the repository has LFS keys.
38/// Why:
39///   `arguments[0]` is `push`; what follows is its option region, which the pre-check and the plan read.
40///
41/// In TS you'd write (pseudocode):
42/// ```ts
43/// async function runLfsAwarePush(git: PushGit, args: string[]): Promise<PushAttempt>;
44/// ```
45pub fn run_push(git: &PushGit, arguments: &[OsString]) -> Result<PushAttempt, SingleFlightError> {
46    let region: &[OsString] = arguments.get(1..).unwrap_or_default();
47    if git.lfs {
48        if let Some(refusal) = lfs_refusal(&[], region, git.environment.as_slice()) {
49            return Ok(PushAttempt {
50                exit_code: REFUSED_EXIT_CODE,
51                output: strip_one_line_break(refusal.as_str()).to_owned(),
52            });
53        }
54        let mut query = |query_arguments: &[&str]| -> Result<String, String> {
55            let owned: Vec<OsString> = query_arguments.iter().map(OsString::from).collect();
56            let output = run_query(git, owned.as_slice()).map_err(|error| {
57                return error.to_string();
58            })?;
59            let text: String = String::from_utf8_lossy(output.stdout.as_slice()).trim().to_owned();
60            return match output.code {
61                Some(0) => Ok(text),
62                Some(1) if text.is_empty() => Ok(text),
63                code => Err(format!("exited with {code:?}: {}", String::from_utf8_lossy(output.stderr.as_slice()).trim())),
64            };
65        };
66        let planned = read_settings(&mut query as Query<'_>).and_then(|settings| {
67            return plan_upload(&[], region, git.environment.as_slice(), git.cwd.as_path(), settings.as_slice(), &mut query);
68        });
69        match planned {
70            Ok(Some(plan)) => {
71                // The plan came from Git queries that exited with status 0,
72                // so Git had its say about the values it consults;
73                // the files are read again,
74                // and a plan that cannot be narrowed is still pushed by `git-lfs` and Git.
75                let layout = read_layout_after_success(git.cwd.as_path(), with_real_git(git.environment.as_slice(), git.real_git.as_path()).as_slice());
76                if let Some(narrowed) = narrow_plan(plan, layout.as_ref())
77                    && let Some(failed) = run_upload_bounded(git, &narrowed)? {
78                    return Ok(failed);
79                }
80            }
81            Ok(None) => {}
82            Err(error) => {
83                return Ok(PushAttempt {
84                    exit_code: REFUSED_EXIT_CODE,
85                    output: strip_one_line_break(plan_failed_message(error.0.as_str()).as_str()).to_owned(),
86                });
87            }
88        }
89    }
90    let mut command = git_command(git, arguments);
91    apply_low_speed_defaults(&mut command, git.environment.as_slice());
92    return run_bounded_push(command, push_deadline(git.environment.as_slice()), STOP_GRACE, git.environment.as_slice());
93}