1use std::fmt::Display;
5use std::path::{Path, PathBuf};
6use std::str::{self};
7use std::sync::LazyLock;
8
9use anyhow::{Context, Result, anyhow};
10use cargo_util::{ProcessBuilder, ProcessError, paths};
11use owo_colors::OwoColorize;
12use tracing::{debug, instrument, warn};
13use url::Url;
14
15use uv_fs::Simplified;
16use uv_git_types::{GitOid, GitReference};
17use uv_redacted::DisplaySafeUrl;
18use uv_static::EnvVars;
19use uv_warnings::warn_user_once;
20
21const CHECKOUT_READY_LOCK: &str = ".ok";
24
25#[derive(Debug, thiserror::Error)]
26pub enum GitError {
27 #[error("Git executable not found. Ensure that Git is installed and available.")]
28 GitNotFound,
29 #[error("Git LFS extension not found. Ensure that Git LFS is installed and available.")]
30 GitLfsNotFound,
31 #[error("Is Git LFS configured? Run `{}` to initialize Git LFS.", "git lfs install".green())]
32 GitLfsNotConfigured,
33 #[error(transparent)]
34 Other(#[from] which::Error),
35 #[error(
36 "Remote Git fetches are not allowed because network connectivity is disabled (i.e., with `--offline`)"
37 )]
38 TransportNotAllowed,
39}
40
41pub static GIT: LazyLock<Result<ProcessBuilder, GitError>> = LazyLock::new(|| {
46 let path = which::which("git").map_err(|err| match err {
47 which::Error::CannotFindBinaryPath => GitError::GitNotFound,
48 err => GitError::Other(err),
49 })?;
50
51 let mut cmd = ProcessBuilder::new(path);
52
53 cmd.env_remove(EnvVars::GIT_DIR)
60 .env_remove(EnvVars::GIT_WORK_TREE)
61 .env_remove(EnvVars::GIT_INDEX_FILE)
62 .env_remove(EnvVars::GIT_OBJECT_DIRECTORY)
63 .env_remove(EnvVars::GIT_ALTERNATE_OBJECT_DIRECTORIES)
64 .env_remove(EnvVars::GIT_COMMON_DIR);
65
66 Ok(cmd)
67});
68
69enum RefspecStrategy {
71 All,
73 First,
75}
76
77#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
79enum ReferenceOrOid<'reference> {
80 Reference(&'reference GitReference),
82 Oid(GitOid),
84}
85
86impl ReferenceOrOid<'_> {
87 fn resolve(&self, repo: &GitRepository) -> Result<GitOid> {
89 let refkind = self.kind_str();
90 let result = match self {
91 Self::Reference(GitReference::Tag(s)) => {
96 repo.rev_parse(&format!("refs/remotes/origin/tags/{s}^0"))
97 }
98
99 Self::Reference(GitReference::Branch(s)) => repo.rev_parse(&format!("origin/{s}^0")),
101
102 Self::Reference(GitReference::BranchOrTag(s)) => repo
104 .rev_parse(&format!("origin/{s}^0"))
105 .or_else(|_| repo.rev_parse(&format!("refs/remotes/origin/tags/{s}^0"))),
106
107 Self::Reference(GitReference::BranchOrTagOrCommit(s)) => repo
109 .rev_parse(&format!("origin/{s}^0"))
110 .or_else(|_| repo.rev_parse(&format!("refs/remotes/origin/tags/{s}^0")))
111 .or_else(|_| repo.rev_parse(&format!("{s}^0"))),
112
113 Self::Reference(GitReference::DefaultBranch) => {
115 repo.rev_parse("refs/remotes/origin/HEAD")
116 }
117
118 Self::Reference(GitReference::NamedRef(s)) => repo.rev_parse(&format!("{s}^0")),
120
121 Self::Oid(s) => repo.rev_parse(&format!("{s}^0")),
123 };
124
125 result.with_context(|| anyhow::format_err!("failed to find {refkind} `{self}`"))
126 }
127
128 fn kind_str(&self) -> &str {
130 match self {
131 Self::Reference(reference) => reference.kind_str(),
132 Self::Oid(_) => "commit",
133 }
134 }
135
136 fn as_rev(&self) -> &str {
138 match self {
139 Self::Reference(r) => r.as_rev(),
140 Self::Oid(rev) => rev.as_str(),
141 }
142 }
143}
144
145impl Display for ReferenceOrOid<'_> {
146 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147 match self {
148 Self::Reference(reference) => write!(f, "{reference}"),
149 Self::Oid(oid) => write!(f, "{oid}"),
150 }
151 }
152}
153
154#[derive(PartialEq, Clone, Debug)]
156pub(crate) struct GitRemote {
157 url: DisplaySafeUrl,
159}
160
161pub(crate) struct GitDatabase {
164 remote: GitRemote,
166 repo: GitRepository,
168 lfs_ready: Option<bool>,
170}
171
172pub(crate) struct GitCheckout {
174 revision: GitOid,
176 repo: GitRepository,
178 lfs_ready: Option<bool>,
180}
181
182pub(crate) struct GitRepository {
184 path: PathBuf,
186}
187
188impl GitRepository {
189 fn open(path: &Path) -> Result<Self> {
191 GIT.as_ref()
193 .cloned()?
194 .arg("rev-parse")
195 .cwd(path)
196 .exec_with_output()?;
197
198 Ok(Self {
199 path: path.to_path_buf(),
200 })
201 }
202
203 fn init(path: &Path) -> Result<Self> {
205 GIT.as_ref()
213 .cloned()?
214 .arg("init")
215 .cwd(path)
216 .exec_with_output()?;
217
218 Ok(Self {
219 path: path.to_path_buf(),
220 })
221 }
222
223 fn rev_parse(&self, refname: &str) -> Result<GitOid> {
225 let result = GIT
226 .as_ref()
227 .cloned()?
228 .arg("rev-parse")
229 .arg(refname)
230 .cwd(&self.path)
231 .exec_with_output()?;
232
233 let mut result = String::from_utf8(result.stdout)?;
234 result.truncate(result.trim_end().len());
235 Ok(result.parse()?)
236 }
237
238 #[instrument(skip_all, fields(path = %self.path.user_display(), refname = %refname))]
240 fn lfs_fsck_objects(&self, refname: &str) -> bool {
241 let mut cmd = if let Ok(lfs) = GIT_LFS.as_ref() {
242 lfs.clone()
243 } else {
244 warn!("Git LFS is not available, skipping LFS fetch");
245 return false;
246 };
247
248 let result = cmd
250 .arg("fsck")
251 .arg("--objects")
252 .arg(refname)
253 .cwd(&self.path)
254 .exec_with_output();
255
256 match result {
257 Ok(_) => true,
258 Err(err) => {
259 let lfs_error = err.to_string();
260 if lfs_error.contains("unknown flag: --objects") {
261 warn_user_once!(
262 "Skipping Git LFS validation as Git LFS extension is outdated. \
263 Upgrade to `git-lfs>=3.0.2` or manually verify git-lfs objects were \
264 properly fetched after the current operation finishes."
265 );
266 true
267 } else {
268 debug!("Git LFS validation failed: {err}");
269 false
270 }
271 }
272 }
273 }
274}
275
276impl GitRemote {
277 pub(crate) fn new(url: DisplaySafeUrl) -> Self {
279 Self { url }
280 }
281
282 pub(crate) fn url(&self) -> &DisplaySafeUrl {
284 &self.url
285 }
286
287 pub(crate) fn checkout(
300 self,
301 into: &Path,
302 db: Option<GitDatabase>,
303 reference: &GitReference,
304 locked_rev: Option<GitOid>,
305 disable_ssl: bool,
306 offline: bool,
307 with_lfs: bool,
308 ) -> Result<(GitDatabase, GitOid)> {
309 let reference = locked_rev
310 .map(ReferenceOrOid::Oid)
311 .unwrap_or(ReferenceOrOid::Reference(reference));
312 if let Some(mut db) = db {
313 fetch(&mut db.repo, &self.url, reference, disable_ssl, offline)
314 .with_context(|| format!("failed to fetch into: {}", into.user_display()))?;
315
316 let resolved_commit_hash = match locked_rev {
317 Some(rev) => db.contains(rev).then_some(rev),
318 None => reference.resolve(&db.repo).ok(),
319 };
320
321 if let Some(rev) = resolved_commit_hash {
322 if with_lfs {
323 let lfs_ready = fetch_lfs(&mut db.repo, &self.url, &rev, disable_ssl)
324 .with_context(|| format!("failed to fetch LFS objects at {rev}"))?;
325 db = db.with_lfs_ready(Some(lfs_ready));
326 }
327 return Ok((db, rev));
328 }
329 }
330
331 match fs_err::remove_dir_all(into) {
335 Ok(()) => {}
336 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
337 Err(e) => return Err(e.into()),
338 }
339
340 fs_err::create_dir_all(into)?;
341 let mut repo = GitRepository::init(into)?;
342 fetch(&mut repo, &self.url, reference, disable_ssl, offline)
343 .with_context(|| format!("failed to clone into: {}", into.user_display()))?;
344 let rev = match locked_rev {
345 Some(rev) => rev,
346 None => reference.resolve(&repo)?,
347 };
348 let lfs_ready = with_lfs
349 .then(|| {
350 fetch_lfs(&mut repo, &self.url, &rev, disable_ssl)
351 .with_context(|| format!("failed to fetch LFS objects at {rev}"))
352 })
353 .transpose()?;
354
355 Ok((
356 GitDatabase {
357 remote: self,
358 repo,
359 lfs_ready,
360 },
361 rev,
362 ))
363 }
364
365 pub(crate) fn db_at(&self, db_path: &Path) -> Result<GitDatabase> {
367 let repo = GitRepository::open(db_path)?;
368 Ok(GitDatabase {
369 remote: self.clone(),
370 repo,
371 lfs_ready: None,
372 })
373 }
374}
375
376impl GitDatabase {
377 pub(crate) fn copy_to(&self, rev: GitOid, destination: &Path) -> Result<GitCheckout> {
379 let checkout = match GitRepository::open(destination)
384 .ok()
385 .map(|repo| GitCheckout::new(rev, repo))
386 .filter(GitCheckout::is_fresh)
387 {
388 Some(co) => co.with_lfs_ready(self.lfs_ready),
389 None => GitCheckout::clone_into(destination, self, rev, self.remote.url())?,
390 };
391 Ok(checkout)
392 }
393
394 pub(crate) fn to_short_id(&self, revision: GitOid) -> Result<String> {
396 let output = GIT
397 .as_ref()
398 .cloned()?
399 .arg("rev-parse")
400 .arg("--short")
401 .arg(revision.as_str())
402 .cwd(&self.repo.path)
403 .exec_with_output()?;
404
405 let mut result = String::from_utf8(output.stdout)?;
406 result.truncate(result.trim_end().len());
407 Ok(result)
408 }
409
410 pub(crate) fn contains(&self, oid: GitOid) -> bool {
412 self.repo.rev_parse(&format!("{oid}^0")).is_ok()
413 }
414
415 pub(crate) fn contains_lfs_artifacts(&self, oid: GitOid) -> bool {
417 self.repo.lfs_fsck_objects(&format!("{oid}^0"))
418 }
419
420 #[must_use]
422 pub(crate) fn with_lfs_ready(mut self, lfs: Option<bool>) -> Self {
423 self.lfs_ready = lfs;
424 self
425 }
426}
427
428impl GitCheckout {
429 fn new(revision: GitOid, repo: GitRepository) -> Self {
434 Self {
435 revision,
436 repo,
437 lfs_ready: None,
438 }
439 }
440
441 fn clone_into(
444 into: &Path,
445 database: &GitDatabase,
446 revision: GitOid,
447 original_remote_url: &DisplaySafeUrl,
448 ) -> Result<Self> {
449 let dirname = into.parent().unwrap();
450 fs_err::create_dir_all(dirname)?;
451 match fs_err::remove_dir_all(into) {
452 Ok(()) => {}
453 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
454 Err(e) => return Err(e.into()),
455 }
456
457 let res = GIT
461 .as_ref()
462 .cloned()?
463 .arg("clone")
464 .arg("--local")
465 .arg(database.repo.path.simplified_display().to_string())
469 .arg(into.simplified_display().to_string())
470 .exec_with_output();
471
472 if let Err(e) = res {
473 debug!("Cloning git repo with --local failed, retrying without hardlinks: {e}");
474
475 GIT.as_ref()
476 .cloned()?
477 .arg("clone")
478 .arg("--no-hardlinks")
479 .arg(database.repo.path.simplified_display().to_string())
480 .arg(into.simplified_display().to_string())
481 .exec_with_output()?;
482 }
483
484 let repo = GitRepository::open(into)?;
485 let checkout = Self::new(revision, repo);
486 let lfs_ready = checkout.reset(database.lfs_ready, original_remote_url)?;
487 Ok(checkout.with_lfs_ready(lfs_ready))
488 }
489
490 fn is_fresh(&self) -> bool {
492 match self.repo.rev_parse("HEAD") {
493 Ok(id) if id == self.revision => {
494 self.repo.path.join(CHECKOUT_READY_LOCK).exists()
496 }
497 _ => false,
498 }
499 }
500
501 pub(crate) fn lfs_ready(&self) -> Option<bool> {
503 self.lfs_ready
504 }
505
506 #[must_use]
508 fn with_lfs_ready(mut self, lfs: Option<bool>) -> Self {
509 self.lfs_ready = lfs;
510 self
511 }
512
513 fn reset(
529 &self,
530 with_lfs: Option<bool>,
531 original_remote_url: &DisplaySafeUrl,
532 ) -> Result<Option<bool>> {
533 let ok_file = self.repo.path.join(CHECKOUT_READY_LOCK);
534 let _ = paths::remove_file(&ok_file);
535
536 let lfs_skip_smudge = if with_lfs == Some(true) { "0" } else { "1" };
540
541 debug!("Reset {} to {}", self.repo.path.display(), self.revision);
542
543 GIT.as_ref()
545 .cloned()?
546 .arg("reset")
547 .arg("--hard")
548 .arg(self.revision.as_str())
549 .env(EnvVars::GIT_LFS_SKIP_SMUDGE, lfs_skip_smudge)
550 .cwd(&self.repo.path)
551 .exec_with_output()?;
552
553 let mut submodule_update = GIT.as_ref().cloned()?;
562 for config in submodule_update_config(original_remote_url) {
563 submodule_update.arg("-c").arg(config);
564 }
565
566 submodule_update
567 .arg("submodule")
568 .arg("update")
569 .arg("--init")
570 .env(EnvVars::GIT_LFS_SKIP_SMUDGE, lfs_skip_smudge)
571 .cwd(&self.repo.path)
572 .exec_with_output()
573 .map_err(|err| redact_git_error(err, original_remote_url))
574 .map(drop)?;
575
576 let mut submodule_update = GIT.as_ref().cloned()?;
580 for config in submodule_auth_config(original_remote_url) {
581 submodule_update.arg("-c").arg(config);
582 }
583
584 submodule_update
585 .arg("submodule")
586 .arg("update")
587 .arg("--recursive")
588 .arg("--init")
589 .env(EnvVars::GIT_LFS_SKIP_SMUDGE, lfs_skip_smudge)
590 .cwd(&self.repo.path)
591 .exec_with_output()
592 .map_err(|err| redact_git_error(err, original_remote_url))
593 .map(drop)?;
594
595 let lfs_validation = match with_lfs {
598 None => None,
599 Some(false) => Some(false),
600 Some(true) => Some(self.repo.lfs_fsck_objects(self.revision.as_str())),
601 };
602
603 if with_lfs.is_none() || lfs_validation == Some(true) {
607 paths::create(ok_file)?;
608 }
609
610 Ok(lfs_validation)
611 }
612}
613
614fn submodule_update_config(original_remote_url: &DisplaySafeUrl) -> Vec<String> {
622 let remote_url = original_remote_url.without_credentials();
623 let mut config = vec![format!("remote.origin.url={}", remote_url.as_str())];
624
625 config.extend(submodule_auth_config(original_remote_url));
626 config
627}
628
629fn submodule_auth_config(original_remote_url: &DisplaySafeUrl) -> Vec<String> {
635 let remote_url = original_remote_url.without_credentials();
636 let mut config = Vec::new();
637
638 if remote_url.as_str() != original_remote_url.as_str() {
639 let safe_root = remote_url_root(remote_url.into_owned());
640 let credentialed_root = remote_url_root((**original_remote_url).clone());
641
642 if safe_root.as_str() != credentialed_root.as_str() {
643 config.push(format!(
644 "url.{}.insteadOf={}",
645 credentialed_root.as_str(),
646 safe_root.as_str()
647 ));
648 }
649 }
650
651 config
652}
653
654fn remote_url_root(mut url: Url) -> Url {
660 url.set_path("/");
661 url.set_query(None);
662 url.set_fragment(None);
663 url
664}
665
666fn fetch(
675 repo: &mut GitRepository,
676 remote_url: &DisplaySafeUrl,
677 reference: ReferenceOrOid<'_>,
678 disable_ssl: bool,
679 offline: bool,
680) -> Result<()> {
681 let oid_to_fetch = if let ReferenceOrOid::Oid(rev) = reference {
682 let local_object = reference.resolve(repo).ok();
683 if let Some(local_object) = local_object {
684 if rev == local_object {
685 return Ok(());
686 }
687 }
688
689 Some(rev)
692 } else {
693 None
694 };
695
696 let mut refspecs = Vec::new();
699 let mut tags = false;
700 let mut refspec_strategy = RefspecStrategy::All;
701 match reference {
705 ReferenceOrOid::Reference(GitReference::Branch(branch)) => {
708 refspecs.push(format!("+refs/heads/{branch}:refs/remotes/origin/{branch}"));
709 }
710
711 ReferenceOrOid::Reference(GitReference::Tag(tag)) => {
712 refspecs.push(format!("+refs/tags/{tag}:refs/remotes/origin/tags/{tag}"));
713 }
714
715 ReferenceOrOid::Reference(GitReference::BranchOrTag(branch_or_tag)) => {
716 refspecs.push(format!(
717 "+refs/heads/{branch_or_tag}:refs/remotes/origin/{branch_or_tag}"
718 ));
719 refspecs.push(format!(
720 "+refs/tags/{branch_or_tag}:refs/remotes/origin/tags/{branch_or_tag}"
721 ));
722 refspec_strategy = RefspecStrategy::First;
723 }
724
725 ReferenceOrOid::Reference(GitReference::BranchOrTagOrCommit(branch_or_tag_or_commit)) => {
728 if let Some(oid_to_fetch) =
732 oid_to_fetch.filter(|oid| is_short_hash_of(branch_or_tag_or_commit, *oid))
733 {
734 refspecs.push(format!("+{oid_to_fetch}:refs/commit/{oid_to_fetch}"));
735 } else {
736 refspecs.push(String::from("+refs/heads/*:refs/remotes/origin/*"));
740 refspecs.push(String::from("+HEAD:refs/remotes/origin/HEAD"));
741 tags = true;
742 }
743 }
744
745 ReferenceOrOid::Reference(GitReference::DefaultBranch) => {
746 refspecs.push(String::from("+HEAD:refs/remotes/origin/HEAD"));
747 }
748
749 ReferenceOrOid::Reference(GitReference::NamedRef(rev)) => {
750 refspecs.push(format!("+{rev}:{rev}"));
751 }
752
753 ReferenceOrOid::Oid(rev) => {
754 refspecs.push(format!("+{rev}:refs/commit/{rev}"));
755 }
756 }
757
758 debug!("Performing a Git fetch for: {remote_url}");
759 let result = match refspec_strategy {
760 RefspecStrategy::All => fetch_with_cli(
761 repo,
762 remote_url,
763 refspecs.as_slice(),
764 tags,
765 disable_ssl,
766 offline,
767 ),
768 RefspecStrategy::First => {
769 let mut errors = refspecs
771 .iter()
772 .map_while(|refspec| {
773 let fetch_result = fetch_with_cli(
774 repo,
775 remote_url,
776 std::slice::from_ref(refspec),
777 tags,
778 disable_ssl,
779 offline,
780 );
781
782 match fetch_result {
784 Err(ref err) => {
785 debug!("Failed to fetch refspec `{refspec}`: {err}");
786 Some(fetch_result)
787 }
788 Ok(()) => None,
789 }
790 })
791 .collect::<Vec<_>>();
792
793 if errors.len() == refspecs.len() {
794 if let Some(result) = errors.pop() {
795 result
797 } else {
798 Ok(())
800 }
801 } else {
802 Ok(())
803 }
804 }
805 };
806 match reference {
807 ReferenceOrOid::Reference(GitReference::DefaultBranch) => result,
809 _ => result.with_context(|| {
810 format!(
811 "failed to fetch {} `{}`",
812 reference.kind_str(),
813 reference.as_rev()
814 )
815 }),
816 }
817}
818
819fn fetch_with_cli(
821 repo: &mut GitRepository,
822 url: &DisplaySafeUrl,
823 refspecs: &[String],
824 tags: bool,
825 disable_ssl: bool,
826 offline: bool,
827) -> Result<()> {
828 let mut cmd = GIT.as_ref().cloned()?;
829 cmd.env(EnvVars::GIT_TERMINAL_PROMPT, "0");
833
834 cmd.arg("fetch");
835 if tags {
836 cmd.arg("--tags");
837 }
838 if disable_ssl {
839 debug!("Disabling SSL verification for Git fetch via `GIT_SSL_NO_VERIFY`");
840 cmd.env(EnvVars::GIT_SSL_NO_VERIFY, "true");
841 }
842 if offline {
843 debug!("Disabling remote protocols for Git fetch via `GIT_ALLOW_PROTOCOL=file`");
844 cmd.env(EnvVars::GIT_ALLOW_PROTOCOL, "file");
845 }
846 cmd.arg("--force") .arg("--update-head-ok") .arg(url.as_str())
849 .args(refspecs)
850 .cwd(&repo.path);
851
852 cmd.exec_with_output().map_err(|err| {
856 let msg = err.to_string();
857 if msg.contains("transport '") && msg.contains("' not allowed") && offline {
858 return GitError::TransportNotAllowed.into();
859 }
860 redact_git_error(err, url)
861 })?;
862
863 Ok(())
864}
865
866pub static GIT_LFS: LazyLock<Result<ProcessBuilder>> = LazyLock::new(|| {
877 if std::env::var_os(EnvVars::UV_INTERNAL__TEST_LFS_DISABLED).is_some() {
878 return Err(anyhow!("Git LFS extension has been forcefully disabled."));
879 }
880
881 let mut cmd = GIT.as_ref()?.clone();
882 cmd.arg("lfs");
883
884 cmd.clone().arg("version").exec_with_output()?;
886 Ok(cmd)
887});
888
889fn fetch_lfs(
891 repo: &mut GitRepository,
892 url: &DisplaySafeUrl,
893 revision: &GitOid,
894 disable_ssl: bool,
895) -> Result<bool> {
896 let mut cmd = if let Ok(lfs) = GIT_LFS.as_ref() {
897 debug!("Fetching Git LFS objects");
898 lfs.clone()
899 } else {
900 warn!("Git LFS is not available, skipping LFS fetch");
902 return Ok(false);
903 };
904
905 if disable_ssl {
906 debug!("Disabling SSL verification for Git LFS");
907 cmd.env(EnvVars::GIT_SSL_NO_VERIFY, "true");
908 }
909
910 cmd.arg("fetch")
911 .arg(url.as_str())
912 .arg(revision.as_str())
913 .env_remove(EnvVars::GIT_LFS_SKIP_SMUDGE)
916 .cwd(&repo.path);
917
918 cmd.exec_with_output()
919 .map_err(|err| redact_git_error(err, url))?;
920
921 let validation_result = repo.lfs_fsck_objects(revision.as_str());
929
930 Ok(validation_result)
931}
932
933fn redact_git_error(mut error: anyhow::Error, url: &DisplaySafeUrl) -> anyhow::Error {
935 let credentialed_root = DisplaySafeUrl::from_url(remote_url_root((**url).clone()));
936 let redact = |message: &str| credentialed_root.redact_in(&url.redact_in(message));
937
938 if let Some(process_error) = error.downcast_mut::<ProcessError>() {
939 process_error.desc = redact(&process_error.desc);
940 return error;
941 }
942
943 anyhow!("{}", redact(&error.to_string()))
944}
945
946fn is_short_hash_of(rev: &str, oid: GitOid) -> bool {
948 let long_hash = oid.to_string();
949 match long_hash.get(..rev.len()) {
950 Some(truncated_long_hash) => truncated_long_hash.eq_ignore_ascii_case(rev),
951 None => false,
952 }
953}
954
955#[cfg(test)]
956mod tests {
957 use super::*;
958
959 #[test]
960 fn submodule_update_config_strips_credentials_from_origin_override() {
961 let url = DisplaySafeUrl::parse("https://user:password@example.com/org/repo.git").unwrap();
962
963 assert_eq!(
964 submodule_update_config(&url),
965 vec![
966 "remote.origin.url=https://example.com/org/repo.git".to_string(),
967 "url.https://user:password@example.com/.insteadOf=https://example.com/".to_string(),
968 ]
969 );
970 }
971
972 #[test]
973 fn submodule_update_config_preserves_git_ssh_user() {
974 let url = DisplaySafeUrl::parse("ssh://git@example.com/org/repo.git").unwrap();
975
976 assert_eq!(
977 submodule_update_config(&url),
978 vec!["remote.origin.url=ssh://git@example.com/org/repo.git".to_string()]
979 );
980 }
981
982 #[test]
983 fn git_process_error_redacts_credentials() -> Result<()> {
984 let url = DisplaySafeUrl::parse("https://git:secret-token@example.com/org/repo.git")?;
985 let stderr = format!("fatal: Authentication failed for '{}'", url.as_str());
986 let error = ProcessError::new_raw(
987 &format!(
988 "process didn't exit successfully: `git fetch --force '{}' '+HEAD:refs/remotes/origin/HEAD'`",
989 url.as_str()
990 ),
991 Some(128),
992 "exit status: 128",
993 Some(b"git output"),
994 Some(stderr.as_bytes()),
995 )
996 .into();
997
998 let error = redact_git_error(error, &url);
999 let process_error = error
1000 .downcast_ref::<ProcessError>()
1001 .context("expected Git process error")?;
1002
1003 assert_eq!(
1004 error.to_string(),
1005 "process didn't exit successfully: `git fetch --force 'https://git:****@example.com/org/repo.git' '+HEAD:refs/remotes/origin/HEAD'` (exit status: 128)\n--- stdout\ngit output\n--- stderr\nfatal: Authentication failed for 'https://git:****@example.com/org/repo.git'"
1006 );
1007 assert_eq!(process_error.code, Some(128));
1008 assert_eq!(
1009 process_error.stdout.as_deref(),
1010 Some(b"git output".as_slice())
1011 );
1012 assert_eq!(process_error.stderr.as_deref(), Some(stderr.as_bytes()));
1013
1014 Ok(())
1015 }
1016
1017 #[test]
1018 fn git_submodule_process_error_redacts_credentials() -> Result<()> {
1019 let url = DisplaySafeUrl::parse("https://git:secret-token@example.com/org/repo.git")?;
1020
1021 for args in ["--init", "--recursive --init"] {
1022 let error = anyhow!(
1023 "process didn't exit successfully: `git -c 'url.https://git:secret-token@example.com/.insteadOf=https://example.com/' submodule update {args}` (exit status: 128)"
1024 );
1025 let redacted = redact_git_error(error, &url).to_string();
1026
1027 assert!(!redacted.contains("secret-token"));
1028 assert_eq!(
1029 redacted,
1030 format!(
1031 "process didn't exit successfully: `git -c 'url.https://git:****@example.com/.insteadOf=https://example.com/' submodule update {args}` (exit status: 128)"
1032 )
1033 );
1034 }
1035
1036 Ok(())
1037 }
1038}