Skip to main content

gix/remote/connection/fetch/update_refs/
update.rs

1use std::path::PathBuf;
2
3use crate::remote::fetch;
4
5mod error {
6    /// The error returned when updating references.
7    #[derive(Debug, thiserror::Error)]
8    #[allow(missing_docs)]
9    pub enum Error {
10        #[error(transparent)]
11        FindReference(#[from] crate::reference::find::Error),
12        #[error("A remote reference had a name that wasn't considered valid. Corrupt remote repo or insufficient checks on remote?")]
13        InvalidRefName(#[from] gix_validate::reference::name::Error),
14        #[error("Failed to update references to their new position to match their remote locations")]
15        EditReferences(#[from] crate::reference::edit::Error),
16        #[error("Failed to read or iterate worktree dir")]
17        WorktreeListing(#[from] std::io::Error),
18        #[error("Could not open worktree repository")]
19        OpenWorktreeRepo(#[from] crate::open::Error),
20        #[error("Could not find local commit for fast-forward ancestor check")]
21        FindCommit(#[from] crate::object::find::existing::Error),
22        #[error("Could not peel symbolic local reference to its ID")]
23        PeelToId(#[from] crate::reference::peel::Error),
24        #[error("Failed to follow a symbolic reference to assure worktree isn't affected")]
25        FollowSymref(#[from] gix_ref::file::find::existing::Error),
26        #[error(transparent)]
27        FindObject(#[from] crate::object::find::Error),
28    }
29}
30
31pub use error::Error;
32
33/// The outcome of the refs-update operation at the end of a fetch.
34#[derive(Debug, Clone)]
35pub struct Outcome {
36    /// All edits that were performed to update local refs.
37    pub edits: Vec<gix_ref::transaction::RefEdit>,
38    /// Each update provides more information about what happened to the corresponding mapping.
39    /// Use [`iter_mapping_updates()`][Self::iter_mapping_updates()] to recombine the update information with ref-edits and their
40    /// mapping.
41    pub updates: Vec<super::Update>,
42}
43
44/// Describe the way a ref was updated, with particular focus on how the (peeled) target commit was affected.
45///
46/// Note that for all the variants that signal a change or `NoChangeNeeded` it's additionally possible to change the target type
47/// from symbolic to direct, or the other way around.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum Mode {
50    /// No change was attempted as the remote ref didn't change compared to the current ref, or because no remote ref was specified
51    /// in the ref-spec. Note that the expected value is still asserted to uncover potential race conditions with other processes.
52    NoChangeNeeded,
53    /// The old ref's commit was an ancestor of the new one, allowing for a fast-forward without a merge.
54    FastForward,
55    /// The ref was set to point to the new commit from the remote without taking into consideration its ancestry.
56    Forced,
57    /// A new ref has been created as there was none before.
58    New,
59    /// The reference belongs to a tag that was listed by the server but whose target didn't get sent as it doesn't point
60    /// to the commit-graph we were fetching explicitly.
61    ///
62    /// This is kind of update is only happening if `remote.<name>.tagOpt` is not set explicitly to either `--tags` or `--no-tags`.
63    ImplicitTagNotSentByRemote,
64    /// The object id to set the target reference to could not be found.
65    RejectedSourceObjectNotFound {
66        /// The id of the object that didn't exist in the object database, even though it should since it should be part of the pack.
67        id: gix_hash::ObjectId,
68    },
69    /// Tags can never be overwritten (whether the new object would be a fast-forward or not, or unchanged), unless the refspec
70    /// specifies force.
71    RejectedTagUpdate,
72    /// The reference update would not have been a fast-forward, and force is not specified in the ref-spec.
73    RejectedNonFastForward,
74    /// The remote has an unborn symbolic reference where we have one that is set. This means the remote
75    /// has reset itself to a newly initialized state or a state that is highly unusual.
76    /// It may also mean that the remote knows the target name, but it's not available locally and not included in the ref-mappings
77    /// to be created, so we would effectively change a valid local ref into one that seems unborn, which is rejected.
78    /// Note that this mode may have an associated ref-edit that is a no-op, or current-state assertion, for logistical reasons only
79    /// and having no edit would be preferred.
80    RejectedToReplaceWithUnborn,
81    /// The update was rejected because the branch is checked out in the given worktree_dir.
82    ///
83    /// Note that the check applies to any known worktree, whether it's present on disk or not.
84    RejectedCurrentlyCheckedOut {
85        /// The path(s) to the worktree directory where the branch is checked out.
86        worktree_dirs: Vec<PathBuf>,
87    },
88}
89
90impl std::fmt::Display for Mode {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        match self {
93            Mode::NoChangeNeeded => "up-to-date",
94            Mode::FastForward => "fast-forward",
95            Mode::Forced => "forced-update",
96            Mode::New => "new",
97            Mode::ImplicitTagNotSentByRemote => "unrelated tag on remote",
98            Mode::RejectedSourceObjectNotFound { id } => return write!(f, "rejected ({id} not found)"),
99            Mode::RejectedTagUpdate => "rejected (would overwrite existing tag)",
100            Mode::RejectedNonFastForward => "rejected (non-fast-forward)",
101            Mode::RejectedToReplaceWithUnborn => "rejected (refusing to overwrite existing with unborn ref)",
102            Mode::RejectedCurrentlyCheckedOut { worktree_dirs } => {
103                return write!(
104                    f,
105                    "rejected (cannot write into checked-out branch at \"{}\")",
106                    worktree_dirs
107                        .iter()
108                        .filter_map(|d| d.to_str())
109                        .collect::<Vec<_>>()
110                        .join(", ")
111                )
112            }
113        }
114        .fmt(f)
115    }
116}
117
118/// Indicates that a ref changes its type.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash)]
120pub enum TypeChange {
121    /// A local direct reference is changed into a symbolic one.
122    DirectToSymbolic,
123    /// A local symbolic reference is changed into a direct one.
124    SymbolicToDirect,
125}
126
127impl Outcome {
128    /// Produce an iterator over all information used to produce the this outcome, ref-update by ref-update, using the `mappings`
129    /// used when producing the ref update.
130    ///
131    /// Note that mappings that don't have a corresponding entry in `refspecs`  these will be `None` even though that should never be the case.
132    /// This can happen if the `refspecs` passed in aren't the respecs used to create the `mapping`, and it's up to the caller to sort it out.
133    pub fn iter_mapping_updates<'a, 'b>(
134        &self,
135        mappings: &'a [fetch::refmap::Mapping],
136        refspecs: &'b [gix_refspec::RefSpec],
137        extra_refspecs: &'b [gix_refspec::RefSpec],
138    ) -> impl Iterator<
139        Item = (
140            &super::Update,
141            &'a fetch::refmap::Mapping,
142            Option<&'b gix_refspec::RefSpec>,
143            Option<&gix_ref::transaction::RefEdit>,
144        ),
145    > {
146        self.updates.iter().zip(mappings.iter()).map(move |(update, mapping)| {
147            (
148                update,
149                mapping,
150                mapping.spec_index.get(refspecs, extra_refspecs),
151                update.edit_index.and_then(|idx| self.edits.get(idx)),
152            )
153        })
154    }
155}