gix_protocol/fetch/refmap/
init.rs

1use bstr::{BString, ByteSlice};
2use gix_transport::client::Capabilities;
3
4use crate::{
5    fetch::{
6        refmap::{Mapping, Source, SpecIndex},
7        RefMap,
8    },
9    handshake::Ref,
10};
11
12/// The error returned by [`crate::Handshake::prepare_lsrefs_or_extract_refmap()`].
13#[derive(Debug, thiserror::Error)]
14#[allow(missing_docs)]
15pub enum Error {
16    #[error("The object format {format:?} as used by the remote is unsupported")]
17    UnknownObjectFormat { format: BString },
18    #[error(transparent)]
19    MappingValidation(#[from] gix_refspec::match_group::validate::Error),
20    #[error(transparent)]
21    ListRefs(#[from] crate::ls_refs::Error),
22}
23
24/// For use in [`RefMap::from_refs()`].
25#[derive(Debug, Clone)]
26pub struct Context {
27    /// All explicit refspecs to identify references on the remote that you are interested in.
28    /// Note that these are copied to [`RefMap::refspecs`] for convenience, as `RefMap::mappings` refer to them by index.
29    pub fetch_refspecs: Vec<gix_refspec::RefSpec>,
30    /// A list of refspecs to use as implicit refspecs which won't be saved or otherwise be part of the remote in question.
31    ///
32    /// This is useful for handling `remote.<name>.tagOpt` for example.
33    pub extra_refspecs: Vec<gix_refspec::RefSpec>,
34}
35
36impl Context {
37    pub(crate) fn aggregate_refspecs(&self) -> Vec<gix_refspec::RefSpec> {
38        let mut all_refspecs = self.fetch_refspecs.clone();
39        all_refspecs.extend(self.extra_refspecs.iter().cloned());
40        all_refspecs
41    }
42}
43
44impl RefMap {
45    /// Create a ref-map from already obtained `remote_refs`. Use `context` to pass in refspecs.
46    /// `capabilities` are used to determine the object format.
47    pub fn from_refs(remote_refs: Vec<Ref>, capabilities: &Capabilities, context: Context) -> Result<RefMap, Error> {
48        let all_refspecs = context.aggregate_refspecs();
49        let Context {
50            fetch_refspecs,
51            extra_refspecs,
52        } = context;
53        let num_explicit_specs = fetch_refspecs.len();
54        let group = gix_refspec::MatchGroup::from_fetch_specs(all_refspecs.iter().map(gix_refspec::RefSpec::to_ref));
55        let null = gix_hash::ObjectId::null(gix_hash::Kind::Sha1); // OK to hardcode Sha1, it's not supposed to match, ever.
56        let (res, fixes) = group
57            .match_lhs(remote_refs.iter().map(|r| {
58                let (full_ref_name, target, object) = r.unpack();
59                gix_refspec::match_group::Item {
60                    full_ref_name,
61                    target: target.unwrap_or(&null),
62                    object,
63                }
64            }))
65            .validated()?;
66
67        let mappings = res.mappings;
68        let mappings = mappings
69            .into_iter()
70            .map(|m| Mapping {
71                remote: m.item_index.map_or_else(
72                    || {
73                        Source::ObjectId(match m.lhs {
74                            gix_refspec::match_group::SourceRef::ObjectId(id) => id,
75                            _ => unreachable!("no item index implies having an object id"),
76                        })
77                    },
78                    |idx| Source::Ref(remote_refs[idx].clone()),
79                ),
80                local: m.rhs.map(std::borrow::Cow::into_owned),
81                spec_index: if m.spec_index < num_explicit_specs {
82                    SpecIndex::ExplicitInRemote(m.spec_index)
83                } else {
84                    SpecIndex::Implicit(m.spec_index - num_explicit_specs)
85                },
86            })
87            .collect();
88
89        // Assume sha1 if server says nothing, otherwise configure anything beyond sha1 in the local repo configuration
90        let object_hash = if let Some(object_format) = capabilities.capability("object-format").and_then(|c| c.value())
91        {
92            let object_format = object_format.to_str().map_err(|_| Error::UnknownObjectFormat {
93                format: object_format.into(),
94            })?;
95            match object_format {
96                "sha1" => gix_hash::Kind::Sha1,
97                unknown => return Err(Error::UnknownObjectFormat { format: unknown.into() }),
98            }
99        } else {
100            gix_hash::Kind::Sha1
101        };
102
103        Ok(Self {
104            mappings,
105            refspecs: fetch_refspecs,
106            extra_refspecs,
107            fixes,
108            remote_refs,
109            object_hash,
110        })
111    }
112}