Skip to main content

jj_lib/
commit.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#![expect(missing_docs)]
16
17use std::cmp::Ordering;
18use std::fmt::Debug;
19use std::fmt::Error;
20use std::fmt::Formatter;
21use std::hash::Hash;
22use std::hash::Hasher;
23use std::sync::Arc;
24
25use futures::future::try_join_all;
26use itertools::Itertools as _;
27use pollster::FutureExt as _;
28
29use crate::backend;
30use crate::backend::BackendError;
31use crate::backend::BackendResult;
32use crate::backend::ChangeId;
33use crate::backend::CommitId;
34use crate::backend::Signature;
35use crate::backend::TreeId;
36use crate::conflict_labels::ConflictLabels;
37use crate::index::IndexResult;
38use crate::merge::Merge;
39use crate::merged_tree::MergedTree;
40use crate::repo::Repo;
41use crate::rewrite::merge_commit_trees;
42use crate::signing::SignResult;
43use crate::signing::Verification;
44use crate::store::Store;
45
46#[derive(Clone, serde::Serialize)]
47pub struct Commit {
48    #[serde(skip)]
49    store: Arc<Store>,
50    #[serde(rename = "commit_id")]
51    id: CommitId,
52    #[serde(flatten)]
53    data: Arc<backend::Commit>,
54}
55
56impl Debug for Commit {
57    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
58        f.debug_struct("Commit").field("id", &self.id).finish()
59        // We intentionally don't print the `data` field. You can debug-print
60        // `commit.store_commit()` to get those details.
61        //
62        // The reason is that `Commit` objects are debug-printed as part of many
63        // other data structures and in tracing.
64    }
65}
66
67impl PartialEq for Commit {
68    fn eq(&self, other: &Self) -> bool {
69        self.id == other.id
70    }
71}
72
73impl Eq for Commit {}
74
75impl Ord for Commit {
76    fn cmp(&self, other: &Self) -> Ordering {
77        self.id.cmp(&other.id)
78    }
79}
80
81impl PartialOrd for Commit {
82    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
83        Some(self.cmp(other))
84    }
85}
86
87impl Hash for Commit {
88    fn hash<H: Hasher>(&self, state: &mut H) {
89        self.id.hash(state);
90    }
91}
92
93impl Commit {
94    pub fn new(store: Arc<Store>, id: CommitId, data: Arc<backend::Commit>) -> Self {
95        Self { store, id, data }
96    }
97
98    pub fn store(&self) -> &Arc<Store> {
99        &self.store
100    }
101
102    pub fn id(&self) -> &CommitId {
103        &self.id
104    }
105
106    pub fn parent_ids(&self) -> &[CommitId] {
107        &self.data.parents
108    }
109
110    pub async fn parents(&self) -> BackendResult<Vec<Self>> {
111        try_join_all(
112            self.data
113                .parents
114                .iter()
115                .map(|id| self.store.get_commit_async(id)),
116        )
117        .await
118    }
119
120    pub fn tree(&self) -> MergedTree {
121        MergedTree::new(
122            self.store.clone(),
123            self.data.root_tree.clone(),
124            ConflictLabels::from_merge(self.data.conflict_labels.clone()),
125        )
126    }
127
128    pub fn tree_ids(&self) -> &Merge<TreeId> {
129        &self.data.root_tree
130    }
131
132    /// Return the parent tree, merging the parent trees if there are multiple
133    /// parents.
134    pub async fn parent_tree(&self, repo: &dyn Repo) -> BackendResult<MergedTree> {
135        // Avoid merging parent trees if known to be empty. The index could be
136        // queried only when parents.len() > 1, but index query would be cheaper
137        // than extracting parent commit from the store.
138        if is_commit_empty_by_index(repo, &self.id)? == Some(true) {
139            return Ok(self.tree());
140        }
141        let parents = self.parents().await?;
142        merge_commit_trees(repo, &parents).await
143    }
144
145    /// Returns whether commit's content is empty. Commit description is not
146    /// taken into consideration.
147    pub fn is_empty(&self, repo: &dyn Repo) -> BackendResult<bool> {
148        if let Some(empty) = is_commit_empty_by_index(repo, &self.id)? {
149            return Ok(empty);
150        }
151        is_backend_commit_empty(repo, &self.store, &self.data)
152    }
153
154    pub fn has_conflict(&self) -> bool {
155        !self.tree_ids().is_resolved()
156    }
157
158    pub fn change_id(&self) -> &ChangeId {
159        &self.data.change_id
160    }
161
162    pub fn store_commit(&self) -> &Arc<backend::Commit> {
163        &self.data
164    }
165
166    pub fn description(&self) -> &str {
167        &self.data.description
168    }
169
170    pub fn author(&self) -> &Signature {
171        &self.data.author
172    }
173
174    pub fn committer(&self) -> &Signature {
175        &self.data.committer
176    }
177
178    ///  A commit is hidden if its commit id is not in the change id index.
179    pub fn is_hidden(&self, repo: &dyn Repo) -> IndexResult<bool> {
180        let maybe_targets = repo.resolve_change_id(self.change_id())?;
181        Ok(maybe_targets.is_none_or(|targets| !targets.has_visible(&self.id)))
182    }
183
184    /// A commit is discardable if it has no change from its parent, and an
185    /// empty description.
186    pub fn is_discardable(&self, repo: &dyn Repo) -> BackendResult<bool> {
187        Ok(self.description().is_empty() && self.is_empty(repo)?)
188    }
189
190    /// A quick way to just check if a signature is present.
191    pub fn is_signed(&self) -> bool {
192        self.data.secure_sig.is_some()
193    }
194
195    /// A slow (but cached) way to get the full verification.
196    pub fn verification(&self) -> SignResult<Option<Verification>> {
197        self.data
198            .secure_sig
199            .as_ref()
200            .map(|sig| self.store.signer().verify(&self.id, &sig.data, &sig.sig))
201            .transpose()
202    }
203
204    /// A string describing the commit to be used in conflict markers. If a
205    /// description is set, it will include the first line of the description.
206    pub fn conflict_label(&self) -> String {
207        if let Some(subject) = self.description().lines().next() {
208            // Example: nlqwxzwn 7dd24e73 "first line of description"
209            format!(
210                "{} \"{}\"",
211                self.conflict_label_short(),
212                // Control characters shouldn't be written in conflict markers, and '\0' isn't
213                // supported by the Git backend, so we just remove them. Unicode characters are
214                // supported, so we don't have to remove them.
215                subject.trim().replace(char::is_control, "")
216            )
217        } else {
218            self.conflict_label_short()
219        }
220    }
221
222    /// A short string describing the commit to be used in conflict markers.
223    /// Does not include the commit description.
224    fn conflict_label_short(&self) -> String {
225        // Example: nlqwxzwn 7dd24e73
226        format!("{:.8} {:.8}", self.change_id(), self.id())
227    }
228
229    /// A string describing the commit's parents to be used in conflict markers.
230    pub async fn parents_conflict_label(&self) -> BackendResult<String> {
231        let parents = self.parents().await?;
232        Ok(conflict_label_for_commits(&parents))
233    }
234}
235
236// If there is a single commit, returns the detailed conflict label for that
237// commit. If there are multiple commits, joins the short conflict labels of
238// each commit.
239pub fn conflict_label_for_commits(commits: &[Commit]) -> String {
240    if commits.len() == 1 {
241        commits[0].conflict_label()
242    } else {
243        commits.iter().map(Commit::conflict_label_short).join(", ")
244    }
245}
246
247pub(crate) fn is_backend_commit_empty(
248    repo: &dyn Repo,
249    store: &Arc<Store>,
250    commit: &backend::Commit,
251) -> BackendResult<bool> {
252    if let [parent_id] = &*commit.parents {
253        return Ok(commit.root_tree == *store.get_commit(parent_id)?.tree_ids());
254    }
255    let parents: Vec<_> = commit
256        .parents
257        .iter()
258        .map(|id| store.get_commit(id))
259        .try_collect()?;
260    let parent_tree = merge_commit_trees(repo, &parents).block_on()?;
261    Ok(commit.root_tree == *parent_tree.tree_ids())
262}
263
264fn is_commit_empty_by_index(repo: &dyn Repo, id: &CommitId) -> BackendResult<Option<bool>> {
265    let maybe_paths = repo
266        .index()
267        .changed_paths_in_commit(id)
268        // TODO: index error shouldn't be a "BackendError"
269        .map_err(|err| BackendError::Other(err.into()))?;
270    Ok(maybe_paths.map(|mut paths| paths.next().is_none()))
271}
272
273pub trait CommitIteratorExt<'c, I> {
274    fn ids(self) -> impl Iterator<Item = &'c CommitId>;
275}
276
277impl<'c, I> CommitIteratorExt<'c, I> for I
278where
279    I: Iterator<Item = &'c Commit>,
280{
281    fn ids(self) -> impl Iterator<Item = &'c CommitId> {
282        self.map(|commit| commit.id())
283    }
284}
285
286/// Wrapper to sort `Commit` by committer timestamp.
287#[derive(Clone, Debug, Eq, Hash, PartialEq)]
288pub(crate) struct CommitByCommitterTimestamp(pub Commit);
289
290impl Ord for CommitByCommitterTimestamp {
291    fn cmp(&self, other: &Self) -> Ordering {
292        let self_timestamp = &self.0.committer().timestamp.timestamp;
293        let other_timestamp = &other.0.committer().timestamp.timestamp;
294        self_timestamp
295            .cmp(other_timestamp)
296            .then_with(|| self.0.cmp(&other.0)) // to comply with Eq
297    }
298}
299
300impl PartialOrd for CommitByCommitterTimestamp {
301    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
302        Some(self.cmp(other))
303    }
304}