gix_protocol/fetch/refmap/
init.rs1use bstr::{BString, ByteSlice};
2use gix_transport::client::Capabilities;
3
4use crate::{
5 fetch::{
6 refmap::{Mapping, Source, SpecIndex},
7 RefMap,
8 },
9 handshake::Ref,
10};
11
12#[derive(Debug, thiserror::Error)]
14#[allow(missing_docs)]
15pub enum Error {
16 #[error("The object format {format:?} as used by the remote is unsupported")]
17 UnknownObjectFormat { format: BString },
18 #[error(transparent)]
19 MappingValidation(#[from] gix_refspec::match_group::validate::Error),
20 #[error(transparent)]
21 ListRefs(#[from] crate::ls_refs::Error),
22}
23
24#[derive(Debug, Clone)]
26pub struct Context {
27 pub fetch_refspecs: Vec<gix_refspec::RefSpec>,
30 pub extra_refspecs: Vec<gix_refspec::RefSpec>,
34}
35
36impl Context {
37 pub(crate) fn aggregate_refspecs(&self) -> Vec<gix_refspec::RefSpec> {
38 let mut all_refspecs = self.fetch_refspecs.clone();
39 all_refspecs.extend(self.extra_refspecs.iter().cloned());
40 all_refspecs
41 }
42}
43
44impl RefMap {
45 pub fn from_refs(remote_refs: Vec<Ref>, capabilities: &Capabilities, context: Context) -> Result<RefMap, Error> {
48 let all_refspecs = context.aggregate_refspecs();
49 let Context {
50 fetch_refspecs,
51 extra_refspecs,
52 } = context;
53 let num_explicit_specs = fetch_refspecs.len();
54 let group = gix_refspec::MatchGroup::from_fetch_specs(all_refspecs.iter().map(gix_refspec::RefSpec::to_ref));
55 let null = gix_hash::ObjectId::null(gix_hash::Kind::Sha1); let (res, fixes) = group
57 .match_lhs(remote_refs.iter().map(|r| {
58 let (full_ref_name, target, object) = r.unpack();
59 gix_refspec::match_group::Item {
60 full_ref_name,
61 target: target.unwrap_or(&null),
62 object,
63 }
64 }))
65 .validated()?;
66
67 let mappings = res.mappings;
68 let mappings = mappings
69 .into_iter()
70 .map(|m| Mapping {
71 remote: m.item_index.map_or_else(
72 || {
73 Source::ObjectId(match m.lhs {
74 gix_refspec::match_group::SourceRef::ObjectId(id) => id,
75 _ => unreachable!("no item index implies having an object id"),
76 })
77 },
78 |idx| Source::Ref(remote_refs[idx].clone()),
79 ),
80 local: m.rhs.map(std::borrow::Cow::into_owned),
81 spec_index: if m.spec_index < num_explicit_specs {
82 SpecIndex::ExplicitInRemote(m.spec_index)
83 } else {
84 SpecIndex::Implicit(m.spec_index - num_explicit_specs)
85 },
86 })
87 .collect();
88
89 let object_hash = if let Some(object_format) = capabilities.capability("object-format").and_then(|c| c.value())
91 {
92 let object_format = object_format.to_str().map_err(|_| Error::UnknownObjectFormat {
93 format: object_format.into(),
94 })?;
95 match object_format {
96 "sha1" => gix_hash::Kind::Sha1,
97 unknown => return Err(Error::UnknownObjectFormat { format: unknown.into() }),
98 }
99 } else {
100 gix_hash::Kind::Sha1
101 };
102
103 Ok(Self {
104 mappings,
105 refspecs: fetch_refspecs,
106 extra_refspecs,
107 fixes,
108 remote_refs,
109 object_hash,
110 })
111 }
112}