use crate::context::ProgressWhen;
use crate::sources::git::fetch::RemoteKind;
use crate::sources::git::oxide;
use crate::sources::git::oxide::cargo_config_to_gitoxide_overrides;
use crate::sources::git::source::GitSource;
use crate::sources::source::Source as _;
use crate::util::HumanBytes;
use crate::util::errors::{CargoResult, GitCliError};
use crate::util::network::http::http_handle;
use crate::util::network::http::needs_custom_http_transport;
use crate::util::{GlobalContext, IntoUrl, MetricsCounter, Progress, network};
use crate::workspace::{GitReference, SourceId};
use anyhow::{Context as _, anyhow};
use cargo_util::{ProcessBuilder, paths};
use cargo_util_terminal::Verbosity;
use git2::{ErrorClass, ObjectType, Oid};
use http::{Request, StatusCode};
use tracing::{debug, info};
use url::Url;
use std::borrow::Cow;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::str;
use std::sync::Once;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
const CHECKOUT_READY_LOCK: &str = ".cargo-ok";
#[derive(PartialEq, Clone, Debug)]
pub struct GitRemote {
url: String,
}
pub struct GitDatabase {
remote: GitRemote,
path: PathBuf,
repo: git2::Repository,
}
pub struct GitCheckout<'a> {
database: &'a GitDatabase,
path: PathBuf,
revision: git2::Oid,
repo: git2::Repository,
}
impl GitRemote {
pub fn new(url: &Url) -> GitRemote {
GitRemote {
url: url.as_str().to_owned(),
}
}
pub(super) fn new_from_str(url: String) -> GitRemote {
GitRemote { url }
}
pub fn url(&self) -> &str {
&self.url
}
pub fn checkout(
&self,
into: &Path,
db: Option<GitDatabase>,
manifest_reference: &GitReference,
reference: &GitReference,
gctx: &GlobalContext,
) -> CargoResult<(GitDatabase, git2::Oid)> {
if let Some(mut db) = db {
fetch(
&mut db.repo,
self.url(),
manifest_reference,
reference,
gctx,
RemoteKind::GitDependency,
)
.with_context(|| format!("failed to fetch into: {}", into.display()))?;
if let Some(rev) = resolve_ref(reference, &db.repo).ok() {
return Ok((db, rev));
}
}
if into.exists() {
paths::remove_dir_all(into)?;
}
paths::create_dir_all(into)?;
let mut repo = init(into, true)?;
fetch(
&mut repo,
self.url(),
manifest_reference,
reference,
gctx,
RemoteKind::GitDependency,
)
.with_context(|| format!("failed to clone into: {}", into.display()))?;
let rev = resolve_ref(reference, &repo)?;
Ok((
GitDatabase {
remote: self.clone(),
path: into.to_path_buf(),
repo,
},
rev,
))
}
pub fn db_at(&self, db_path: &Path) -> CargoResult<GitDatabase> {
let repo = git2::Repository::open(db_path)?;
Ok(GitDatabase {
remote: self.clone(),
path: db_path.to_path_buf(),
repo,
})
}
}
impl GitDatabase {
#[tracing::instrument(skip(self, gctx))]
pub fn copy_to(
&self,
rev: git2::Oid,
dest: &Path,
gctx: &GlobalContext,
quiet: bool,
) -> CargoResult<GitCheckout<'_>> {
let checkout = match git2::Repository::open(dest)
.ok()
.map(|repo| GitCheckout::new(self, rev, repo))
.filter(|co| co.is_fresh())
{
Some(co) => co,
None => {
let (checkout, guard) = GitCheckout::clone_into(dest, self, rev, gctx)?;
checkout.update_submodules(gctx, quiet)?;
guard.mark_ok()?;
checkout
}
};
Ok(checkout)
}
pub fn to_short_id(&self, rev: git2::Oid) -> CargoResult<String> {
const MIN_ABBREV_LEN: usize = 7; let odb = self.repo.odb()?;
let mut len = MIN_ABBREV_LEN;
let mut hex = rev.to_string();
while len < hex.len() {
match odb.exists_prefix(rev, len) {
Ok(_) => break,
Err(err) if err.code() == git2::ErrorCode::Ambiguous => len += 1,
Err(err) => return Err(err.into()),
}
}
hex.truncate(len);
Ok(hex)
}
pub fn contains(&self, oid: git2::Oid) -> bool {
self.repo.revparse_single(&oid.to_string()).is_ok()
}
pub fn resolve(&self, r: &GitReference) -> CargoResult<git2::Oid> {
resolve_ref(r, &self.repo)
}
}
pub fn resolve_ref(gitref: &GitReference, repo: &git2::Repository) -> CargoResult<git2::Oid> {
let id = match gitref {
GitReference::Tag(s) => (|| -> CargoResult<git2::Oid> {
let refname = format!("refs/remotes/origin/tags/{}", s);
let id = repo.refname_to_id(&refname)?;
let obj = repo.find_object(id, None)?;
let obj = obj.peel(ObjectType::Commit)?;
Ok(obj.id())
})()
.with_context(|| format!("failed to find tag `{}`", s))?,
GitReference::Branch(s) => {
let name = format!("origin/{}", s);
let b = repo
.find_branch(&name, git2::BranchType::Remote)
.with_context(|| format!("failed to find branch `{}`", s))?;
b.get()
.target()
.ok_or_else(|| anyhow::format_err!("branch `{}` did not have a target", s))?
}
GitReference::DefaultBranch => {
let head_id = repo.refname_to_id("refs/remotes/origin/HEAD")?;
let head = repo.find_object(head_id, None)?;
head.peel(ObjectType::Commit)?.id()
}
GitReference::Rev(s) => {
let obj = repo.revparse_single(s)?;
match obj.as_tag() {
Some(tag) => tag.target_id(),
None => obj.id(),
}
}
};
Ok(id)
}
impl<'a> GitCheckout<'a> {
fn new(
database: &'a GitDatabase,
revision: git2::Oid,
repo: git2::Repository,
) -> GitCheckout<'a> {
let path = repo.workdir().unwrap_or_else(|| repo.path());
GitCheckout {
path: path.to_path_buf(),
database,
revision,
repo,
}
}
fn remote_url(&self) -> &str {
self.database.remote.url()
}
fn clone_into(
into: &Path,
database: &'a GitDatabase,
revision: git2::Oid,
gctx: &GlobalContext,
) -> CargoResult<(GitCheckout<'a>, CheckoutGuard)> {
let dirname = into.parent().unwrap();
paths::create_dir_all(&dirname)?;
if into.exists() {
paths::remove_dir_all(into)?;
}
let git_config = git2::Config::new()?;
let url = database.path.into_url()?;
let mut repo = None;
with_fetch_options(&git_config, url.as_str(), gctx, &mut |fopts| {
let mut checkout = git2::build::CheckoutBuilder::new();
checkout.dry_run();
let r = git2::build::RepoBuilder::new()
.clone_local(git2::build::CloneLocal::Local)
.with_checkout(checkout)
.fetch_options(fopts)
.clone(url.as_str(), into)?;
if database.repo.is_shallow() {
std::fs::copy(
database.repo.path().join("shallow"),
r.path().join("shallow"),
)?;
}
repo = Some(r);
Ok(())
})?;
let repo = repo.unwrap();
let checkout = GitCheckout::new(database, revision, repo);
let guard = checkout.reset(gctx)?;
Ok((checkout, guard))
}
fn is_fresh(&self) -> bool {
match self.repo.revparse_single("HEAD") {
Ok(ref head) if head.id() == self.revision => {
self.path.join(CHECKOUT_READY_LOCK).exists()
}
_ => false,
}
}
fn reset(&self, gctx: &GlobalContext) -> CargoResult<CheckoutGuard> {
let guard = CheckoutGuard::guard(&self.path);
info!("reset {} to {}", self.repo.path().display(), self.revision);
if let Ok(mut git_config) = self.repo.config() {
git_config.set_bool("core.autocrlf", false)?;
}
let object = self.repo.find_object(self.revision, None)?;
reset(&self.repo, &object, gctx)?;
Ok(guard)
}
fn update_submodules(&self, gctx: &GlobalContext, quiet: bool) -> CargoResult<()> {
return update_submodules(&self.repo, gctx, quiet, self.remote_url());
fn update_submodules(
repo: &git2::Repository,
gctx: &GlobalContext,
quiet: bool,
parent_remote_url: &str,
) -> CargoResult<()> {
debug!("update submodules for: {:?}", repo.workdir().unwrap());
for mut child in repo.submodules()? {
update_submodule(repo, &mut child, gctx, quiet, parent_remote_url).with_context(
|| {
format!(
"failed to update submodule `{}`",
child.name().unwrap_or("")
)
},
)?;
}
Ok(())
}
fn update_submodule(
parent: &git2::Repository,
child: &mut git2::Submodule<'_>,
gctx: &GlobalContext,
quiet: bool,
parent_remote_url: &str,
) -> CargoResult<()> {
child.init(false)?;
let child_url_str = child
.url()
.with_context(|| {
format!("failed to update submodule `{}`", child.path().display())
})?
.ok_or_else(|| {
anyhow::format_err!(
"unable to update submodule `{}` without a path",
child.name().unwrap_or("")
)
})?;
if child.update_strategy() == git2::SubmoduleUpdate::None {
gctx.shell().status(
"Skipping",
format!(
"git submodule `{}` due to update strategy in .gitmodules",
child_url_str
),
)?;
return Ok(());
}
let child_remote_url = absolute_submodule_url(parent_remote_url, child_url_str)?;
let Some(head) = child.head_id() else {
return Ok(());
};
let head_and_repo = child.open().and_then(|repo| {
let target = repo.head()?.target();
Ok((target, repo))
});
let repo = match head_and_repo {
Ok((head, repo)) => {
if child.head_id() == head {
return update_submodules(&repo, gctx, quiet, &child_remote_url);
}
repo
}
Err(..) => {
let path = parent.workdir().unwrap().join(child.path());
let _ = paths::remove_dir_all(&path);
init(&path, false)?
}
};
let reference = GitReference::Rev(head.to_string());
let (source_url, fetch_url) = match child_remote_url.as_ref().into_url() {
Ok(url) => (url, None),
Err(_) => {
let ssh_url = scp_to_ssh(&child_remote_url)
.ok_or_else(|| anyhow::format_err!("invalid url `{child_remote_url}`"))?
.as_str()
.into_url()?;
(ssh_url, Some(child_remote_url.into_owned()))
}
};
let source_id =
SourceId::for_git(&source_url, reference)?.with_git_precise(Some(head.to_string()));
let mut source = match &fetch_url {
Some(url) => GitSource::new_for_submodule(source_id, url.to_owned(), gctx)?,
None => GitSource::new(source_id, gctx)?,
};
source.set_quiet(quiet);
let (db, actual_rev) = source.fetch_db(true).with_context(|| {
let name = child.name().unwrap_or("");
let url = fetch_url.unwrap_or_else(|| source_url.to_string());
format!("failed to fetch submodule `{name}` from {url}")
})?;
db.copy_to(actual_rev, repo.path(), gctx, quiet)?;
Ok(())
}
}
}
#[must_use]
struct CheckoutGuard {
ok_file: PathBuf,
}
impl CheckoutGuard {
fn guard(path: &Path) -> Self {
let ok_file = path.join(CHECKOUT_READY_LOCK);
let _ = paths::remove_file(&ok_file);
Self { ok_file }
}
fn mark_ok(self) -> CargoResult<()> {
let _ = paths::create(self.ok_file)?;
Ok(())
}
}
fn absolute_submodule_url<'s>(base_url: &str, submodule_url: &'s str) -> CargoResult<Cow<'s, str>> {
let absolute_url = if ["./", "../"].iter().any(|p| submodule_url.starts_with(p)) {
match Url::parse(base_url) {
Ok(mut base_url) => {
let path = base_url.path();
if !path.ends_with('/') {
base_url.set_path(&format!("{path}/"));
}
let absolute_url = base_url.join(submodule_url).with_context(|| {
format!(
"failed to parse relative child submodule url `{submodule_url}` \
using parent base url `{base_url}`"
)
})?;
Cow::from(absolute_url.to_string())
}
Err(_) => {
let mut absolute_url = base_url.to_string();
if !absolute_url.ends_with('/') {
absolute_url.push('/');
}
absolute_url.push_str(submodule_url);
Cow::from(absolute_url)
}
}
} else {
Cow::from(submodule_url)
};
Ok(absolute_url)
}
fn scp_to_ssh(url: &str) -> Option<String> {
let mut gix_url = gix::url::parse(gix::bstr::BStr::new(url.as_bytes())).ok()?;
if gix_url.serialize_alternative_form && gix_url.scheme == gix::url::Scheme::Ssh {
gix_url.serialize_alternative_form = false;
Some(gix_url.to_bstring().to_string())
} else {
None
}
}
fn with_authentication<T, F>(
gctx: &GlobalContext,
url: &str,
cfg: &git2::Config,
mut f: F,
) -> CargoResult<T>
where
F: FnMut(&mut git2::Credentials<'_>) -> CargoResult<T>,
{
let mut cred_helper = git2::CredentialHelper::new(url);
cred_helper.config(cfg);
let mut ssh_username_requested = false;
let mut cred_helper_bad = None;
let mut ssh_agent_attempts = Vec::new();
let mut any_attempts = false;
let mut tried_sshkey = false;
let mut url_attempt = None;
let orig_url = url;
let mut res = f(&mut |url, username, allowed| {
any_attempts = true;
if url != orig_url {
url_attempt = Some(url.to_string());
}
if allowed.contains(git2::CredentialType::USERNAME) {
debug_assert!(username.is_none());
ssh_username_requested = true;
return Err(git2::Error::from_str("gonna try usernames later"));
}
if allowed.contains(git2::CredentialType::SSH_KEY) && !tried_sshkey {
tried_sshkey = true;
let username = username.unwrap();
debug_assert!(!ssh_username_requested);
ssh_agent_attempts.push(username.to_string());
return git2::Cred::ssh_key_from_agent(username);
}
if allowed.contains(git2::CredentialType::USER_PASS_PLAINTEXT) && cred_helper_bad.is_none()
{
let r = git2::Cred::credential_helper(cfg, url, username);
cred_helper_bad = Some(r.is_err());
return r;
}
if allowed.contains(git2::CredentialType::DEFAULT) {
return git2::Cred::default();
}
Err(git2::Error::from_str("no authentication methods succeeded"))
});
if ssh_username_requested {
debug_assert!(res.is_err());
let mut attempts = vec![String::from("git")];
if let Ok(s) = gctx.get_env("USER").or_else(|_| gctx.get_env("USERNAME")) {
attempts.push(s.to_string());
}
if let Some(ref s) = cred_helper.username {
attempts.push(s.clone());
}
while let Some(s) = attempts.pop() {
let mut attempts = 0;
res = f(&mut |_url, username, allowed| {
if allowed.contains(git2::CredentialType::USERNAME) {
return git2::Cred::username(&s);
}
if allowed.contains(git2::CredentialType::SSH_KEY) {
debug_assert_eq!(Some(&s[..]), username);
attempts += 1;
if attempts == 1 {
ssh_agent_attempts.push(s.to_string());
return git2::Cred::ssh_key_from_agent(&s);
}
}
Err(git2::Error::from_str("no authentication methods succeeded"))
});
if attempts != 2 {
break;
}
}
}
let mut err = match res {
Ok(e) => return Ok(e),
Err(e) => e,
};
if any_attempts {
let mut msg = "failed to authenticate when downloading \
repository"
.to_string();
if let Some(attempt) = &url_attempt {
if url != attempt {
msg.push_str(": ");
msg.push_str(attempt);
}
}
msg.push('\n');
if !ssh_agent_attempts.is_empty() {
let names = ssh_agent_attempts
.iter()
.map(|s| format!("`{}`", s))
.collect::<Vec<_>>()
.join(", ");
msg.push_str(&format!(
"\n* attempted ssh-agent authentication, but \
no usernames succeeded: {}",
names
));
}
if let Some(failed_cred_helper) = cred_helper_bad {
if failed_cred_helper {
msg.push_str(
"\n* attempted to find username/password via \
git's `credential.helper` support, but failed",
);
} else {
msg.push_str(
"\n* attempted to find username/password via \
`credential.helper`, but maybe the found \
credentials were incorrect",
);
}
}
msg.push_str("\n\n");
msg.push_str("if the git CLI succeeds then `net.git-fetch-with-cli` may help here\n");
msg.push_str("https://doc.rust-lang.org/cargo/reference/config.html#netgit-fetch-with-cli");
err = err.context(msg);
} else if let Some(e) = err.downcast_ref::<git2::Error>() {
match e.class() {
ErrorClass::Net
| ErrorClass::Ssl
| ErrorClass::Submodule
| ErrorClass::FetchHead
| ErrorClass::Ssh
| ErrorClass::Http => {
let msg = format!(
concat!(
"network failure seems to have happened\n",
"if a proxy or similar is necessary `net.git-fetch-with-cli` may help here\n",
"https://doc.rust-lang.org/cargo/reference/config.html#netgit-fetch-with-cli",
"{}"
),
note_github_pull_request(url).unwrap_or_default()
);
err = err.context(msg);
}
ErrorClass::Callback => {
err = anyhow::format_err!("{}", e.message());
}
_ => {}
}
}
Err(err)
}
#[tracing::instrument(skip_all)]
fn reset(repo: &git2::Repository, obj: &git2::Object<'_>, gctx: &GlobalContext) -> CargoResult<()> {
let mut pb = Progress::new("Checkout", gctx);
let mut opts = git2::build::CheckoutBuilder::new();
opts.progress(|_, cur, max| {
drop(pb.tick(cur, max, ""));
});
debug!("doing reset");
repo.reset(obj, git2::ResetType::Hard, Some(&mut opts))?;
debug!("reset done");
Ok(())
}
pub fn with_fetch_options(
git_config: &git2::Config,
url: &str,
gctx: &GlobalContext,
cb: &mut dyn FnMut(git2::FetchOptions<'_>) -> CargoResult<()>,
) -> CargoResult<()> {
let mut progress = Progress::new("Fetch", gctx);
let ssh_config = gctx.net_config()?.ssh.as_ref();
let config_known_hosts = ssh_config.and_then(|ssh| ssh.known_hosts.as_ref());
let diagnostic_home_config = gctx.diagnostic_home_config();
network::retry::with_retry(gctx, || {
let mut check_cb_result = Ok(());
let auth_result = with_authentication(gctx, url, git_config, |f| {
let port = Url::parse(url).ok().and_then(|url| url.port());
let mut last_update = Instant::now();
let mut rcb = git2::RemoteCallbacks::new();
let mut counter = MetricsCounter::<10>::new(0, last_update);
rcb.credentials(f);
rcb.certificate_check(|cert, host| {
match super::known_hosts::certificate_check(
gctx,
cert,
host,
port,
config_known_hosts,
&diagnostic_home_config,
) {
Ok(status) => Ok(status),
Err(e) => {
check_cb_result = Err(e);
Err(git2::Error::from_str(
"invalid or unknown remote ssh hostkey",
))
}
}
});
rcb.transfer_progress(|stats| {
let indexed_deltas = stats.indexed_deltas();
let msg = if indexed_deltas > 0 {
format!(
", ({}/{}) resolving deltas",
indexed_deltas,
stats.total_deltas()
)
} else {
let now = Instant::now();
if now - last_update > Duration::from_millis(300) {
counter.add(stats.received_bytes(), now);
last_update = now;
}
let rate = HumanBytes(counter.rate() as u64);
format!(", {rate:.2}/s")
};
progress
.tick(stats.indexed_objects(), stats.total_objects(), &msg)
.is_ok()
});
let mut opts = git2::FetchOptions::new();
opts.remote_callbacks(rcb);
cb(opts)
});
if auth_result.is_err() {
check_cb_result?;
}
auth_result?;
Ok(())
})
}
#[tracing::instrument(skip_all)]
pub fn fetch(
repo: &mut git2::Repository,
remote_url: &str,
manifest_reference: &GitReference,
locked_reference: &GitReference,
gctx: &GlobalContext,
remote_kind: RemoteKind,
) -> CargoResult<()> {
if let Some(offline_flag) = gctx.offline_flag() {
anyhow::bail!(
"attempting to update a git repository, but {offline_flag} \
was specified"
)
}
let shallow = remote_kind.to_shallow_setting(repo.is_shallow(), gctx);
let mut fast_path_rev: bool = false;
let oid_to_fetch = match github_fast_path(repo, remote_url, locked_reference, gctx) {
Ok(FastPathRev::UpToDate) => return Ok(()),
Ok(FastPathRev::NeedsFetch(rev)) => Some(rev),
Ok(FastPathRev::Indeterminate) => None,
Err(e) => {
debug!("failed to check github {:?}", e);
None
}
};
maybe_gc_repo(repo, gctx)?;
clean_repo_temp_files(repo);
let mut refspecs = Vec::new();
let mut tags = false;
match locked_reference {
GitReference::Branch(b) => {
refspecs.push(format!("+refs/heads/{0}:refs/remotes/origin/{0}", b));
}
GitReference::Tag(t) => {
refspecs.push(format!("+refs/tags/{0}:refs/remotes/origin/tags/{0}", t));
}
GitReference::DefaultBranch => {
refspecs.push(String::from("+HEAD:refs/remotes/origin/HEAD"));
}
GitReference::Rev(rev) => {
if rev.starts_with("refs/") {
refspecs.push(format!("+{0}:{0}", rev));
} else if let Some(oid_to_fetch) = oid_to_fetch {
fast_path_rev = true;
refspecs.push(format!("+{0}:refs/commit/{0}", oid_to_fetch));
} else if !matches!(shallow, gix::remote::fetch::Shallow::NoChange)
&& rev_to_oid(rev).is_some()
{
refspecs.push(format!("+{0}:refs/remotes/origin/HEAD", rev));
} else if let GitReference::Rev(rev) = manifest_reference
&& rev.starts_with("refs/")
{
refspecs.push(format!("+{0}:{0}", rev));
} else {
refspecs.push(String::from("+refs/heads/*:refs/remotes/origin/*"));
refspecs.push(String::from("+HEAD:refs/remotes/origin/HEAD"));
tags = true;
}
}
}
debug!("doing a fetch for {remote_url}");
let result = if let Some(true) = gctx.net_config()?.git_fetch_with_cli {
fetch_with_cli(repo, remote_url, &refspecs, tags, shallow, gctx)
} else if gctx.cli_unstable().gitoxide.map_or(false, |git| git.fetch) {
fetch_with_gitoxide(repo, remote_url, refspecs, tags, shallow, gctx)
} else {
fetch_with_libgit2(repo, remote_url, refspecs, tags, shallow, gctx)
};
if fast_path_rev {
if let Some(oid) = oid_to_fetch {
return result.with_context(|| format!("revision {} not found", oid));
}
}
result
}
fn has_shallow_lock_file(err: &crate::sources::git::fetch::Error) -> bool {
matches!(
err,
gix::env::collate::fetch::Error::Fetch(gix::remote::fetch::Error::Fetch(
gix::protocol::fetch::Error::LockShallowFile(_)
))
)
}
#[tracing::instrument(skip(repo, gctx))]
fn fetch_with_cli(
repo: &git2::Repository,
url: &str,
refspecs: &[String],
tags: bool,
shallow: gix::remote::fetch::Shallow,
gctx: &GlobalContext,
) -> CargoResult<()> {
debug!(target: "git-fetch", backend = "git-cli");
let mut cmd = ProcessBuilder::new("git");
cmd.arg("-c").arg("core.fsmonitor=false");
cmd.arg("fetch");
if tags {
cmd.arg("--tags");
} else {
cmd.arg("--no-tags");
}
if let gix::remote::fetch::Shallow::DepthAtRemote(depth) = shallow {
let depth = 0i32.saturating_add_unsigned(depth.get());
cmd.arg(format!("--depth={depth}"));
}
let progress_config = gctx.progress_config();
let progress = match progress_config.when {
ProgressWhen::Always => true,
ProgressWhen::Never => false,
ProgressWhen::Auto => {
let width = progress_config
.width
.or_else(|| gctx.shell().err_width().progress_max_width());
gctx.shell().progress_supported() && width.is_some()
}
};
if gctx.shell().verbosity() == Verbosity::Verbose {
cmd.arg("--verbose");
} else if !progress {
cmd.arg("--quiet");
}
cmd.arg("--force") .arg("--update-head-ok") .arg(url)
.args(refspecs)
.env("GIT_DIR", repo.path())
.env_remove("GIT_WORK_TREE")
.env_remove("GIT_INDEX_FILE")
.env_remove("GIT_OBJECT_DIRECTORY")
.env_remove("GIT_ALTERNATE_OBJECT_DIRECTORIES")
.cwd(repo.path());
gctx.shell()
.verbose(|s| s.status("Running", &cmd.to_string()))?;
network::retry::with_retry(gctx, || {
cmd.exec().map_err(|error| {
GitCliError::new(error)
.spurious(true)
.workaround(
"help: re-try with `net.git-fetch-with-cli = false` to see if it resolves the problem
https://doc.rust-lang.org/cargo/reference/config.html#netgit-fetch-with-cli",
)
.into()
})
})?;
Ok(())
}
#[tracing::instrument(skip(repo, gctx))]
fn fetch_with_gitoxide(
repo: &mut git2::Repository,
remote_url: &str,
refspecs: Vec<String>,
tags: bool,
shallow: gix::remote::fetch::Shallow,
gctx: &GlobalContext,
) -> CargoResult<()> {
debug!(target: "git-fetch", backend = "gitoxide");
let git2_repo = repo;
let config_overrides = cargo_config_to_gitoxide_overrides(gctx)?;
let repo_reinitialized = AtomicBool::default();
let res = oxide::with_retry_and_progress(
git2_repo.path(),
gctx,
remote_url,
&|repo_path,
should_interrupt,
mut progress,
url_for_authentication: &mut dyn FnMut(&gix::bstr::BStr)| {
loop {
let res = oxide::open_repo(
repo_path,
config_overrides.clone(),
oxide::OpenMode::ForFetch,
)
.map_err(crate::sources::git::fetch::Error::from)
.and_then(|repo| {
debug!("initiating fetch of {refspecs:?} from {remote_url}");
let url_for_authentication = &mut *url_for_authentication;
let remote = repo
.remote_at(remote_url)?
.with_fetch_tags(if tags {
gix::remote::fetch::Tags::All
} else {
gix::remote::fetch::Tags::Included
})
.with_refspecs(
refspecs.iter().map(|s| s.as_str()),
gix::remote::Direction::Fetch,
)
.map_err(crate::sources::git::fetch::Error::Other)?;
let url = remote
.url(gix::remote::Direction::Fetch)
.expect("set at init")
.to_owned();
let connection = remote.connect(gix::remote::Direction::Fetch)?;
let mut authenticate = connection.configured_credentials(url)?;
let connection = connection.with_credentials(
move |action: gix::protocol::credentials::helper::Action| {
if let Some(url) = action
.context()
.and_then(|gctx| gctx.url.as_ref().filter(|url| *url != remote_url))
{
url_for_authentication(url.as_ref());
}
authenticate(action)
},
);
let outcome = connection
.prepare_fetch(&mut progress, gix::remote::ref_map::Options::default())?
.with_shallow(shallow.clone())
.receive(&mut progress, should_interrupt)?;
Ok(outcome)
});
let err = match res {
Ok(_) => break,
Err(e) => e,
};
debug!("fetch failed: {}", err);
if !repo_reinitialized.load(Ordering::Relaxed)
&& err.is_corrupted()
|| has_shallow_lock_file(&err)
{
repo_reinitialized.store(true, Ordering::Relaxed);
debug!(
"looks like this is a corrupt repository, reinitializing \
and trying again"
);
if oxide::reinitialize(repo_path).is_ok() {
continue;
}
}
return Err(err.into());
}
Ok(())
},
);
if repo_reinitialized.load(Ordering::Relaxed) {
*git2_repo = git2::Repository::open(git2_repo.path())?;
}
res
}
#[tracing::instrument(skip(repo, gctx))]
fn fetch_with_libgit2(
repo: &mut git2::Repository,
remote_url: &str,
refspecs: Vec<String>,
tags: bool,
shallow: gix::remote::fetch::Shallow,
gctx: &GlobalContext,
) -> CargoResult<()> {
debug!(target: "git-fetch", backend = "libgit2");
static INIT: Once = Once::new();
INIT.call_once(|| {
unsafe { init_git_transports(gctx) };
});
let git_config = git2::Config::open_default()?;
with_fetch_options(&git_config, remote_url, gctx, &mut |mut opts| {
if tags {
opts.download_tags(git2::AutotagOption::All);
}
if let gix::remote::fetch::Shallow::DepthAtRemote(depth) = shallow {
opts.depth(0i32.saturating_add_unsigned(depth.get()));
}
let mut repo_reinitialized = false;
loop {
debug!("initiating fetch of {refspecs:?} from {remote_url}");
let res = repo
.remote_anonymous(remote_url)?
.fetch(&refspecs, Some(&mut opts), None);
let err = match res {
Ok(()) => break,
Err(e) => e,
};
debug!("fetch failed: {}", err);
if !repo_reinitialized && matches!(err.class(), ErrorClass::Reference | ErrorClass::Odb)
{
repo_reinitialized = true;
debug!(
"looks like this is a corrupt repository, reinitializing \
and trying again"
);
if reinitialize(repo).is_ok() {
continue;
}
}
return Err(err.into());
}
Ok(())
})
}
#[tracing::instrument(skip_all)]
unsafe fn init_git_transports(gctx: &GlobalContext) {
match needs_custom_http_transport(gctx) {
Ok(true) => {}
_ => return,
}
let handle = match http_handle(gctx) {
Ok(handle) => handle,
Err(..) => return,
};
unsafe {
git2_curl::register(handle);
}
}
fn maybe_gc_repo(repo: &mut git2::Repository, gctx: &GlobalContext) -> CargoResult<()> {
let mut cmd = Command::new("git");
if let Ok(limit) = gctx.get_env("__CARGO_PACKFILE_LIMIT") {
cmd.arg(format!("-c gc.autoPackLimit={}", limit));
}
cmd.arg("gc").arg("--auto").current_dir(repo.path());
match cmd.output() {
Ok(out) => {
debug!(
"git-gc --auto status: {}\n\nstdout ---\n{}\nstderr ---\n{}",
out.status,
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
);
if out.status.success() {
let new = git2::Repository::open(repo.path())?;
*repo = new;
return Ok(());
}
}
Err(e) => debug!("git-gc --auto failed to spawn: {}", e),
}
reinitialize(repo)
}
fn clean_repo_temp_files(repo: &git2::Repository) {
let path = repo.path().join("objects/pack/pack_git2_*");
let Some(pattern) = path.to_str() else {
tracing::warn!("cannot convert {path:?} to a string");
return;
};
let Ok(paths) = glob::glob(pattern) else {
return;
};
for path in paths {
if let Ok(path) = path {
match paths::remove_file(&path) {
Ok(_) => tracing::debug!("removed stale temp git file {path:?}"),
Err(e) => {
tracing::warn!("failed to remove {path:?} while cleaning temp files: {e}")
}
}
}
}
}
fn reinitialize(repo: &mut git2::Repository) -> CargoResult<()> {
let path = repo.path().to_path_buf();
debug!("reinitializing git repo at {:?}", path);
let tmp = path.join("tmp");
let bare = !repo.path().ends_with(".git");
*repo = init(&tmp, false)?;
for entry in path.read_dir()? {
let entry = entry?;
if entry.file_name().to_str() == Some("tmp") {
continue;
}
let path = entry.path();
drop(paths::remove_file(&path).or_else(|_| paths::remove_dir_all(&path)));
}
*repo = init(&path, bare)?;
paths::remove_dir_all(&tmp)?;
Ok(())
}
fn init(path: &Path, bare: bool) -> CargoResult<git2::Repository> {
let mut opts = git2::RepositoryInitOptions::new();
opts.external_template(false);
opts.bare(bare);
Ok(git2::Repository::init_opts(&path, &opts)?)
}
enum FastPathRev {
UpToDate,
NeedsFetch(Oid),
Indeterminate,
}
#[tracing::instrument(skip(repo, gctx))]
fn github_fast_path(
repo: &git2::Repository,
url: &str,
reference: &GitReference,
gctx: &GlobalContext,
) -> CargoResult<FastPathRev> {
let url = Url::parse(url)?;
if !is_github(&url) {
return Ok(FastPathRev::Indeterminate);
}
let local_object = resolve_ref(reference, repo).ok();
let github_branch_name = match reference {
GitReference::Branch(branch) => branch,
GitReference::Tag(tag) => tag,
GitReference::DefaultBranch => "HEAD",
GitReference::Rev(rev) => {
if rev.starts_with("refs/") {
rev
} else if looks_like_commit_hash(rev) {
if let Some(local_object) = local_object {
if is_short_hash_of(rev, local_object) {
debug!("github fast path already has {local_object}");
return Ok(FastPathRev::UpToDate);
}
}
if let Some(oid) = rev_to_oid(rev) {
debug!("github fast path is already a full commit hash {rev}");
return Ok(FastPathRev::NeedsFetch(oid));
}
rev
} else {
debug!("can't use github fast path with `rev = \"{}\"`", rev);
return Ok(FastPathRev::Indeterminate);
}
}
};
let mut pieces = url
.path_segments()
.ok_or_else(|| anyhow!("no path segments on url"))?;
let username = pieces
.next()
.ok_or_else(|| anyhow!("couldn't find username"))?;
let repository = pieces
.next()
.ok_or_else(|| anyhow!("couldn't find repository name"))?;
if pieces.next().is_some() {
anyhow::bail!("too many segments on URL");
}
let repository = repository.strip_suffix(".git").unwrap_or(repository);
let url = format!(
"https://api.github.com/repos/{}/{}/commits/{}",
username, repository, github_branch_name,
);
debug!("attempting GitHub fast path for {}", url);
let mut request =
Request::get(url).header(http::header::ACCEPT, "application/vnd.github.3.sha");
if let Some(local_object) = local_object {
request = request.header(http::header::IF_NONE_MATCH, &format!("\"{local_object}\""));
}
let response = gctx
.http_async()?
.request_blocking(request.body(Vec::new())?)?;
let response_code = response.status();
if response_code == StatusCode::NOT_MODIFIED {
debug!("github fast path up-to-date");
Ok(FastPathRev::UpToDate)
} else if response_code == StatusCode::OK
&& let Some(oid_to_fetch) = rev_to_oid(str::from_utf8(&response.body())?)
{
debug!("github fast path fetch {oid_to_fetch}");
Ok(FastPathRev::NeedsFetch(oid_to_fetch))
} else {
debug!("github fast path bad response code {response_code}");
Ok(FastPathRev::Indeterminate)
}
}
fn is_github(url: &Url) -> bool {
url.host_str() == Some("github.com")
}
pub(crate) fn note_github_pull_request(url: &str) -> Option<String> {
if let Ok(url) = url.parse::<Url>()
&& is_github(&url)
{
let path_segments = url
.path_segments()
.map(|p| p.into_iter().collect::<Vec<_>>())
.unwrap_or_default();
if let [owner, repo, "pull", pr_number, ..] = path_segments[..] {
let repo_url = format!("https://github.com/{owner}/{repo}.git");
let rev = format!("refs/pull/{pr_number}/head");
return Some(format!(
concat!(
"\n\nnote: GitHub url {} is not a repository. \n",
"help: Replace the dependency with \n",
" `git = \"{}\" rev = \"{}\"` \n",
" to specify pull requests as dependencies' revision."
),
url, repo_url, rev
));
}
}
None
}
fn looks_like_commit_hash(rev: &str) -> bool {
rev.len() >= 7 && rev.chars().all(|ch| ch.is_ascii_hexdigit())
}
fn is_short_hash_of(rev: &str, oid: Oid) -> bool {
let long_hash = oid.to_string();
match long_hash.get(..rev.len()) {
Some(truncated_long_hash) => truncated_long_hash.eq_ignore_ascii_case(rev),
None => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn github_fast_path_full_hash_returns_needs_fetch() {
let temp_dir = tempfile::TempDir::new().unwrap();
let repo = git2::Repository::init_bare(temp_dir.path()).unwrap();
let full_hash = "c9040898c9183ddbb9402dcbf749ed06d6ea90ad";
let reference = GitReference::Rev(full_hash.to_string());
let gctx = GlobalContext::default().unwrap();
let expected_oid = rev_to_oid(full_hash).unwrap();
let result =
github_fast_path(&repo, "https://github.com/user/repo", &reference, &gctx).unwrap();
assert!(matches!(result, FastPathRev::NeedsFetch(oid) if oid == expected_oid));
}
#[test]
fn test_absolute_submodule_url() {
let cases = [
(
"ssh://git@gitub.com/rust-lang/cargo",
"git@github.com:rust-lang/cargo.git",
"git@github.com:rust-lang/cargo.git",
),
(
"ssh://git@gitub.com/rust-lang/cargo",
"./",
"ssh://git@gitub.com/rust-lang/cargo/",
),
(
"ssh://git@gitub.com/rust-lang/cargo",
"../",
"ssh://git@gitub.com/rust-lang/",
),
(
"ssh://git@gitub.com/rust-lang/cargo",
"./foo",
"ssh://git@gitub.com/rust-lang/cargo/foo",
),
(
"ssh://git@gitub.com/rust-lang/cargo/",
"./foo",
"ssh://git@gitub.com/rust-lang/cargo/foo",
),
(
"ssh://git@gitub.com/rust-lang/cargo/",
"../foo",
"ssh://git@gitub.com/rust-lang/foo",
),
(
"ssh://git@gitub.com/rust-lang/cargo",
"../foo",
"ssh://git@gitub.com/rust-lang/foo",
),
(
"ssh://git@gitub.com/rust-lang/cargo",
"../foo/bar/../baz",
"ssh://git@gitub.com/rust-lang/foo/baz",
),
(
"git@github.com:rust-lang/cargo.git",
"ssh://git@gitub.com/rust-lang/cargo",
"ssh://git@gitub.com/rust-lang/cargo",
),
(
"git@github.com:rust-lang/cargo.git",
"./",
"git@github.com:rust-lang/cargo.git/./",
),
(
"git@github.com:rust-lang/cargo.git",
"../",
"git@github.com:rust-lang/cargo.git/../",
),
(
"git@github.com:rust-lang/cargo.git",
"./foo",
"git@github.com:rust-lang/cargo.git/./foo",
),
(
"git@github.com:rust-lang/cargo.git/",
"./foo",
"git@github.com:rust-lang/cargo.git/./foo",
),
(
"git@github.com:rust-lang/cargo.git",
"../foo",
"git@github.com:rust-lang/cargo.git/../foo",
),
(
"git@github.com:rust-lang/cargo.git/",
"../foo",
"git@github.com:rust-lang/cargo.git/../foo",
),
(
"git@github.com:rust-lang/cargo.git",
"../foo/bar/../baz",
"git@github.com:rust-lang/cargo.git/../foo/bar/../baz",
),
];
for (base_url, submodule_url, expected) in cases {
let url = absolute_submodule_url(base_url, submodule_url).unwrap();
assert_eq!(
expected, url,
"base `{base_url}`; submodule `{submodule_url}`"
);
}
}
}
pub(super) fn rev_to_oid(rev: &str) -> Option<Oid> {
Oid::from_str(rev)
.ok()
.filter(|oid| oid.as_bytes().len() * 2 == rev.len())
}