1use std::collections::{HashMap, HashSet};
8use std::path::Path;
9
10use thiserror::Error;
11
12use crate::config::ConfigSet;
13use crate::objects::ObjectId;
14use crate::refspec::{parse_fetch_refspec, RefspecError, RefspecItem};
15use crate::remote::{Remote, RemoteError, DEFAULT_REMOTE};
16use crate::repo_handles::has_remote_section;
17use crate::transfer::{match_positive, ref_excluded, MatchedRef};
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum FetchRefspecSourceKind {
22 ExactRemoteRef,
24 DwimHeads,
26 DwimTags,
28 DwimRefsPrefix,
30 DwimLiteral,
32 Head,
34 ObjectId,
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum FetchHeadPolicy {
41 ForMerge,
43 Ignore,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct ResolvedFetchRef {
50 pub remote_ref: String,
52 pub oid: Option<ObjectId>,
54 pub local_ref: Option<String>,
56 pub force: bool,
58 pub fetch_head: FetchHeadPolicy,
60 pub source_kind: FetchRefspecSourceKind,
62}
63
64#[derive(Debug, Clone)]
66pub enum FetchRefspecPlan {
67 Pattern {
69 positive: Vec<RefspecItem>,
71 negatives: Vec<RefspecItem>,
73 },
74 Mixed {
76 explicit: Vec<ResolvedFetchRef>,
78 pattern_positive: Vec<RefspecItem>,
80 negatives: Vec<RefspecItem>,
82 },
83}
84
85#[derive(Debug, Error, Clone, PartialEq, Eq)]
87#[non_exhaustive]
88pub enum FetchRefspecError {
89 #[error("invalid refspec '{spec}': {message}")]
91 InvalidRefspec {
92 spec: String,
94 message: String,
96 },
97 #[error("remote has no ref matching fetch source '{ref_name}'")]
99 SourceNotFound {
100 ref_name: String,
102 spec: String,
104 },
105 #[error("fetch source '{ref_name}' is ambiguous on the remote")]
107 AmbiguousSource {
108 ref_name: String,
110 spec: String,
112 },
113}
114
115impl From<RefspecError> for FetchRefspecError {
116 fn from(e: RefspecError) -> Self {
117 match e {
118 RefspecError::Invalid { spec: s } => Self::InvalidRefspec {
119 spec: s.clone(),
120 message: s,
121 },
122 }
123 }
124}
125
126#[derive(Debug, Clone, Copy, Default)]
128pub struct FetchRemoteAdvertisement<'a> {
129 pub refs: &'a [(String, ObjectId)],
131 pub head_oid: Option<ObjectId>,
133}
134
135#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct FetchInvocation {
138 pub remote: String,
140 pub user_refspecs: Vec<String>,
142}
143
144pub fn resolve_remote_argument(
156 config: &ConfigSet,
157 remote_or_url: &str,
158) -> crate::error::Result<Remote> {
159 if has_remote_section(config, remote_or_url) {
160 return Remote::from_config(config, remote_or_url);
161 }
162 if looks_like_path_or_url(remote_or_url) || remote_or_url.contains(':') {
163 return Remote::from_url(remote_or_url);
164 }
165 Err(RemoteError::UnknownRemote {
166 name: remote_or_url.to_owned(),
167 }
168 .into())
169}
170
171fn branch_remote(config: &ConfigSet, branch: Option<&str>) -> Option<String> {
173 branch
174 .and_then(|name| config.value(&format!("branch.{name}.remote")))
175 .map(|remote| remote.trim().to_owned())
176 .filter(|remote| !remote.is_empty())
177}
178
179#[must_use]
193pub fn configured_remote_for_pull(config: &ConfigSet, branch: Option<&str>) -> String {
194 branch_remote(config, branch).unwrap_or_else(|| DEFAULT_REMOTE.to_owned())
195}
196
197#[must_use]
208pub(crate) fn configured_remote_for_fetch(config: &ConfigSet, branch: Option<&str>) -> String {
209 branch_remote(config, branch)
210 .filter(|remote| remote != ".")
211 .unwrap_or_else(|| DEFAULT_REMOTE.to_owned())
212}
213
214#[must_use]
226pub fn resolve_fetch_invocation(
227 config: &ConfigSet,
228 remote: Option<&str>,
229 refspecs: &[String],
230 current_branch: Option<&str>,
231) -> FetchInvocation {
232 classify_invocation(config, remote, refspecs, || {
233 configured_remote_for_fetch(config, current_branch)
234 })
235}
236
237#[must_use]
242pub fn resolve_pull_invocation(
243 config: &ConfigSet,
244 remote: Option<&str>,
245 refspecs: &[String],
246 current_branch: Option<&str>,
247) -> FetchInvocation {
248 classify_invocation(config, remote, refspecs, || {
249 configured_remote_for_pull(config, current_branch)
250 })
251}
252
253fn classify_invocation(
254 config: &ConfigSet,
255 remote: Option<&str>,
256 refspecs: &[String],
257 default_remote: impl FnOnce() -> String,
258) -> FetchInvocation {
259 if let Some(name) = remote.filter(|s| !s.is_empty()) {
260 return FetchInvocation {
261 remote: name.to_owned(),
262 user_refspecs: refspecs.to_vec(),
263 };
264 }
265 match refspecs.split_first() {
266 Some((first, rest)) if is_fetch_remote_token(config, first) => FetchInvocation {
267 remote: first.clone(),
268 user_refspecs: rest.to_vec(),
269 },
270 _ => FetchInvocation {
271 remote: default_remote(),
272 user_refspecs: refspecs.to_vec(),
273 },
274 }
275}
276
277fn is_fetch_remote_token(config: &ConfigSet, token: &str) -> bool {
278 if has_remote_section(config, token) {
279 return true;
280 }
281 if looks_like_path_or_url(token) {
282 return true;
283 }
284 if token.contains(':') && !token.contains(' ') {
285 return !looks_like_fetch_refspec(token);
286 }
287 false
288}
289
290fn looks_like_path_or_url(token: &str) -> bool {
295 token.contains("://")
296 || token.starts_with('/')
297 || token.starts_with("./")
298 || token.starts_with("../")
299 || token.ends_with(".git")
300 || token.ends_with(".bundle")
301 || Path::new(token).exists()
302}
303
304fn looks_like_fetch_refspec(token: &str) -> bool {
306 if token.contains('@') {
307 return false;
308 }
309 let Ok(item) = parse_fetch_refspec(token) else {
310 return false;
311 };
312 if item.negative || item.pattern || item.matching {
313 return false;
314 }
315 if !token.contains(':') || item.src.is_none() {
316 return false;
317 }
318 let src = item.src.as_deref().unwrap_or("");
319 let dst = item.dst.as_deref().unwrap_or("");
320 if src.contains('.') && !src.starts_with("refs/") {
321 return false;
322 }
323 if dst.contains('/') && !dst.starts_with("refs/") {
324 return false;
325 }
326 true
327}
328
329#[derive(Debug, Clone, Default)]
331pub struct FetchRefspecInput {
332 pub user_refspecs: Vec<String>,
334 pub configured_refspecs: Vec<String>,
336 pub remote_name: Option<String>,
338 pub allow_missing_explicit_for_prune: bool,
341}
342
343fn refspec_item_is_explicit(item: &RefspecItem) -> bool {
344 !item.pattern && !item.matching && !item.negative
345}
346
347impl FetchRefspecPlan {
348 pub fn resolve(
354 input: &FetchRefspecInput,
355 remote: FetchRemoteAdvertisement<'_>,
356 ) -> Result<Self, FetchRefspecError> {
357 let effective = if input.user_refspecs.is_empty() {
358 input.configured_refspecs.clone()
359 } else {
360 input.user_refspecs.clone()
361 };
362
363 let mut negatives = Vec::new();
364 let mut positive_strings = Vec::new();
365 for spec in &effective {
366 let item =
367 parse_fetch_refspec(spec).map_err(|e| FetchRefspecError::InvalidRefspec {
368 spec: spec.clone(),
369 message: e.to_string(),
370 })?;
371 if item.negative {
372 negatives.push(item);
373 } else {
374 positive_strings.push(spec.clone());
375 }
376 }
377
378 let has_explicit = positive_strings.iter().any(|s| {
379 parse_fetch_refspec(s)
380 .map(|i| refspec_item_is_explicit(&i))
381 .unwrap_or(false)
382 });
383
384 if !has_explicit {
385 let positive = positive_strings
386 .iter()
387 .map(|s| parse_fetch_refspec(s))
388 .collect::<Result<Vec<_>, _>>()?;
389 return Ok(Self::Pattern {
390 positive,
391 negatives,
392 });
393 }
394
395 let remote_index: HashMap<&str, ObjectId> =
396 remote.refs.iter().map(|(n, o)| (n.as_str(), *o)).collect();
397
398 let mut explicit = Vec::new();
399 let mut pattern_positive = Vec::new();
400
401 for spec in &positive_strings {
402 let item =
403 parse_fetch_refspec(spec).map_err(|e| FetchRefspecError::InvalidRefspec {
404 spec: spec.clone(),
405 message: e.to_string(),
406 })?;
407 if item.pattern || item.matching {
408 pattern_positive.push(item);
409 continue;
410 }
411 let src_raw = item.src.as_deref().unwrap_or("");
412 if item.exact_sha1 {
413 if !ObjectId::is_full_hex(src_raw) {
414 return Err(FetchRefspecError::InvalidRefspec {
415 spec: spec.clone(),
416 message: "invalid object id".into(),
417 });
418 }
419 let oid =
420 ObjectId::from_hex(src_raw).map_err(|_| FetchRefspecError::InvalidRefspec {
421 spec: spec.clone(),
422 message: "invalid object id".into(),
423 })?;
424 let local_ref = resolve_explicit_destination(item.dst.as_deref(), src_raw);
425 explicit.push(ResolvedFetchRef {
426 remote_ref: src_raw.to_owned(),
427 oid: Some(oid),
428 local_ref,
429 force: item.force,
430 fetch_head: FetchHeadPolicy::ForMerge,
431 source_kind: FetchRefspecSourceKind::ObjectId,
432 });
433 continue;
434 }
435 let (remote_ref, kind, oid) =
436 match resolve_explicit_source(src_raw, &remote_index, remote.head_oid, spec) {
437 Ok(resolved) => resolved,
438 Err(FetchRefspecError::SourceNotFound { .. })
439 if input.allow_missing_explicit_for_prune =>
440 {
441 let remote_ref = explicit_remote_ref_for_prune(src_raw);
442 (remote_ref, FetchRefspecSourceKind::ExactRemoteRef, None)
443 }
444 Err(e) => return Err(e),
445 };
446 let local_ref = resolve_explicit_destination(item.dst.as_deref(), &remote_ref);
447 explicit.push(ResolvedFetchRef {
448 remote_ref,
449 oid,
450 local_ref,
451 force: item.force,
452 fetch_head: FetchHeadPolicy::ForMerge,
453 source_kind: kind,
454 });
455 }
456
457 append_opportunistic_tracking(
458 &mut explicit,
459 &input.configured_refspecs,
460 input.remote_name.as_deref(),
461 );
462
463 Ok(Self::Mixed {
464 explicit,
465 pattern_positive,
466 negatives,
467 })
468 }
469
470 #[must_use]
472 pub fn is_explicit(&self) -> bool {
473 matches!(self, Self::Mixed { .. })
474 }
475}
476
477pub(crate) fn matched_refs_with_negatives(
482 plan: &FetchRefspecPlan,
483 remote: FetchRemoteAdvertisement<'_>,
484 negatives: &[RefspecItem],
485 prune_missing_explicit: bool,
486) -> Result<Vec<MatchedRef>, FetchRefspecError> {
487 match plan {
488 FetchRefspecPlan::Pattern { positive, .. } => {
489 pattern_matched_refs(remote.refs, positive, negatives)
490 }
491 FetchRefspecPlan::Mixed {
492 explicit,
493 pattern_positive,
494 ..
495 } => {
496 let mut matched = pattern_matched_refs(remote.refs, pattern_positive, negatives)?;
497 let remote_index: HashMap<&str, ObjectId> =
498 remote.refs.iter().map(|(n, o)| (n.as_str(), *o)).collect();
499 for entry in explicit {
500 if ref_excluded(&entry.remote_ref, negatives) {
501 continue;
502 }
503 let oid = if let Some(o) = entry.oid {
504 o
505 } else if let Some(o) = remote_index.get(entry.remote_ref.as_str()).copied() {
506 o
507 } else if prune_missing_explicit {
508 continue;
509 } else {
510 return Err(FetchRefspecError::SourceNotFound {
511 ref_name: entry.remote_ref.clone(),
512 spec: entry.remote_ref.clone(),
513 });
514 };
515 matched.push(MatchedRef {
516 remote_ref: entry.remote_ref.clone(),
517 local_ref: entry.local_ref.clone(),
518 oid,
519 force: entry.force,
520 is_tag: entry.remote_ref.starts_with("refs/tags/"),
521 auto_followed: false,
522 dest_is_tag: ref_update_uses_tag_rules(entry.local_ref.as_deref()),
523 advertised_peel: None,
524 fetch_head: entry.fetch_head,
525 });
526 }
527 Ok(matched)
528 }
529 }
530}
531
532fn pattern_matched_refs(
533 remote_refs: &[(String, ObjectId)],
534 positive: &[RefspecItem],
535 negatives: &[RefspecItem],
536) -> Result<Vec<MatchedRef>, FetchRefspecError> {
537 let mut matched = Vec::new();
538 let mut seen = HashSet::new();
539 for (name, oid) in remote_refs {
540 if ref_excluded(name, negatives) {
541 continue;
542 }
543 if let Some(local_ref) = match_positive(name, positive) {
544 let key = (name.clone(), local_ref.clone());
545 if seen.insert(key) {
546 matched.push(MatchedRef {
547 remote_ref: name.clone(),
548 local_ref: local_ref.clone(),
549 oid: *oid,
550 force: crate::transfer::refspecs_force(name, positive),
551 is_tag: name.starts_with("refs/tags/"),
552 auto_followed: false,
553 dest_is_tag: ref_update_uses_tag_rules(local_ref.as_deref()),
554 advertised_peel: None,
555 fetch_head: FetchHeadPolicy::ForMerge,
556 });
557 }
558 }
559 }
560 Ok(matched)
561}
562
563fn append_opportunistic_tracking(
564 entries: &mut Vec<ResolvedFetchRef>,
565 configured: &[String],
566 remote_name: Option<&str>,
567) {
568 if configured.is_empty() {
569 return;
570 }
571 let Some(remote_name) = remote_name else {
572 return;
573 };
574 if remote_name.contains('/') || remote_name.starts_with('.') {
575 return;
576 }
577
578 let mut configured_positive = Vec::new();
579 for spec in configured {
580 if let Ok(item) = parse_fetch_refspec(spec) {
581 if !item.negative {
582 configured_positive.push(item);
583 }
584 }
585 }
586 if configured_positive.is_empty() {
587 return;
588 }
589
590 let primary_remotes: Vec<String> = entries.iter().map(|e| e.remote_ref.clone()).collect();
591 let mut have_local: HashSet<String> =
592 entries.iter().filter_map(|e| e.local_ref.clone()).collect();
593
594 for remote_ref in primary_remotes {
595 if let Some(local) = match_positive(&remote_ref, &configured_positive) {
596 let Some(local) = local else {
597 continue;
598 };
599 if have_local.contains(&local) {
600 continue;
601 }
602 have_local.insert(local.clone());
603 entries.push(ResolvedFetchRef {
604 remote_ref: remote_ref.to_owned(),
605 oid: None,
606 local_ref: Some(local),
607 force: configured_positive.iter().any(|item| {
608 item.force
609 && item.src.as_deref().is_some_and(|src| {
610 crate::transfer::apply_refspec(
611 src,
612 item.dst.as_deref(),
613 remote_ref.as_str(),
614 )
615 .is_some()
616 })
617 }),
618 fetch_head: FetchHeadPolicy::Ignore,
619 source_kind: FetchRefspecSourceKind::ExactRemoteRef,
620 });
621 }
622 }
623}
624
625fn explicit_remote_ref_for_prune(src: &str) -> String {
628 if src.is_empty() || src == "HEAD" || src == "@" {
629 return "HEAD".to_owned();
630 }
631 if src.starts_with("refs/") {
632 src.to_owned()
633 } else {
634 format!("refs/heads/{src}")
635 }
636}
637
638pub(crate) fn supplement_positive_for_explicit_prune(
643 positive: &mut Vec<RefspecItem>,
644 configured_refspecs: &[String],
645 remote_name: Option<&str>,
646) {
647 let Some(remote_name) = remote_name else {
648 return;
649 };
650 if remote_name.contains('/') || remote_name.starts_with('.') {
651 return;
652 }
653 let mut configured_positive = Vec::new();
654 for spec in configured_refspecs {
655 if let Ok(item) = parse_fetch_refspec(spec) {
656 if !item.negative {
657 configured_positive.push(item);
658 }
659 }
660 }
661 if configured_positive.is_empty() {
662 return;
663 }
664
665 let mut extras = Vec::new();
666 for item in positive.iter() {
667 if item.negative || item.pattern || item.matching {
668 continue;
669 }
670 if item.dst.as_ref().is_some_and(|d| !d.is_empty()) {
671 continue;
672 }
673 let Some(src) = item.src.as_deref() else {
674 continue;
675 };
676 let remote_ref = explicit_remote_ref_for_prune(src);
677 let Some(local) =
678 crate::transfer::match_positive(&remote_ref, &configured_positive).and_then(|o| o)
679 else {
680 continue;
681 };
682 extras.push(RefspecItem {
683 dst: Some(local),
684 ..item.clone()
685 });
686 }
687 positive.extend(extras);
688}
689
690fn resolve_explicit_source(
691 src: &str,
692 remote: &HashMap<&str, ObjectId>,
693 head_oid: Option<ObjectId>,
694 spec: &str,
695) -> Result<(String, FetchRefspecSourceKind, Option<ObjectId>), FetchRefspecError> {
696 if src.is_empty() || src == "HEAD" || src == "@" {
697 let Some(oid) = head_oid.filter(|o| !o.is_zero()) else {
698 return Err(FetchRefspecError::SourceNotFound {
699 ref_name: "HEAD".to_owned(),
700 spec: spec.to_owned(),
701 });
702 };
703 return Ok(("HEAD".to_owned(), FetchRefspecSourceKind::Head, Some(oid)));
704 }
705
706 if remote.contains_key(src) {
707 return Ok((src.to_owned(), FetchRefspecSourceKind::ExactRemoteRef, None));
708 }
709
710 let mut candidates: Vec<(u8, String, FetchRefspecSourceKind)> = Vec::new();
711 let try_push =
712 |candidates: &mut Vec<_>, priority: u8, name: String, kind: FetchRefspecSourceKind| {
713 if remote.contains_key(name.as_str()) {
714 candidates.push((priority, name, kind));
715 }
716 };
717
718 try_push(
719 &mut candidates,
720 0,
721 format!("refs/heads/{src}"),
722 FetchRefspecSourceKind::DwimHeads,
723 );
724 try_push(
725 &mut candidates,
726 1,
727 format!("refs/tags/{src}"),
728 FetchRefspecSourceKind::DwimTags,
729 );
730 if src.starts_with("refs/") {
731 try_push(
732 &mut candidates,
733 2,
734 src.to_owned(),
735 FetchRefspecSourceKind::DwimLiteral,
736 );
737 } else {
738 try_push(
739 &mut candidates,
740 2,
741 format!("refs/{src}"),
742 FetchRefspecSourceKind::DwimRefsPrefix,
743 );
744 try_push(
745 &mut candidates,
746 3,
747 src.to_owned(),
748 FetchRefspecSourceKind::DwimLiteral,
749 );
750 }
751
752 candidates.sort_by_key(|(p, _, _)| *p);
753 match candidates.len() {
754 0 => Err(FetchRefspecError::SourceNotFound {
755 ref_name: src.to_owned(),
756 spec: spec.to_owned(),
757 }),
758 1 => Ok((candidates[0].1.clone(), candidates[0].2, None)),
759 _ => {
760 let best = candidates[0].0;
761 let at_best: Vec<_> = candidates.iter().filter(|(p, _, _)| *p == best).collect();
762 if at_best.len() == 1 {
763 Ok((at_best[0].1.clone(), at_best[0].2, None))
764 } else {
765 Err(FetchRefspecError::AmbiguousSource {
766 ref_name: src.to_owned(),
767 spec: spec.to_owned(),
768 })
769 }
770 }
771 }
772}
773
774#[must_use]
776pub(crate) fn ref_update_uses_tag_rules(local_ref: Option<&str>) -> bool {
777 local_ref.is_some_and(|r| r.starts_with("refs/tags/"))
778}
779
780fn resolve_explicit_destination(dst: Option<&str>, _remote_ref: &str) -> Option<String> {
781 match dst {
782 None | Some("") => None,
783 Some(d) if d.starts_with("refs/") => Some(d.to_owned()),
784 Some(d)
785 if d.starts_with("heads/") || d.starts_with("tags/") || d.starts_with("remotes/") =>
786 {
787 Some(format!("refs/{d}"))
788 }
789 Some(d) => Some(format!("refs/heads/{d}")),
790 }
791}
792
793#[must_use]
795pub(crate) fn fetch_head_description(remote_ref: &str, is_tag: bool, source: &str) -> String {
796 if remote_ref == "HEAD" {
797 return format!("HEAD of {source}");
798 }
799 if is_tag || remote_ref.starts_with("refs/tags/") {
800 let short = remote_ref.strip_prefix("refs/tags/").unwrap_or(remote_ref);
801 return format!("tag '{short}' of {source}");
802 }
803 if let Some(short) = remote_ref.strip_prefix("refs/heads/") {
804 return format!("branch '{short}' of {source}");
805 }
806 format!("'{remote_ref}' of {source}")
807}
808
809#[must_use]
811#[allow(dead_code)]
812pub(crate) fn refname_match_fetch_dwim(abbrev: &str, full: &str) -> u32 {
813 if abbrev == full {
814 return 100;
815 }
816 if full == format!("refs/heads/{abbrev}") {
817 return 90;
818 }
819 if full == format!("refs/tags/{abbrev}") {
820 return 80;
821 }
822 if full == format!("refs/{abbrev}") {
823 return 70;
824 }
825 0
826}
827
828#[cfg(test)]
829mod tests {
830 use super::*;
831
832 fn remote_refs(names: &[&str]) -> Vec<(String, ObjectId)> {
833 let oid = ObjectId::from_hex("0000000000000000000000000000000000000001").unwrap();
834 names.iter().map(|n| (n.to_string(), oid)).collect()
835 }
836
837 fn adv<'a>(refs: &'a [(String, ObjectId)]) -> FetchRemoteAdvertisement<'a> {
838 FetchRemoteAdvertisement {
839 refs,
840 head_oid: None,
841 }
842 }
843
844 fn matched_from_plan(
845 plan: &FetchRefspecPlan,
846 remote: FetchRemoteAdvertisement<'_>,
847 ) -> Vec<MatchedRef> {
848 let negatives = match plan {
849 FetchRefspecPlan::Pattern { negatives, .. }
850 | FetchRefspecPlan::Mixed { negatives, .. } => negatives.as_slice(),
851 };
852 matched_refs_with_negatives(plan, remote, negatives, false).unwrap()
853 }
854
855 #[test]
856 fn dwim_prefers_heads_over_tags() {
857 let refs = remote_refs(&["refs/heads/main", "refs/tags/main"]);
858 let (name, kind, _) = resolve_explicit_source(
859 "main",
860 &refs.iter().map(|(n, o)| (n.as_str(), *o)).collect(),
861 None,
862 "main",
863 )
864 .unwrap();
865 assert_eq!(name, "refs/heads/main");
866 assert_eq!(kind, FetchRefspecSourceKind::DwimHeads);
867 }
868
869 #[test]
870 fn pull_request_ref_expands_under_refs() {
871 let refs = remote_refs(&["refs/pull/123/head"]);
872 let (name, kind, _) = resolve_explicit_source(
873 "pull/123/head",
874 &refs.iter().map(|(n, o)| (n.as_str(), *o)).collect(),
875 None,
876 "pull/123/head",
877 )
878 .unwrap();
879 assert_eq!(name, "refs/pull/123/head");
880 assert_eq!(kind, FetchRefspecSourceKind::DwimRefsPrefix);
881 }
882
883 #[test]
884 fn head_uses_advertised_head_oid() {
885 let oid = ObjectId::from_hex("00000000000000000000000000000000000000ab").unwrap();
886 let (name, kind, resolved) =
887 resolve_explicit_source("HEAD", &HashMap::new(), Some(oid), "HEAD").unwrap();
888 assert_eq!(name, "HEAD");
889 assert_eq!(kind, FetchRefspecSourceKind::Head);
890 assert_eq!(resolved, Some(oid));
891 }
892
893 #[test]
894 fn mixed_explicit_and_pattern_refspecs() {
895 let refs = remote_refs(&["refs/heads/main", "refs/heads/extra"]);
896 let plan = FetchRefspecPlan::resolve(
897 &FetchRefspecInput {
898 user_refspecs: vec!["main".into(), "+refs/heads/*:refs/remotes/other/*".into()],
899 configured_refspecs: vec![],
900 remote_name: Some("origin".into()),
901 ..Default::default()
902 },
903 adv(&refs),
904 )
905 .unwrap();
906 let matched = matched_from_plan(&plan, adv(&refs));
907 assert!(
908 matched
909 .iter()
910 .any(|m| m.local_ref.as_deref() == Some("refs/remotes/other/main")),
911 "pattern refspec should map main to other/*"
912 );
913 }
914
915 #[test]
916 fn opportunistic_exact_configured_mapping() {
917 let refs = remote_refs(&["refs/heads/main"]);
918 let plan = FetchRefspecPlan::resolve(
919 &FetchRefspecInput {
920 user_refspecs: vec!["main".into()],
921 configured_refspecs: vec!["refs/heads/main:refs/remotes/origin/main".into()],
922 remote_name: Some("origin".into()),
923 ..Default::default()
924 },
925 adv(&refs),
926 )
927 .unwrap();
928 let matched = matched_from_plan(&plan, adv(&refs));
929 assert!(
930 matched
931 .iter()
932 .any(|m| m.local_ref.as_deref() == Some("refs/remotes/origin/main")),
933 "exact configured mapping should opportunistically update tracking ref"
934 );
935 }
936
937 #[test]
938 fn extra_negative_refspec_excludes_from_wildcard_match() {
939 let refs = remote_refs(&["refs/heads/main", "refs/heads/topic", "refs/heads/side"]);
940 let plan = FetchRefspecPlan::resolve(
941 &FetchRefspecInput {
942 user_refspecs: vec!["+refs/heads/*:refs/remotes/origin/*".into()],
943 ..Default::default()
944 },
945 adv(&refs),
946 )
947 .unwrap();
948 let extra = vec![parse_fetch_refspec("^refs/heads/topic").unwrap()];
949 let matched = matched_refs_with_negatives(&plan, adv(&refs), &extra, false).unwrap();
950 assert!(
951 matched
952 .iter()
953 .any(|m| m.local_ref.as_deref() == Some("refs/remotes/origin/main")),
954 "main must match"
955 );
956 assert!(
957 matched
958 .iter()
959 .any(|m| m.local_ref.as_deref() == Some("refs/remotes/origin/side")),
960 "side must match"
961 );
962 assert!(
963 !matched
964 .iter()
965 .any(|m| m.local_ref.as_deref() == Some("refs/remotes/origin/topic")),
966 "negative refspec must drop topic"
967 );
968 }
969
970 #[test]
971 fn explicit_remote_ref_for_prune_keeps_head_symbol() {
972 assert_eq!(explicit_remote_ref_for_prune("HEAD"), "HEAD");
973 assert_eq!(explicit_remote_ref_for_prune("@"), "HEAD");
974 assert_eq!(explicit_remote_ref_for_prune(""), "HEAD");
975 assert_eq!(explicit_remote_ref_for_prune("topic"), "refs/heads/topic");
976 }
977
978 #[test]
979 fn vanished_head_prune_does_not_match_refs_heads_head_branch() {
980 let oid = ObjectId::from_hex("0000000000000000000000000000000000000002").unwrap();
981 let refs = vec![("refs/heads/HEAD".to_string(), oid)];
982 let plan = FetchRefspecPlan::resolve(
983 &FetchRefspecInput {
984 user_refspecs: vec!["HEAD".into()],
985 allow_missing_explicit_for_prune: true,
986 ..Default::default()
987 },
988 FetchRemoteAdvertisement {
989 refs: &refs,
990 head_oid: None,
991 },
992 )
993 .unwrap();
994 let matched = matched_refs_with_negatives(
995 &plan,
996 FetchRemoteAdvertisement {
997 refs: &refs,
998 head_oid: None,
999 },
1000 &[],
1001 true,
1002 )
1003 .unwrap();
1004 assert!(
1005 matched.is_empty(),
1006 "vanished HEAD must not be confused with a refs/heads/HEAD branch"
1007 );
1008 }
1009
1010 #[test]
1011 fn supplement_positive_adds_tracking_dst_for_short_explicit_prune() {
1012 let mut positive = vec![parse_fetch_refspec("topic").unwrap()];
1013 supplement_positive_for_explicit_prune(
1014 &mut positive,
1015 &["+refs/heads/*:refs/remotes/origin/*".into()],
1016 Some("origin"),
1017 );
1018 assert!(
1019 positive.iter().any(|i| {
1020 i.src.as_deref() == Some("topic")
1021 && i.dst.as_deref() == Some("refs/remotes/origin/topic")
1022 }),
1023 "short explicit refspec must gain configured tracking dst for prune"
1024 );
1025 }
1026
1027 #[test]
1028 fn prune_skips_missing_explicit_source_instead_of_error() {
1029 let refs = remote_refs(&["refs/heads/main"]);
1030 let plan = FetchRefspecPlan::resolve(
1031 &FetchRefspecInput {
1032 user_refspecs: vec!["+refs/heads/topic:refs/remotes/origin/topic".into()],
1033 configured_refspecs: vec![],
1034 remote_name: None,
1035 allow_missing_explicit_for_prune: true,
1036 },
1037 adv(&refs),
1038 )
1039 .unwrap();
1040 let matched = matched_refs_with_negatives(&plan, adv(&refs), &[], true).unwrap();
1041 assert!(
1042 matched.is_empty(),
1043 "vanished explicit source with prune must not error or match"
1044 );
1045 }
1046
1047 #[test]
1048 fn duplicate_remote_ref_two_destinations() {
1049 let refs = remote_refs(&["refs/heads/main"]);
1050 let plan = FetchRefspecPlan::resolve(
1051 &FetchRefspecInput {
1052 user_refspecs: vec!["main:refs/heads/a".into(), "main:refs/heads/b".into()],
1053 ..Default::default()
1054 },
1055 adv(&refs),
1056 )
1057 .unwrap();
1058 let matched = matched_from_plan(&plan, adv(&refs));
1059 assert_eq!(
1060 matched
1061 .iter()
1062 .filter(|m| m.remote_ref == "refs/heads/main")
1063 .count(),
1064 2
1065 );
1066 }
1067
1068 #[test]
1069 fn object_id_refspec_carries_oid() {
1070 let oid = ObjectId::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
1071 let refs: Vec<(String, ObjectId)> = vec![];
1072 let plan = FetchRefspecPlan::resolve(
1073 &FetchRefspecInput {
1074 user_refspecs: vec![format!("{oid}:refs/heads/imported")],
1075 ..Default::default()
1076 },
1077 adv(&refs),
1078 )
1079 .unwrap();
1080 let matched = matched_from_plan(&plan, adv(&refs));
1081 assert_eq!(matched.len(), 1);
1082 assert_eq!(matched[0].oid, oid);
1083 }
1084
1085 #[test]
1086 fn short_destination_maps_to_refs_heads() {
1087 assert_eq!(
1088 resolve_explicit_destination(Some("pr-123"), "refs/pull/123/head").as_deref(),
1089 Some("refs/heads/pr-123")
1090 );
1091 }
1092
1093 #[test]
1094 fn opportunistic_tracking_adds_origin_main() {
1095 let mut entries = vec![ResolvedFetchRef {
1096 remote_ref: "refs/heads/main".into(),
1097 oid: None,
1098 local_ref: Some("refs/heads/local-main".into()),
1099 force: false,
1100 fetch_head: FetchHeadPolicy::ForMerge,
1101 source_kind: FetchRefspecSourceKind::DwimHeads,
1102 }];
1103 append_opportunistic_tracking(
1104 &mut entries,
1105 &["+refs/heads/*:refs/remotes/origin/*".into()],
1106 Some("origin"),
1107 );
1108 assert!(entries.iter().any(
1109 |e| e.local_ref.as_deref() == Some("refs/remotes/origin/main")
1110 && e.fetch_head == FetchHeadPolicy::Ignore
1111 ));
1112 }
1113
1114 #[test]
1115 fn refname_match_fetch_dwim_ordering() {
1116 assert!(
1117 refname_match_fetch_dwim("main", "refs/heads/main")
1118 > refname_match_fetch_dwim("main", "refs/tags/main")
1119 );
1120 }
1121
1122 #[test]
1123 fn colon_refspec_is_not_treated_as_remote() {
1124 use super::{resolve_fetch_invocation, FetchInvocation};
1125 use crate::config::{ConfigFile, ConfigScope, ConfigSet};
1126
1127 let file = ConfigFile::parse(
1128 std::path::Path::new("cfg"),
1129 "[remote \"origin\"]\n\turl = /tmp/x.git\n",
1130 ConfigScope::Local,
1131 )
1132 .expect("parse");
1133 let mut config = ConfigSet::new();
1134 config.merge(&file);
1135
1136 assert_eq!(
1137 resolve_fetch_invocation(&config, None, &["main:refs/heads/feature".into()], None),
1138 FetchInvocation {
1139 remote: "origin".into(),
1140 user_refspecs: vec!["main:refs/heads/feature".into()],
1141 }
1142 );
1143 }
1144
1145 #[test]
1146 fn explicit_remote_positional_includes_scp_style_urls() {
1147 use super::{resolve_fetch_invocation, FetchInvocation};
1148 use crate::config::ConfigSet;
1149
1150 let config = ConfigSet::new();
1151 assert_eq!(
1152 resolve_fetch_invocation(&config, Some("example.com:repo"), &[], None),
1153 FetchInvocation {
1154 remote: "example.com:repo".into(),
1155 user_refspecs: vec![],
1156 }
1157 );
1158 assert_eq!(
1159 resolve_fetch_invocation(&config, Some("git@host:org/repo"), &[], None),
1160 FetchInvocation {
1161 remote: "git@host:org/repo".into(),
1162 user_refspecs: vec![],
1163 }
1164 );
1165 }
1166
1167 #[test]
1168 fn resolve_remote_argument_prefers_configured_then_url_forms() {
1169 use crate::config::{ConfigFile, ConfigScope, ConfigSet};
1170 use crate::remote::RemoteUrl;
1171
1172 let file = ConfigFile::parse(
1173 std::path::Path::new("cfg"),
1174 "[remote \"origin\"]\n\turl = /tmp/x.git\n[remote \"nourl\"]\n\tfetch = +refs/heads/*:refs/remotes/nourl/*\n",
1175 ConfigScope::Local,
1176 )
1177 .expect("parse");
1178 let mut config = ConfigSet::new();
1179 config.merge(&file);
1180
1181 let origin = resolve_remote_argument(&config, "origin").expect("origin");
1182 assert_eq!(origin.name.as_deref(), Some("origin"));
1183
1184 for url in [
1185 "https://example.com/r.git",
1186 "./sibling",
1187 "../sibling",
1188 "/abs/repo",
1189 "git@host:org/repo",
1190 "host:repo",
1191 ] {
1192 let remote = resolve_remote_argument(&config, url).expect(url);
1193 assert_eq!(remote.name, None, "{url}");
1194 }
1195 assert!(matches!(
1196 resolve_remote_argument(&config, "host:repo").map(|r| r.fetch_url().clone()),
1197 Ok(RemoteUrl::Ssh(_))
1198 ));
1199
1200 assert!(matches!(
1201 resolve_remote_argument(&config, "nourl"),
1202 Err(crate::error::Error::Remote(RemoteError::NoUrl { remote: Some(name) })) if name == "nourl"
1203 ));
1204 let err = resolve_remote_argument(&config, "nosuch").expect_err("unknown");
1205 assert!(
1206 matches!(&err, crate::error::Error::Remote(RemoteError::UnknownRemote { name }) if name == "nosuch")
1207 );
1208 assert_eq!(err.to_string(), "unknown remote 'nosuch'");
1209 }
1210
1211 #[test]
1212 fn url_less_configured_remote_is_consumed_as_the_remote() {
1213 use super::{resolve_fetch_invocation, FetchInvocation};
1214 use crate::config::{ConfigFile, ConfigScope, ConfigSet};
1215
1216 let file = ConfigFile::parse(
1217 std::path::Path::new("cfg"),
1218 "[remote \"half\"]\n\tfetch = +refs/heads/*:refs/remotes/half/*\n",
1219 ConfigScope::Local,
1220 )
1221 .expect("parse");
1222 let mut config = ConfigSet::new();
1223 config.merge(&file);
1224
1225 let invocation =
1226 resolve_fetch_invocation(&config, None, &["half".into(), "main".into()], None);
1227 assert_eq!(
1228 invocation,
1229 FetchInvocation {
1230 remote: "half".into(),
1231 user_refspecs: vec!["main".into()],
1232 }
1233 );
1234 assert!(matches!(
1235 resolve_remote_argument(&config, &invocation.remote),
1236 Err(crate::error::Error::Remote(RemoteError::NoUrl { remote: Some(name) })) if name == "half"
1237 ));
1238 }
1239
1240 #[test]
1241 fn configured_remote_with_colon_refspec() {
1242 use super::{resolve_fetch_invocation, FetchInvocation};
1243 use crate::config::{ConfigFile, ConfigScope, ConfigSet};
1244
1245 let file = ConfigFile::parse(
1246 std::path::Path::new("cfg"),
1247 "[remote \"origin\"]\n\turl = /tmp/x.git\n",
1248 ConfigScope::Local,
1249 )
1250 .expect("parse");
1251 let mut config = ConfigSet::new();
1252 config.merge(&file);
1253
1254 assert_eq!(
1255 resolve_fetch_invocation(&config, Some("origin"), &["a:b".into()], None),
1256 FetchInvocation {
1257 remote: "origin".into(),
1258 user_refspecs: vec!["a:b".into()],
1259 }
1260 );
1261 }
1262
1263 #[test]
1264 fn resolve_fetch_invocation_remote_vs_refspec() {
1265 use super::{resolve_fetch_invocation, FetchInvocation};
1266 use crate::config::{ConfigFile, ConfigScope, ConfigSet};
1267
1268 let file = ConfigFile::parse(
1269 std::path::Path::new("cfg"),
1270 "[remote \"origin\"]\n\turl = /tmp/x.git\n",
1271 ConfigScope::Local,
1272 )
1273 .expect("parse");
1274 let mut config = ConfigSet::new();
1275 config.merge(&file);
1276
1277 assert_eq!(
1278 resolve_fetch_invocation(&config, Some("origin"), &["main".into()], None),
1279 FetchInvocation {
1280 remote: "origin".into(),
1281 user_refspecs: vec!["main".into()],
1282 }
1283 );
1284 assert_eq!(
1285 resolve_fetch_invocation(&config, None, &["main".into()], None),
1286 FetchInvocation {
1287 remote: "origin".into(),
1288 user_refspecs: vec!["main".into()],
1289 }
1290 );
1291
1292 let refspec = "refs/heads/main:refs/remotes/origin/main".to_owned();
1293 assert_eq!(
1294 resolve_fetch_invocation(&config, None, &[refspec.clone()], None),
1295 FetchInvocation {
1296 remote: "origin".into(),
1297 user_refspecs: vec![refspec],
1298 }
1299 );
1300
1301 assert!(super::is_fetch_remote_token(
1302 &config,
1303 "git@github.com:org/repo.git"
1304 ));
1305 assert!(!super::looks_like_fetch_refspec(
1306 "git@github.com:org/repo.git"
1307 ));
1308 }
1309
1310 fn branch_remote_config(body: &str) -> crate::config::ConfigSet {
1311 use crate::config::{ConfigFile, ConfigScope, ConfigSet};
1312
1313 let file = ConfigFile::parse(std::path::Path::new("cfg"), body, ConfigScope::Local)
1314 .expect("parse");
1315 let mut config = ConfigSet::new();
1316 config.merge(&file);
1317 config
1318 }
1319
1320 const BRANCH_REMOTES: &str =
1321 "[remote \"origin\"]\n\turl = /tmp/a.git\n[remote \"backup\"]\n\turl = /tmp/b.git\n\
1322 [branch \"main\"]\n\tremote = backup\n[branch \"local\"]\n\tremote = .\n\
1323 [branch \"blank\"]\n\tremote = \" \"\n[branch \"padded\"]\n\tremote = \" backup \"\n";
1324
1325 #[test]
1326 fn configured_remote_for_pull_uses_branch_remote_then_origin() {
1327 use super::configured_remote_for_pull;
1328
1329 let config = branch_remote_config(BRANCH_REMOTES);
1330 assert_eq!(configured_remote_for_pull(&config, Some("main")), "backup");
1331 assert_eq!(configured_remote_for_pull(&config, Some("local")), ".");
1332 assert_eq!(configured_remote_for_pull(&config, Some("blank")), "origin");
1333 assert_eq!(
1334 configured_remote_for_pull(&config, Some("padded")),
1335 "backup"
1336 );
1337 assert_eq!(configured_remote_for_pull(&config, Some("other")), "origin");
1338 assert_eq!(configured_remote_for_pull(&config, None), "origin");
1339 assert_eq!(
1340 configured_remote_for_pull(&crate::config::ConfigSet::new(), Some("main")),
1341 "origin"
1342 );
1343 }
1344
1345 #[test]
1346 fn configured_remote_for_fetch_skips_local_upstream() {
1347 use super::configured_remote_for_fetch;
1348
1349 let config = branch_remote_config(BRANCH_REMOTES);
1350 assert_eq!(configured_remote_for_fetch(&config, Some("main")), "backup");
1351 assert_eq!(
1352 configured_remote_for_fetch(&config, Some("local")),
1353 "origin"
1354 );
1355 assert_eq!(
1356 configured_remote_for_fetch(&config, Some("blank")),
1357 "origin"
1358 );
1359 assert_eq!(
1360 configured_remote_for_fetch(&config, Some("padded")),
1361 "backup"
1362 );
1363 assert_eq!(configured_remote_for_fetch(&config, None), "origin");
1364 }
1365
1366 #[test]
1367 fn configured_remotes_ignore_push_remotes() {
1368 use super::{configured_remote_for_fetch, configured_remote_for_pull};
1369
1370 let config = branch_remote_config(
1371 "[remote]\n\tpushDefault = backup\n[branch \"main\"]\n\tpushRemote = backup\n",
1372 );
1373 assert_eq!(configured_remote_for_fetch(&config, Some("main")), "origin");
1374 assert_eq!(configured_remote_for_pull(&config, Some("main")), "origin");
1375 }
1376
1377 #[test]
1378 fn local_upstream_defaults_differ_between_fetch_and_pull() {
1379 use super::{resolve_fetch_invocation, resolve_pull_invocation, FetchInvocation};
1380
1381 let config = branch_remote_config(BRANCH_REMOTES);
1382 assert_eq!(
1383 resolve_fetch_invocation(&config, None, &[], Some("local")),
1384 FetchInvocation {
1385 remote: "origin".into(),
1386 user_refspecs: vec![],
1387 }
1388 );
1389 assert_eq!(
1390 resolve_pull_invocation(&config, None, &[], Some("local")),
1391 FetchInvocation {
1392 remote: ".".into(),
1393 user_refspecs: vec![],
1394 }
1395 );
1396 assert_eq!(
1397 resolve_pull_invocation(&config, None, &["backup".into()], Some("local")),
1398 FetchInvocation {
1399 remote: "backup".into(),
1400 user_refspecs: vec![],
1401 }
1402 );
1403 assert_eq!(
1404 resolve_pull_invocation(&config, None, &[], Some("main")),
1405 FetchInvocation {
1406 remote: "backup".into(),
1407 user_refspecs: vec![],
1408 }
1409 );
1410 }
1411
1412 #[test]
1413 fn resolve_fetch_invocation_defaults_to_current_branch_remote() {
1414 use super::{resolve_fetch_invocation, FetchInvocation};
1415
1416 let config = branch_remote_config(
1417 "[remote \"origin\"]\n\turl = /tmp/a.git\n[remote \"backup\"]\n\turl = /tmp/b.git\n\
1418 [branch \"main\"]\n\tremote = backup\n",
1419 );
1420 assert_eq!(
1421 resolve_fetch_invocation(&config, None, &[], Some("main")),
1422 FetchInvocation {
1423 remote: "backup".into(),
1424 user_refspecs: vec![],
1425 }
1426 );
1427 assert_eq!(
1428 resolve_fetch_invocation(&config, None, &["topic".into()], Some("main")),
1429 FetchInvocation {
1430 remote: "backup".into(),
1431 user_refspecs: vec!["topic".into()],
1432 }
1433 );
1434 assert_eq!(
1435 resolve_fetch_invocation(&config, None, &["origin".into()], Some("main")),
1436 FetchInvocation {
1437 remote: "origin".into(),
1438 user_refspecs: vec![],
1439 }
1440 );
1441 assert_eq!(
1442 resolve_fetch_invocation(&config, Some("origin"), &[], Some("main")),
1443 FetchInvocation {
1444 remote: "origin".into(),
1445 user_refspecs: vec![],
1446 }
1447 );
1448 assert_eq!(
1449 resolve_fetch_invocation(&config, None, &[], None),
1450 FetchInvocation {
1451 remote: "origin".into(),
1452 user_refspecs: vec![],
1453 }
1454 );
1455 }
1456}