Skip to main content

cargo/sources/git/
utils.rs

1//! Utilities for handling git repositories, mainly around
2//! authentication/cloning.
3
4use crate::sources::git::cli::fetch_with_cli;
5use crate::sources::git::cli::git_version;
6use crate::sources::git::fetch::RemoteKind;
7use crate::sources::git::libgit2::fetch_with_libgit2;
8use crate::sources::git::libgit2::with_fetch_options;
9use crate::sources::git::oxide::fetch_with_gitoxide;
10use crate::sources::git::source::GitSource;
11use crate::sources::source::Source as _;
12use crate::util::errors::CargoResult;
13use crate::util::{GlobalContext, IntoUrl, Progress};
14use crate::workspace::{GitReference, SourceId};
15
16use anyhow::{Context as _, anyhow};
17use cargo_util::paths;
18use git2::ObjectType;
19use git2::Oid;
20use http::{Request, StatusCode};
21use tracing::{debug, info};
22use url::Url;
23
24use std::borrow::Cow;
25use std::path::{Path, PathBuf};
26use std::process::Command;
27use std::str;
28
29/// A file indicates that if present, `git reset` has been done and a repo
30/// checkout is ready to go. See [`GitCheckout::reset`] for why we need this.
31const CHECKOUT_READY_LOCK: &str = ".cargo-ok";
32
33/// A remote repository. It gets cloned into a local [`GitDatabase`].
34#[derive(PartialEq, Clone, Debug)]
35pub struct GitRemote {
36    /// URL to a remote repository.
37    ///
38    /// This may differ from the [`SourceId`] URL when the original URL
39    /// can't be represented as a WHATWG [`Url`], for example SCP-like URLs.
40    /// See <https://github.com/rust-lang/cargo/issues/16740>.
41    url: String,
42}
43
44/// A local clone of a remote repository's database. Multiple [`GitCheckout`]s
45/// can be cloned from a single [`GitDatabase`].
46pub struct GitDatabase {
47    /// The remote repository where this database is fetched from.
48    remote: GitRemote,
49    /// Path to the root of the underlying Git repository on the local filesystem.
50    path: PathBuf,
51    /// Underlying Git repository instance for this database.
52    repo: git2::Repository,
53}
54
55/// A local checkout of a particular revision from a [`GitDatabase`].
56pub struct GitCheckout<'a> {
57    /// The git database where this checkout is cloned from.
58    database: &'a GitDatabase,
59    /// Path to the root of the underlying Git repository on the local filesystem.
60    path: PathBuf,
61    /// The git revision this checkout is for.
62    revision: git2::Oid,
63    /// Underlying Git repository instance for this checkout.
64    repo: git2::Repository,
65}
66
67impl GitRemote {
68    /// Creates an instance for a remote repository URL.
69    pub fn new(url: &Url) -> GitRemote {
70        GitRemote {
71            url: url.as_str().to_owned(),
72        }
73    }
74
75    /// Creates an instance with an URL that may not be a valid WHATWG URL.
76    ///
77    /// This is needed because [`SourceId`] hasn't yet supported SCP-like URLs.
78    pub(super) fn new_from_str(url: String) -> GitRemote {
79        GitRemote { url }
80    }
81
82    /// Gets the remote repository URL.
83    pub fn url(&self) -> &str {
84        &self.url
85    }
86
87    /// Fetches and checkouts to a reference or a revision from this remote
88    /// into a local path.
89    ///
90    /// This ensures that it gets the up-to-date commit when a named reference
91    /// is given (tag, branch, refs/*). Thus, network connection is involved.
92    ///
93    /// If we have a previous instance of [`GitDatabase`] then fetch into that
94    /// if we can. If that can successfully load our revision then we've
95    /// populated the database with the latest version of `reference`, so
96    /// return that database and the rev we resolve to.
97    pub fn checkout(
98        &self,
99        into: &Path,
100        db: Option<GitDatabase>,
101        manifest_reference: &GitReference,
102        reference: &GitReference,
103        gctx: &GlobalContext,
104    ) -> CargoResult<(GitDatabase, git2::Oid)> {
105        if let Some(mut db) = db {
106            fetch(
107                &mut db.repo,
108                self.url(),
109                manifest_reference,
110                reference,
111                gctx,
112                RemoteKind::GitDependency,
113            )
114            .with_context(|| format!("failed to fetch into: {}", into.display()))?;
115
116            if let Some(rev) = resolve_ref(reference, &db.repo).ok() {
117                return Ok((db, rev));
118            }
119        }
120
121        // Otherwise start from scratch to handle corrupt git repositories.
122        // After our fetch (which is interpreted as a clone now) we do the same
123        // resolution to figure out what we cloned.
124        if into.exists() {
125            paths::remove_dir_all(into)?;
126        }
127        paths::create_dir_all(into)?;
128        let mut repo = init(into, true)?;
129        fetch(
130            &mut repo,
131            self.url(),
132            manifest_reference,
133            reference,
134            gctx,
135            RemoteKind::GitDependency,
136        )
137        .with_context(|| format!("failed to clone into: {}", into.display()))?;
138        let rev = resolve_ref(reference, &repo)?;
139
140        Ok((
141            GitDatabase {
142                remote: self.clone(),
143                path: into.to_path_buf(),
144                repo,
145            },
146            rev,
147        ))
148    }
149
150    /// Creates a [`GitDatabase`] of this remote at `db_path`.
151    pub fn db_at(&self, db_path: &Path) -> CargoResult<GitDatabase> {
152        let repo = git2::Repository::open(db_path)?;
153        Ok(GitDatabase {
154            remote: self.clone(),
155            path: db_path.to_path_buf(),
156            repo,
157        })
158    }
159}
160
161impl GitDatabase {
162    /// Checkouts to a revision at `dest`ination from this database.
163    #[tracing::instrument(skip(self, gctx))]
164    pub fn copy_to(
165        &self,
166        rev: git2::Oid,
167        dest: &Path,
168        gctx: &GlobalContext,
169        quiet: bool,
170    ) -> CargoResult<GitCheckout<'_>> {
171        // If the existing checkout exists, and it is fresh, use it.
172        // A non-fresh checkout can happen if the checkout operation was
173        // interrupted. In that case, the checkout gets deleted and a new
174        // clone is created.
175        let checkout = match git2::Repository::open(dest)
176            .ok()
177            .map(|repo| GitCheckout::new(self, rev, repo))
178            .filter(|co| co.is_fresh())
179        {
180            Some(co) => co,
181            None => {
182                let (checkout, guard) = GitCheckout::clone_into(dest, self, rev, gctx)?;
183                checkout.update_submodules(gctx, quiet)?;
184                guard.mark_ok()?;
185                checkout
186            }
187        };
188
189        Ok(checkout)
190    }
191
192    /// Get a short OID for a `revision`, 7 chars or more if ambiguous.
193    ///
194    /// Like [`git2::Object::short_id`]
195    /// but ignores the user's `core.abbrev` git config.
196    pub fn to_short_id(&self, rev: git2::Oid) -> CargoResult<String> {
197        const MIN_ABBREV_LEN: usize = 7; // this is git/libgit2's default
198        let odb = self.repo.odb()?;
199        let mut len = MIN_ABBREV_LEN;
200        let mut hex = rev.to_string();
201        // quasi- re-implementation of
202        // https://github.com/libgit2/libgit2/blob/26055f5af74ab/src/libgit2/object.c#L523-L573
203        while len < hex.len() {
204            match odb.exists_prefix(rev, len) {
205                Ok(_) => break,
206                Err(err) if err.code() == git2::ErrorCode::Ambiguous => len += 1,
207                Err(err) => return Err(err.into()),
208            }
209        }
210        hex.truncate(len);
211        Ok(hex)
212    }
213
214    /// Checks if the database contains the object of this `oid`..
215    pub fn contains(&self, oid: git2::Oid) -> bool {
216        self.repo.revparse_single(&oid.to_string()).is_ok()
217    }
218
219    /// [`resolve_ref`]s this reference with this database.
220    pub fn resolve(&self, r: &GitReference) -> CargoResult<git2::Oid> {
221        resolve_ref(r, &self.repo)
222    }
223}
224
225/// Resolves [`GitReference`] to an object ID with objects the `repo` currently has.
226pub fn resolve_ref(gitref: &GitReference, repo: &git2::Repository) -> CargoResult<git2::Oid> {
227    let id = match gitref {
228        // Note that we resolve the named tag here in sync with where it's
229        // fetched into via `fetch` below.
230        GitReference::Tag(s) => (|| -> CargoResult<git2::Oid> {
231            let refname = format!("refs/remotes/origin/tags/{}", s);
232            let id = repo.refname_to_id(&refname)?;
233            let obj = repo.find_object(id, None)?;
234            let obj = obj.peel(ObjectType::Commit)?;
235            Ok(obj.id())
236        })()
237        .with_context(|| format!("failed to find tag `{}`", s))?,
238
239        // Resolve the remote name since that's all we're configuring in
240        // `fetch` below.
241        GitReference::Branch(s) => {
242            let name = format!("origin/{}", s);
243            let b = repo
244                .find_branch(&name, git2::BranchType::Remote)
245                .with_context(|| format!("failed to find branch `{}`", s))?;
246            b.get()
247                .target()
248                .ok_or_else(|| anyhow::format_err!("branch `{}` did not have a target", s))?
249        }
250
251        // We'll be using the HEAD commit
252        GitReference::DefaultBranch => {
253            let head_id = repo.refname_to_id("refs/remotes/origin/HEAD")?;
254            let head = repo.find_object(head_id, None)?;
255            head.peel(ObjectType::Commit)?.id()
256        }
257
258        GitReference::Rev(s) => {
259            let obj = repo.revparse_single(s)?;
260            match obj.as_tag() {
261                Some(tag) => tag.target_id(),
262                None => obj.id(),
263            }
264        }
265    };
266    Ok(id)
267}
268
269impl<'a> GitCheckout<'a> {
270    /// Creates an instance of [`GitCheckout`]. This doesn't imply the checkout
271    /// is done. Use [`GitCheckout::is_fresh`] to check.
272    ///
273    /// * The `database` is where this checkout is from.
274    /// * The `repo` will be the checked out Git repository.
275    fn new(
276        database: &'a GitDatabase,
277        revision: git2::Oid,
278        repo: git2::Repository,
279    ) -> GitCheckout<'a> {
280        let path = repo.workdir().unwrap_or_else(|| repo.path());
281        GitCheckout {
282            path: path.to_path_buf(),
283            database,
284            revision,
285            repo,
286        }
287    }
288
289    /// Gets the remote repository URL.
290    fn remote_url(&self) -> &str {
291        self.database.remote.url()
292    }
293
294    /// Clone a repo for a `revision` into a local path from a `database`.
295    /// This is a filesystem-to-filesystem clone.
296    fn clone_into(
297        into: &Path,
298        database: &'a GitDatabase,
299        revision: git2::Oid,
300        gctx: &GlobalContext,
301    ) -> CargoResult<(GitCheckout<'a>, CheckoutGuard)> {
302        let dirname = into.parent().unwrap();
303        paths::create_dir_all(&dirname)?;
304        if into.exists() {
305            paths::remove_dir_all(into)?;
306        }
307
308        // we're doing a local filesystem-to-filesystem clone so there should
309        // be no need to respect global configuration options, so pass in
310        // an empty instance of `git2::Config` below.
311        let git_config = git2::Config::new()?;
312
313        // Clone the repository, but make sure we use the "local" option in
314        // libgit2 which will attempt to use hardlinks to set up the database.
315        // This should speed up the clone operation quite a bit if it works.
316        //
317        // Note that we still use the same fetch options because while we don't
318        // need authentication information we may want progress bars and such.
319        let url = database.path.into_url()?;
320        let mut repo = None;
321        with_fetch_options(&git_config, url.as_str(), gctx, &mut |fopts| {
322            let mut checkout = git2::build::CheckoutBuilder::new();
323            checkout.dry_run(); // we'll do this below during a `reset`
324
325            let r = git2::build::RepoBuilder::new()
326                // use hard links and/or copy the database, we're doing a
327                // filesystem clone so this'll speed things up quite a bit.
328                .clone_local(git2::build::CloneLocal::Local)
329                .with_checkout(checkout)
330                .fetch_options(fopts)
331                .clone(url.as_str(), into)?;
332            // `git2` doesn't seem to handle shallow repos correctly when doing
333            // a local clone. Fortunately all that's needed is the copy of the
334            // one file that defines the shallow boundary, the commits which
335            // have their parents omitted as part of the shallow clone.
336            //
337            // TODO(git2): remove this when git2 supports shallow clone correctly
338            if database.repo.is_shallow() {
339                std::fs::copy(
340                    database.repo.path().join("shallow"),
341                    r.path().join("shallow"),
342                )?;
343            }
344            repo = Some(r);
345            Ok(())
346        })?;
347        let repo = repo.unwrap();
348
349        let checkout = GitCheckout::new(database, revision, repo);
350        let guard = checkout.reset(gctx)?;
351        Ok((checkout, guard))
352    }
353
354    /// Checks if the `HEAD` of this checkout points to the expected revision.
355    fn is_fresh(&self) -> bool {
356        match self.repo.revparse_single("HEAD") {
357            Ok(ref head) if head.id() == self.revision => {
358                // See comments in reset() for why we check this
359                self.path.join(CHECKOUT_READY_LOCK).exists()
360            }
361            _ => false,
362        }
363    }
364
365    /// Similar to [`reset()`]. This roughly performs `git reset --hard` to the
366    /// revision of this checkout, with additional interrupt protection by a
367    /// dummy file [`CHECKOUT_READY_LOCK`].
368    ///
369    /// If we're interrupted while performing a `git reset` (e.g., we die
370    /// because of a signal) Cargo needs to be sure to try to check out this
371    /// repo again on the next go-round.
372    ///
373    /// To enable this we have a dummy file in our checkout, [`.cargo-ok`],
374    /// which if present means that the repo has been successfully reset and is
375    /// ready to go. Hence if we start to do a reset, we make sure this file
376    /// *doesn't* exist. The caller of [`reset`] has an option to perform additional operations
377    /// (e.g. submodule update) before marking the check-out as ready.
378    ///
379    /// [`.cargo-ok`]: CHECKOUT_READY_LOCK
380    fn reset(&self, gctx: &GlobalContext) -> CargoResult<CheckoutGuard> {
381        let guard = CheckoutGuard::guard(&self.path);
382        info!("reset {} to {}", self.repo.path().display(), self.revision);
383
384        if let Ok(mut git_config) = self.repo.config() {
385            // Ensure libgit2 won't mess with newlines when we vendor.
386            git_config.set_bool("core.autocrlf", false)?;
387            // Allow libgit2 to check out paths longer than `MAX_PATH` on Windows.
388            git_config.set_bool("core.longpaths", true)?;
389        }
390
391        let object = self.repo.find_object(self.revision, None)?;
392        reset(&self.repo, &object, gctx)?;
393
394        Ok(guard)
395    }
396
397    /// Like `git submodule update --recursive` but for this git checkout.
398    ///
399    /// This function respects `submodule.<name>.update = none`[^1] git config.
400    /// Submodules set to `none` won't be fetched.
401    ///
402    /// [^1]: <https://git-scm.com/docs/git-submodule#Documentation/git-submodule.txt-none>
403    fn update_submodules(&self, gctx: &GlobalContext, quiet: bool) -> CargoResult<()> {
404        return update_submodules(&self.repo, gctx, quiet, self.remote_url());
405
406        /// Recursive helper for [`GitCheckout::update_submodules`].
407        fn update_submodules(
408            repo: &git2::Repository,
409            gctx: &GlobalContext,
410            quiet: bool,
411            parent_remote_url: &str,
412        ) -> CargoResult<()> {
413            debug!("update submodules for: {:?}", repo.workdir().unwrap());
414
415            for mut child in repo.submodules()? {
416                update_submodule(repo, &mut child, gctx, quiet, parent_remote_url).with_context(
417                    || {
418                        format!(
419                            "failed to update submodule `{}`",
420                            child.name().unwrap_or("")
421                        )
422                    },
423                )?;
424            }
425            Ok(())
426        }
427
428        /// Update a single Git submodule, and recurse into its submodules.
429        fn update_submodule(
430            parent: &git2::Repository,
431            child: &mut git2::Submodule<'_>,
432            gctx: &GlobalContext,
433            quiet: bool,
434            parent_remote_url: &str,
435        ) -> CargoResult<()> {
436            child.init(false)?;
437
438            let child_url_str = child
439                .url()
440                .with_context(|| {
441                    format!("failed to update submodule `{}`", child.path().display())
442                })?
443                .ok_or_else(|| {
444                    anyhow::format_err!(
445                        "unable to update submodule `{}` without a path",
446                        child.name().unwrap_or("")
447                    )
448                })?;
449
450            // Skip the submodule if the config says not to update it.
451            if child.update_strategy() == git2::SubmoduleUpdate::None {
452                gctx.shell().status(
453                    "Skipping",
454                    format!(
455                        "git submodule `{}` due to update strategy in .gitmodules",
456                        child_url_str
457                    ),
458                )?;
459                return Ok(());
460            }
461
462            let child_remote_url = absolute_submodule_url(parent_remote_url, child_url_str)?;
463
464            // A submodule which is listed in .gitmodules but not actually
465            // checked out will not have a head id, so we should ignore it.
466            let Some(head) = child.head_id() else {
467                return Ok(());
468            };
469
470            // If the submodule hasn't been checked out yet, we need to
471            // clone it. If it has been checked out and the head is the same
472            // as the submodule's head, then we can skip an update and keep
473            // recursing.
474            let head_and_repo = child.open().and_then(|repo| {
475                let target = repo.head()?.target();
476                Ok((target, repo))
477            });
478            let repo = match head_and_repo {
479                Ok((head, repo)) => {
480                    if child.head_id() == head {
481                        return update_submodules(&repo, gctx, quiet, &child_remote_url);
482                    }
483                    repo
484                }
485                Err(..) => {
486                    let path = parent.workdir().unwrap().join(child.path());
487                    let _ = paths::remove_dir_all(&path);
488                    init(&path, false)?
489                }
490            };
491            // Fetch submodule database and checkout to target revision
492            let reference = GitReference::Rev(head.to_string());
493
494            // SCP-like URL is not a WHATWG Standard URL.
495            // `url` crate can't parse SCP-like URLs.
496            // We convert to `ssh://` for SourceId,
497            // but preserve the original URL for fetch to maintain correct semantics
498            // See <https://github.com/rust-lang/cargo/issues/16740>
499            let (source_url, fetch_url) = match child_remote_url.as_ref().into_url() {
500                Ok(url) => (url, None),
501                Err(_) => {
502                    let ssh_url = scp_to_ssh(&child_remote_url)
503                        .ok_or_else(|| anyhow::format_err!("invalid url `{child_remote_url}`"))?
504                        .as_str()
505                        .into_url()?;
506                    (ssh_url, Some(child_remote_url.into_owned()))
507                }
508            };
509
510            // GitSource created from SourceId without git precise will result to
511            // locked_rev being Deferred and fetch_db always try to fetch if online
512            let source_id =
513                SourceId::for_git(&source_url, reference)?.with_git_precise(Some(head.to_string()));
514
515            let mut source = match &fetch_url {
516                Some(url) => GitSource::new_for_submodule(source_id, url.to_owned(), gctx)?,
517                None => GitSource::new(source_id, gctx)?,
518            };
519            source.set_quiet(quiet);
520
521            let (db, actual_rev) = source.fetch_db(true).with_context(|| {
522                let name = child.name().unwrap_or("");
523                let url = fetch_url.unwrap_or_else(|| source_url.to_string());
524                format!("failed to fetch submodule `{name}` from {url}")
525            })?;
526            db.copy_to(actual_rev, repo.path(), gctx, quiet)?;
527            Ok(())
528        }
529    }
530}
531
532/// See [`GitCheckout::reset`] for rationale on this type.
533#[must_use]
534struct CheckoutGuard {
535    ok_file: PathBuf,
536}
537
538impl CheckoutGuard {
539    fn guard(path: &Path) -> Self {
540        let ok_file = path.join(CHECKOUT_READY_LOCK);
541        let _ = paths::remove_file(&ok_file);
542        Self { ok_file }
543    }
544
545    fn mark_ok(self) -> CargoResult<()> {
546        let _ = paths::create(self.ok_file)?;
547        Ok(())
548    }
549}
550
551/// Constructs an absolute URL for a child submodule URL with its parent base URL.
552///
553/// Git only assumes a submodule URL is a relative path if it starts with `./`
554/// or `../` [^1]. To fetch the correct repo, we need to construct an absolute
555/// submodule URL.
556///
557/// At this moment it comes with some limitations:
558///
559/// * GitHub doesn't accept non-normalized URLs with relative paths.
560///   (`ssh://git@github.com/rust-lang/cargo.git/relative/..` is invalid)
561/// * `url` crate cannot parse SCP-like URLs.
562///   (`git@github.com:rust-lang/cargo.git` is not a valid WHATWG URL)
563///
564/// To overcome these, this patch always tries [`Url::parse`] first to normalize
565/// the path. If it couldn't, append the relative path and/or convert SCP-like URLs
566/// to ssh:// format as the last resorts and pray the remote git service supports
567/// non-normalized URLs.
568///
569/// See also rust-lang/cargo#12404 and rust-lang/cargo#12295.
570///
571/// [^1]: <https://git-scm.com/docs/git-submodule>
572fn absolute_submodule_url<'s>(base_url: &str, submodule_url: &'s str) -> CargoResult<Cow<'s, str>> {
573    let absolute_url = if ["./", "../"].iter().any(|p| submodule_url.starts_with(p)) {
574        match Url::parse(base_url) {
575            Ok(mut base_url) => {
576                let path = base_url.path();
577                if !path.ends_with('/') {
578                    base_url.set_path(&format!("{path}/"));
579                }
580                let absolute_url = base_url.join(submodule_url).with_context(|| {
581                    format!(
582                        "failed to parse relative child submodule url `{submodule_url}` \
583                        using parent base url `{base_url}`"
584                    )
585                })?;
586                Cow::from(absolute_url.to_string())
587            }
588            Err(_) => {
589                let mut absolute_url = base_url.to_string();
590                if !absolute_url.ends_with('/') {
591                    absolute_url.push('/');
592                }
593                absolute_url.push_str(submodule_url);
594                Cow::from(absolute_url)
595            }
596        }
597    } else {
598        Cow::from(submodule_url)
599    };
600
601    Ok(absolute_url)
602}
603
604/// Converts an SCP-like URL to `ssh://` format for cache/SourceId identity, not fetching.
605fn scp_to_ssh(url: &str) -> Option<String> {
606    let gix_url = gix::url::parse(gix::bstr::BStr::new(url.as_bytes())).ok()?;
607    if gix_url.serialize_alternative_form && gix_url.scheme == gix::url::Scheme::Ssh {
608        Some(ssh_url_for_source_id(gix_url))
609    } else {
610        None
611    }
612}
613
614/// Serializes an SSH URL as a WHATWG URL for [`SourceId`] and cache identity.
615///
616/// gix preserves relative SCP paths because `host:repo` and `ssh://host/repo`
617/// fetch different repositories. SourceId cannot represent SCP syntax, so make
618/// the path absolute here and retain the original URL for fetching. Tilde paths
619/// already have a lossless `ssh://` form and need no adjustment.
620pub(super) fn ssh_url_for_source_id(mut url: gix::Url) -> String {
621    url.serialize_alternative_form = false;
622    if !url.path.starts_with(b"/") && !url.path.starts_with(b"~") {
623        url.path.insert(0, b'/');
624    }
625    url.to_bstring().to_string()
626}
627
628/// `git reset --hard` to the given `obj` for the `repo`.
629///
630/// The `obj` is a commit-ish to which the head should be moved.
631#[tracing::instrument(skip_all)]
632fn reset(repo: &git2::Repository, obj: &git2::Object<'_>, gctx: &GlobalContext) -> CargoResult<()> {
633    let mut pb = Progress::new("Checkout", gctx);
634    let mut opts = git2::build::CheckoutBuilder::new();
635    opts.progress(|_, cur, max| {
636        drop(pb.tick(cur, max, ""));
637    });
638    debug!("doing reset");
639    repo.reset(obj, git2::ResetType::Hard, Some(&mut opts))?;
640    debug!("reset done");
641    Ok(())
642}
643
644/// Attempts to fetch the given git `reference` for a Git repository.
645///
646/// This is the main entry for git clone/fetch. It does the followings:
647///
648/// * Turns [`GitReference`] into refspecs accordingly.
649/// * Dispatches `git fetch` using libgit2, gitoxide, or git CLI.
650///
651/// The `remote_url` argument is the git remote URL where we want to fetch from.
652///
653/// The `remote_kind` argument is a thing for [`-Zgitoxide`] shallow clones
654/// at this time. It could be extended when libgit2 supports shallow clones.
655///
656/// [`-Zgitoxide`]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#gitoxide
657#[tracing::instrument(skip_all)]
658pub fn fetch(
659    repo: &mut git2::Repository,
660    remote_url: &str,
661    manifest_reference: &GitReference,
662    locked_reference: &GitReference,
663    gctx: &GlobalContext,
664    remote_kind: RemoteKind,
665) -> CargoResult<()> {
666    if let Some(offline_flag) = gctx.offline_flag() {
667        anyhow::bail!(
668            "attempting to update a git repository, but {offline_flag} \
669             was specified"
670        )
671    }
672
673    let shallow = remote_kind.to_shallow_setting(repo.is_shallow(), gctx);
674
675    // Flag to keep track if the rev is a full commit hash
676    let mut fast_path_rev: bool = false;
677
678    let oid_to_fetch = match github_fast_path(repo, remote_url, locked_reference, gctx) {
679        Ok(FastPathRev::UpToDate) => return Ok(()),
680        Ok(FastPathRev::NeedsFetch(rev)) => Some(rev),
681        Ok(FastPathRev::Indeterminate) => None,
682        Err(e) => {
683            debug!("failed to check github {:?}", e);
684            None
685        }
686    };
687
688    maybe_gc_repo(repo, gctx)?;
689
690    clean_repo_temp_files(repo);
691
692    // Translate the reference desired here into an actual list of refspecs
693    // which need to get fetched. Additionally record if we're fetching tags.
694    let mut refspecs = Vec::new();
695    let mut tags = false;
696    // The `+` symbol on the refspec means to allow a forced (fast-forward)
697    // update which is needed if there is ever a force push that requires a
698    // fast-forward.
699    match locked_reference {
700        // For branches and tags we can fetch simply one reference and copy it
701        // locally, no need to fetch other branches/tags.
702        GitReference::Branch(b) => {
703            refspecs.push(format!("+refs/heads/{0}:refs/remotes/origin/{0}", b));
704        }
705
706        GitReference::Tag(t) => {
707            refspecs.push(format!("+refs/tags/{0}:refs/remotes/origin/tags/{0}", t));
708        }
709
710        GitReference::DefaultBranch => {
711            refspecs.push(String::from("+HEAD:refs/remotes/origin/HEAD"));
712        }
713
714        GitReference::Rev(rev) => {
715            if rev.starts_with("refs/") {
716                refspecs.push(format!("+{0}:{0}", rev));
717            } else if let Some(oid_to_fetch) = oid_to_fetch {
718                fast_path_rev = true;
719                refspecs.push(format!("+{0}:refs/commit/{0}", oid_to_fetch));
720            } else if !matches!(shallow, gix::remote::fetch::Shallow::NoChange)
721                && rev_to_oid(rev).is_some()
722            {
723                // There is a specific commit to fetch and we will do so in shallow-mode only
724                // to not disturb the previous logic.
725                // Note that with typical settings for shallowing, we will just fetch a single `rev`
726                // as single commit.
727                // The reason we write to `refs/remotes/origin/HEAD` is that it's of special significance
728                // when during `GitReference::resolve()`, but otherwise it shouldn't matter.
729                refspecs.push(format!("+{0}:refs/remotes/origin/HEAD", rev));
730            } else if let GitReference::Rev(rev) = manifest_reference
731                && rev.starts_with("refs/")
732            {
733                // If the lockfile has a commit. we can't directly fetch it (unless we're talking
734                // to GitHub), so we fetch the ref associated with it from the manifest.
735                refspecs.push(format!("+{0}:{0}", rev));
736            } else {
737                // We don't know what the rev will point to. To handle this
738                // situation we fetch all branches and tags, and then we pray
739                // it's somewhere in there.
740                refspecs.push(String::from("+refs/heads/*:refs/remotes/origin/*"));
741                refspecs.push(String::from("+HEAD:refs/remotes/origin/HEAD"));
742                tags = true;
743            }
744        }
745    }
746
747    debug!("doing a fetch for {remote_url}");
748    let result = if gctx
749        .net_config()?
750        .git_fetch_with_cli
751        .unwrap_or_else(|| git_version().is_some())
752    {
753        fetch_with_cli(repo, remote_url, &refspecs, tags, shallow, gctx)
754    } else {
755        if gctx.net_config()?.git_fetch_with_cli.is_none() && git_version().is_none() {
756            gctx.shell().warn(
757                "no compatible `git` found
758note: this may become a hard error in the future, see <https://github.com/rust-lang/cargo/issues/17227>
759help: to still use `git` for fetching, install it
760help: to use builtin native git support, re-try with `net.git-fetch-with-cli = false`
761https://doc.rust-lang.org/cargo/reference/config.html#netgit-fetch-with-cli"
762            )?;
763        }
764        if gctx.cli_unstable().gitoxide.map_or(false, |git| git.fetch) {
765            fetch_with_gitoxide(repo, remote_url, refspecs, tags, shallow, gctx)
766        } else {
767            fetch_with_libgit2(repo, remote_url, refspecs, tags, shallow, gctx)
768        }
769    };
770
771    if fast_path_rev {
772        if let Some(oid) = oid_to_fetch {
773            return result.with_context(|| format!("revision {} not found", oid));
774        }
775    }
776    result
777}
778
779/// Attempts to `git gc` a repository.
780///
781/// Cargo has a bunch of long-lived git repositories in its global cache and
782/// some, like the index, are updated very frequently. Right now each update
783/// creates a new "pack file" inside the git database, and over time this can
784/// cause bad performance and bad current behavior in libgit2.
785///
786/// One pathological use case today is where libgit2 opens hundreds of file
787/// descriptors, getting us dangerously close to blowing out the OS limits of
788/// how many fds we can have open. This is detailed in [#4403].
789///
790/// Instead of trying to be clever about when gc is needed, we just run
791/// `git gc --auto` and let git figure it out. It checks its own thresholds
792/// (gc.auto, gc.autoPackLimit) and either does the work or exits quickly.
793/// If git isn't installed, no worries - we skip it.
794///
795/// [#4403]: https://github.com/rust-lang/cargo/issues/4403
796fn maybe_gc_repo(repo: &mut git2::Repository, gctx: &GlobalContext) -> CargoResult<()> {
797    // Let git decide whether gc is actually needed based on its own thresholds
798    // (gc.auto, gc.autoPackLimit). This avoids duplicating git's internal logic
799    // for deciding when housekeeping is needed.
800    //
801    // For testing purposes, __CARGO_PACKFILE_LIMIT can be set to override
802    // gc.autoPackLimit, which has the same meaning. This lets tests force gc
803    // to run by setting a low threshold without depending on git's defaults.
804    let mut cmd = Command::new("git");
805    // Run gc in the foreground, so gc doesn't outlive Cargo cache lock.
806    // Otherwise it may modify the database while it is in use.
807    cmd.arg("-c").arg("gc.autoDetach=false");
808    if let Ok(limit) = gctx.get_env("__CARGO_PACKFILE_LIMIT") {
809        cmd.arg("-c").arg(format!("gc.autoPackLimit={limit}"));
810    }
811    cmd.arg("gc")
812        .arg("--auto")
813        // Explicitly set `GIT_DIR` so `safe.bareRepository=explicit` doesn't reject it.
814        .env("GIT_DIR", repo.path())
815        .current_dir(repo.path());
816
817    match cmd.output() {
818        Ok(out) => {
819            debug!(
820                "git-gc --auto status: {}\n\nstdout ---\n{}\nstderr ---\n{}",
821                out.status,
822                String::from_utf8_lossy(&out.stdout),
823                String::from_utf8_lossy(&out.stderr)
824            );
825            if out.status.success() {
826                let new = git2::Repository::open(repo.path())?;
827                *repo = new;
828                return Ok(());
829            }
830        }
831        Err(e) => debug!("git-gc --auto failed to spawn: {}", e),
832    }
833
834    // Alright all else failed, let's start over.
835    reinitialize(repo)
836}
837
838/// Removes temporary files left from previous activity.
839///
840/// If libgit2 is interrupted while indexing pack files, it will leave behind
841/// some temporary files that it doesn't clean up. These can be quite large in
842/// size, so this tries to clean things up.
843///
844/// This intentionally ignores errors. This is only an opportunistic cleaning,
845/// and we don't really care if there are issues (there's unlikely anything
846/// that can be done).
847///
848/// The git CLI has similar behavior (its temp files look like
849/// `objects/pack/tmp_pack_9kUSA8`). Those files are normally deleted via `git
850/// prune` which is run by `git gc`. However, it doesn't know about libgit2's
851/// filenames, so they never get cleaned up.
852fn clean_repo_temp_files(repo: &git2::Repository) {
853    let path = repo.path().join("objects/pack/pack_git2_*");
854    let Some(pattern) = path.to_str() else {
855        tracing::warn!("cannot convert {path:?} to a string");
856        return;
857    };
858    let Ok(paths) = glob::glob(pattern) else {
859        return;
860    };
861    for path in paths {
862        if let Ok(path) = path {
863            match paths::remove_file(&path) {
864                Ok(_) => tracing::debug!("removed stale temp git file {path:?}"),
865                Err(e) => {
866                    tracing::warn!("failed to remove {path:?} while cleaning temp files: {e}")
867                }
868            }
869        }
870    }
871}
872
873/// Reinitializes a given Git repository. This is useful when a Git repository
874/// seems corrupted and we want to start over.
875pub(super) fn reinitialize(repo: &mut git2::Repository) -> CargoResult<()> {
876    // Here we want to drop the current repository object pointed to by `repo`,
877    // so we initialize temporary repository in a sub-folder, blow away the
878    // existing git folder, and then recreate the git repo. Finally we blow away
879    // the `tmp` folder we allocated.
880    let path = repo.path().to_path_buf();
881    debug!("reinitializing git repo at {:?}", path);
882    let tmp = path.join("tmp");
883    let bare = !repo.path().ends_with(".git");
884    *repo = init(&tmp, false)?;
885    for entry in path.read_dir()? {
886        let entry = entry?;
887        if entry.file_name().to_str() == Some("tmp") {
888            continue;
889        }
890        let path = entry.path();
891        drop(paths::remove_file(&path).or_else(|_| paths::remove_dir_all(&path)));
892    }
893    *repo = init(&path, bare)?;
894    paths::remove_dir_all(&tmp)?;
895    Ok(())
896}
897
898/// Initializes a Git repository at `path`.
899fn init(path: &Path, bare: bool) -> CargoResult<git2::Repository> {
900    let mut opts = git2::RepositoryInitOptions::new();
901    // Skip anything related to templates, they just call all sorts of issues as
902    // we really don't want to use them yet they insist on being used. See #6240
903    // for an example issue that comes up.
904    opts.external_template(false);
905    opts.bare(bare);
906    Ok(git2::Repository::init_opts(&path, &opts)?)
907}
908
909/// The result of GitHub fast path check. See [`github_fast_path`] for more.
910enum FastPathRev {
911    /// The local rev (determined by `reference.resolve(repo)`) is already up to
912    /// date with what this rev resolves to on GitHub's server.
913    UpToDate,
914    /// The following SHA must be fetched in order for the local rev to become
915    /// up to date.
916    NeedsFetch(Oid),
917    /// Don't know whether local rev is up to date. We'll fetch _all_ branches
918    /// and tags from the server and see what happens.
919    Indeterminate,
920}
921
922/// Attempts GitHub's special fast path for testing if we've already got an
923/// up-to-date copy of the repository.
924///
925/// Updating the index is done pretty regularly so we want it to be as fast as
926/// possible. For registries hosted on GitHub (like the crates.io index) there's
927/// a fast path available to use[^1] to tell us that there's no updates to be
928/// made.
929///
930/// Note that this function should never cause an actual failure because it's
931/// just a fast path. As a result, a caller should ignore `Err` returned from
932/// this function and move forward on the normal path.
933///
934/// [^1]: <https://developer.github.com/v3/repos/commits/#get-the-sha-1-of-a-commit-reference>
935#[tracing::instrument(skip(repo, gctx))]
936fn github_fast_path(
937    repo: &git2::Repository,
938    url: &str,
939    reference: &GitReference,
940    gctx: &GlobalContext,
941) -> CargoResult<FastPathRev> {
942    let url = Url::parse(url)?;
943    if !is_github(&url) {
944        return Ok(FastPathRev::Indeterminate);
945    }
946
947    let local_object = resolve_ref(reference, repo).ok();
948
949    let github_branch_name = match reference {
950        GitReference::Branch(branch) => branch,
951        GitReference::Tag(tag) => tag,
952        GitReference::DefaultBranch => "HEAD",
953        GitReference::Rev(rev) => {
954            if rev.starts_with("refs/") {
955                rev
956            } else if looks_like_commit_hash(rev) {
957                // `revparse_single` (used by `resolve`) is the only way to turn
958                // short hash -> long hash, but it also parses other things,
959                // like branch and tag names, which might coincidentally be
960                // valid hex.
961                //
962                // We only return early if `rev` is a prefix of the object found
963                // by `revparse_single`. Don't bother talking to GitHub in that
964                // case, since commit hashes are permanent. If a commit with the
965                // requested hash is already present in the local clone, its
966                // contents must be the same as what is on the server for that
967                // hash.
968                //
969                // If `rev` is not found locally by `revparse_single`, we'll
970                // need GitHub to resolve it and get a hash. If `rev` is found
971                // but is not a short hash of the found object, it's probably a
972                // branch and we also need to get a hash from GitHub, in case
973                // the branch has moved.
974                if let Some(local_object) = local_object {
975                    if is_short_hash_of(rev, local_object) {
976                        debug!("github fast path already has {local_object}");
977                        return Ok(FastPathRev::UpToDate);
978                    }
979                }
980                // If `rev` is a full commit hash, the only thing it can resolve
981                // to is itself. Don't bother talking to GitHub in that case
982                // either. (This ensures that we always attempt to fetch the
983                // commit directly even if we can't reach the GitHub API.)
984                if let Some(oid) = rev_to_oid(rev) {
985                    debug!("github fast path is already a full commit hash {rev}");
986                    return Ok(FastPathRev::NeedsFetch(oid));
987                }
988                rev
989            } else {
990                debug!("can't use github fast path with `rev = \"{}\"`", rev);
991                return Ok(FastPathRev::Indeterminate);
992            }
993        }
994    };
995
996    // This expects GitHub urls in the form `github.com/user/repo` and nothing
997    // else
998    let mut pieces = url
999        .path_segments()
1000        .ok_or_else(|| anyhow!("no path segments on url"))?;
1001    let username = pieces
1002        .next()
1003        .ok_or_else(|| anyhow!("couldn't find username"))?;
1004    let repository = pieces
1005        .next()
1006        .ok_or_else(|| anyhow!("couldn't find repository name"))?;
1007    if pieces.next().is_some() {
1008        anyhow::bail!("too many segments on URL");
1009    }
1010
1011    // Trim off the `.git` from the repository, if present, since that's
1012    // optional for GitHub and won't work when we try to use the API as well.
1013    let repository = repository.trim_suffix(".git");
1014
1015    let url = format!(
1016        "https://api.github.com/repos/{}/{}/commits/{}",
1017        username, repository, github_branch_name,
1018    );
1019    debug!("attempting GitHub fast path for {}", url);
1020    let mut request =
1021        Request::get(url).header(http::header::ACCEPT, "application/vnd.github.3.sha");
1022    if let Some(local_object) = local_object {
1023        request = request.header(http::header::IF_NONE_MATCH, &format!("\"{local_object}\""));
1024    }
1025    let response = gctx
1026        .http_async()?
1027        .request_blocking(request.body(Vec::new())?)?;
1028    let response_code = response.status();
1029    if response_code == StatusCode::NOT_MODIFIED {
1030        debug!("github fast path up-to-date");
1031        Ok(FastPathRev::UpToDate)
1032    } else if response_code == StatusCode::OK
1033        && let Some(oid_to_fetch) = rev_to_oid(str::from_utf8(&response.body())?)
1034    {
1035        // response expected to be a full hash hexstring (40 or 64 chars)
1036        debug!("github fast path fetch {oid_to_fetch}");
1037        Ok(FastPathRev::NeedsFetch(oid_to_fetch))
1038    } else {
1039        // Usually response_code == 404 if the repository does not exist, and
1040        // response_code == 422 if exists but GitHub is unable to resolve the
1041        // requested rev.
1042        debug!("github fast path bad response code {response_code}");
1043        Ok(FastPathRev::Indeterminate)
1044    }
1045}
1046
1047/// Whether a `url` is one from GitHub.
1048fn is_github(url: &Url) -> bool {
1049    url.host_str() == Some("github.com")
1050}
1051
1052// Give some messages on GitHub PR URL given as is
1053pub(crate) fn note_github_pull_request(url: &str) -> Option<String> {
1054    if let Ok(url) = url.parse::<Url>()
1055        && is_github(&url)
1056    {
1057        let path_segments = url
1058            .path_segments()
1059            .map(|p| p.into_iter().collect::<Vec<_>>())
1060            .unwrap_or_default();
1061        if let [owner, repo, "pull", pr_number, ..] = path_segments[..] {
1062            let repo_url = format!("https://github.com/{owner}/{repo}.git");
1063            let rev = format!("refs/pull/{pr_number}/head");
1064            return Some(format!(
1065                concat!(
1066                    "\n\nnote: GitHub url {} is not a repository\n",
1067                    "help: to specify a pull request as a dependency, replace the dependency with:\n",
1068                    "       `git = \"{}\" rev = \"{}\"`",
1069                ),
1070                url, repo_url, rev
1071            ));
1072        }
1073    }
1074
1075    None
1076}
1077
1078pub(crate) fn note_ssh_config(gctx: &GlobalContext) -> CargoResult<Option<&'static str>> {
1079    let net_config = gctx.net_config()?;
1080    if let Some(ssh_config) = net_config.ssh.as_ref()
1081        && ssh_config.known_hosts.is_some()
1082    {
1083        Ok(Some(
1084            "
1085note: `cargo`s `net.ssh.known-hosts` is not applied to `git`, check your system SSH configuration to ensure it is set there",
1086        ))
1087    } else {
1088        Ok(None)
1089    }
1090}
1091
1092pub(crate) fn note_git_config(gctx: &GlobalContext) -> CargoResult<Option<String>> {
1093    let mut fields = Vec::new();
1094
1095    // As this is for errors, the focus is on things that impact functionality
1096    let http_config = gctx.http_config()?;
1097    if http_config.proxy.is_some() {
1098        fields.push("http.proxy (git: http.proxy)");
1099    }
1100    if http_config.low_speed_limit.is_some() {
1101        fields.push("http.low-speed-limit (git: http.lowSpeedLimit)");
1102    }
1103    if http_config.timeout.is_some() {
1104        fields.push("http.timeout (git: http.lowSpeedTime)");
1105    }
1106    if http_config.cainfo.is_some() {
1107        fields.push("http.cainfo (git: http.sslCAInfo)");
1108    }
1109    if http_config.proxy_cainfo.is_some() {
1110        fields.push("http.proxy-cainfo (git: http.proxySSLCAInfo)");
1111    }
1112    if http_config.check_revoke.is_some() {
1113        fields.push("http.check-revoke (git: http.schannelCheckRevoke)");
1114    }
1115    if http_config.multiplexing.is_some() {
1116        fields.push("http.multiplexing (git: http.version)");
1117    }
1118    if http_config.ssl_version.is_some() {
1119        fields.push("http.ssl-version (git: http.sslVersion)");
1120    }
1121
1122    if !fields.is_empty() {
1123        Ok(Some(format!("
1124note: `cargo` does not apply the following config to `git`, check your git configuration to ensure they are set there
1125    {}", fields.join("\n    "))))
1126    } else {
1127        Ok(None)
1128    }
1129}
1130
1131/// Whether a `rev` looks like a commit hash (ASCII hex digits).
1132fn looks_like_commit_hash(rev: &str) -> bool {
1133    rev.len() >= 7 && rev.chars().all(|ch| ch.is_ascii_hexdigit())
1134}
1135
1136/// Whether `rev` is a shorter hash of `oid`.
1137fn is_short_hash_of(rev: &str, oid: Oid) -> bool {
1138    let long_hash = oid.to_string();
1139    match long_hash.get(..rev.len()) {
1140        Some(truncated_long_hash) => truncated_long_hash.eq_ignore_ascii_case(rev),
1141        None => false,
1142    }
1143}
1144
1145#[cfg(test)]
1146mod tests {
1147    use super::*;
1148
1149    #[test]
1150    fn scp_to_ssh_produces_parseable_cache_urls() {
1151        assert!(
1152            "git@github.com:foo/bar.git".into_url().is_err(),
1153            "SourceId needs a WHATWG URL, which cannot represent SCP syntax"
1154        );
1155        for (input, expected) in [
1156            (
1157                "git@github.com:foo/bar.git",
1158                "ssh://git@github.com/foo/bar.git",
1159            ),
1160            (
1161                "git@github.com:/foo/bar.git",
1162                "ssh://git@github.com/foo/bar.git",
1163            ),
1164            ("git@github.com:~/bar.git", "ssh://git@github.com/~/bar.git"),
1165            (
1166                "git@github.com:~other/bar.git",
1167                "ssh://git@github.com/~other/bar.git",
1168            ),
1169            ("host:foo/bar.git", "ssh://host/foo/bar.git"),
1170        ] {
1171            let url = scp_to_ssh(input).unwrap();
1172            assert_eq!(
1173                url, expected,
1174                "conversion must preserve the pre-update cache URL"
1175            );
1176            let cache_url = url.as_str().into_url().unwrap();
1177            let source_id = SourceId::for_git(&cache_url, GitReference::DefaultBranch).unwrap();
1178            assert_eq!(source_id.url().as_str(), expected);
1179        }
1180        assert!(scp_to_ssh("https://github.com/foo/bar.git").is_none());
1181    }
1182
1183    #[test]
1184    fn github_fast_path_full_hash_returns_needs_fetch() {
1185        let temp_dir = tempfile::TempDir::new().unwrap();
1186        let repo = git2::Repository::init_bare(temp_dir.path()).unwrap();
1187        let full_hash = "c9040898c9183ddbb9402dcbf749ed06d6ea90ad";
1188        let reference = GitReference::Rev(full_hash.to_string());
1189        let gctx = GlobalContext::default().unwrap();
1190        let expected_oid = rev_to_oid(full_hash).unwrap();
1191
1192        let result =
1193            github_fast_path(&repo, "https://github.com/user/repo", &reference, &gctx).unwrap();
1194
1195        assert!(matches!(result, FastPathRev::NeedsFetch(oid) if oid == expected_oid));
1196    }
1197
1198    #[test]
1199    fn test_absolute_submodule_url() {
1200        let cases = [
1201            (
1202                "ssh://git@gitub.com/rust-lang/cargo",
1203                "git@github.com:rust-lang/cargo.git",
1204                "git@github.com:rust-lang/cargo.git",
1205            ),
1206            (
1207                "ssh://git@gitub.com/rust-lang/cargo",
1208                "./",
1209                "ssh://git@gitub.com/rust-lang/cargo/",
1210            ),
1211            (
1212                "ssh://git@gitub.com/rust-lang/cargo",
1213                "../",
1214                "ssh://git@gitub.com/rust-lang/",
1215            ),
1216            (
1217                "ssh://git@gitub.com/rust-lang/cargo",
1218                "./foo",
1219                "ssh://git@gitub.com/rust-lang/cargo/foo",
1220            ),
1221            (
1222                "ssh://git@gitub.com/rust-lang/cargo/",
1223                "./foo",
1224                "ssh://git@gitub.com/rust-lang/cargo/foo",
1225            ),
1226            (
1227                "ssh://git@gitub.com/rust-lang/cargo/",
1228                "../foo",
1229                "ssh://git@gitub.com/rust-lang/foo",
1230            ),
1231            (
1232                "ssh://git@gitub.com/rust-lang/cargo",
1233                "../foo",
1234                "ssh://git@gitub.com/rust-lang/foo",
1235            ),
1236            (
1237                "ssh://git@gitub.com/rust-lang/cargo",
1238                "../foo/bar/../baz",
1239                "ssh://git@gitub.com/rust-lang/foo/baz",
1240            ),
1241            (
1242                "git@github.com:rust-lang/cargo.git",
1243                "ssh://git@gitub.com/rust-lang/cargo",
1244                "ssh://git@gitub.com/rust-lang/cargo",
1245            ),
1246            (
1247                "git@github.com:rust-lang/cargo.git",
1248                "./",
1249                "git@github.com:rust-lang/cargo.git/./",
1250            ),
1251            (
1252                "git@github.com:rust-lang/cargo.git",
1253                "../",
1254                "git@github.com:rust-lang/cargo.git/../",
1255            ),
1256            (
1257                "git@github.com:rust-lang/cargo.git",
1258                "./foo",
1259                "git@github.com:rust-lang/cargo.git/./foo",
1260            ),
1261            (
1262                "git@github.com:rust-lang/cargo.git/",
1263                "./foo",
1264                "git@github.com:rust-lang/cargo.git/./foo",
1265            ),
1266            (
1267                "git@github.com:rust-lang/cargo.git",
1268                "../foo",
1269                "git@github.com:rust-lang/cargo.git/../foo",
1270            ),
1271            (
1272                "git@github.com:rust-lang/cargo.git/",
1273                "../foo",
1274                "git@github.com:rust-lang/cargo.git/../foo",
1275            ),
1276            (
1277                "git@github.com:rust-lang/cargo.git",
1278                "../foo/bar/../baz",
1279                "git@github.com:rust-lang/cargo.git/../foo/bar/../baz",
1280            ),
1281        ];
1282
1283        for (base_url, submodule_url, expected) in cases {
1284            let url = absolute_submodule_url(base_url, submodule_url).unwrap();
1285            assert_eq!(
1286                expected, url,
1287                "base `{base_url}`; submodule `{submodule_url}`"
1288            );
1289        }
1290    }
1291
1292    #[test]
1293    fn test_scp_to_ssh() {
1294        // Standard SCP-like URLs should be converted to ssh:// form.
1295        assert_eq!(
1296            scp_to_ssh("git@github.com:rust-lang/cargo.git"),
1297            Some("ssh://git@github.com/rust-lang/cargo.git".to_string()),
1298        );
1299        assert_eq!(
1300            scp_to_ssh("git@github.com:foo/bar.git"),
1301            Some("ssh://git@github.com/foo/bar.git".to_string()),
1302        );
1303        // A path starting with '~' should also be converted.
1304        assert_eq!(
1305            scp_to_ssh("git@github.com:~user/repo.git"),
1306            Some("ssh://git@github.com/~user/repo.git".to_string()),
1307        );
1308        // Non-SCP URLs should not be converted and return None.
1309        assert_eq!(scp_to_ssh("ssh://git@github.com/rust-lang/cargo.git"), None);
1310        assert_eq!(scp_to_ssh("https://github.com/rust-lang/cargo.git"), None);
1311        // Unparsable input should also return None.
1312        assert_eq!(scp_to_ssh("not-a-url"), None);
1313    }
1314}
1315
1316/// Turns a full commit hash revision into an oid.
1317///
1318/// Git object ID is supposed to be a hex string of 20 (SHA1) or 32 (SHA256) bytes.
1319/// Its length must be double to the underlying bytes (40 or 64),
1320/// otherwise libgit2 would happily zero-pad the returned oid.
1321///
1322/// See:
1323///
1324/// * <https://github.com/rust-lang/cargo/issues/13188>
1325/// * <https://github.com/rust-lang/cargo/issues/13968>
1326pub(super) fn rev_to_oid(rev: &str) -> Option<Oid> {
1327    Oid::from_str(rev)
1328        .ok()
1329        .filter(|oid| oid.as_bytes().len() * 2 == rev.len())
1330}