Skip to main content

grit_lib/revwalk/
resolve.rs

1//! Revision resolution on [`RevWalk`]: [`RevWalk::resolve`] with [`ResolveOptions`], peeling,
2//! abbreviation and symbolic names.
3use crate::error::Result;
4use crate::objects::ObjectId;
5use crate::rev_parse::{self, TreeishBlobAtPath};
6use crate::revwalk::RevWalk;
7
8/// Object kind [`RevWalk::resolve`] peels the named object to.
9///
10/// The kind also breaks ties when abbreviated hex matches several objects: [`Peel::Commit`]
11/// prefers commits, [`Peel::Tree`] tree-ish objects and [`Peel::Blob`] blobs. An explicit
12/// `^{kind}` suffix in the spec always wins over the hint.
13#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
14#[non_exhaustive]
15pub enum Peel {
16    /// The object the spec names, unpeeled. Ambiguous abbreviated hex follows
17    /// `core.disambiguate`, or [`ResolvePurpose::RangeEnd`] when set.
18    #[default]
19    Any,
20    /// A commit: tags are peeled, `A..B` resolves to `B` (an empty side means `HEAD`) and
21    /// `A...B` to the merge base of `A` and `B`, like Git's commit-ish arguments to `log`
22    /// or `reset`.
23    Commit,
24    /// A tree: a commit yields its root tree and tags are peeled, like Git's tree-ish
25    /// arguments (`commit-tree`, `read-tree`).
26    Tree,
27    /// A blob: tags are peeled; any other kind is an error.
28    Blob,
29}
30
31/// How a name that matches no ref or object is treated: as a possible path (porcelain) or as
32/// a bad revision (plumbing).
33///
34/// With [`IndexDwim::On`], such a name fails with
35/// [`RevParseError::AmbiguousArgument`](super::rev_parse_error::RevParseError::AmbiguousArgument)
36/// (Git's "unknown revision or path not in the working tree"), so a caller can fall back to
37/// treating it as a pathspec; in a bare repository a tracked path resolves to its index entry
38/// like `:path`. Git's plumbing (`rev-parse --verify`) and commands that must tell revisions
39/// from pathspecs (`reset <commit> -- <paths>`) use [`IndexDwim::Off`], where the name fails
40/// with [`RevParseError::InvalidObjectName`](super::rev_parse_error::RevParseError::InvalidObjectName).
41#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
42#[non_exhaustive]
43pub enum IndexDwim {
44    /// Treat an unknown name as a possible path.
45    #[default]
46    On,
47    /// Resolve refs and object names only.
48    Off,
49}
50
51/// The kind of argument being resolved, which tunes disambiguation like Git's per-command
52/// lookups.
53#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
54#[non_exhaustive]
55pub enum ResolvePurpose {
56    /// A plain revision argument.
57    #[default]
58    Revision,
59    /// An endpoint of a range (`A..B`) or a `rev-parse --verify` argument: ambiguous
60    /// abbreviated hex prefers commits. [`Peel::Commit`] implies this; [`Peel::Tree`] and
61    /// [`Peel::Blob`] prefer their own kind instead.
62    RangeEnd,
63    /// A `checkout` / `switch` target with remote-branch guessing off (Git's `--no-guess`):
64    /// a bare `name` does not resolve to the one `refs/remotes/<remote>/name` that matches.
65    CheckoutNoGuess,
66}
67
68/// How [`RevWalk::resolve`] interprets a revision spec.
69///
70/// The default resolves any object, reports an unknown name as a possible path, and treats
71/// the spec as a plain revision argument.
72///
73/// # Examples
74///
75/// ```
76/// use grit_lib::revwalk::{IndexDwim, Peel, ResolveOptions, ResolvePurpose};
77///
78/// // `git rev-parse --verify <spec>`
79/// let verify = ResolveOptions::default()
80///     .with_index_dwim(IndexDwim::Off)
81///     .with_purpose(ResolvePurpose::RangeEnd);
82/// // A commit-ish argument such as `git log <rev>`
83/// let commit = ResolveOptions::default().with_peel(Peel::Commit);
84/// assert_ne!(verify, commit);
85/// ```
86#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
87#[non_exhaustive]
88pub struct ResolveOptions {
89    /// Object kind the result is peeled to.
90    pub peel: Peel,
91    /// Whether a tracked path may resolve to its index entry.
92    pub index_dwim: IndexDwim,
93    /// The kind of argument being resolved.
94    pub purpose: ResolvePurpose,
95}
96
97impl ResolveOptions {
98    /// Sets [`peel`](Self::peel).
99    #[must_use]
100    pub fn with_peel(mut self, peel: Peel) -> Self {
101        self.peel = peel;
102        self
103    }
104
105    /// Sets [`index_dwim`](Self::index_dwim).
106    #[must_use]
107    pub fn with_index_dwim(mut self, index_dwim: IndexDwim) -> Self {
108        self.index_dwim = index_dwim;
109        self
110    }
111
112    /// Sets [`purpose`](Self::purpose).
113    #[must_use]
114    pub fn with_purpose(mut self, purpose: ResolvePurpose) -> Self {
115        self.purpose = purpose;
116        self
117    }
118}
119
120/// How many hex digits [`RevWalk::abbreviate`] starts from.
121#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
122#[non_exhaustive]
123pub enum AbbrevLength {
124    /// `core.abbrev`, or Git's automatic length for the object count when it is unset or
125    /// `auto`.
126    #[default]
127    Configured,
128    /// At least this many digits (clamped to 4 through the full hex length).
129    AtLeast(usize),
130}
131
132impl<'repo> RevWalk<'repo> {
133    /// Resolve a revision `spec` (`HEAD`, `main~2`, `v1.0^{tree}`, `HEAD:path`, `@{-1}`,
134    /// `:/message`, an abbreviated object id, ...) to an object id.
135    ///
136    /// # Parameters
137    ///
138    /// - `spec` - one revision expression.
139    /// - `options` - what the result is peeled to, how an unknown name is reported, and how
140    ///   ambiguous abbreviated hex is broken ([`ResolveOptions`]).
141    ///
142    /// # Errors
143    ///
144    /// - [`RevParseError::AmbiguousArgument`](super::rev_parse_error::RevParseError::AmbiguousArgument)
145    ///   for an unknown name with [`IndexDwim::On`] and
146    ///   [`RevParseError::InvalidObjectName`](super::rev_parse_error::RevParseError::InvalidObjectName)
147    ///   with [`IndexDwim::Off`];
148    ///   [`RevParseError::AmbiguousShortObject`](super::rev_parse_error::RevParseError::AmbiguousShortObject)
149    ///   when abbreviated hex matches several objects the options can't choose between, and
150    ///   other rev-parse errors.
151    /// - [`RefError::Invalid`](crate::error::RefError::Invalid) when [`Peel::Commit`] meets a
152    ///   tree or blob, and [`ObjectError::NotFound`](crate::error::ObjectError::NotFound) when
153    ///   [`Peel::Tree`] or [`Peel::Blob`] cannot peel the object.
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// # fn main() -> grit_lib::error::Result<()> {
159    /// use grit_lib::objects::ObjectKind;
160    /// use grit_lib::refs::store::RefName;
161    /// use grit_lib::repo::{InitOptions, Repository};
162    /// use grit_lib::revwalk::{Peel, ResolveOptions};
163    /// let dir = tempfile::tempdir()?;
164    /// let options = InitOptions::default().with_initial_branch("main");
165    /// let (repo, _) = Repository::init(dir.path(), &options)?;
166    /// let tree = repo.odb().write(ObjectKind::Tree, b"")?;
167    /// let body = format!("tree {tree}\nauthor A <a@example.com> 1700000000 +0000\ncommitter A <a@example.com> 1700000000 +0000\n\ndoc\n");
168    /// let commit = repo.odb().write(ObjectKind::Commit, body.as_bytes())?;
169    /// let main = RefName::try_from("refs/heads/main").expect("valid ref name");
170    /// repo.references().update(&main, &commit)?;
171    /// let revwalk = repo.revwalk();
172    /// let commit = revwalk.resolve("refs/heads/main", &ResolveOptions::default())?;
173    /// let tree = revwalk.resolve("HEAD", &ResolveOptions::default().with_peel(Peel::Tree))?;
174    /// assert_ne!(commit, tree);
175    /// # Ok(())
176    /// # }
177    /// ```
178    pub fn resolve(&self, spec: &str, options: &ResolveOptions) -> Result<ObjectId> {
179        rev_parse::resolve_revision_with_options(self.repository(), spec, options)
180    }
181
182    /// Peel `oid` through tags to a commit.
183    ///
184    /// # Errors
185    ///
186    /// Returns [`RefError::Invalid`](crate::error::RefError::Invalid) when the object peels
187    /// to a tree or blob, and object read errors.
188    pub fn peel_to_commit(&self, oid: ObjectId) -> Result<ObjectId> {
189        rev_parse::peel_to_commit_for_merge_base(self.repository(), oid)
190    }
191
192    /// Peel `oid` to a tree: a commit yields its root tree, tags are peeled, a tree is
193    /// returned unchanged.
194    ///
195    /// # Errors
196    ///
197    /// Returns [`ObjectError::NotFound`](crate::error::ObjectError::NotFound) when the
198    /// object peels to a blob, and object read errors.
199    pub fn peel_to_tree(&self, oid: ObjectId) -> Result<ObjectId> {
200        rev_parse::peel_to_tree(self.repository(), oid)
201    }
202
203    /// Resolve `rev:path` to the blob (or symlink) at `path` in the tree of `rev`.
204    ///
205    /// # Errors
206    ///
207    /// Fails when `spec` is not `treeish:path`, when the path is missing, or when it names a
208    /// tree or gitlink.
209    pub fn blob_at_path(&self, spec: &str) -> Result<TreeishBlobAtPath> {
210        rev_parse::resolve_treeish_blob_at_path(self.repository(), spec)
211    }
212
213    /// Shortest unique abbreviation of `oid`, starting from `length` hex digits.
214    ///
215    /// An id missing from the object database is cut to the starting length.
216    ///
217    /// # Errors
218    ///
219    /// Propagates config read and object database lookup failures.
220    pub fn abbreviate(&self, oid: ObjectId, length: AbbrevLength) -> Result<String> {
221        let repo = self.repository();
222        let min_len = match length {
223            AbbrevLength::AtLeast(len) => len,
224            AbbrevLength::Configured => {
225                let config = repo.config().snapshot()?;
226                crate::commit_pretty::resolve_core_abbrev_len(&config, repo.odb())?
227            }
228        };
229        rev_parse::abbreviate_object_id(repo, oid, min_len)
230    }
231
232    /// Every object id (loose, packed and in alternates) whose hex starts with `prefix`.
233    ///
234    /// # Errors
235    ///
236    /// Propagates object database lookup failures.
237    pub fn abbrev_matches(&self, prefix: &str) -> Result<Vec<ObjectId>> {
238        rev_parse::list_all_abbrev_matches(self.repository(), prefix)
239    }
240
241    /// Full ref name `spec` names (`rev-parse --symbolic-full-name`): `HEAD` gives its
242    /// branch, `main` gives `refs/heads/main`, `@{-1}` the previous branch, and
243    /// `@{upstream}` / `@{push}` the remote-tracking ref.
244    ///
245    /// Returns [`None`] when `spec` does not name a ref.
246    #[must_use]
247    pub fn symbolic_full_name(&self, spec: &str) -> Option<String> {
248        rev_parse::symbolic_full_name(self.repository(), spec)
249    }
250
251    /// Remote-tracking ref an `@{upstream}`, `@{u}` or `@{push}` spec names
252    /// (`main@{u}` gives `refs/remotes/origin/main`).
253    ///
254    /// # Errors
255    ///
256    /// Returns [`RevParseError::NoUpstream`](super::rev_parse_error::RevParseError::NoUpstream),
257    /// [`RevParseError::UpstreamNotTracked`](super::rev_parse_error::RevParseError::UpstreamNotTracked)
258    /// and the `@{push}` variants of
259    /// [`RevParseError`](super::rev_parse_error::RevParseError), or
260    /// [`RefError::Invalid`](crate::error::RefError::Invalid) when `spec` has no upstream
261    /// suffix.
262    pub fn upstream_symbolic_name(&self, spec: &str) -> Result<String> {
263        rev_parse::resolve_upstream_symbolic_name(self.repository(), spec)
264    }
265}