Skip to main content

jj_lib/
commit_builder.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::sync::Arc;
18
19use pollster::FutureExt as _;
20
21use crate::backend;
22use crate::backend::BackendError;
23use crate::backend::BackendResult;
24use crate::backend::ChangeId;
25use crate::backend::CommitId;
26use crate::backend::Signature;
27use crate::backend::TreeId;
28use crate::commit::Commit;
29use crate::commit::is_backend_commit_empty;
30use crate::conflict_labels::ConflictLabels;
31use crate::merge::Merge;
32use crate::merged_tree::MergedTree;
33use crate::repo::MutableRepo;
34use crate::repo::Repo;
35use crate::settings::JJRng;
36use crate::settings::SignSettings;
37use crate::settings::UserSettings;
38use crate::signing::SignBehavior;
39use crate::store::Store;
40
41#[must_use]
42pub struct CommitBuilder<'repo> {
43    mut_repo: &'repo mut MutableRepo,
44    inner: DetachedCommitBuilder,
45}
46
47impl CommitBuilder<'_> {
48    /// Detaches from `&'repo mut` lifetime. The returned builder can be used in
49    /// order to obtain a temporary commit object.
50    pub fn detach(self) -> DetachedCommitBuilder {
51        self.inner
52    }
53
54    /// Clears the source commit to not record new commit as rewritten from it.
55    ///
56    /// The caller should also assign new change id to not create divergence.
57    pub fn clear_rewrite_source(mut self) -> Self {
58        self.inner.clear_rewrite_source();
59        self
60    }
61
62    pub fn parents(&self) -> &[CommitId] {
63        self.inner.parents()
64    }
65
66    pub fn set_parents(mut self, parents: Vec<CommitId>) -> Self {
67        self.inner.set_parents(parents);
68        self
69    }
70
71    pub fn predecessors(&self) -> &[CommitId] {
72        self.inner.predecessors()
73    }
74
75    pub fn set_predecessors(mut self, predecessors: Vec<CommitId>) -> Self {
76        self.inner.set_predecessors(predecessors);
77        self
78    }
79
80    pub fn tree(&self) -> MergedTree {
81        self.inner.tree()
82    }
83
84    pub fn tree_ids(&self) -> &Merge<TreeId> {
85        self.inner.tree_ids()
86    }
87
88    pub fn set_tree(mut self, tree: MergedTree) -> Self {
89        self.inner.set_tree(tree);
90        self
91    }
92
93    /// [`Commit::is_empty()`] for the new commit.
94    pub async fn is_empty(&self) -> BackendResult<bool> {
95        self.inner.is_empty(self.mut_repo).await
96    }
97
98    pub fn change_id(&self) -> &ChangeId {
99        self.inner.change_id()
100    }
101
102    pub fn set_change_id(mut self, change_id: ChangeId) -> Self {
103        self.inner.set_change_id(change_id);
104        self
105    }
106
107    pub fn generate_new_change_id(mut self) -> Self {
108        self.inner.generate_new_change_id();
109        self
110    }
111
112    pub fn description(&self) -> &str {
113        self.inner.description()
114    }
115
116    pub fn set_description(mut self, description: impl Into<String>) -> Self {
117        self.inner.set_description(description);
118        self
119    }
120
121    pub fn author(&self) -> &Signature {
122        self.inner.author()
123    }
124
125    pub fn set_author(mut self, author: Signature) -> Self {
126        self.inner.set_author(author);
127        self
128    }
129
130    pub fn committer(&self) -> &Signature {
131        self.inner.committer()
132    }
133
134    pub fn set_committer(mut self, committer: Signature) -> Self {
135        self.inner.set_committer(committer);
136        self
137    }
138
139    /// [`Commit::is_discardable()`] for the new commit.
140    pub async fn is_discardable(&self) -> BackendResult<bool> {
141        self.inner.is_discardable(self.mut_repo).await
142    }
143
144    pub fn sign_settings(&self) -> &SignSettings {
145        self.inner.sign_settings()
146    }
147
148    pub fn set_sign_behavior(mut self, sign_behavior: SignBehavior) -> Self {
149        self.inner.set_sign_behavior(sign_behavior);
150        self
151    }
152
153    pub fn set_sign_key(mut self, sign_key: String) -> Self {
154        self.inner.set_sign_key(sign_key);
155        self
156    }
157
158    pub fn clear_sign_key(mut self) -> Self {
159        self.inner.clear_sign_key();
160        self
161    }
162
163    pub async fn write(self) -> BackendResult<Commit> {
164        self.inner.write(self.mut_repo).await
165    }
166
167    /// Records the old commit as abandoned instead of writing new commit. This
168    /// is noop for the builder created by [`MutableRepo::new_commit()`].
169    pub fn abandon(self) {
170        self.inner.abandon(self.mut_repo);
171    }
172}
173
174/// Like `CommitBuilder`, but doesn't mutably borrow `MutableRepo`.
175#[derive(Debug)]
176pub struct DetachedCommitBuilder {
177    store: Arc<Store>,
178    rng: Arc<JJRng>,
179    commit: backend::Commit,
180    predecessors: Vec<CommitId>,
181    rewrite_source: Option<Commit>,
182    sign_settings: SignSettings,
183    record_predecessors_in_commit: bool,
184}
185
186impl DetachedCommitBuilder {
187    /// Only called from [`MutableRepo::new_commit`]. Use that function instead.
188    pub(crate) fn for_new_commit(
189        repo: &dyn Repo,
190        settings: &UserSettings,
191        parents: Vec<CommitId>,
192        tree: MergedTree,
193    ) -> Self {
194        let store = repo.store().clone();
195        let signature = settings.signature();
196        assert!(!parents.is_empty());
197        let rng = settings.get_rng();
198        let (root_tree, conflict_labels) = tree.into_tree_ids_and_labels();
199        let change_id = rng.new_change_id(store.change_id_length());
200        let commit = backend::Commit {
201            parents,
202            predecessors: vec![],
203            root_tree,
204            conflict_labels: conflict_labels.into_merge(),
205            change_id,
206            description: String::new(),
207            author: signature.clone(),
208            committer: signature,
209            secure_sig: None,
210        };
211        let record_predecessors_in_commit = settings
212            .get_bool("experimental.record-predecessors-in-commit")
213            .unwrap();
214        Self {
215            store,
216            rng,
217            commit,
218            rewrite_source: None,
219            predecessors: vec![],
220            sign_settings: settings.sign_settings(),
221            record_predecessors_in_commit,
222        }
223    }
224
225    /// Only called from [`MutableRepo::rewrite_commit`]. Use that function
226    /// instead.
227    pub(crate) fn for_rewrite_from(
228        repo: &dyn Repo,
229        settings: &UserSettings,
230        predecessor: &Commit,
231    ) -> Self {
232        let store = repo.store().clone();
233        let mut commit = backend::Commit::clone(predecessor.store_commit());
234        commit.predecessors = vec![];
235        commit.committer = settings.signature();
236        // If the user had not configured a name and email before but now they have,
237        // update the author fields with the new information.
238        if commit.author.name.is_empty() {
239            commit.author.name.clone_from(&commit.committer.name);
240        }
241        if commit.author.email.is_empty() {
242            commit.author.email.clone_from(&commit.committer.email);
243        }
244
245        // Reset author timestamp on discardable commits if the author is the
246        // committer. While it's unlikely we'll have somebody else's commit
247        // with no description in our repo, we'd like to be extra safe.
248        if commit.author.name == commit.committer.name
249            && commit.author.email == commit.committer.email
250            && predecessor
251                .is_discardable(repo)
252                .block_on()
253                .unwrap_or_default()
254        {
255            commit.author.timestamp = commit.committer.timestamp;
256        }
257
258        let record_predecessors_in_commit = settings
259            .get_bool("experimental.record-predecessors-in-commit")
260            .unwrap();
261        Self {
262            store,
263            commit,
264            rng: settings.get_rng(),
265            rewrite_source: Some(predecessor.clone()),
266            predecessors: vec![predecessor.id().clone()],
267            sign_settings: settings.sign_settings(),
268            record_predecessors_in_commit,
269        }
270    }
271
272    /// Attaches the underlying `mut_repo`.
273    pub fn attach(self, mut_repo: &mut MutableRepo) -> CommitBuilder<'_> {
274        assert!(Arc::ptr_eq(&self.store, mut_repo.store()));
275        CommitBuilder {
276            mut_repo,
277            inner: self,
278        }
279    }
280
281    /// Clears the source commit to not record new commit as rewritten from it.
282    ///
283    /// The caller should also assign new change id to not create divergence.
284    pub fn clear_rewrite_source(&mut self) {
285        self.rewrite_source = None;
286    }
287
288    pub fn parents(&self) -> &[CommitId] {
289        &self.commit.parents
290    }
291
292    pub fn set_parents(&mut self, parents: Vec<CommitId>) -> &mut Self {
293        assert!(!parents.is_empty());
294        self.commit.parents = parents;
295        self
296    }
297
298    pub fn predecessors(&self) -> &[CommitId] {
299        &self.predecessors
300    }
301
302    pub fn set_predecessors(&mut self, predecessors: Vec<CommitId>) -> &mut Self {
303        self.predecessors = predecessors;
304        self
305    }
306
307    pub fn tree(&self) -> MergedTree {
308        MergedTree::new(
309            self.store.clone(),
310            self.commit.root_tree.clone(),
311            ConflictLabels::from_merge(self.commit.conflict_labels.clone()),
312        )
313    }
314
315    pub fn tree_ids(&self) -> &Merge<TreeId> {
316        &self.commit.root_tree
317    }
318
319    pub fn set_tree(&mut self, tree: MergedTree) -> &mut Self {
320        assert!(Arc::ptr_eq(tree.store(), &self.store));
321        let (root_tree, conflict_labels) = tree.into_tree_ids_and_labels();
322        self.commit.root_tree = root_tree;
323        self.commit.conflict_labels = conflict_labels.into_merge();
324        self
325    }
326
327    /// [`Commit::is_empty()`] for the new commit.
328    pub async fn is_empty(&self, repo: &dyn Repo) -> BackendResult<bool> {
329        is_backend_commit_empty(repo, &self.store, &self.commit).await
330    }
331
332    pub fn change_id(&self) -> &ChangeId {
333        &self.commit.change_id
334    }
335
336    pub fn set_change_id(&mut self, change_id: ChangeId) -> &mut Self {
337        self.commit.change_id = change_id;
338        self
339    }
340
341    pub fn generate_new_change_id(&mut self) -> &mut Self {
342        self.commit.change_id = self.rng.new_change_id(self.store.change_id_length());
343        self
344    }
345
346    pub fn description(&self) -> &str {
347        &self.commit.description
348    }
349
350    pub fn set_description(&mut self, description: impl Into<String>) -> &mut Self {
351        self.commit.description = description.into();
352        self
353    }
354
355    pub fn author(&self) -> &Signature {
356        &self.commit.author
357    }
358
359    pub fn set_author(&mut self, author: Signature) -> &mut Self {
360        self.commit.author = author;
361        self
362    }
363
364    pub fn committer(&self) -> &Signature {
365        &self.commit.committer
366    }
367
368    pub fn set_committer(&mut self, committer: Signature) -> &mut Self {
369        self.commit.committer = committer;
370        self
371    }
372
373    /// [`Commit::is_discardable()`] for the new commit.
374    pub async fn is_discardable(&self, repo: &dyn Repo) -> BackendResult<bool> {
375        Ok(self.description().is_empty() && self.is_empty(repo).await?)
376    }
377
378    pub fn sign_settings(&self) -> &SignSettings {
379        &self.sign_settings
380    }
381
382    pub fn set_sign_behavior(&mut self, sign_behavior: SignBehavior) -> &mut Self {
383        self.sign_settings.behavior = sign_behavior;
384        self
385    }
386
387    pub fn set_sign_key(&mut self, sign_key: String) -> &mut Self {
388        self.sign_settings.key = Some(sign_key);
389        self
390    }
391
392    pub fn clear_sign_key(&mut self) -> &mut Self {
393        self.sign_settings.key = None;
394        self
395    }
396
397    /// Writes new commit and makes it visible in the `mut_repo`.
398    pub async fn write(mut self, mut_repo: &mut MutableRepo) -> BackendResult<Commit> {
399        if self.record_predecessors_in_commit {
400            self.commit.predecessors = self.predecessors.clone();
401        }
402        let commit = write_to_store(&self.store, self.commit, &self.sign_settings).await?;
403        // FIXME: Google's index.has_id() always returns true.
404        if mut_repo.is_backed_by_default_index()
405            && mut_repo
406                .index()
407                .has_id(commit.id())
408                // TODO: indexing error shouldn't be a "BackendError"
409                .map_err(|err| BackendError::Other(err.into()))?
410        {
411            // Recording existing commit as new would create cycle in
412            // predecessors/parent mappings within the current transaction, and
413            // in predecessors graph globally.
414            return Err(BackendError::Other(
415                format!("Newly-created commit {id} already exists", id = commit.id()).into(),
416            ));
417        }
418        mut_repo.add_head(&commit).await?;
419        mut_repo.set_predecessors(commit.id().clone(), self.predecessors);
420        if let Some(rewrite_source) = self.rewrite_source {
421            mut_repo.set_rewritten_commit(rewrite_source.id().clone(), commit.id().clone());
422        }
423        Ok(commit)
424    }
425
426    /// Writes new commit without making it visible in the repo.
427    ///
428    /// This does not consume the builder, so you can reuse the current
429    /// configuration to create another commit later.
430    pub async fn write_hidden(&self) -> BackendResult<Commit> {
431        let mut commit = self.commit.clone();
432        if self.record_predecessors_in_commit {
433            commit.predecessors = self.predecessors.clone();
434        }
435        write_to_store(&self.store, commit, &self.sign_settings).await
436    }
437
438    /// Records the old commit as abandoned in the `mut_repo`.
439    ///
440    /// This is noop if there's no old commit that would be rewritten to the new
441    /// commit by `write()`.
442    pub fn abandon(self, mut_repo: &mut MutableRepo) {
443        let commit = self.commit;
444        if let Some(rewrite_source) = &self.rewrite_source {
445            mut_repo
446                .record_abandoned_commit_with_parents(rewrite_source.id().clone(), commit.parents);
447        }
448    }
449}
450
451async fn write_to_store(
452    store: &Arc<Store>,
453    mut commit: backend::Commit,
454    sign_settings: &SignSettings,
455) -> BackendResult<Commit> {
456    let should_sign = store.signer().can_sign() && sign_settings.should_sign(&commit);
457    let sign_fn = |data: &[u8]| store.signer().sign(data, sign_settings.key.as_deref());
458
459    // Commit backend doesn't use secure_sig for writing and enforces it with an
460    // assert, but sign_settings.should_sign check above will want to know
461    // if we're rewriting a signed commit
462    commit.secure_sig = None;
463
464    store
465        .write_commit(commit, should_sign.then_some(&mut &sign_fn))
466        .await
467}