Skip to main content

gix_protocol/fetch/refmap/
init.rs

1use bstr::ByteSlice;
2use gix_error::{Result, ResultExt, corruption, message};
3use gix_transport::client::Capabilities;
4
5use crate::{
6    fetch::{
7        RefMap,
8        refmap::{Mapping, Source, SpecIndex},
9    },
10    handshake::Ref,
11};
12
13/// For use in [`RefMap::from_refs()`].
14#[derive(Debug, Clone)]
15pub struct Context {
16    /// All explicit refspecs to identify references on the remote that you are interested in.
17    /// Note that these are copied to [`RefMap::refspecs`] for convenience, as `RefMap::mappings` refer to them by index.
18    pub fetch_refspecs: Vec<gix_refspec::RefSpec>,
19    /// A list of refspecs to use as implicit refspecs which won't be saved or otherwise be part of the remote in question.
20    ///
21    /// This is useful for handling `remote.<name>.tagOpt` for example.
22    pub extra_refspecs: Vec<gix_refspec::RefSpec>,
23}
24
25impl Context {
26    pub(crate) fn aggregate_refspecs(&self) -> Vec<gix_refspec::RefSpec> {
27        let mut all_refspecs = self.fetch_refspecs.clone();
28        all_refspecs.extend(self.extra_refspecs.iter().cloned());
29        all_refspecs
30    }
31}
32
33impl RefMap {
34    /// Create a ref-map from already obtained `remote_refs`. Use `context` to pass in refspecs.
35    /// `capabilities` are used to determine the object format.
36    /// Invalid or unsupported object formats include their bytes as `input` [metadata](gix_error::Error::metadata()).
37    pub fn from_refs(remote_refs: Vec<Ref>, capabilities: &Capabilities, context: Context) -> Result<RefMap> {
38        let all_refspecs = context.aggregate_refspecs();
39        let Context {
40            fetch_refspecs,
41            extra_refspecs,
42        } = context;
43        let num_explicit_specs = fetch_refspecs.len();
44        let group = gix_refspec::MatchGroup::from_fetch_specs(all_refspecs.iter().map(gix_refspec::RefSpec::to_ref));
45        let object_hash = extract_object_hash(capabilities)?;
46        let (res, fixes) = group
47            .match_lhs(remote_refs.iter().map(|r| {
48                let (full_ref_name, target, object) = r.unpack();
49                gix_refspec::match_group::Item {
50                    full_ref_name,
51                    target,
52                    object,
53                }
54            }))
55            .validated()
56            .or_raise(|| message("Failed to validate mappings between remote and local references"))?;
57
58        let mappings = res.mappings;
59        let mappings = mappings
60            .into_iter()
61            .map(|m| Mapping {
62                remote: m.item_index.map_or_else(
63                    || {
64                        Source::ObjectId(match m.lhs {
65                            gix_refspec::match_group::SourceRef::ObjectId(id) => id,
66                            _ => unreachable!("no item index implies having an object id"),
67                        })
68                    },
69                    |idx| Source::Ref(remote_refs[idx].clone()),
70                ),
71                local: m.rhs.map(std::borrow::Cow::into_owned),
72                spec_index: if m.spec_index < num_explicit_specs {
73                    SpecIndex::ExplicitInRemote(m.spec_index)
74                } else {
75                    SpecIndex::Implicit(m.spec_index - num_explicit_specs)
76                },
77            })
78            .collect();
79
80        Ok(Self {
81            mappings,
82            refspecs: fetch_refspecs,
83            extra_refspecs,
84            fixes,
85            remote_refs,
86            object_hash,
87        })
88    }
89}
90
91/// Resolve the object format advertised by the server through the `object-format` capability.
92///
93/// When the capability is absent, the server is implicitly speaking Sha1 - older servers
94/// don't advertise it at all, and even newer ones may omit it for empty repositories.
95/// In builds whose `gix-hash` lacks the `sha1` feature, it's treated as unknown object format error.
96/// Errors include the object format bytes as `input` [metadata](gix_error::Error::metadata()).
97fn extract_object_hash(capabilities: &Capabilities) -> Result<gix_hash::Kind> {
98    let object_format = match capabilities.capability("object-format").and_then(|c| c.value()) {
99        Some(object_format) => object_format.to_str().or_raise(|| {
100            corruption("The object format used by the remote isn't valid UTF-8").with_input(object_format.as_bytes())
101        })?,
102        None => "sha1",
103    };
104    match object_format.parse::<gix_hash::Kind>() {
105        Ok(kind) => Ok(kind),
106        Err(err) => Err(message!("The object format used by the remote is unsupported: {err}")
107            .with_input(object_format.as_bytes())
108            .unsupported_error()),
109    }
110}