Skip to main content

cargo/sources/git/
cli.rs

1//! Git operations through the `git` executable.
2
3use crate::context::ProgressWhen;
4use crate::sources::git::utils::note_git_config;
5use crate::sources::git::utils::note_github_pull_request;
6use crate::sources::git::utils::note_ssh_config;
7use crate::util::GlobalContext;
8use crate::util::errors::CargoResult;
9use crate::util::errors::GitCliError;
10use crate::util::network;
11
12use cargo_util::ProcessBuilder;
13use cargo_util::Stdio;
14use cargo_util_terminal::Verbosity;
15use tracing::debug;
16
17pub(super) fn git_version() -> Option<GitVersion> {
18    #[tracing::instrument(skip_all)]
19    fn git_version() -> Option<GitVersion> {
20        use std::process::Stdio;
21
22        let output = std::process::Command::new("git")
23            .arg("--version")
24            .stdin(Stdio::null())
25            .output()
26            .ok()?;
27        if !output.status.success() {
28            return None;
29        }
30        let Ok(stdout) = String::from_utf8(output.stdout) else {
31            return None;
32        };
33        // All else fails, we can at least report the lowest common denominator of what we support
34        let default_version = GitVersion {
35            major: 2,
36            minor: 0,
37            patch: 0,
38        };
39        Some(GitVersion::from_version_stdout(&stdout).unwrap_or(default_version))
40    }
41
42    static CACHE: std::sync::OnceLock<Option<GitVersion>> = std::sync::OnceLock::new();
43    *CACHE.get_or_init(git_version)
44}
45
46#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
47#[allow(unused)]
48pub(super) struct GitVersion {
49    major: usize,
50    minor: usize,
51    patch: usize,
52}
53
54impl GitVersion {
55    fn from_version_stdout(stdout: &str) -> Result<Self, anyhow::Error> {
56        // See https://github.com/git/git/blob/f78ce2f7b6df702f93d40b85d6bda92a3f65da79/help.c#L779-L784
57        let Some(version) = stdout.strip_prefix("git version ") else {
58            anyhow::bail!("unrecognized `git --version` output: {stdout}")
59        };
60        let (version, _) = version.split_once(" ").unwrap_or((version, ""));
61        let (version, _) = version.split_once("\n").unwrap_or((version, ""));
62        version.parse()
63    }
64}
65
66impl std::str::FromStr for GitVersion {
67    type Err = anyhow::Error;
68
69    fn from_str(version: &str) -> Result<Self, Self::Err> {
70        let unreleased = "GIT";
71
72        let s = version;
73        let (major, s) = s.split_once(".").unwrap_or((s, ""));
74        let mut major: usize = major.parse().map_err(|_err| {
75            anyhow::format_err!("unrecognized major version `{major}` in `{version}`")
76        })?;
77        let (minor, s) = s.split_once(".").unwrap_or((s, ""));
78        let mut minor: usize = if minor == unreleased {
79            0
80        } else {
81            minor.parse().map_err(|_err| {
82                anyhow::format_err!("unrecognized minor version `{minor}` in `{version}`")
83            })?
84        };
85        let (patch, s) = s.split_once(".").unwrap_or((s, ""));
86        let mut patch: usize = if patch == unreleased {
87            0
88        } else {
89            patch.parse().map_err(|_err| {
90                anyhow::format_err!("unrecognized patch version `{patch}` in `{version}`")
91            })?
92        };
93
94        let more = s;
95        if !more.is_empty() {
96            // `more` can be either pre-release or post-release.
97            // The difference should be minimal, so be conservative and assume they are pre-release
98            if let Some(sub) = patch.checked_sub(1) {
99                patch = sub;
100            } else if let Some(sub) = minor.checked_sub(1) {
101                minor = sub;
102            } else if let Some(sub) = major.checked_sub(1) {
103                major = sub;
104            }
105        }
106
107        Ok(Self {
108            major,
109            minor,
110            patch,
111        })
112    }
113}
114
115/// Attempts to use `git` CLI installed on the system to fetch a repository,
116/// when the config value [`net.git-fetch-with-cli`][1] is set.
117///
118/// Unfortunately `libgit2` is notably lacking in the realm of authentication
119/// when compared to the `git` command line. As a result, allow an escape
120/// hatch for users that would prefer to use `git`-the-CLI for fetching
121/// repositories instead of `libgit2`-the-library. This should make more
122/// flavors of authentication possible while also still giving us all the
123/// speed and portability of using `libgit2`.
124///
125/// [1]: https://doc.rust-lang.org/nightly/cargo/reference/config.html#netgit-fetch-with-cli
126#[tracing::instrument(skip(repo, gctx))]
127pub(super) fn fetch_with_cli(
128    repo: &git2::Repository,
129    url: &str,
130    refspecs: &[String],
131    tags: bool,
132    shallow: gix::remote::fetch::Shallow,
133    gctx: &GlobalContext,
134) -> CargoResult<()> {
135    debug!(target: "git-fetch", backend = "git-cli");
136
137    let Some(git_version) = git_version() else {
138        anyhow::bail!(
139            "`git` is not available
140help: to still use `git` for fetching, please install it
141help: to use Cargo's native git support, re-try with `net.git-fetch-with-cli = false`
142https://doc.rust-lang.org/cargo/reference/config.html#netgit-fetch-with-cli"
143        );
144    };
145
146    let mut cmd = ProcessBuilder::new("git");
147    // Avoid potential for unused work that may also hang (#15775)
148    cmd.arg("-c").arg("core.fsmonitor=false");
149    // Avoid warnings with `--no-show-forced-updates`
150    cmd.arg("-c").arg("advice.fetchShowForcedUpdates=false");
151
152    // The implicit gc from `git fetch` is redundant
153    // as we run `maybe_gc_repo` unconditionally for all git backend before fetch.
154    cmd.arg("-c").arg("maintenance.auto=false");
155    cmd.arg("-c").arg("gc.auto=0");
156
157    // Have 429's retried in git, where supported
158    let max_retries = gctx
159        .net_config()?
160        .retry
161        .unwrap_or(network::retry::MAX_RETRY_DEFAULT);
162    cmd.arg("-c").arg(format!("http.maxRetries={max_retries}"));
163    cmd.arg("-c").arg("http.retryAfter=1"); // `network::retry` has a growing value starting with 500ms, so choosing 1s
164    cmd.arg("-c").arg(format!(
165        "http.maxRetryTime={}",
166        network::retry::MAX_RETRY_SLEEP_S
167    ));
168
169    cmd.arg("fetch");
170    if tags {
171        cmd.arg("--tags");
172    } else {
173        cmd.arg("--no-tags");
174    }
175    if let gix::remote::fetch::Shallow::DepthAtRemote(depth) = shallow {
176        let depth = 0i32.saturating_add_unsigned(depth.get());
177        cmd.arg(format!("--depth={depth}"));
178    }
179
180    let progress_config = gctx.progress_config();
181    let progress = match progress_config.when {
182        ProgressWhen::Always => true,
183        ProgressWhen::Never => false,
184        ProgressWhen::Auto => {
185            // Recreate the same conditions used with `Progress`
186            let width = progress_config
187                .width
188                .or_else(|| gctx.shell().err_width().progress_max_width());
189            gctx.shell().progress_supported() && width.is_some()
190        }
191    };
192    if gctx.shell().verbosity() == Verbosity::Verbose {
193        cmd.arg("--verbose");
194    } else if progress {
195        cmd.arg("--progress");
196        // https://github.com/git/git/blob/1630431f326e15fcde608827b5ff38422528eb59/Documentation/RelNotes/2.41.0.adoc?plain=1#L113-L114
197        let min_version_porcelain = GitVersion {
198            major: 2,
199            minor: 41,
200            patch: 0,
201        };
202        if min_version_porcelain <= git_version {
203            // Move ref update status to `stdout` and silence it
204            cmd.arg("--porcelain").stdout(Stdio::Null);
205        }
206    } else {
207        cmd.arg("--quiet");
208    }
209
210    // https://github.com/git/git/blob/1630431f326e15fcde608827b5ff38422528eb59/Documentation/RelNotes/2.23.0.adoc?plain=1#L56-L59
211    let min_version_no_show_forced_update = GitVersion {
212        major: 2,
213        minor: 23,
214        patch: 0,
215    };
216    if min_version_no_show_forced_update <= git_version {
217        // skip unneeded expensive calculations
218        cmd.arg("--no-show-forced-updates");
219    }
220
221    cmd.arg("--force") // handle force pushes
222        .arg("--update-head-ok") // see discussion in #2078
223        .arg("--recurse-submodules=no") // we handle this, incompatible with `--porcelain`
224        .arg(url)
225        .args(refspecs)
226        // If cargo is run by git (for example, the `exec` command in `git
227        // rebase`), the GIT_DIR is set by git and will point to the wrong
228        // location. This makes sure GIT_DIR is always the repository path.
229        .env("GIT_DIR", repo.path())
230        // The reset of these may not be necessary, but I'm including them
231        // just to be extra paranoid and avoid any issues.
232        .env_remove("GIT_WORK_TREE")
233        .env_remove("GIT_INDEX_FILE")
234        .env_remove("GIT_OBJECT_DIRECTORY")
235        .env_remove("GIT_ALTERNATE_OBJECT_DIRECTORIES")
236        .cwd(repo.path());
237    gctx.shell()
238        .verbose(|s| s.status("Running", &cmd.to_string()))?;
239    // https://github.com/git/git/blob/1630431f326e15fcde608827b5ff38422528eb59/Documentation/RelNotes/2.54.0.adoc?plain=1#L107
240    let min_version_max_retries = GitVersion {
241        major: 2,
242        minor: 54,
243        patch: 0,
244    };
245    network::retry::with_retry(gctx, || {
246        cmd.exec().map_err(|_error| {
247            let spurious = git_version < min_version_max_retries;
248            let pr_hint = note_github_pull_request(url).unwrap_or_default();
249            let ssh_config_hint = note_ssh_config(gctx).unwrap_or_default().unwrap_or_default();
250            let git_config_hint = note_git_config(gctx).unwrap_or_default().unwrap_or_default();
251            let with_depth = if let gix::remote::fetch::Shallow::DepthAtRemote(depth) = shallow {
252                format!(" with depth={depth}")
253            } else {
254                "".to_owned()
255            };
256            GitCliError::new(anyhow::format_err!("`git fetch` failed for {url}{with_depth}{pr_hint}{ssh_config_hint}{git_config_hint}"))
257                .spurious(spurious)
258                .workaround(
259                    "help: re-try with `net.git-fetch-with-cli = false` to see if it resolves the problem
260https://doc.rust-lang.org/cargo/reference/config.html#netgit-fetch-with-cli",
261                )
262                .into()
263        })
264    })?;
265
266    Ok(())
267}
268
269#[cfg(test)]
270mod test {
271    use super::*;
272
273    #[test]
274    fn git_version_empty() {
275        let input = "";
276        GitVersion::from_version_stdout(input).unwrap_err();
277    }
278
279    #[test]
280    fn git_version_version() {
281        let input = "git version 2.19.0";
282        let actual = GitVersion::from_version_stdout(input).unwrap();
283        let expected = GitVersion {
284            major: 2,
285            minor: 19,
286            patch: 0,
287        };
288        assert_eq!(actual, expected);
289    }
290
291    #[test]
292    fn git_version_version_nl() {
293        let input = "git version 2.19.0\n";
294        let actual = GitVersion::from_version_stdout(input).unwrap();
295        let expected = GitVersion {
296            major: 2,
297            minor: 19,
298            patch: 0,
299        };
300        assert_eq!(actual, expected);
301    }
302
303    #[test]
304    fn git_version_version_platform() {
305        let input = "git version 2.19.0 (Apple Git-117)";
306        let actual = GitVersion::from_version_stdout(input).unwrap();
307        let expected = GitVersion {
308            major: 2,
309            minor: 19,
310            patch: 0,
311        };
312        assert_eq!(actual, expected);
313    }
314
315    #[test]
316    fn git_version_version_vendor() {
317        let input = "git version 2.19.0.windows.1";
318        let actual = GitVersion::from_version_stdout(input).unwrap();
319        let expected = GitVersion {
320            major: 2,
321            minor: 18,
322            patch: 0,
323        };
324        assert_eq!(actual, expected);
325    }
326
327    #[test]
328    fn git_version_version_rc() {
329        let input = "git version 2.19.0.rc0";
330        let actual = GitVersion::from_version_stdout(input).unwrap();
331        let expected = GitVersion {
332            major: 2,
333            minor: 18,
334            patch: 0,
335        };
336        assert_eq!(actual, expected);
337    }
338
339    #[test]
340    fn git_version_version_unreleased() {
341        let input = "git version 2.55.GIT";
342        let actual = GitVersion::from_version_stdout(input).unwrap();
343        let expected = GitVersion {
344            major: 2,
345            minor: 55,
346            patch: 0,
347        };
348        assert_eq!(actual, expected);
349    }
350}