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    fn shortest_unique_commit_id_prefix_len(&self, commit_id: &CommitId) -> IndexResult<usize>;
109
110    /// Searches the index for commit IDs matching `prefix`. Returns a
111    /// [`PrefixResolution`] with a [`CommitId`] if the prefix matches a single
112    /// commit.
113    fn resolve_commit_id_prefix(
114        &self,
115        prefix: &HexPrefix,
116    ) -> IndexResult<PrefixResolution<CommitId>>;
117
118    /// Returns true if `commit_id` is present in the index.
119    fn has_id(&self, commit_id: &CommitId) -> IndexResult<bool>;
120
121    /// Returns true if `ancestor_id` commit is an ancestor of the
122    /// `descendant_id` commit, or if `ancestor_id` equals `descendant_id`.
123    async fn is_ancestor(
124        &self,
125        ancestor_id: &CommitId,
126        descendant_id: &CommitId,
127    ) -> IndexResult<bool>;
128
129    /// Returns the best common ancestor or ancestors of the commits in `set1`
130    /// and `set2`. A "best common ancestor" has no descendants that are also
131    /// common ancestors.
132    fn common_ancestors(&self, set1: &[CommitId], set2: &[CommitId]) -> IndexResult<Vec<CommitId>>;
133
134    /// Heads among all indexed commits at the associated operation.
135    ///
136    /// Suppose the index contains all the historical heads and their ancestors
137    /// reachable from the associated operation, this function returns the heads
138    /// that should be preserved on garbage collection.
139    ///
140    /// The iteration order is unspecified.
141    fn all_heads_for_gc(&self) -> IndexResult<Box<dyn Iterator<Item = CommitId> + '_>>;
142
143    /// Returns the subset of commit IDs in `candidates` which are not ancestors
144    /// of other commits in `candidates`. If a commit id is duplicated in the
145    /// `candidates` list it will appear at most once in the output.
146    async fn heads(
147        &self,
148        candidates: &mut (dyn Iterator<Item = &CommitId> + Send),
149    ) -> IndexResult<Vec<CommitId>>;
150
151    /// Returns iterator over paths changed at the specified commit. The paths
152    /// are sorted. Returns `None` if the commit wasn't indexed.
153    fn changed_paths_in_commit(
154        &self,
155        commit_id: &CommitId,
156    ) -> IndexResult<Option<Box<dyn Iterator<Item = RepoPathBuf> + '_>>>;
157
158    /// Resolves the revset `expression` against the index and corresponding
159    /// `store`.
160    fn evaluate_revset(
161        &self,
162        expression: &ResolvedExpression,
163        store: &Arc<Store>,
164    ) -> Result<Box<dyn Revset + '_>, RevsetEvaluationError>;
165}
166
167#[expect(missing_docs)]
168pub trait ReadonlyIndex: Any + Send + Sync {
169    fn as_index(&self) -> &dyn Index;
170
171    fn change_id_index(&self, heads: &mut dyn Iterator<Item = &CommitId>)
172    -> Box<dyn ChangeIdIndex>;
173
174    fn start_modification(&self) -> Box<dyn MutableIndex>;
175}
176
177impl dyn ReadonlyIndex {
178    /// Returns reference of the implementation type.
179    pub fn downcast_ref<T: ReadonlyIndex>(&self) -> Option<&T> {
180        (self as &dyn Any).downcast_ref()
181    }
182}
183
184#[expect(missing_docs)]
185#[async_trait]
186pub trait MutableIndex: Any {
187    fn as_index(&self) -> &dyn Index;
188
189    fn change_id_index(
190        &self,
191        heads: &mut dyn Iterator<Item = &CommitId>,
192    ) -> Box<dyn ChangeIdIndex + '_>;
193
194    async fn add_commit(&mut self, commit: &Commit) -> IndexResult<()>;
195
196    fn merge_in(&mut self, other: &dyn ReadonlyIndex) -> IndexResult<()>;
197}
198
199impl dyn MutableIndex {
200    /// Downcasts to the implementation type.
201    pub fn downcast<T: MutableIndex>(self: Box<Self>) -> Option<Box<T>> {
202        (self as Box<dyn Any>).downcast().ok()
203    }
204
205    /// Returns reference of the implementation type.
206    pub fn downcast_ref<T: MutableIndex>(&self) -> Option<&T> {
207        (self as &dyn Any).downcast_ref()
208    }
209}
210
211/// The state of a commit with a given change ID.
212#[derive(Copy, Clone, Eq, PartialEq, Debug)]
213pub enum ResolvedChangeState {
214    /// The commit is visible (reachable from the visible heads).
215    Visible,
216    /// The commit is hidden (not reachable from the visible heads).
217    Hidden,
218}
219
220/// Represents the possible target commits of a resolved change ID. If the
221/// change is divergent, there may be multiple visible commits. Hidden commits
222/// can also be returned to allow showing a change offset number in the evolog.
223#[derive(Clone, Eq, PartialEq, Debug)]
224pub struct ResolvedChangeTargets {
225    /// All indexed commits with this change ID. The sort order of the commits
226    /// is determined by the index implementation, but it is preferred that more
227    /// recent commits should be sorted before later commits when possible. All
228    /// visible commits must be included, but some hidden commits may be omitted
229    /// if it would be inefficient for the index to support them.
230    pub targets: Vec<(CommitId, ResolvedChangeState)>,
231}
232
233impl ResolvedChangeTargets {
234    /// Returns an iterator over all visible commits for this change ID, as well
235    /// as their offsets.
236    pub fn visible_with_offsets(&self) -> impl Iterator<Item = (usize, &CommitId)> {
237        self.targets
238            .iter()
239            .enumerate()
240            .filter_map(|(i, (target, state))| {
241                (*state == ResolvedChangeState::Visible).then_some((i, target))
242            })
243    }
244
245    /// Returns true if the commit ID is one of the visible targets of this
246    /// change ID.
247    pub fn has_visible(&self, commit: &CommitId) -> bool {
248        self.visible_with_offsets()
249            .any(|(_, target)| target == commit)
250    }
251
252    /// Returns true if there are multiple visible targets for this change ID.
253    pub fn is_divergent(&self) -> bool {
254        self.visible_with_offsets().take(2).count() > 1
255    }
256
257    /// Returns the commit ID at a given offset. The change offset of a commit
258    /// can be found using [`ResolvedChangeTargets::find_offset`].
259    pub fn at_offset(&self, offset: usize) -> Option<&CommitId> {
260        self.targets.get(offset).map(|(target, _state)| target)
261    }
262
263    /// Finds the change offset corresponding to a commit. Newer commits should
264    /// generally have a lower offset than older commits, but this is not
265    /// guaranteed. Hidden commits may not have an offset at all.
266    pub fn find_offset(&self, commit_id: &CommitId) -> Option<usize> {
267        self.targets
268            .iter()
269            .position(|(target, _state)| target == commit_id)
270    }
271
272    /// Extracts the visible commits for this change ID. Returns `None` if there
273    /// are no visible commits with this change ID.
274    pub fn into_visible(self) -> Option<Vec<CommitId>> {
275        let visible = self
276            .targets
277            .into_iter()
278            .filter_map(|(target, state)| (state == ResolvedChangeState::Visible).then_some(target))
279            .collect_vec();
280        (!visible.is_empty()).then_some(visible)
281    }
282}
283
284/// Defines the interface for types that provide an index of the commits in a
285/// repository by [`ChangeId`].
286pub trait ChangeIdIndex: Send + Sync {
287    /// Resolve an unambiguous change ID prefix to the commit IDs in the index.
288    fn resolve_prefix(
289        &self,
290        prefix: &HexPrefix,
291    ) -> IndexResult<PrefixResolution<ResolvedChangeTargets>>;
292
293    /// This function returns the shortest length of a prefix of `key` that
294    /// disambiguates it from every other key in the index.
295    ///
296    /// The length returned is a number of hexadecimal digits.
297    ///
298    /// This has some properties that we do not currently make much use of:
299    ///
300    /// - The algorithm works even if `key` itself is not in the index.
301    ///
302    /// - In the special case when there are keys in the trie for which our
303    ///   `key` is an exact prefix, returns `key.len() + 1`. Conceptually, in
304    ///   order to disambiguate, you need every letter of the key *and* the
305    ///   additional fact that it's the entire key). This case is extremely
306    ///   unlikely for hashes with 12+ hexadecimal characters.
307    fn shortest_unique_prefix_len(&self, change_id: &ChangeId) -> IndexResult<usize>;
308}