gix_protocol/fetch/refmap/
init.rs1use 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#[derive(Debug, Clone)]
15pub struct Context {
16 pub fetch_refspecs: Vec<gix_refspec::RefSpec>,
19 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 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
91fn 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}