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 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
92fn 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}