Skip to main content

grit_lib/revwalk/
merge_bases.rs

1//! Merge bases, ancestry and reachability counts on [`RevWalk`].
2use std::collections::HashSet;
3
4use crate::error::Result;
5use crate::merge_base::{
6    self, ReachableCountFilter, ReachableWalkCommitterCutoffs, ReachableWalkLimit,
7};
8use crate::objects::ObjectId;
9use crate::revwalk::RevWalk;
10
11/// Which merge bases [`RevWalk::merge_bases`] computes.
12#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
13#[non_exhaustive]
14pub enum MergeBaseMode {
15    /// `git merge-base A B...`: the best common ancestor of the first commit and a
16    /// hypothetical merge of the others. At most one id.
17    #[default]
18    Best,
19    /// `git merge-base --all`: every best common ancestor, newest committer date first for
20    /// two commits.
21    All,
22    /// `git merge-base --octopus`: the best ancestors common to every commit.
23    Octopus,
24}
25
26/// Options for [`RevWalk::reachable_excluding`].
27#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
28#[non_exhaustive]
29pub struct ReachableWalkOptions {
30    /// How the walk bounds its output.
31    pub limit: ReachableWalkLimit,
32    /// Committer-date cutoffs (`--since` / `--until`).
33    pub cutoffs: ReachableWalkCommitterCutoffs,
34}
35
36impl ReachableWalkOptions {
37    /// Sets [`limit`](Self::limit).
38    #[must_use]
39    pub fn with_limit(mut self, limit: ReachableWalkLimit) -> Self {
40        self.limit = limit;
41        self
42    }
43
44    /// Sets [`cutoffs`](Self::cutoffs).
45    #[must_use]
46    pub fn with_cutoffs(mut self, cutoffs: ReachableWalkCommitterCutoffs) -> Self {
47        self.cutoffs = cutoffs;
48        self
49    }
50}
51
52/// Options for [`RevWalk::ahead_behind`].
53#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
54#[non_exhaustive]
55pub struct AheadBehindOptions {
56    /// How many of the newest ahead commits to return in [`AheadBehind::newest_ahead`].
57    pub retain_newest_ahead: usize,
58    /// How many of the newest behind commits to return in [`AheadBehind::newest_behind`].
59    pub retain_newest_behind: usize,
60}
61
62impl AheadBehindOptions {
63    /// Sets [`retain_newest_ahead`](Self::retain_newest_ahead).
64    #[must_use]
65    pub fn with_retain_newest_ahead(mut self, count: usize) -> Self {
66        self.retain_newest_ahead = count;
67        self
68    }
69
70    /// Sets [`retain_newest_behind`](Self::retain_newest_behind).
71    #[must_use]
72    pub fn with_retain_newest_behind(mut self, count: usize) -> Self {
73        self.retain_newest_behind = count;
74        self
75    }
76}
77
78/// How far a commit is ahead of and behind another ([`RevWalk::ahead_behind`]).
79#[derive(Debug, Clone, Default, PartialEq, Eq)]
80#[non_exhaustive]
81pub struct AheadBehind {
82    /// Commits reachable from the head but not from the target.
83    pub ahead: usize,
84    /// Commits reachable from the target but not from the head.
85    pub behind: usize,
86    /// The newest ahead commits, newest first, up to
87    /// [`AheadBehindOptions::retain_newest_ahead`].
88    pub newest_ahead: Vec<ObjectId>,
89    /// The newest behind commits, newest first, up to
90    /// [`AheadBehindOptions::retain_newest_behind`].
91    pub newest_behind: Vec<ObjectId>,
92}
93
94impl<'repo> RevWalk<'repo> {
95    /// Merge bases of `commits` (`git merge-base`, `--all` or `--octopus` by `mode`).
96    ///
97    /// Returns an empty list for no commits or unrelated histories, and the commit itself
98    /// for one commit.
99    ///
100    /// # Errors
101    ///
102    /// Returns object read and commit parse errors from the walk.
103    ///
104    /// # Examples
105    ///
106    /// ```
107    /// # fn main() -> grit_lib::error::Result<()> {
108    /// use grit_lib::objects::ObjectKind;
109    /// use grit_lib::refs::store::RefName;
110    /// use grit_lib::repo::{InitOptions, Repository};
111    /// use grit_lib::revwalk::{MergeBaseMode, ResolveOptions};
112    /// let dir = tempfile::tempdir()?;
113    /// let options = InitOptions::default().with_initial_branch("main");
114    /// let (repo, _) = Repository::init(dir.path(), &options)?;
115    /// let tree = repo.odb().write(ObjectKind::Tree, b"")?;
116    /// let body = format!("tree {tree}\nauthor A <a@example.com> 1700000000 +0000\ncommitter A <a@example.com> 1700000000 +0000\n\ndoc\n");
117    /// let commit = repo.odb().write(ObjectKind::Commit, body.as_bytes())?;
118    /// let main = RefName::try_from("refs/heads/main").expect("valid ref name");
119    /// repo.references().update(&main, &commit)?;
120    /// let revwalk = repo.revwalk();
121    /// let head = revwalk.resolve("HEAD", &ResolveOptions::default())?;
122    /// assert_eq!(revwalk.merge_bases(&[head, head], MergeBaseMode::Best)?, vec![head]);
123    /// assert!(revwalk.is_ancestor(head, head)?);
124    /// # Ok(())
125    /// # }
126    /// ```
127    pub fn merge_bases(&self, commits: &[ObjectId], mode: MergeBaseMode) -> Result<Vec<ObjectId>> {
128        let repo = self.repository();
129        match mode {
130            MergeBaseMode::Best => match commits.split_first() {
131                Some((&first, rest)) => merge_base::merge_bases_first_vs_rest(repo, first, rest),
132                None => Ok(Vec::new()),
133            },
134            MergeBaseMode::All => merge_base::merge_bases_all(repo, commits),
135            MergeBaseMode::Octopus => merge_base::merge_bases_octopus(repo, commits),
136        }
137    }
138
139    /// The single merge base of `a` and `b`, as `git diff --merge-base` needs it.
140    ///
141    /// # Errors
142    ///
143    /// Returns [`RevisionError::NoMergeBase`](crate::error::RevisionError::NoMergeBase) for
144    /// unrelated histories,
145    /// [`RevisionError::MultipleMergeBases`](crate::error::RevisionError::MultipleMergeBases) when
146    /// there is more than one base, and object read errors from the walk.
147    pub fn merge_base_for_diff(&self, a: ObjectId, b: ObjectId) -> Result<ObjectId> {
148        merge_base::merge_base_for_diff_two_commits(self.repository(), a, b)
149    }
150
151    /// Whether `ancestor` is reachable from `descendant` (`git merge-base --is-ancestor`).
152    /// A commit is its own ancestor.
153    ///
154    /// # Errors
155    ///
156    /// Returns object read and commit parse errors from the walk.
157    pub fn is_ancestor(&self, ancestor: ObjectId, descendant: ObjectId) -> Result<bool> {
158        merge_base::is_ancestor(self.repository(), ancestor, descendant)
159    }
160
161    /// The commits of `commits` that no other one of them can reach
162    /// (`git merge-base --independent`), in input order.
163    ///
164    /// # Errors
165    ///
166    /// Returns object read and commit parse errors from the walk.
167    pub fn independent(&self, commits: &[ObjectId]) -> Result<Vec<ObjectId>> {
168        merge_base::independent_commits(self.repository(), commits)
169    }
170
171    /// Every commit reachable from `tip`, including `tip`.
172    ///
173    /// # Errors
174    ///
175    /// Returns object read and commit parse errors from the walk.
176    pub fn ancestor_closure(&self, tip: ObjectId) -> Result<HashSet<ObjectId>> {
177        merge_base::ancestor_closure(self.repository(), tip)
178    }
179
180    /// Fork point of `head` from the upstream named `upstream_spec`, as
181    /// `git merge-base --fork-point` computes it: the merge base of `head` and every commit
182    /// the upstream's reflog has held, when that base is itself one of those commits.
183    ///
184    /// Returns [`None`] when there is no such commit (Git prints nothing and exits 1), for
185    /// example when the upstream was rewritten so that its old tips share several merge
186    /// bases with `head`.
187    ///
188    /// # Parameters
189    ///
190    /// - `upstream_spec` - the upstream as the user named it (`origin/main`, `main@{u}`);
191    ///   picks the reflog to read.
192    /// - `upstream_tip` - the commit `upstream_spec` resolves to, used when the reflog is
193    ///   empty.
194    /// - `head` - the commit whose fork point is wanted.
195    ///
196    /// # Errors
197    ///
198    /// Returns `@{upstream}` resolution, reflog, object read and commit parse errors.
199    pub fn fork_point(
200        &self,
201        upstream_spec: &str,
202        upstream_tip: ObjectId,
203        head: ObjectId,
204    ) -> Result<Option<ObjectId>> {
205        let repo = self.repository();
206        let reflog_ref = if crate::rev_parse::upstream_suffix_info(upstream_spec).is_some() {
207            crate::rev_parse::resolve_upstream_symbolic_name(repo, upstream_spec)?
208        } else {
209            merge_base::resolve_fork_point_reflog_ref(repo, upstream_spec)
210        };
211        merge_base::try_reflog_fork_point(repo, &reflog_ref, upstream_tip, head)
212    }
213
214    /// Commit counts `head` is ahead of and behind `target`, optionally with the newest
215    /// commits on each side.
216    ///
217    /// # Errors
218    ///
219    /// Returns object read and commit parse errors from the walk.
220    pub fn ahead_behind(
221        &self,
222        head: ObjectId,
223        target: ObjectId,
224        options: &AheadBehindOptions,
225    ) -> Result<AheadBehind> {
226        let (ahead, behind, newest_ahead, newest_behind) =
227            merge_base::ahead_behind_of_target_commits(
228                self.repository(),
229                head,
230                target,
231                options.retain_newest_ahead,
232                options.retain_newest_behind,
233            )?;
234        Ok(AheadBehind {
235            ahead,
236            behind,
237            newest_ahead,
238            newest_behind,
239        })
240    }
241
242    /// Walk the commits reachable from `tips` that are not ancestors of any `hide` commit,
243    /// newest committer date first (`git rev-list tips ^hide`).
244    ///
245    /// Returns `(emitted, commits)`: with [`ReachableWalkLimit::CountAllRetainNewest`],
246    /// `emitted` counts the whole set while `commits` holds only the newest ones.
247    ///
248    /// # Errors
249    ///
250    /// Returns object read and commit parse errors from the walk.
251    pub fn reachable_excluding(
252        &self,
253        tips: &[ObjectId],
254        hide: &[ObjectId],
255        options: &ReachableWalkOptions,
256    ) -> Result<(usize, Vec<ObjectId>)> {
257        merge_base::walk_commits_reachable_excluding_ancestors_of_cutoffs(
258            self.repository(),
259            tips,
260            hide,
261            options.limit,
262            options.cutoffs,
263        )
264    }
265
266    /// Count the commits reachable from `tips` that are not ancestors of any `hide` commit
267    /// (`git rev-list --count tips ^hide`), without collecting them.
268    ///
269    /// Uses pack bitmaps and the commit-graph when they apply.
270    ///
271    /// # Errors
272    ///
273    /// Returns object read and commit parse errors from the walk.
274    pub fn count_reachable_excluding(
275        &self,
276        tips: &[ObjectId],
277        hide: &[ObjectId],
278        filter: ReachableCountFilter,
279    ) -> Result<usize> {
280        merge_base::count_commits_reachable_excluding_ancestors_of(
281            self.repository(),
282            tips,
283            hide,
284            filter,
285        )
286    }
287}