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 null = object_hash.null();
47        let (res, fixes) = group
48            .match_lhs(remote_refs.iter().map(|r| {
49                let (full_ref_name, target, object) = r.unpack();
50                gix_refspec::match_group::Item {
51                    full_ref_name,
52                    target: target.unwrap_or(&null),
53                    object,
54                }
55            }))
56            .validated()
57            .or_raise(|| message("Failed to validate mappings between remote and local references"))?;
58
59        let mappings = res.mappings;
60        let mappings = mappings
61            .into_iter()
62            .map(|m| Mapping {
63                remote: m.item_index.map_or_else(
64                    || {
65                        Source::ObjectId(match m.lhs {
66                            gix_refspec::match_group::SourceRef::ObjectId(id) => id,
67                            _ => unreachable!("no item index implies having an object id"),
68                        })
69                    },
70                    |idx| Source::Ref(remote_refs[idx].clone()),
71                ),
72                local: m.rhs.map(std::borrow::Cow::into_owned),
73                spec_index: if m.spec_index < num_explicit_specs {
74                    SpecIndex::ExplicitInRemote(m.spec_index)
75                } else {
76                    SpecIndex::Implicit(m.spec_index - num_explicit_specs)
77                },
78            })
79            .collect();
80
81        Ok(Self {
82            mappings,
83            refspecs: fetch_refspecs,
84            extra_refspecs,
85            fixes,
86            remote_refs,
87            object_hash,
88        })
89    }
90}
91
92/// Resolve the object format advertised by the server through the `object-format` capability.
93///
94/// When the capability is absent, the server is implicitly speaking Sha1 - older servers
95/// don't advertise it at all, and even newer ones may omit it for empty repositories.
96/// In builds whose `gix-hash` lacks the `sha1` feature, it's treated as unknown object format error.
97/// Errors include the object format bytes as `input` [metadata](gix_error::Error::metadata()).
98fn extract_object_hash(capabilities: &Capabilities) -> Result<gix_hash::Kind> {
99    let object_format = match capabilities.capability("object-format").and_then(|c| c.value()) {
100        Some(object_format) => object_format.to_str().or_raise(|| {
101            corruption("The object format used by the remote isn't valid UTF-8").with_input(object_format.as_bytes())
102        })?,
103        None => "sha1",
104    };
105    match object_format.parse::<gix_hash::Kind>() {
106        Ok(kind) => Ok(kind),
107        Err(err) => Err(message!("The object format used by the remote is unsupported: {err}")
108            .with_input(object_format.as_bytes())
109            .unsupported_error()),
110    }
111}