Skip to main content

git_remote_refs/
resolve.rs

1use crate::{Error, ObjectId, Ref, RefList, check_ref_name};
2use alloc::{format, string::String, vec, vec::Vec};
3
4#[derive(Clone, Debug, PartialEq, Eq)]
5pub enum Resolution {
6    Ref {
7        name: String,
8        target: Ref,
9        others: Vec<String>,
10    },
11    Object {
12        oid: ObjectId,
13        refs: Vec<String>,
14    },
15    NotFound,
16    Incomplete {
17        missing: Vec<String>,
18    },
19}
20
21pub fn candidates(name: &str) -> Vec<String> {
22    vec![
23        name.into(),
24        format!("refs/{name}"),
25        format!("refs/tags/{name}"),
26        format!("refs/heads/{name}"),
27        format!("refs/remotes/{name}"),
28        format!("refs/remotes/{name}/HEAD"),
29    ]
30}
31
32pub fn resolve(list: &RefList, name: &str) -> Result<Resolution, Error> {
33    let oid = ObjectId::from_hex(name.as_bytes()).filter(|oid| oid.format() == list.format);
34    if oid.is_none() {
35        check_ref_name(name)?;
36    }
37    let mut found = Vec::new();
38    let mut missing = Vec::new();
39    for candidate in candidates(name) {
40        if list.refs.contains_key(&candidate) {
41            found.push(candidate);
42        } else if !list.covers(&candidate) {
43            missing.push(candidate);
44        }
45    }
46    if !missing.is_empty() {
47        return Ok(Resolution::Incomplete { missing });
48    }
49    if let Some(oid) = oid {
50        return Ok(Resolution::Object { oid, refs: found });
51    }
52    let mut found = found.into_iter();
53    Ok(match found.next() {
54        Some(name) => Resolution::Ref {
55            target: list.refs[&name].clone(),
56            name,
57            others: found.collect(),
58        },
59        None => Resolution::NotFound,
60    })
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66    use crate::ObjectFormat;
67    use alloc::collections::BTreeMap;
68
69    fn list(names: &[&str]) -> RefList {
70        let oid: ObjectId = "1111111111111111111111111111111111111111".parse().unwrap();
71        RefList {
72            format: ObjectFormat::Sha1,
73            refs: names
74                .iter()
75                .map(|name| {
76                    (
77                        String::from(*name),
78                        Ref {
79                            oid,
80                            peeled: None,
81                            symref_target: None,
82                        },
83                    )
84                })
85                .collect(),
86            unborn: BTreeMap::new(),
87            prefixes: None,
88        }
89    }
90
91    #[test]
92    fn follows_git_order_and_reports_ambiguity() {
93        let refs = list(&[
94            "refs/heads/v2",
95            "refs/tags/v2",
96            "refs/heads/heads/x",
97            "refs/heads/x",
98        ]);
99        let Resolution::Ref { name, others, .. } = resolve(&refs, "v2").unwrap() else {
100            panic!("expected ref");
101        };
102        assert_eq!(
103            (name.as_str(), others),
104            ("refs/tags/v2", vec![String::from("refs/heads/v2")])
105        );
106        let Resolution::Ref { name, others, .. } = resolve(&refs, "heads/x").unwrap() else {
107            panic!("expected ref");
108        };
109        assert_eq!(
110            (name.as_str(), others),
111            ("refs/heads/x", vec![String::from("refs/heads/heads/x")])
112        );
113        assert_eq!(resolve(&refs, "nope"), Ok(Resolution::NotFound));
114        assert_eq!(resolve(&refs, "a..b"), Err(Error::InvalidRefName));
115    }
116
117    #[test]
118    fn full_object_ids_win_over_refs() {
119        let hex = "2222222222222222222222222222222222222222";
120        let refs = list(&[&format!("refs/tags/{hex}")]);
121        assert_eq!(
122            resolve(&refs, hex),
123            Ok(Resolution::Object {
124                oid: hex.parse().unwrap(),
125                refs: vec![format!("refs/tags/{hex}")],
126            })
127        );
128        let sha256 = "a".repeat(64);
129        assert_eq!(resolve(&refs, &sha256), Ok(Resolution::NotFound));
130    }
131
132    #[test]
133    fn partial_listing_reports_unlisted_candidates() {
134        let refs = list(&["refs/heads/v2"]).restrict(&["refs/heads/"]).unwrap();
135        let Resolution::Incomplete { missing } = resolve(&refs, "v2").unwrap() else {
136            panic!("expected incomplete");
137        };
138        assert_eq!(missing.len(), 5);
139        assert!(missing.contains(&String::from("refs/tags/v2")));
140        let covered = list(&["refs/heads/v2"])
141            .restrict(
142                &candidates("v2")
143                    .iter()
144                    .map(String::as_str)
145                    .collect::<Vec<_>>(),
146            )
147            .unwrap();
148        assert!(matches!(
149            resolve(&covered, "v2"),
150            Ok(Resolution::Ref { .. })
151        ));
152    }
153}