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 .or_else(|| {
311 if let GitReference::BranchOrTagOrCommit(revision) = reference {
312 revision.parse::<GitOid>().ok()
313 } else {
314 None
315 }
316 })
317 .map(ReferenceOrOid::Oid)
318 .unwrap_or(ReferenceOrOid::Reference(reference));
319 if let Some(mut db) = db {
320 fetch(&mut db.repo, &self.url, reference, disable_ssl, offline)
321 .with_context(|| format!("failed to fetch into: {}", into.user_display()))?;
322
323 let resolved_commit_hash = match locked_rev {
324 Some(rev) => db.contains(rev).then_some(rev),
325 None => reference.resolve(&db.repo).ok(),
326 };
327
328 if let Some(rev) = resolved_commit_hash {
329 if with_lfs {
330 let lfs_ready = fetch_lfs(&mut db.repo, &self.url, &rev, disable_ssl)
331 .with_context(|| format!("failed to fetch LFS objects at {rev}"))?;
332 db = db.with_lfs_ready(Some(lfs_ready));
333 }
334 return Ok((db, rev));
335 }
336 }
337
338 match fs_err::remove_dir_all(into) {
342 Ok(()) => {}
343 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
344 Err(e) => return Err(e.into()),
345 }
346
347 fs_err::create_dir_all(into)?;
348 let mut repo = GitRepository::init(into)?;
349 fetch(&mut repo, &self.url, reference, disable_ssl, offline)
350 .with_context(|| format!("failed to clone into: {}", into.user_display()))?;
351 let rev = match locked_rev {
352 Some(rev) => rev,
353 None => reference.resolve(&repo)?,
354 };
355 let lfs_ready = with_lfs
356 .then(|| {
357 fetch_lfs(&mut repo, &self.url, &rev, disable_ssl)
358 .with_context(|| format!("failed to fetch LFS objects at {rev}"))
359 })
360 .transpose()?;
361
362 Ok((
363 GitDatabase {
364 remote: self,
365 repo,
366 lfs_ready,
367 },
368 rev,
369 ))
370 }
371
372 pub(crate) fn db_at(&self, db_path: &Path) -> Result<GitDatabase> {
374 let repo = GitRepository::open(db_path)?;
375 Ok(GitDatabase {
376 remote: self.clone(),
377 repo,
378 lfs_ready: None,
379 })
380 }
381}
382
383impl GitDatabase {
384 pub(crate) fn copy_to(&self, rev: GitOid, destination: &Path) -> Result<GitCheckout> {
386 let checkout = match GitRepository::open(destination)
391 .ok()
392 .map(|repo| GitCheckout::new(rev, repo))
393 .filter(GitCheckout::is_fresh)
394 {
395 Some(co) => co.with_lfs_ready(self.lfs_ready),
396 None => GitCheckout::clone_into(destination, self, rev, self.remote.url())?,
397 };
398 Ok(checkout)
399 }
400
401 pub(crate) fn to_short_id(&self, revision: GitOid) -> Result<String> {
403 let output = GIT
404 .as_ref()
405 .cloned()?
406 .arg("rev-parse")
407 .arg("--short")
408 .arg(revision.as_str())
409 .cwd(&self.repo.path)
410 .exec_with_output()?;
411
412 let mut result = String::from_utf8(output.stdout)?;
413 result.truncate(result.trim_end().len());
414 Ok(result)
415 }
416
417 pub(crate) fn contains(&self, oid: GitOid) -> bool {
419 self.repo.rev_parse(&format!("{oid}^0")).is_ok()
420 }
421
422 pub(crate) fn contains_lfs_artifacts(&self, oid: GitOid) -> bool {
424 self.repo.lfs_fsck_objects(&format!("{oid}^0"))
425 }
426
427 #[must_use]
429 pub(crate) fn with_lfs_ready(mut self, lfs: Option<bool>) -> Self {
430 self.lfs_ready = lfs;
431 self
432 }
433}
434
435impl GitCheckout {
436 fn new(revision: GitOid, repo: GitRepository) -> Self {
441 Self {
442 revision,
443 repo,
444 lfs_ready: None,
445 }
446 }
447
448 fn clone_into(
451 into: &Path,
452 database: &GitDatabase,
453 revision: GitOid,
454 original_remote_url: &DisplaySafeUrl,
455 ) -> Result<Self> {
456 let dirname = into.parent().unwrap();
457 fs_err::create_dir_all(dirname)?;
458 match fs_err::remove_dir_all(into) {
459 Ok(()) => {}
460 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
461 Err(e) => return Err(e.into()),
462 }
463
464 let res = GIT
468 .as_ref()
469 .cloned()?
470 .arg("clone")
471 .arg("--local")
472 .arg(database.repo.path.simplified_display().to_string())
476 .arg(into.simplified_display().to_string())
477 .exec_with_output();
478
479 if let Err(e) = res {
480 debug!("Cloning git repo with --local failed, retrying without hardlinks: {e}");
481
482 GIT.as_ref()
483 .cloned()?
484 .arg("clone")
485 .arg("--no-hardlinks")
486 .arg(database.repo.path.simplified_display().to_string())
487 .arg(into.simplified_display().to_string())
488 .exec_with_output()?;
489 }
490
491 let repo = GitRepository::open(into)?;
492 let checkout = Self::new(revision, repo);
493 let lfs_ready = checkout.reset(database.lfs_ready, original_remote_url)?;
494 Ok(checkout.with_lfs_ready(lfs_ready))
495 }
496
497 fn is_fresh(&self) -> bool {
499 match self.repo.rev_parse("HEAD") {
500 Ok(id) if id == self.revision => {
501 self.repo.path.join(CHECKOUT_READY_LOCK).exists()
503 }
504 _ => false,
505 }
506 }
507
508 pub(crate) fn lfs_ready(&self) -> Option<bool> {
510 self.lfs_ready
511 }
512
513 #[must_use]
515 fn with_lfs_ready(mut self, lfs: Option<bool>) -> Self {
516 self.lfs_ready = lfs;
517 self
518 }
519
520 fn reset(
536 &self,
537 with_lfs: Option<bool>,
538 original_remote_url: &DisplaySafeUrl,
539 ) -> Result<Option<bool>> {
540 let ok_file = self.repo.path.join(CHECKOUT_READY_LOCK);
541 let _ = paths::remove_file(&ok_file);
542
543 let lfs_skip_smudge = if with_lfs == Some(true) { "0" } else { "1" };
547
548 debug!("Reset {} to {}", self.repo.path.display(), self.revision);
549
550 GIT.as_ref()
552 .cloned()?
553 .arg("reset")
554 .arg("--hard")
555 .arg(self.revision.as_str())
556 .env(EnvVars::GIT_LFS_SKIP_SMUDGE, lfs_skip_smudge)
557 .cwd(&self.repo.path)
558 .exec_with_output()?;
559
560 let mut submodule_update = GIT.as_ref().cloned()?;
569 for config in submodule_update_config(original_remote_url) {
570 submodule_update.arg("-c").arg(config);
571 }
572
573 submodule_update
574 .arg("submodule")
575 .arg("update")
576 .arg("--init")
577 .env(EnvVars::GIT_LFS_SKIP_SMUDGE, lfs_skip_smudge)
578 .cwd(&self.repo.path)
579 .exec_with_output()
580 .map_err(|err| redact_git_error(err, original_remote_url))
581 .map(drop)?;
582
583 let mut submodule_update = GIT.as_ref().cloned()?;
587 for config in submodule_auth_config(original_remote_url) {
588 submodule_update.arg("-c").arg(config);
589 }
590
591 submodule_update
592 .arg("submodule")
593 .arg("update")
594 .arg("--recursive")
595 .arg("--init")
596 .env(EnvVars::GIT_LFS_SKIP_SMUDGE, lfs_skip_smudge)
597 .cwd(&self.repo.path)
598 .exec_with_output()
599 .map_err(|err| redact_git_error(err, original_remote_url))
600 .map(drop)?;
601
602 let lfs_validation = match with_lfs {
605 None => None,
606 Some(false) => Some(false),
607 Some(true) => Some(self.repo.lfs_fsck_objects(self.revision.as_str())),
608 };
609
610 if with_lfs.is_none() || lfs_validation == Some(true) {
614 paths::create(ok_file)?;
615 }
616
617 Ok(lfs_validation)
618 }
619}
620
621fn submodule_update_config(original_remote_url: &DisplaySafeUrl) -> Vec<String> {
629 let remote_url = original_remote_url.without_credentials();
630 let mut config = vec![format!("remote.origin.url={}", remote_url.as_str())];
631
632 config.extend(submodule_auth_config(original_remote_url));
633 config
634}
635
636fn submodule_auth_config(original_remote_url: &DisplaySafeUrl) -> Vec<String> {
642 let remote_url = original_remote_url.without_credentials();
643 let mut config = Vec::new();
644
645 if remote_url.as_str() != original_remote_url.as_str() {
646 let safe_root = remote_url_root(remote_url.into_owned());
647 let credentialed_root = remote_url_root((**original_remote_url).clone());
648
649 if safe_root.as_str() != credentialed_root.as_str() {
650 config.push(format!(
651 "url.{}.insteadOf={}",
652 credentialed_root.as_str(),
653 safe_root.as_str()
654 ));
655 }
656 }
657
658 config
659}
660
661fn remote_url_root(mut url: Url) -> Url {
667 url.set_path("/");
668 url.set_query(None);
669 url.set_fragment(None);
670 url
671}
672
673fn fetch(
682 repo: &mut GitRepository,
683 remote_url: &DisplaySafeUrl,
684 reference: ReferenceOrOid<'_>,
685 disable_ssl: bool,
686 offline: bool,
687) -> Result<()> {
688 if let ReferenceOrOid::Oid(rev) = reference {
689 let local_object = reference.resolve(repo).ok();
690 if let Some(local_object) = local_object {
691 if rev == local_object {
692 return Ok(());
693 }
694 }
695 }
696
697 let mut refspecs = Vec::new();
700 let mut tags = false;
701 let mut refspec_strategy = RefspecStrategy::All;
702 match reference {
706 ReferenceOrOid::Reference(GitReference::Branch(branch)) => {
709 refspecs.push(format!("+refs/heads/{branch}:refs/remotes/origin/{branch}"));
710 }
711
712 ReferenceOrOid::Reference(GitReference::Tag(tag)) => {
713 refspecs.push(format!("+refs/tags/{tag}:refs/remotes/origin/tags/{tag}"));
714 }
715
716 ReferenceOrOid::Reference(GitReference::BranchOrTag(branch_or_tag)) => {
717 refspecs.push(format!(
718 "+refs/heads/{branch_or_tag}:refs/remotes/origin/{branch_or_tag}"
719 ));
720 refspecs.push(format!(
721 "+refs/tags/{branch_or_tag}:refs/remotes/origin/tags/{branch_or_tag}"
722 ));
723 refspec_strategy = RefspecStrategy::First;
724 }
725
726 ReferenceOrOid::Reference(GitReference::BranchOrTagOrCommit(_)) => {
729 refspecs.push(String::from("+refs/heads/*:refs/remotes/origin/*"));
730 refspecs.push(String::from("+HEAD:refs/remotes/origin/HEAD"));
731 tags = true;
732 }
733
734 ReferenceOrOid::Reference(GitReference::DefaultBranch) => {
735 refspecs.push(String::from("+HEAD:refs/remotes/origin/HEAD"));
736 }
737
738 ReferenceOrOid::Reference(GitReference::NamedRef(rev)) => {
739 refspecs.push(format!("+{rev}:{rev}"));
740 }
741
742 ReferenceOrOid::Oid(rev) => {
743 refspecs.push(format!("+{rev}:refs/commit/{rev}"));
744 }
745 }
746
747 debug!("Performing a Git fetch for: {remote_url}");
748 let result = match refspec_strategy {
749 RefspecStrategy::All => fetch_with_cli(
750 repo,
751 remote_url,
752 refspecs.as_slice(),
753 tags,
754 disable_ssl,
755 offline,
756 ),
757 RefspecStrategy::First => {
758 let mut errors = refspecs
760 .iter()
761 .map_while(|refspec| {
762 let fetch_result = fetch_with_cli(
763 repo,
764 remote_url,
765 std::slice::from_ref(refspec),
766 tags,
767 disable_ssl,
768 offline,
769 );
770
771 match fetch_result {
773 Err(ref err) => {
774 debug!("Failed to fetch refspec `{refspec}`: {err}");
775 Some(fetch_result)
776 }
777 Ok(()) => None,
778 }
779 })
780 .collect::<Vec<_>>();
781
782 if errors.len() == refspecs.len() {
783 if let Some(result) = errors.pop() {
784 result
786 } else {
787 Ok(())
789 }
790 } else {
791 Ok(())
792 }
793 }
794 };
795 match reference {
796 ReferenceOrOid::Reference(GitReference::DefaultBranch) => result,
798 _ => result.with_context(|| {
799 format!(
800 "failed to fetch {} `{}`",
801 reference.kind_str(),
802 reference.as_rev()
803 )
804 }),
805 }
806}
807
808fn fetch_with_cli(
810 repo: &mut GitRepository,
811 url: &DisplaySafeUrl,
812 refspecs: &[String],
813 tags: bool,
814 disable_ssl: bool,
815 offline: bool,
816) -> Result<()> {
817 let mut cmd = GIT.as_ref().cloned()?;
818 cmd.env(EnvVars::GIT_TERMINAL_PROMPT, "0");
822
823 cmd.arg("fetch");
824 if tags {
825 cmd.arg("--tags");
826 }
827 if disable_ssl {
828 debug!("Disabling SSL verification for Git fetch via `GIT_SSL_NO_VERIFY`");
829 cmd.env(EnvVars::GIT_SSL_NO_VERIFY, "true");
830 }
831 if offline {
832 debug!("Disabling remote protocols for Git fetch via `GIT_ALLOW_PROTOCOL=file`");
833 cmd.env(EnvVars::GIT_ALLOW_PROTOCOL, "file");
834 }
835 cmd.arg("--force") .arg("--update-head-ok") .arg(url.as_str())
838 .args(refspecs)
839 .cwd(&repo.path);
840
841 cmd.exec_with_output().map_err(|err| {
845 let msg = err.to_string();
846 if msg.contains("transport '") && msg.contains("' not allowed") && offline {
847 return GitError::TransportNotAllowed.into();
848 }
849 redact_git_error(err, url)
850 })?;
851
852 Ok(())
853}
854
855pub static GIT_LFS: LazyLock<Result<ProcessBuilder>> = LazyLock::new(|| {
866 if std::env::var_os(EnvVars::UV_INTERNAL__TEST_LFS_DISABLED).is_some() {
867 return Err(anyhow!("Git LFS extension has been forcefully disabled."));
868 }
869
870 let mut cmd = GIT.as_ref()?.clone();
871 cmd.arg("lfs");
872
873 cmd.clone().arg("version").exec_with_output()?;
875 Ok(cmd)
876});
877
878fn fetch_lfs(
880 repo: &mut GitRepository,
881 url: &DisplaySafeUrl,
882 revision: &GitOid,
883 disable_ssl: bool,
884) -> Result<bool> {
885 let mut cmd = if let Ok(lfs) = GIT_LFS.as_ref() {
886 debug!("Fetching Git LFS objects");
887 lfs.clone()
888 } else {
889 warn!("Git LFS is not available, skipping LFS fetch");
891 return Ok(false);
892 };
893
894 if disable_ssl {
895 debug!("Disabling SSL verification for Git LFS");
896 cmd.env(EnvVars::GIT_SSL_NO_VERIFY, "true");
897 }
898
899 cmd.arg("fetch")
900 .arg(url.as_str())
901 .arg(revision.as_str())
902 .env_remove(EnvVars::GIT_LFS_SKIP_SMUDGE)
905 .cwd(&repo.path);
906
907 cmd.exec_with_output()
908 .map_err(|err| redact_git_error(err, url))?;
909
910 let validation_result = repo.lfs_fsck_objects(revision.as_str());
918
919 Ok(validation_result)
920}
921
922fn redact_git_error(mut error: anyhow::Error, url: &DisplaySafeUrl) -> anyhow::Error {
924 let credentialed_root = DisplaySafeUrl::from_url(remote_url_root((**url).clone()));
925 let redact = |message: &str| credentialed_root.redact_in(&url.redact_in(message));
926
927 if let Some(process_error) = error.downcast_mut::<ProcessError>() {
928 process_error.desc = redact(&process_error.desc);
929 return error;
930 }
931
932 anyhow!("{}", redact(&error.to_string()))
933}
934
935#[cfg(test)]
936mod tests {
937 use super::*;
938
939 #[test]
940 fn submodule_update_config_strips_credentials_from_origin_override() {
941 let url = DisplaySafeUrl::parse("https://user:password@example.com/org/repo.git").unwrap();
942
943 assert_eq!(
944 submodule_update_config(&url),
945 vec![
946 "remote.origin.url=https://example.com/org/repo.git".to_string(),
947 "url.https://user:password@example.com/.insteadOf=https://example.com/".to_string(),
948 ]
949 );
950 }
951
952 #[test]
953 fn submodule_update_config_preserves_git_ssh_user() {
954 let url = DisplaySafeUrl::parse("ssh://git@example.com/org/repo.git").unwrap();
955
956 assert_eq!(
957 submodule_update_config(&url),
958 vec!["remote.origin.url=ssh://git@example.com/org/repo.git".to_string()]
959 );
960 }
961
962 #[test]
963 fn git_process_error_redacts_credentials() -> Result<()> {
964 let url = DisplaySafeUrl::parse("https://git:secret-token@example.com/org/repo.git")?;
965 let stderr = format!("fatal: Authentication failed for '{}'", url.as_str());
966 let error = ProcessError::new_raw(
967 &format!(
968 "process didn't exit successfully: `git fetch --force '{}' '+HEAD:refs/remotes/origin/HEAD'`",
969 url.as_str()
970 ),
971 Some(128),
972 "exit status: 128",
973 Some(b"git output"),
974 Some(stderr.as_bytes()),
975 )
976 .into();
977
978 let error = redact_git_error(error, &url);
979 let process_error = error
980 .downcast_ref::<ProcessError>()
981 .context("expected Git process error")?;
982
983 assert_eq!(
984 error.to_string(),
985 "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'"
986 );
987 assert_eq!(process_error.code, Some(128));
988 assert_eq!(
989 process_error.stdout.as_deref(),
990 Some(b"git output".as_slice())
991 );
992 assert_eq!(process_error.stderr.as_deref(), Some(stderr.as_bytes()));
993
994 Ok(())
995 }
996
997 #[test]
998 fn git_submodule_process_error_redacts_credentials() -> Result<()> {
999 let url = DisplaySafeUrl::parse("https://git:secret-token@example.com/org/repo.git")?;
1000
1001 for args in ["--init", "--recursive --init"] {
1002 let error = anyhow!(
1003 "process didn't exit successfully: `git -c 'url.https://git:secret-token@example.com/.insteadOf=https://example.com/' submodule update {args}` (exit status: 128)"
1004 );
1005 let redacted = redact_git_error(error, &url).to_string();
1006
1007 assert!(!redacted.contains("secret-token"));
1008 assert_eq!(
1009 redacted,
1010 format!(
1011 "process didn't exit successfully: `git -c 'url.https://git:****@example.com/.insteadOf=https://example.com/' submodule update {args}` (exit status: 128)"
1012 )
1013 );
1014 }
1015
1016 Ok(())
1017 }
1018}