Skip to main content

jj_lib/
index.rs

1// Copyright 2020 The Jujutsu Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Interfaces for indexes of the commits in a repository.
16
17use std::any::Any;
18use std::fmt::Debug;
19use std::sync::Arc;
20
21use async_trait::async_trait;
22use itertools::Itertools as _;
23use thiserror::Error;
24
25use crate::backend::ChangeId;
26use crate::backend::CommitId;
27use crate::commit::Commit;
28use crate::object_id::HexPrefix;
29use crate::object_id::PrefixResolution;
30use crate::operation::Operation;
31use crate::repo_path::RepoPathBuf;
32use crate::revset::ResolvedExpression;
33use crate::revset::Revset;
34use crate::revset::RevsetEvaluationError;
35use crate::store::Store;
36
37/// Returned by [`IndexStore`] in the event of an error.
38#[derive(Debug, Error)]
39pub enum IndexStoreError {
40    /// Error reading a [`ReadonlyIndex`] from the [`IndexStore`].
41    #[error("Failed to read index")]
42    Read(#[source] Box<dyn std::error::Error + Send + Sync>),
43    /// Error writing a [`MutableIndex`] to the [`IndexStore`].
44    #[error("Failed to write index")]
45    Write(#[source] Box<dyn std::error::Error + Send + Sync>),
46}
47
48/// Result of [`IndexStore`] operations.
49pub type IndexStoreResult<T> = Result<T, IndexStoreError>;
50
51/// Returned by [`Index`] backend in the event of an error.
52#[derive(Debug, Error)]
53pub enum IndexError {
54    /// Error returned if [`Index::all_heads_for_gc()`] is not supported by the
55    /// [`Index`] backend.
56    #[error("Cannot collect all heads by index of this type")]
57    AllHeadsForGcUnsupported,
58    /// Some other index error.
59    #[error(transparent)]
60    Other(Box<dyn std::error::Error + Send + Sync>),
61}
62
63/// Result of [`Index`] operations.
64pub type IndexResult<T> = Result<T, IndexError>;
65
66/// Defines the interface for types that provide persistent storage for an
67/// index.
68#[async_trait(?Send)]
69pub trait IndexStore: Any + Send + Sync + Debug {
70    /// Returns a name representing the type of index that the `IndexStore` is
71    /// compatible with. For example, the `IndexStore` for the default index
72    /// returns "default".
73    fn name(&self) -> &str;
74
75    /// Returns the index at the specified operation.
76    async fn get_index_at_op(
77        &self,
78        op: &Operation,
79        store: &Arc<Store>,
80    ) -> IndexStoreResult<Box<dyn ReadonlyIndex>>;
81
82    /// Writes `index` to the index store and returns a read-only version of the
83    /// index.
84    fn write_index(
85        &self,
86        index: Box<dyn MutableIndex>,
87        op: &Operation,
88    ) -> IndexStoreResult<Box<dyn ReadonlyIndex>>;
89}
90
91impl dyn IndexStore {
92    /// Returns reference of the implementation type.
93    pub fn downcast_ref<T: IndexStore>(&self) -> Option<&T> {
94        (self as &dyn Any).downcast_ref()
95    }
96}
97
98/// Defines the interface for types that provide an index of the commits in a
99/// repository by [`CommitId`].
100#[async_trait]
101pub trait Index: Send + Sync {
102    /// Returns the minimum prefix length to disambiguate `commit_id` from other
103    /// commits in the index. The length returned is the number of hexadecimal
104    /// digits in the minimum prefix.
105    ///
106    /// If the given `commit_id` doesn't exist, returns the minimum prefix
107    /// length which matches none of the commits in the index.
108    async fn shortest_unique_commit_id_prefix_len(
109        &self,
110        commit_id: &CommitId,
111    ) -> IndexResult<usize>;
112
113    /// Searches the index for commit IDs matching `prefix`. Returns a
114    /// [`PrefixResolution`] with a [`CommitId`] if the prefix matches a single
115    /// commit.
116    async fn resolve_commit_id_prefix(
117        &self,
118        prefix: &HexPrefix,
119    ) -> IndexResult<PrefixResolution<CommitId>>;
120
121    /// Returns true if `commit_id` is present in the index.
122    async fn has_id(&self, commit_id: &CommitId) -> IndexResult<bool>;
123
124    /// Returns true if `ancestor_id` commit is an ancestor of the
125    /// `descendant_id` commit, or if `ancestor_id` equals `descendant_id`.
126    async fn is_ancestor(
127        &self,
128        ancestor_id: &CommitId,
129        descendant_id: &CommitId,
130    ) -> IndexResult<bool>;
131
132    /// Returns the best common ancestor or ancestors of the commits in `set1`
133    /// and `set2`. A "best common ancestor" has no descendants that are also
134    /// common ancestors.
135    async fn common_ancestors(
136        &self,
137        set1: &[CommitId],
138        set2: &[CommitId],
139    ) -> IndexResult<Vec<CommitId>>;
140
141    /// Heads among all indexed commits at the associated operation.
142    ///
143    /// Suppose the index contains all the historical heads and their ancestors
144    /// reachable from the associated operation, this function returns the heads
145    /// that should be preserved on garbage collection.
146    ///
147    /// The iteration order is unspecified.
148    fn all_heads_for_gc(&self) -> IndexResult<Box<dyn Iterator<Item = CommitId> + '_>>;
149
150    /// Returns the subset of commit IDs in `candidates` which are not ancestors
151    /// of other commits in `candidates`. If a commit id is duplicated in the
152    /// `candidates` list it will appear at most once in the output.
153    async fn heads(
154        &self,
155        candidates: &mut (dyn Iterator<Item = &CommitId> + Send),
156    ) -> IndexResult<Vec<CommitId>>;
157
158    /// Returns iterator over paths changed at the specified commit. The paths
159    /// are sorted. Returns `None` if the commit wasn't indexed.
160    async fn changed_paths_in_commit(
161        &self,
162        commit_id: &CommitId,
163    ) -> IndexResult<Option<Box<dyn Iterator<Item = RepoPathBuf> + '_>>>;
164
165    /// Resolves the revset `expression` against the index and corresponding
166    /// `store`.
167    fn evaluate_revset(
168        &self,
169        expression: &ResolvedExpression,
170        store: &Arc<Store>,
171    ) -> Result<Box<dyn Revset>, RevsetEvaluationError>;
172}
173
174#[expect(missing_docs)]
175pub trait ReadonlyIndex: Any + Send + Sync {
176    fn as_index(&self) -> &dyn Index;
177
178    fn change_id_index(
179        &self,
180        heads: &mut dyn Iterator<Item = &CommitId>,
181    ) -> IndexResult<Box<dyn ChangeIdIndex>>;
182
183    fn start_modification(&self) -> Box<dyn MutableIndex>;
184}
185
186impl dyn ReadonlyIndex {
187    /// Returns reference of the implementation type.
188    pub fn downcast_ref<T: ReadonlyIndex>(&self) -> Option<&T> {
189        (self as &dyn Any).downcast_ref()
190    }
191}
192
193#[expect(missing_docs)]
194#[async_trait]
195pub trait MutableIndex: Any {
196    fn as_index(&self) -> &dyn Index;
197
198    fn change_id_index(
199        &self,
200        heads: &mut dyn Iterator<Item = &CommitId>,
201    ) -> IndexResult<Box<dyn ChangeIdIndex + '_>>;
202
203    async fn add_commit(&mut self, commit: &Commit) -> IndexResult<()>;
204
205    fn merge_in(&mut self, other: &dyn ReadonlyIndex) -> IndexResult<()>;
206}
207
208impl dyn MutableIndex {
209    /// Downcasts to the implementation type.
210    pub fn downcast<T: MutableIndex>(self: Box<Self>) -> Option<Box<T>> {
211        (self as Box<dyn Any>).downcast().ok()
212    }
213
214    /// Returns reference of the implementation type.
215    pub fn downcast_ref<T: MutableIndex>(&self) -> Option<&T> {
216        (self as &dyn Any).downcast_ref()
217    }
218}
219
220/// The state of a commit with a given change ID.
221#[derive(Copy, Clone, Eq, PartialEq, Debug)]
222pub enum ResolvedChangeState {
223    /// The commit is visible (reachable from the visible heads).
224    Visible,
225    /// The commit is hidden (not reachable from the visible heads).
226    Hidden,
227}
228
229/// Represents the possible target commits of a resolved change ID. If the
230/// change is divergent, there may be multiple visible commits. Hidden commits
231/// can also be returned to allow showing a change offset number in the evolog.
232#[derive(Clone, Eq, PartialEq, Debug)]
233pub struct ResolvedChangeTargets {
234    /// All indexed commits with this change ID. The sort order of the commits
235    /// is determined by the index implementation, but it is preferred that more
236    /// recent commits should be sorted before later commits when possible. All
237    /// visible commits must be included, but some hidden commits may be omitted
238    /// if it would be inefficient for the index to support them.
239    pub targets: Vec<(CommitId, ResolvedChangeState)>,
240}
241
242impl ResolvedChangeTargets {
243    /// Returns an iterator over all visible commits for this change ID, as well
244    /// as their offsets.
245    pub fn visible_with_offsets(&self) -> impl Iterator<Item = (usize, &CommitId)> {
246        self.targets
247            .iter()
248            .enumerate()
249            .filter_map(|(i, (target, state))| {
250                (*state == ResolvedChangeState::Visible).then_some((i, target))
251            })
252    }
253
254    /// Returns true if the commit ID is one of the visible targets of this
255    /// change ID.
256    pub fn has_visible(&self, commit: &CommitId) -> bool {
257        self.visible_with_offsets()
258            .any(|(_, target)| target == commit)
259    }
260
261    /// Returns true if there are multiple visible targets for this change ID.
262    pub fn is_divergent(&self) -> bool {
263        self.visible_with_offsets().take(2).count() > 1
264    }
265
266    /// Returns the commit ID at a given offset. The change offset of a commit
267    /// can be found using [`ResolvedChangeTargets::find_offset`].
268    pub fn at_offset(&self, offset: usize) -> Option<&CommitId> {
269        self.targets.get(offset).map(|(target, _state)| target)
270    }
271
272    /// Finds the change offset corresponding to a commit. Newer commits should
273    /// generally have a lower offset than older commits, but this is not
274    /// guaranteed. Hidden commits may not have an offset at all.
275    pub fn find_offset(&self, commit_id: &CommitId) -> Option<usize> {
276        self.targets
277            .iter()
278            .position(|(target, _state)| target == commit_id)
279    }
280
281    /// Extracts the visible commits for this change ID. Returns `None` if there
282    /// are no visible commits with this change ID.
283    pub fn into_visible(self) -> Option<Vec<CommitId>> {
284        let visible = self
285            .targets
286            .into_iter()
287            .filter_map(|(target, state)| (state == ResolvedChangeState::Visible).then_some(target))
288            .collect_vec();
289        (!visible.is_empty()).then_some(visible)
290    }
291}
292
293/// Defines the interface for types that provide an index of the commits in a
294/// repository by [`ChangeId`].
295#[async_trait]
296pub trait ChangeIdIndex: Send + Sync {
297    /// Resolve an unambiguous change ID prefix to the commit IDs in the index.
298    async fn resolve_prefix(
299        &self,
300        prefix: &HexPrefix,
301    ) -> IndexResult<PrefixResolution<ResolvedChangeTargets>>;
302
303    /// This function returns the shortest length of a prefix of `key` that
304    /// disambiguates it from every other key in the index.
305    ///
306    /// The length returned is a number of hexadecimal digits.
307    ///
308    /// This has some properties that we do not currently make much use of:
309    ///
310    /// - The algorithm works even if `key` itself is not in the index.
311    ///
312    /// - In the special case when there are keys in the trie for which our
313    ///   `key` is an exact prefix, returns `key.len() + 1`. Conceptually, in
314    ///   order to disambiguate, you need every letter of the key *and* the
315    ///   additional fact that it's the entire key). This case is extremely
316    ///   unlikely for hashes with 12+ hexadecimal characters.
317    async fn shortest_unique_prefix_len(&self, change_id: &ChangeId) -> IndexResult<usize>;
318}