Skip to main content

gix_protocol/fetch/
types.rs

1use std::path::PathBuf;
2
3use crate::fetch::response::{Acknowledgement, ShallowUpdate, WantedRef};
4
5/// Options for use in [`fetch()`](`crate::fetch()`)
6#[derive(Debug, Clone)]
7pub struct Options<'a> {
8    /// The path to the file containing the shallow commit boundary.
9    ///
10    /// When needed, it will be locked in preparation for being modified.
11    pub shallow_file: PathBuf,
12    /// The parsed `core.sharedRepository` policy to apply when writing the shallow boundary.
13    pub shared_repository_permissions: gix_fs::SharedPermissions,
14    /// How to deal with shallow repositories. It does affect how negotiations are performed.
15    pub shallow: &'a Shallow,
16    /// Describe how to handle tags when fetching.
17    pub tags: Tags,
18    /// If `true`, if we fetch from a remote that only offers shallow clones, the operation will fail with an error
19    /// instead of writing the shallow boundary to the shallow file.
20    pub reject_shallow_remote: bool,
21}
22
23/// For use in [`crate::Handshake::prepare_lsrefs_or_extract_refmap()`] and [`fetch`](crate::fetch()).
24#[cfg(feature = "handshake")]
25pub struct Context<'a, T> {
26    /// The outcome of the handshake performed with the remote.
27    ///
28    /// Note that it's mutable as depending on the protocol, it may contain refs that have been sent unconditionally.
29    pub handshake: &'a mut crate::Handshake,
30    /// The transport to use when making an `ls-refs` or `fetch` call.
31    ///
32    /// This is always done if the underlying protocol is V2, which is implied by the absence of refs in the `handshake` outcome.
33    pub transport: &'a mut T,
34    /// How to self-identify during the `ls-refs` call in [`crate::Handshake::prepare_lsrefs_or_extract_refmap()`] or the `fetch` call in [`fetch()`](crate::fetch()).
35    ///
36    /// This could be read from the `gitoxide.userAgent` configuration variable.
37    pub user_agent: crate::command::Feature,
38    /// If `true`, output all packetlines using the `gix-trace` machinery.
39    pub trace_packetlines: bool,
40}
41
42#[cfg(feature = "fetch")]
43mod with_fetch {
44    use bstr::ByteSlice;
45    use gix_error::Result;
46
47    use crate::fetch::{self, negotiate, refmap};
48
49    /// For use in [`fetch`](crate::fetch()).
50    pub struct NegotiateContext<'a, 'b, 'c, Objects, Alternates, AlternatesOut, Find>
51    where
52        Objects: gix_object::Find + gix_object::FindHeader + gix_object::Exists,
53        Alternates: FnOnce() -> Result<AlternatesOut>,
54        AlternatesOut: Iterator<Item = (gix_ref::file::Store, Find)>,
55        Find: gix_object::Find,
56    {
57        /// Access to the object database.
58        /// *Note* that the `exists()` calls must not trigger a refresh of the ODB packs as plenty of them might fail, i.e. find on object.
59        pub objects: &'a Objects,
60        /// Access to the git references database.
61        pub refs: &'a gix_ref::file::Store,
62        /// A function that returns an iterator over `(refs, objects)` for each alternate repository, to assure all known objects are added also according to their tips.
63        pub alternates: Alternates,
64        /// The implementation that performs the negotiation later, i.e. prepare wants and haves.
65        pub negotiator: &'a mut dyn gix_negotiate::Negotiator,
66        /// The commit-graph for use by the `negotiator` - we populate it with tips to initialize the graph traversal.
67        pub graph: &'a mut gix_negotiate::Graph<'b, 'c>,
68    }
69
70    /// A trait to encapsulate steps to negotiate the contents of the pack.
71    ///
72    /// Typical implementations use the utilities found in the [`negotiate`] module.
73    pub trait Negotiate {
74        /// Typically invokes [`negotiate::mark_complete_and_common_ref()`].
75        fn mark_complete_and_common_ref(&mut self) -> Result<negotiate::Action>;
76        /// Typically invokes [`negotiate::add_wants()`].
77        /// Returns `true` if wants were added, or `false` if the negotiation should be aborted.
78        #[must_use]
79        fn add_wants(&mut self, arguments: &mut fetch::Arguments, remote_ref_target_known: &[bool]) -> bool;
80        /// Typically invokes [`negotiate::one_round()`].
81        fn one_round(
82            &mut self,
83            state: &mut negotiate::one_round::State,
84            arguments: &mut fetch::Arguments,
85            previous_response: Option<&fetch::Response>,
86        ) -> Result<(negotiate::Round, bool)>;
87    }
88
89    /// The outcome of [`fetch()`](crate::fetch()).
90    #[derive(Debug, Clone)]
91    pub struct Outcome {
92        /// The most recent server response.
93        ///
94        /// Useful to obtain information about new shallow boundaries.
95        pub last_response: fetch::Response,
96        /// Information about the negotiation to receive the new pack.
97        pub negotiate: NegotiateOutcome,
98    }
99
100    /// The negotiation-specific outcome of [`fetch()`](crate::fetch()).
101    #[derive(Debug, Clone)]
102    pub struct NegotiateOutcome {
103        /// The outcome of the negotiation stage of the fetch operation.
104        ///
105        /// If it is…
106        ///
107        /// * [`negotiate::Action::MustNegotiate`] there will always be a `pack`.
108        /// * [`negotiate::Action::SkipToRefUpdate`] there is no `pack` but references can be updated right away.
109        ///
110        /// Note that this is never [negotiate::Action::NoChange`] as this would mean there is no negotiation information at all
111        /// so this structure wouldn't be present.
112        pub action: negotiate::Action,
113        /// Additional information for each round of negotiation.
114        pub rounds: Vec<negotiate::Round>,
115    }
116
117    /// Information about the relationship between our refspecs, and remote references with their local counterparts.
118    ///
119    /// It's the first stage that offers connection to the server, and is typically required to perform one or more fetch operations.
120    #[derive(Default, Debug, Clone)]
121    pub struct RefMap {
122        /// A mapping between a remote reference and a local tracking branch.
123        pub mappings: Vec<refmap::Mapping>,
124        /// The explicit refspecs that were supposed to be used for fetching.
125        ///
126        /// Typically, they are configured by the remote and are referred to by
127        /// [`refmap::SpecIndex::ExplicitInRemote`] in [`refmap::Mapping`].
128        pub refspecs: Vec<gix_refspec::RefSpec>,
129        /// Refspecs which have been added implicitly due to settings of the `remote`, usually pre-initialized from
130        /// [`extra_refspecs` in RefMap options](refmap::init::Context).
131        /// They are referred to by [`refmap::SpecIndex::Implicit`] in [`refmap::Mapping`].
132        ///
133        /// They are never persisted nor are they typically presented to the user.
134        pub extra_refspecs: Vec<gix_refspec::RefSpec>,
135        /// Information about the fixes applied to the `mapping` due to validation and sanitization.
136        pub fixes: Vec<gix_refspec::match_group::validate::Fix>,
137        /// All refs advertised by the remote.
138        pub remote_refs: Vec<crate::handshake::Ref>,
139        /// The kind of hash used for all data sent by the server, if understood by this client implementation.
140        ///
141        /// It was extracted from the `handshake` as advertised by the server.
142        pub object_hash: gix_hash::Kind,
143    }
144
145    impl RefMap {
146        /// Return `true` if the explicit fetch refspecs represented by this mapping failed to match the remote in a way
147        /// that should typically be reported as "no mapping".
148        ///
149        /// Use this before negotiation or reference updates when callers need to reject a fetch early instead of proceeding
150        /// with an empty or purely implicit mapping set.
151        ///
152        /// This is the case if the server advertised refs but none matched at all, or if only implicit mappings were produced
153        /// while at least one explicit refspec required an actual ref match, as is the case for exact ref names like `HEAD`
154        /// or `refs/heads/main`.
155        pub fn is_missing_required_mapping(&self) -> bool {
156            let has_explicit_mapping = self
157                .mappings
158                .iter()
159                .any(|mapping| matches!(mapping.spec_index, crate::fetch::refmap::SpecIndex::ExplicitInRemote(_)));
160
161            (self.mappings.is_empty() && !self.remote_refs.is_empty())
162                || (!has_explicit_mapping && explicit_fetch_refspecs_require_a_match(&self.refspecs))
163        }
164    }
165
166    fn explicit_fetch_refspecs_require_a_match(refspecs: &[gix_refspec::RefSpec]) -> bool {
167        refspecs.iter().any(|spec| match spec.to_ref().instruction() {
168            gix_refspec::Instruction::Fetch(
169                gix_refspec::instruction::Fetch::Only { src } | gix_refspec::instruction::Fetch::AndUpdate { src, .. },
170            ) => src.find_byteset(b"*?[]\\").is_none() && gix_hash::ObjectId::from_hex(src).is_err(),
171            gix_refspec::Instruction::Fetch(gix_refspec::instruction::Fetch::Exclude { .. })
172            | gix_refspec::Instruction::Push(_) => false,
173        })
174    }
175}
176#[cfg(feature = "fetch")]
177pub use with_fetch::*;
178
179/// Describe how shallow clones are handled when fetching, with variants defining how the *shallow boundary* is handled.
180///
181/// The *shallow boundary* is a set of commits whose parents are not present in the repository.
182#[derive(Default, Debug, Clone, PartialEq, Eq)]
183pub enum Shallow {
184    /// Fetch all changes from the remote without affecting the shallow boundary at all.
185    ///
186    /// This also means that repositories that aren't shallow will remain like that.
187    #[default]
188    NoChange,
189    /// Receive update to `depth` commits in the history of the refs to fetch (from the viewpoint of the remote),
190    /// with the value of `1` meaning to receive only the commit a ref is pointing to.
191    ///
192    /// This may update the shallow boundary to increase or decrease the amount of available history.
193    DepthAtRemote(std::num::NonZeroU32),
194    /// Increase the number of commits and thus expand the shallow boundary by `depth` commits as seen from our local
195    /// shallow boundary, with a value of `0` having no effect.
196    Deepen(u32),
197    /// Set the shallow boundary at the `cutoff` time, meaning that there will be no commits beyond that time.
198    Since {
199        /// The date beyond which there will be no history.
200        cutoff: gix_date::Time,
201    },
202    /// Receive all history excluding all commits reachable from `remote_refs`. These can be long or short
203    /// ref names or tag names.
204    Exclude {
205        /// The ref names to exclude, short or long. Note that ambiguous short names will cause the remote to abort
206        /// without an error message being transferred (because the protocol does not support it)
207        remote_refs: Vec<gix_ref::PartialName>,
208        /// If some, this field has the same meaning as [`Shallow::Since`] which can be used in combination
209        /// with excluded references.
210        since_cutoff: Option<gix_date::Time>,
211    },
212}
213
214impl Shallow {
215    /// Produce a variant that causes the repository to loose its shallow boundary, effectively by extending it
216    /// beyond all limits.
217    pub fn undo() -> Self {
218        Shallow::DepthAtRemote((i32::MAX as u32).try_into().expect("valid at compile time"))
219    }
220}
221
222/// Describe how to handle tags when fetching
223#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
224pub enum Tags {
225    /// Fetch all tags from the remote, even if these are not reachable from objects referred to by our refspecs.
226    All,
227    /// Fetch only the tags that point to the objects being sent.
228    /// That way, annotated tags that point to an object we receive are automatically transmitted and their refs are created.
229    /// The same goes for lightweight tags.
230    #[default]
231    Included,
232    /// Do not fetch any tags.
233    None,
234}
235
236impl Tags {
237    /// Obtain a refspec that determines whether or not to fetch all tags, depending on this variant.
238    ///
239    /// The returned refspec is the default refspec for tags, but won't overwrite local tags ever.
240    #[cfg(feature = "fetch")]
241    pub fn to_refspec(&self) -> Option<gix_refspec::RefSpecRef<'static>> {
242        match self {
243            Tags::All | Tags::Included => Some(
244                gix_refspec::parse("refs/tags/*:refs/tags/*".into(), gix_refspec::parse::Operation::Fetch)
245                    .expect("valid"),
246            ),
247            Tags::None => None,
248        }
249    }
250}
251
252/// A representation of a complete fetch response
253#[derive(Debug, Clone)]
254pub struct Response {
255    pub(crate) acks: Vec<Acknowledgement>,
256    pub(crate) shallows: Vec<ShallowUpdate>,
257    pub(crate) wanted_refs: Vec<WantedRef>,
258    pub(crate) has_pack: bool,
259}
260
261/// The progress ids used in during various steps of the fetch operation.
262///
263/// Note that tagged progress isn't very widely available yet, but support can be improved as needed.
264///
265/// Use this information to selectively extract the progress of interest in case the parent application has custom visualization.
266#[derive(Debug, Copy, Clone)]
267pub enum ProgressId {
268    /// The progress name is defined by the remote and the progress messages it sets, along with their progress values and limits.
269    RemoteProgress,
270}
271
272impl From<ProgressId> for gix_utils::progress::Id {
273    fn from(v: ProgressId) -> Self {
274        match v {
275            ProgressId::RemoteProgress => *b"FERP",
276        }
277    }
278}