gix_protocol/fetch/refmap/
init.rs1use bstr::ByteSlice;
2use gix_error::ExnResult;
3use gix_error::{ErrorExt, ResultExt, message};
4use gix_transport::client::Capabilities;
5
6use crate::{
7 fetch::{
8 RefMap,
9 refmap::{Mapping, Source, SpecIndex},
10 },
11 handshake::Ref,
12};
13
14#[derive(Debug, Clone)]
16pub struct Context {
17 pub fetch_refspecs: Vec<gix_refspec::RefSpec>,
20 pub extra_refspecs: Vec<gix_refspec::RefSpec>,
24}
25
26impl Context {
27 pub(crate) fn aggregate_refspecs(&self) -> Vec<gix_refspec::RefSpec> {
28 let mut all_refspecs = self.fetch_refspecs.clone();
29 all_refspecs.extend(self.extra_refspecs.iter().cloned());
30 all_refspecs
31 }
32}
33
34impl RefMap {
35 pub fn from_refs(remote_refs: Vec<Ref>, capabilities: &Capabilities, context: Context) -> ExnResult<RefMap> {
39 let all_refspecs = context.aggregate_refspecs();
40 let Context {
41 fetch_refspecs,
42 extra_refspecs,
43 } = context;
44 let num_explicit_specs = fetch_refspecs.len();
45 let group = gix_refspec::MatchGroup::from_fetch_specs(all_refspecs.iter().map(gix_refspec::RefSpec::to_ref));
46 let object_hash = extract_object_hash(capabilities)?;
47 let null = object_hash.null();
48 let (res, fixes) = group
49 .match_lhs(remote_refs.iter().map(|r| {
50 let (full_ref_name, target, object) = r.unpack();
51 gix_refspec::match_group::Item {
52 full_ref_name,
53 target: target.unwrap_or(&null),
54 object,
55 }
56 }))
57 .validated()
58 .or_raise_erased(|| message("Failed to validate mappings between remote and local references"))?;
59
60 let mappings = res.mappings;
61 let mappings = mappings
62 .into_iter()
63 .map(|m| Mapping {
64 remote: m.item_index.map_or_else(
65 || {
66 Source::ObjectId(match m.lhs {
67 gix_refspec::match_group::SourceRef::ObjectId(id) => id,
68 _ => unreachable!("no item index implies having an object id"),
69 })
70 },
71 |idx| Source::Ref(remote_refs[idx].clone()),
72 ),
73 local: m.rhs.map(std::borrow::Cow::into_owned),
74 spec_index: if m.spec_index < num_explicit_specs {
75 SpecIndex::ExplicitInRemote(m.spec_index)
76 } else {
77 SpecIndex::Implicit(m.spec_index - num_explicit_specs)
78 },
79 })
80 .collect();
81
82 Ok(Self {
83 mappings,
84 refspecs: fetch_refspecs,
85 extra_refspecs,
86 fixes,
87 remote_refs,
88 object_hash,
89 })
90 }
91}
92
93fn extract_object_hash(capabilities: &Capabilities) -> ExnResult<gix_hash::Kind> {
100 let object_format = match capabilities.capability("object-format").and_then(|c| c.value()) {
101 Some(object_format) => object_format.to_str().or_raise_erased(|| {
102 gix_error::validation("The object format used by the remote isn't valid UTF-8")
103 .with("input", object_format.as_bytes())
104 })?,
105 None => "sha1",
106 };
107 match object_format.parse::<gix_hash::Kind>() {
108 Ok(kind) => Ok(kind),
109 Err(err) => Err(
110 gix_error::validation(format!("The object format used by the remote is unsupported: {err}"))
111 .with("input", object_format.as_bytes())
112 .raise_erased(),
113 ),
114 }
115}