1use 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
29const CHECKOUT_READY_LOCK: &str = ".cargo-ok";
32
33#[derive(PartialEq, Clone, Debug)]
35pub struct GitRemote {
36 url: String,
42}
43
44pub struct GitDatabase {
47 remote: GitRemote,
49 path: PathBuf,
51 repo: git2::Repository,
53}
54
55pub struct GitCheckout<'a> {
57 database: &'a GitDatabase,
59 path: PathBuf,
61 revision: git2::Oid,
63 repo: git2::Repository,
65}
66
67impl GitRemote {
68 pub fn new(url: &Url) -> GitRemote {
70 GitRemote {
71 url: url.as_str().to_owned(),
72 }
73 }
74
75 pub(super) fn new_from_str(url: String) -> GitRemote {
79 GitRemote { url }
80 }
81
82 pub fn url(&self) -> &str {
84 &self.url
85 }
86
87 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 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 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 #[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 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 pub fn to_short_id(&self, rev: git2::Oid) -> CargoResult<String> {
197 const MIN_ABBREV_LEN: usize = 7; let odb = self.repo.odb()?;
199 let mut len = MIN_ABBREV_LEN;
200 let mut hex = rev.to_string();
201 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 pub fn contains(&self, oid: git2::Oid) -> bool {
216 self.repo.revparse_single(&oid.to_string()).is_ok()
217 }
218
219 pub fn resolve(&self, r: &GitReference) -> CargoResult<git2::Oid> {
221 resolve_ref(r, &self.repo)
222 }
223}
224
225pub fn resolve_ref(gitref: &GitReference, repo: &git2::Repository) -> CargoResult<git2::Oid> {
227 let id = match gitref {
228 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 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 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 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 fn remote_url(&self) -> &str {
291 self.database.remote.url()
292 }
293
294 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 let git_config = git2::Config::new()?;
312
313 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(); let r = git2::build::RepoBuilder::new()
326 .clone_local(git2::build::CloneLocal::Local)
329 .with_checkout(checkout)
330 .fetch_options(fopts)
331 .clone(url.as_str(), into)?;
332 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 fn is_fresh(&self) -> bool {
356 match self.repo.revparse_single("HEAD") {
357 Ok(ref head) if head.id() == self.revision => {
358 self.path.join(CHECKOUT_READY_LOCK).exists()
360 }
361 _ => false,
362 }
363 }
364
365 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 git_config.set_bool("core.autocrlf", false)?;
387 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 fn update_submodules(&self, gctx: &GlobalContext, quiet: bool) -> CargoResult<()> {
404 return update_submodules(&self.repo, gctx, quiet, self.remote_url());
405
406 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 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 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 let Some(head) = child.head_id() else {
467 return Ok(());
468 };
469
470 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 let reference = GitReference::Rev(head.to_string());
493
494 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 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#[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
551fn 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
604fn 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
614pub(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#[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#[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 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 let mut refspecs = Vec::new();
695 let mut tags = false;
696 match locked_reference {
700 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 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 refspecs.push(format!("+{0}:{0}", rev));
736 } else {
737 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
779fn maybe_gc_repo(repo: &mut git2::Repository, gctx: &GlobalContext) -> CargoResult<()> {
797 let mut cmd = Command::new("git");
805 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 .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 reinitialize(repo)
836}
837
838fn 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
873pub(super) fn reinitialize(repo: &mut git2::Repository) -> CargoResult<()> {
876 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
898fn init(path: &Path, bare: bool) -> CargoResult<git2::Repository> {
900 let mut opts = git2::RepositoryInitOptions::new();
901 opts.external_template(false);
905 opts.bare(bare);
906 Ok(git2::Repository::init_opts(&path, &opts)?)
907}
908
909enum FastPathRev {
911 UpToDate,
914 NeedsFetch(Oid),
917 Indeterminate,
920}
921
922#[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 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 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 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 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 debug!("github fast path fetch {oid_to_fetch}");
1037 Ok(FastPathRev::NeedsFetch(oid_to_fetch))
1038 } else {
1039 debug!("github fast path bad response code {response_code}");
1043 Ok(FastPathRev::Indeterminate)
1044 }
1045}
1046
1047fn is_github(url: &Url) -> bool {
1049 url.host_str() == Some("github.com")
1050}
1051
1052pub(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 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
1131fn looks_like_commit_hash(rev: &str) -> bool {
1133 rev.len() >= 7 && rev.chars().all(|ch| ch.is_ascii_hexdigit())
1134}
1135
1136fn 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 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 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 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 assert_eq!(scp_to_ssh("not-a-url"), None);
1313 }
1314}
1315
1316pub(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}