Skip to main content

git_policy_cli/lfs/
lfs_upload.rs

1//! What:
2//!  The parent's run of the Git LFS upload before a push: `git-lfs push <remote> <refs>` as one child it owns.
3//! Why:
4//!  Without an upload step a push publishes pointer files whose objects the LFS server never received.
5//!  The wrapper runs `git-lfs push` itself, so a failure is explained by the process that saw it and the push, which
6//!  then carries no hook, is never started. Nothing here starts the wrapper, writes shell text or injects Git
7//!  configuration (`doc/planning/cli-git-no-self-invocation.md`). What to upload is decided in `lfs_upload_plan`.
8//!  The child sees what the caller gave Git: the global `-c` options travel as `GIT_CONFIG_COUNT` pairs, `--git-dir`,
9//!  `--work-tree` and `--namespace` as their variables, `-C` as the working directory, and the real Git's directory
10//!  leads its `PATH` so a `git` it starts is never the wrapper while `git-lfs` itself is the one the caller's `PATH`
11//!  finds first.
12//!
13//! In TS you'd write (pseudocode):
14//! ```ts
15//! const code = await spawn(findProgram(env.PATH), plan.arguments(), { env: withPrefix(env, globalPrefix), stdio: 'inherit' });
16//! ```
17
18/// The attempt record, the coordinator's Git and its error type.
19use crate::auto_push_single_flight::{PushAttempt, PushGit, SingleFlightError};
20/// The deadline, the grace and the push runner.
21use crate::bounded_push::{STOPPED_EXIT_CODE, STOP_GRACE, push_patience, run_bounded_push};
22/// The invocation's environment values.
23use crate::child_environment::environment_value;
24/// How a child ended, as a status.
25use crate::forwarding::{ChildOutcome, exit_code, outcome_of};
26/// The texts, the program lookup and the plan.
27use crate::lfs_pre_push::{failed_message, find_program, missing_program_message};
28/// Hides the credentials in a URL of relayed text.
29use crate::lfs_output_mask::{mask_userinfo, mask_userinfo_text};
30use crate::lfs_upload_plan::UploadPlan;
31/// The anonymous file the interactive upload's standard error goes to.
32use crate::scratch_location::scratch_file;
33/// Relays signals to the child.
34use crate::signal_relay::SignalGuard;
35/// Starts that ride out a short shortage of processes.
36use crate::start_retry::RetryStart;
37/// Owned OS text for arguments.
38use std::ffi::OsString;
39/// The real Git whose directory leads `PATH`.
40use std::path::Path;
41/// The child and its standard error.
42use std::process::{Command, Stdio};
43/// Reading the captured standard error back.
44use std::io::{Read, Seek, SeekFrom};
45
46/// `PATH` with the directory of the real Git first, so a `git` that `git-lfs` starts is the real Git and never the
47///  wrapper (Git does the same for the hooks it starts).
48fn path_with_real_git_first(environment: &[(OsString, OsString)], real_git: &Path) -> OsString {
49    let existing: OsString = environment_value(environment, "PATH").unwrap_or_default();
50    let mut directories: Vec<std::path::PathBuf> = Vec::new();
51    if let Some(directory) = real_git.parent() {
52        directories.push(directory.to_path_buf());
53    }
54    directories.extend(std::env::split_paths(existing.as_os_str()));
55    return std::env::join_paths(directories).unwrap_or(existing);
56}
57
58/// What:
59///  The variables that carry the global options of a push into a child that reads Git's configuration.
60/// Why:
61///   `-c name=value` becomes `GIT_CONFIG_KEY_n`/`GIT_CONFIG_VALUE_n` after any pairs the environment already holds
62///  (a `-c` without `=` is the boolean true), `--git-dir`, `--work-tree` and `--namespace` become `GIT_DIR`,
63///  `GIT_WORK_TREE` and `GIT_NAMESPACE`; `-C` is the working directory and is applied by the caller.
64///  No shell is involved, and an `-c http.extraHeader=...` or `-c lfs.url=...` reaches `git-lfs` as it reached the
65///  Git that used to run the hook.
66///
67/// In TS you'd write (pseudocode):
68/// ```ts
69/// function prefixVariables(globalPrefix: string[], environment): [string, string][];
70/// ```
71pub fn prefix_variables(global_prefix: &[OsString], environment: &[(OsString, OsString)]) -> Vec<(OsString, OsString)> {
72    let mut pairs: Vec<(OsString, OsString)> = Vec::new();
73    let mut variables: Vec<(OsString, OsString)> = Vec::new();
74    let mut tokens = global_prefix.iter();
75    while let Some(token) = tokens.next() {
76        let text: String = token.to_string_lossy().into_owned();
77        if text == "-c" {
78            if let Some(setting) = tokens.next() {
79                let setting_text: String = setting.to_string_lossy().into_owned();
80                let (name, value) = setting_text.split_once('=').unwrap_or((setting_text.as_str(), "true"));
81                pairs.push((OsString::from(name), OsString::from(value)));
82            }
83            continue;
84        }
85        for (option, variable) in [("--git-dir", "GIT_DIR"), ("--work-tree", "GIT_WORK_TREE"), ("--namespace", "GIT_NAMESPACE")] {
86            if text == option {
87                if let Some(value) = tokens.next() {
88                    variables.push((OsString::from(variable), value.clone()));
89                }
90            } else if let Some(value) = text.strip_prefix(format!("{option}=").as_str()) {
91                variables.push((OsString::from(variable), OsString::from(value)));
92            }
93        }
94    }
95    let existing: usize = environment_value(environment, "GIT_CONFIG_COUNT")
96        .and_then(|value| {
97            return value.to_str().and_then(|count| {
98                return count.parse::<usize>().ok();
99            });
100        })
101        .unwrap_or(0);
102    if !pairs.is_empty() {
103        variables.push((OsString::from("GIT_CONFIG_COUNT"), OsString::from((existing + pairs.len()).to_string())));
104    }
105    for (offset, (name, value)) in pairs.into_iter().enumerate() {
106        variables.push((OsString::from(format!("GIT_CONFIG_KEY_{}", existing + offset)), name));
107        variables.push((OsString::from(format!("GIT_CONFIG_VALUE_{}", existing + offset)), value));
108    }
109    return variables;
110}
111
112/// Why a run with captured standard error did not produce an outcome.
113enum CaptureError {
114    /// The file for the standard error could not be made; the text says why.
115    Scratch(String),
116    /// The program could not be started.
117    Start,
118}
119
120/// The most standard error text one run keeps and relays; the rest is dropped, so a flood cannot fill memory.
121const MAX_RELAYED_BYTES: u64 = 4 * 1024 * 1024;
122
123/// What:
124///  Run the command with its standard error in an anonymous file and return how it ended with that text, the
125///  credentials of every URL in it hidden.
126/// Why:
127///   Standard output stays the caller's, so the progress meter is unchanged. The standard error is where `git-lfs`
128///  prints its errors, which can carry the `lfs.url` token, so it is relayed only after its URLs are masked. A file needs no reader thread that a
129///  stuck helper could keep alive.
130///
131/// In TS you'd write (pseudocode):
132/// ```ts
133/// const { outcome, stderr } = await spawnCapturingStderr(command); return [outcome, maskUserinfo(stderr)];
134/// ```
135fn run_with_captured_stderr(
136    command: &mut Command,
137    environment: &[(OsString, OsString)],
138) -> Result<(ChildOutcome, Vec<u8>), CaptureError> {
139    let mut captured: std::fs::File = scratch_file(environment).map_err(|error| {
140        return CaptureError::Scratch(error.to_string());
141    })?;
142    let for_child: std::fs::File = captured.try_clone().map_err(|error| {
143        return CaptureError::Scratch(error.to_string());
144    })?;
145    command.stderr(Stdio::from(for_child));
146    let outcome: std::io::Result<ChildOutcome> = match SignalGuard::install() {
147        Ok(guard) => guard.run_child(command),
148        Err(_) => command.status_retrying().map(outcome_of),
149    };
150    let Ok(ended) = outcome else {
151        return Err(CaptureError::Start);
152    };
153    let mut bytes: Vec<u8> = Vec::new();
154    captured
155        .seek(SeekFrom::Start(0))
156        .and_then(|_| {
157            return captured.by_ref().take(MAX_RELAYED_BYTES).read_to_end(&mut bytes);
158        })
159        .map_err(|error| {
160            return CaptureError::Scratch(error.to_string());
161        })?;
162    return Ok((ended, mask_userinfo(bytes.as_slice())));
163}
164
165/// The refusal printed when the standard error of the upload cannot be captured.
166fn capture_failed_message(why: &str) -> String {
167    return format!(
168        "cli-git: this push was stopped before it sent anything. The wrapper reads the output of `git-lfs push` through \
169         a private temporary file, to hide the credentials in the URLs it names, and that file could not be made ({why}). Ways forward: fix the cause named in the parentheses (the \
170         wrapper needs a writable `XDG_STATE_HOME`, or a `HOME`, for its private scratch directory) and push again; or \
171         skip the upload for this push with `GIT_LFS_SKIP_PUSH=1` or `git push --no-verify`, which publishes pointer \
172         files without their objects.\n"
173    );
174}
175
176/// What:
177///  Run the upload as a child with the caller's streams and return the status to stop with, or nothing when it succeeded.
178/// Why:
179///   The parent saw the child end, so it prints the explanation after the program's own output; the push is not started.
180///  A signal sent to the wrapper is relayed to the child, so stopping the wrapper stops the upload. A push that also
181///  pushes submodules gets a notice, because their objects are not part of this upload.
182///
183/// In TS you'd write (pseudocode):
184/// ```ts
185/// const code = await spawn('git-lfs', plan.arguments(), { stdio: 'inherit' }); if (code) { print(failedMessage(...)); return code; }
186/// ```
187pub fn run_upload_interactive(
188    plan: &UploadPlan,
189    global_prefix: &[OsString],
190    directory: &Path,
191    real_git: &Path,
192    environment: &[(OsString, OsString)],
193    overlay: &[(OsString, OsString)],
194    diagnostics: &mut dyn std::io::Write,
195) -> Option<i32> {
196    let Some(program) = find_program(environment_value(environment, "PATH").unwrap_or_default().as_os_str()) else {
197        // Terminal output error: the exit status already carries the refusal.
198        let _written = diagnostics.write_all(missing_program_message().as_bytes());
199        return Some(1);
200    };
201    if plan.submodules {
202        // Terminal output error: the notice is advisory.
203        let _written = diagnostics.write_all(submodule_notice().as_bytes());
204    }
205    // A server error (an HTTP 5xx answer of the LFS server) is not run again here: it is outside our control, like a network that
206    //  is down, and the commit service's push retry plan tries the push again by itself (pick 12 of
207    //  `doc/planning/cli-git-shipped-limits-audit.md`, the coordinator's under the owner's delegation). A typed push ends and says so.
208    for arguments in plan.remotes.iter().flat_map(|remote| { return plan.runs(remote.as_os_str()); }) {
209        let mut command: Command = Command::new(&program);
210        command
211            .current_dir(directory)
212            .args(arguments.as_slice())
213            .env("PATH", path_with_real_git_first(environment, real_git));
214        for (name, value) in prefix_variables(global_prefix, environment).into_iter().chain(overlay.iter().cloned()) {
215            command.env(name, value);
216        }
217        let (ended, relayed): (ChildOutcome, Vec<u8>) = match run_with_captured_stderr(&mut command, environment) {
218            Ok(finished) => finished,
219            Err(CaptureError::Scratch(why)) => {
220                // Terminal output error: the exit status already carries the refusal.
221                let _written = diagnostics.write_all(capture_failed_message(why.as_str()).as_bytes());
222                return Some(1);
223            }
224            Err(CaptureError::Start) => {
225                // Terminal output error: see above.
226                let _written = diagnostics.write_all(missing_program_message().as_bytes());
227                return Some(1);
228            }
229        };
230        // Terminal output error: the program's own words are advisory; the exit status carries the result.
231        let _relayed = diagnostics.write_all(relayed.as_slice());
232        let code: i32 = exit_code(ended);
233        if code == 0 {
234            continue;
235        }
236        let description: String = match ended {
237            ChildOutcome::Exited(status) => format!("exited with status {status}"),
238            ChildOutcome::Signaled(signal) => format!("was ended by signal {signal}"),
239        };
240        // Terminal output error: see above.
241        let _written = diagnostics.write_all(failed_message(description.as_str()).as_bytes());
242        return Some(code);
243    }
244    return None;
245}
246
247/// What:
248///  The notice for a push that also pushes submodules.
249/// Why:
250///   Git pushes a submodule's commits itself; their LFS objects are not uploaded by the wrapper, and the pointer files
251///  would be published without them. Every way forward is named.
252///
253/// In TS you'd write (pseudocode):
254/// ```ts
255/// 'cli-git: this push also pushes submodules, ...'
256/// ```
257pub fn submodule_notice() -> String {
258    return String::from(
259        "cli-git: this push also pushes submodules (`--recurse-submodules`), and the wrapper uploads Git LFS objects only \\
260         for this repository's own refs. If a submodule uses Git LFS, upload its objects first by running \\
261         `git lfs push --all <remote>` inside it, or push the submodule on its own; otherwise its pointer files are \\
262         published without their objects.\\n",
263    );
264}
265
266/// What:
267///  Run the upload as a bounded child whose output is captured, and return the failed attempt to stop with, or nothing
268///  when it succeeded.
269/// Why:
270///   The auto-push records and shows a failed attempt's output; the explanation is part of it. A stop by deadline says
271///  so.
272///
273/// In TS you'd write (pseudocode):
274/// ```ts
275/// const attempt = await runBoundedPush({ command: gitLfs(plan), deadlineMs }); return attempt.exitCode ? withExplanation(attempt) : undefined;
276/// ```
277pub fn run_upload_bounded(git: &PushGit, plan: &UploadPlan) -> Result<Option<PushAttempt>, SingleFlightError> {
278    let Some(program) = find_program(environment_value(git.environment.as_slice(), "PATH").unwrap_or_default().as_os_str())
279    else {
280        return Ok(Some(PushAttempt { exit_code: 1, output: missing_program_message().trim_end().to_owned() }));
281    };
282    // A server error is not run again here, for the reason given in `run_upload_interactive`: the service's push retry plan
283    //  tries the push again by itself.
284    for arguments in plan.remotes.iter().flat_map(|remote| { return plan.runs(remote.as_os_str()); }) {
285        let mut command: Command = Command::new(&program);
286        command
287            .current_dir(&git.cwd)
288            .env_clear()
289            .envs(git.environment.iter().map(|(name, value)| {
290                return (name, value);
291            }))
292            .env("PATH", path_with_real_git_first(git.environment.as_slice(), git.real_git.as_path()))
293            .args(arguments.as_slice());
294        let attempt: PushAttempt =
295            match run_bounded_push(command, push_patience(git.environment.as_slice()), STOP_GRACE, git.environment.as_slice()) {
296                Ok(finished) => finished,
297                Err(SingleFlightError::Start(_)) => {
298                    return Ok(Some(PushAttempt { exit_code: 1, output: missing_program_message().trim_end().to_owned() }));
299                }
300                Err(other) => return Err(other),
301            };
302        if attempt.exit_code == 0 {
303            continue;
304        }
305        let shown: String = mask_userinfo_text(attempt.output.as_str());
306        return Ok(Some(explained(PushAttempt { exit_code: attempt.exit_code, output: shown })));
307    }
308    return Ok(None);
309}
310
311/// The failed attempt with the explanation after the program's own output; a stop by deadline says so.
312fn explained(attempt: PushAttempt) -> PushAttempt {
313    let description: String = if attempt.exit_code == STOPPED_EXIT_CODE {
314        String::from("did not finish and was stopped")
315    } else {
316        format!("exited with status {}", attempt.exit_code)
317    };
318    let explanation: String = failed_message(description.as_str());
319    let shown: &str = explanation.trim_end();
320    let output: String = if attempt.output.is_empty() { shown.to_owned() } else { format!("{}\n{shown}", attempt.output) };
321    return PushAttempt { exit_code: attempt.exit_code, output };
322}
323
324/// The runs are controlled in the test module.
325#[cfg(test)]
326#[path = "lfs_upload_tests.rs"]
327mod tests;