Skip to main content

jj_lib/
rewrite.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::collections::HashMap;
18use std::collections::HashSet;
19use std::slice;
20use std::sync::Arc;
21
22use futures::StreamExt as _;
23use futures::TryStreamExt as _;
24use futures::future::try_join_all;
25use futures::try_join;
26use indexmap::IndexMap;
27use indexmap::IndexSet;
28use itertools::Itertools as _;
29use tracing::instrument;
30
31use crate::backend::BackendError;
32use crate::backend::BackendResult;
33use crate::backend::CommitId;
34use crate::commit::Commit;
35use crate::commit::CommitIteratorExt as _;
36use crate::commit::conflict_label_for_commits;
37use crate::commit_builder::CommitBuilder;
38use crate::conflict_labels::ConflictLabels;
39use crate::index::Index;
40use crate::index::IndexResult;
41use crate::index::ResolvedChangeTargets;
42use crate::iter_util::fallible_any;
43use crate::matchers::FilesMatcher;
44use crate::matchers::Matcher;
45use crate::matchers::Visit;
46use crate::merge::Diff;
47use crate::merge::Merge;
48use crate::merged_tree::MergedTree;
49use crate::merged_tree_builder::MergedTreeBuilder;
50use crate::repo::MutableRepo;
51use crate::repo::Repo;
52use crate::repo_path::RepoPath;
53use crate::revset::RevsetExpression;
54use crate::revset::RevsetStreamExt as _;
55use crate::store::Store;
56
57/// Merges `commits` and tries to resolve any conflicts recursively.
58#[instrument(skip(repo))]
59pub async fn merge_commit_trees(repo: &dyn Repo, commits: &[Commit]) -> BackendResult<MergedTree> {
60    if let [commit] = commits {
61        Ok(commit.tree())
62    } else {
63        merge_commit_trees_no_resolve(repo, commits)
64            .await?
65            .resolve()
66            .await
67    }
68}
69
70/// Merges `commits` without attempting to resolve file conflicts.
71pub async fn merge_commit_trees_no_resolve(
72    repo: &dyn Repo,
73    commits: &[Commit],
74) -> BackendResult<MergedTree> {
75    if let [commit] = commits {
76        Ok(commit.tree())
77    } else {
78        merge_commit_trees_no_resolve_without_repo(repo.store(), repo.index(), commits).await
79    }
80}
81
82/// Merges `commits` without attempting to resolve file conflicts.
83#[instrument(skip(index))]
84pub async fn merge_commit_trees_no_resolve_without_repo(
85    store: &Arc<Store>,
86    index: &dyn Index,
87    commits: &[Commit],
88) -> BackendResult<MergedTree> {
89    let commit_ids = commits
90        .iter()
91        .map(|commit| commit.id().clone())
92        .collect_vec();
93    let commit_id_merge = find_recursive_merge_commits(store, index, commit_ids)?;
94    let tree_merge: Merge<(MergedTree, String)> = commit_id_merge
95        .try_map_async(async |commit_id| {
96            let commit = store.get_commit_async(commit_id).await?;
97            Ok::<_, BackendError>((commit.tree(), commit.conflict_label()))
98        })
99        .await?;
100    Ok(MergedTree::merge_no_resolve(tree_merge))
101}
102
103/// Find the commits to use as input to the recursive merge algorithm.
104pub fn find_recursive_merge_commits(
105    store: &Arc<Store>,
106    index: &dyn Index,
107    mut commit_ids: Vec<CommitId>,
108) -> BackendResult<Merge<CommitId>> {
109    if commit_ids.is_empty() {
110        Ok(Merge::resolved(store.root_commit_id().clone()))
111    } else if commit_ids.len() == 1 {
112        Ok(Merge::resolved(commit_ids.pop().unwrap()))
113    } else {
114        let mut result = Merge::resolved(commit_ids[0].clone());
115        for (i, other_commit_id) in commit_ids.iter().enumerate().skip(1) {
116            let ancestor_ids = index
117                .common_ancestors(&commit_ids[0..i], &commit_ids[i..][..1])
118                // TODO: indexing error shouldn't be a "BackendError"
119                .map_err(|err| BackendError::Other(err.into()))?;
120            let ancestor_merge = find_recursive_merge_commits(store, index, ancestor_ids)?;
121            result = Merge::from_vec(vec![
122                result,
123                ancestor_merge,
124                Merge::resolved(other_commit_id.clone()),
125            ])
126            .flatten();
127        }
128        Ok(result)
129    }
130}
131
132/// Restore matching paths from the source into the destination.
133pub async fn restore_tree(
134    source: &MergedTree,
135    destination: &MergedTree,
136    source_label: String,
137    destination_label: String,
138    matcher: &dyn Matcher,
139) -> BackendResult<MergedTree> {
140    if matcher.visit(RepoPath::root()) == Visit::AllRecursively {
141        // Optimization for a common case
142        return Ok(source.clone());
143    }
144    let mut diff_stream = source.diff_stream(destination, matcher);
145    let mut paths = Vec::new();
146    while let Some(entry) = diff_stream.next().await {
147        // TODO: We should be able to not traverse deeper in the diff if the matcher
148        // matches an entire subtree.
149        paths.push(entry.path);
150    }
151    let matcher = FilesMatcher::new(paths);
152
153    let select_matching =
154        async |tree: &MergedTree, labels: ConflictLabels| -> BackendResult<MergedTree> {
155            let empty_tree_ids = Merge::repeated(
156                tree.store().empty_tree_id().clone(),
157                tree.tree_ids().num_sides(),
158            );
159            let labeled_empty_tree = MergedTree::new(tree.store().clone(), empty_tree_ids, labels);
160            let mut builder = MergedTreeBuilder::new(labeled_empty_tree);
161            for (path, value) in tree.entries_matching(&matcher) {
162                // TODO: if https://github.com/jj-vcs/jj/issues/4152 is implemented, we will need
163                // to expand resolved conflicts into `Merge::repeated(value, num_sides)`.
164                builder.set_or_remove(path, value?);
165            }
166            builder.write_tree().await
167        };
168
169    const RESTORE_BASE_LABEL: &str = "base files for restore";
170
171    // To avoid confusion between the destination tree and the base tree, we add a
172    // prefix to the conflict labels of the base tree.
173    let base_labels = ConflictLabels::from_merge(destination.labels().as_merge().map(|label| {
174        if label.is_empty() || label.starts_with(RESTORE_BASE_LABEL) {
175            label.clone()
176        } else {
177            format!("{RESTORE_BASE_LABEL} (from {label})")
178        }
179    }));
180
181    // Merging the trees this way ensures that when restoring a conflicted file into
182    // a conflicted commit, we preserve the labels of both commits even if the
183    // commits had different conflict labels. The labels we add here for
184    // non-conflicted trees will generally not be visible to users since they will
185    // always be removed during simplification when materializing any individual
186    // file. However, they could be useful in the future if we add a command which
187    // shows the labels for all the sides of a conflicted commit, and they are also
188    // useful for debugging.
189    // TODO: using a merge is required for retaining conflict labels when restoring
190    // from/into conflicted trees, but maybe we could optimize the case where both
191    // trees are already resolved.
192    MergedTree::merge(Merge::from_vec(vec![
193        (
194            destination.clone(),
195            format!("{destination_label} (restore destination)"),
196        ),
197        (
198            select_matching(destination, base_labels).await?,
199            format!("{RESTORE_BASE_LABEL} (from {destination_label})"),
200        ),
201        (
202            select_matching(source, source.labels().clone()).await?,
203            format!("restored files (from {source_label})"),
204        ),
205    ]))
206    .await
207}
208
209pub async fn rebase_commit(
210    mut_repo: &mut MutableRepo,
211    old_commit: Commit,
212    new_parents: Vec<CommitId>,
213) -> BackendResult<Commit> {
214    let rewriter = CommitRewriter::new(mut_repo, old_commit, new_parents);
215    let builder = rewriter.rebase().await?;
216    builder.write().await
217}
218
219/// Helps rewrite a commit.
220pub struct CommitRewriter<'repo> {
221    mut_repo: &'repo mut MutableRepo,
222    old_commit: Commit,
223    new_parents: Vec<CommitId>,
224}
225
226impl<'repo> CommitRewriter<'repo> {
227    /// Create a new instance.
228    pub fn new(
229        mut_repo: &'repo mut MutableRepo,
230        old_commit: Commit,
231        new_parents: Vec<CommitId>,
232    ) -> Self {
233        Self {
234            mut_repo,
235            old_commit,
236            new_parents,
237        }
238    }
239
240    /// Returns the `MutableRepo`.
241    pub fn repo_mut(&mut self) -> &mut MutableRepo {
242        self.mut_repo
243    }
244
245    /// The commit we're rewriting.
246    pub fn old_commit(&self) -> &Commit {
247        &self.old_commit
248    }
249
250    /// Get the old commit's intended new parents.
251    pub fn new_parents(&self) -> &[CommitId] {
252        &self.new_parents
253    }
254
255    /// Set the old commit's intended new parents.
256    pub fn set_new_parents(&mut self, new_parents: Vec<CommitId>) {
257        self.new_parents = new_parents;
258    }
259
260    /// Set the old commit's intended new parents to be the rewritten versions
261    /// of the given parents.
262    pub fn set_new_rewritten_parents(&mut self, unrewritten_parents: &[CommitId]) {
263        self.new_parents = self.mut_repo.new_parents(unrewritten_parents);
264    }
265
266    /// Update the intended new parents by replacing any occurrence of
267    /// `old_parent` by `new_parents`.
268    pub fn replace_parent<'a>(
269        &mut self,
270        old_parent: &CommitId,
271        new_parents: impl IntoIterator<Item = &'a CommitId>,
272    ) {
273        if let Some(i) = self.new_parents.iter().position(|p| p == old_parent) {
274            self.new_parents
275                .splice(i..i + 1, new_parents.into_iter().cloned());
276            let mut unique = HashSet::new();
277            self.new_parents.retain(|p| unique.insert(p.clone()));
278        }
279    }
280
281    /// Checks if the intended new parents are different from the old commit's
282    /// parents.
283    pub fn parents_changed(&self) -> bool {
284        self.new_parents != self.old_commit.parent_ids()
285    }
286
287    /// If a merge commit would end up with one parent being an ancestor of the
288    /// other, then filter out the ancestor.
289    pub fn simplify_ancestor_merge(&mut self) -> IndexResult<()> {
290        let head_set: HashSet<_> = self
291            .mut_repo
292            .index()
293            .heads(&mut self.new_parents.iter())?
294            .into_iter()
295            .collect();
296        self.new_parents.retain(|parent| head_set.contains(parent));
297        Ok(())
298    }
299
300    /// Records the old commit as abandoned with the new parents.
301    ///
302    /// This is equivalent to `reparent(settings).abandon()`, but is cheaper.
303    pub fn abandon(self) {
304        let old_commit_id = self.old_commit.id().clone();
305        let new_parents = self.new_parents;
306        self.mut_repo
307            .record_abandoned_commit_with_parents(old_commit_id, new_parents);
308    }
309
310    /// Rebase the old commit onto the new parents. Returns a `CommitBuilder`
311    /// for the new commit. Returns `None` if the commit was abandoned.
312    pub async fn rebase_with_empty_behavior(
313        self,
314        empty: EmptyBehavior,
315    ) -> BackendResult<Option<CommitBuilder<'repo>>> {
316        let old_parents_fut = self.old_commit.parents();
317        let new_parents_fut = try_join_all(
318            self.new_parents
319                .iter()
320                .map(|new_parent_id| self.mut_repo.store().get_commit_async(new_parent_id)),
321        );
322        let (old_parents, new_parents) = try_join!(old_parents_fut, new_parents_fut)?;
323        let old_parent_trees = old_parents
324            .iter()
325            .map(|parent| parent.tree_ids().clone())
326            .collect_vec();
327        let new_parent_trees = new_parents
328            .iter()
329            .map(|parent| parent.tree_ids().clone())
330            .collect_vec();
331
332        let (was_empty, new_tree) = if new_parent_trees == old_parent_trees {
333            (
334                // Optimization: was_empty is only used for newly empty, but when the
335                // parents haven't changed it can't be newly empty.
336                true,
337                // Optimization: Skip merging.
338                self.old_commit.tree(),
339            )
340        } else {
341            // We wouldn't need to resolve merge conflicts here if the
342            // same-change rule is "keep". See 9d4a97381f30 "rewrite: don't
343            // resolve intermediate parent tree when rebasing" for details.
344            let old_base_tree_fut = merge_commit_trees(self.mut_repo, &old_parents);
345            let new_base_tree_fut = merge_commit_trees(self.mut_repo, &new_parents);
346            let old_tree = self.old_commit.tree();
347            let (old_base_tree, new_base_tree) = try_join!(old_base_tree_fut, new_base_tree_fut)?;
348            (
349                old_base_tree.tree_ids() == self.old_commit.tree_ids(),
350                MergedTree::merge(Merge::from_vec(vec![
351                    (
352                        new_base_tree,
353                        format!(
354                            "{} (rebase destination)",
355                            conflict_label_for_commits(&new_parents)
356                        ),
357                    ),
358                    (
359                        old_base_tree,
360                        format!(
361                            "{} (parents of rebased revision)",
362                            conflict_label_for_commits(&old_parents)
363                        ),
364                    ),
365                    (
366                        old_tree,
367                        format!("{} (rebased revision)", self.old_commit.conflict_label()),
368                    ),
369                ]))
370                .await?,
371            )
372        };
373        // Ensure we don't abandon commits with multiple parents (merge commits), even
374        // if they're empty.
375        if let [parent] = &new_parents[..] {
376            let should_abandon = match empty {
377                EmptyBehavior::Keep => false,
378                EmptyBehavior::AbandonNewlyEmpty => {
379                    parent.tree_ids() == new_tree.tree_ids() && !was_empty
380                }
381                EmptyBehavior::AbandonAllEmpty => parent.tree_ids() == new_tree.tree_ids(),
382            };
383            if should_abandon {
384                self.abandon();
385                return Ok(None);
386            }
387        }
388
389        let builder = self
390            .mut_repo
391            .rewrite_commit(&self.old_commit)
392            .set_parents(self.new_parents)
393            .set_tree(new_tree);
394        Ok(Some(builder))
395    }
396
397    /// Rebase the old commit onto the new parents. Returns a `CommitBuilder`
398    /// for the new commit.
399    pub async fn rebase(self) -> BackendResult<CommitBuilder<'repo>> {
400        let builder = self.rebase_with_empty_behavior(EmptyBehavior::Keep).await?;
401        Ok(builder.unwrap())
402    }
403
404    /// Rewrite the old commit onto the new parents without changing its
405    /// contents. Returns a `CommitBuilder` for the new commit.
406    pub fn reparent(self) -> CommitBuilder<'repo> {
407        self.mut_repo
408            .rewrite_commit(&self.old_commit)
409            .set_parents(self.new_parents)
410    }
411}
412
413#[derive(Debug)]
414pub enum RebasedCommit {
415    Rewritten(Commit),
416    Abandoned { parent_id: CommitId },
417}
418
419pub async fn rebase_commit_with_options(
420    mut rewriter: CommitRewriter<'_>,
421    options: &RebaseOptions,
422) -> BackendResult<RebasedCommit> {
423    // If specified, don't create commit where one parent is an ancestor of another.
424    if options.simplify_ancestor_merge {
425        rewriter
426            .simplify_ancestor_merge()
427            // TODO: indexing error shouldn't be a "BackendError"
428            .map_err(|err| BackendError::Other(err.into()))?;
429    }
430
431    let single_parent = match &rewriter.new_parents[..] {
432        [parent_id] => Some(parent_id.clone()),
433        _ => None,
434    };
435    let new_parents_len = rewriter.new_parents.len();
436    if let Some(builder) = rewriter.rebase_with_empty_behavior(options.empty).await? {
437        let new_commit = builder.write().await?;
438        Ok(RebasedCommit::Rewritten(new_commit))
439    } else {
440        assert_eq!(new_parents_len, 1);
441        Ok(RebasedCommit::Abandoned {
442            parent_id: single_parent.unwrap(),
443        })
444    }
445}
446
447/// Moves changes from `sources` to the `destination` parent, returns new tree.
448// TODO: pass conflict labels as argument to provide more specific information
449pub async fn rebase_to_dest_parent(
450    repo: &dyn Repo,
451    sources: &[Commit],
452    destination: &Commit,
453) -> BackendResult<MergedTree> {
454    if let [source] = sources
455        && source.parent_ids() == destination.parent_ids()
456    {
457        return Ok(source.tree());
458    }
459
460    let diffs: Vec<_> = try_join_all(sources.iter().map(async |source| -> BackendResult<_> {
461        Ok(Diff::new(
462            (
463                source.parent_tree(repo).await?,
464                format!(
465                    "{} (original parents)",
466                    source.parents_conflict_label().await?
467                ),
468            ),
469            (
470                source.tree(),
471                format!("{} (original revision)", source.conflict_label()),
472            ),
473        ))
474    }))
475    .await?;
476    MergedTree::merge(Merge::from_diffs(
477        (
478            destination.parent_tree(repo).await?,
479            format!(
480                "{} (new parents)",
481                destination.parents_conflict_label().await?
482            ),
483        ),
484        diffs,
485    ))
486    .await
487}
488
489#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
490pub enum EmptyBehavior {
491    /// Always keep empty commits
492    #[default]
493    Keep,
494    /// Skips commits that would be empty after the rebase, but that were not
495    /// originally empty.
496    /// Will never skip merge commits with multiple non-empty parents.
497    AbandonNewlyEmpty,
498    /// Skips all empty commits, including ones that were empty before the
499    /// rebase.
500    /// Will never skip merge commits with multiple non-empty parents.
501    AbandonAllEmpty,
502}
503
504/// Controls the configuration of a rebase.
505// If we wanted to add a flag similar to `git rebase --ignore-date`, then this
506// makes it much easier by ensuring that the only changes required are to
507// change the RebaseOptions construction in the CLI, and changing the
508// rebase_commit function to actually use the flag, and ensure we don't need to
509// plumb it in.
510#[derive(Clone, Debug, Default)]
511pub struct RebaseOptions {
512    pub empty: EmptyBehavior,
513    pub rewrite_refs: RewriteRefsOptions,
514    /// If a merge commit would end up with one parent being an ancestor of the
515    /// other, then filter out the ancestor.
516    pub simplify_ancestor_merge: bool,
517}
518
519/// Configuration for [`MutableRepo::update_rewritten_references()`].
520#[derive(Clone, Debug, Default)]
521pub struct RewriteRefsOptions {
522    /// Whether or not delete bookmarks pointing to the abandoned commits.
523    ///
524    /// If false, bookmarks will be moved to the parents of the abandoned
525    /// commit.
526    pub delete_abandoned_bookmarks: bool,
527}
528
529#[derive(Debug)]
530pub struct MoveCommitsStats {
531    /// The number of commits in the target set which were rebased.
532    pub num_rebased_targets: u32,
533    /// The number of descendant commits which were rebased.
534    pub num_rebased_descendants: u32,
535    /// The number of commits for which rebase was skipped, due to the commit
536    /// already being in place.
537    pub num_skipped_rebases: u32,
538    /// The number of commits which were abandoned due to being empty.
539    pub num_abandoned_empty: u32,
540    /// The rebased commits
541    pub rebased_commits: HashMap<CommitId, RebasedCommit>,
542}
543
544/// Target and destination commits to be rebased by [`move_commits()`].
545#[derive(Clone, Debug)]
546pub struct MoveCommitsLocation {
547    pub new_parent_ids: Vec<CommitId>,
548    pub new_child_ids: Vec<CommitId>,
549    pub target: MoveCommitsTarget,
550}
551
552#[derive(Clone, Debug)]
553pub enum MoveCommitsTarget {
554    /// The commits to be moved. Commits should be mutable and in reverse
555    /// topological order.
556    Commits(Vec<CommitId>),
557    /// The root commits to be moved, along with all their descendants.
558    Roots(Vec<CommitId>),
559}
560
561#[derive(Clone, Debug)]
562pub struct ComputedMoveCommits {
563    target_commit_ids: IndexSet<CommitId>,
564    descendants: Vec<Commit>,
565    commit_new_parents_map: HashMap<CommitId, Vec<CommitId>>,
566    to_abandon: HashSet<CommitId>,
567}
568
569impl ComputedMoveCommits {
570    fn empty() -> Self {
571        Self {
572            target_commit_ids: IndexSet::new(),
573            descendants: vec![],
574            commit_new_parents_map: HashMap::new(),
575            to_abandon: HashSet::new(),
576        }
577    }
578
579    /// Records a set of commits to abandon while rebasing.
580    ///
581    /// Abandoning these commits while rebasing ensures that their descendants
582    /// are still rebased properly. [`MutableRepo::record_abandoned_commit`] is
583    /// similar, but it can lead to issues when abandoning a target commit
584    /// before the rebase.
585    pub fn record_to_abandon(&mut self, commit_ids: impl IntoIterator<Item = CommitId>) {
586        self.to_abandon.extend(commit_ids);
587    }
588
589    pub async fn apply(
590        self,
591        mut_repo: &mut MutableRepo,
592        options: &RebaseOptions,
593    ) -> BackendResult<MoveCommitsStats> {
594        apply_move_commits(mut_repo, self, options).await
595    }
596}
597
598/// Moves `loc.target` commits from their current location to a new location in
599/// the graph.
600///
601/// Commits in `target` are rebased onto the new parents given by
602/// `new_parent_ids`, while the `new_child_ids` commits are rebased onto the
603/// heads of the commits in `targets`. This assumes that commits in `target` and
604/// `new_child_ids` can be rewritten, and there will be no cycles in the
605/// resulting graph. Commits in `target` should be in reverse topological order.
606pub async fn move_commits(
607    mut_repo: &mut MutableRepo,
608    loc: &MoveCommitsLocation,
609    options: &RebaseOptions,
610) -> BackendResult<MoveCommitsStats> {
611    compute_move_commits(mut_repo, loc)
612        .await?
613        .apply(mut_repo, options)
614        .await
615}
616
617pub async fn compute_move_commits(
618    repo: &MutableRepo,
619    loc: &MoveCommitsLocation,
620) -> BackendResult<ComputedMoveCommits> {
621    let target_commit_ids: IndexSet<CommitId>;
622    let connected_target_commits: Vec<Commit>;
623    let connected_target_commits_internal_parents: HashMap<CommitId, IndexSet<CommitId>>;
624    let target_roots: HashSet<CommitId>;
625
626    match &loc.target {
627        MoveCommitsTarget::Commits(commit_ids) => {
628            if commit_ids.is_empty() {
629                return Ok(ComputedMoveCommits::empty());
630            }
631
632            target_commit_ids = commit_ids.iter().cloned().collect();
633
634            connected_target_commits = RevsetExpression::commits(commit_ids.clone())
635                .connected()
636                .evaluate(repo)
637                .map_err(|err| err.into_backend_error())?
638                .stream()
639                .commits(repo.store())
640                .try_collect()
641                .await
642                .map_err(|err| err.into_backend_error())?;
643            connected_target_commits_internal_parents =
644                compute_internal_parents_within(&target_commit_ids, &connected_target_commits);
645
646            target_roots = connected_target_commits_internal_parents
647                .iter()
648                .filter(|&(commit_id, parents)| {
649                    target_commit_ids.contains(commit_id) && parents.is_empty()
650                })
651                .map(|(commit_id, _)| commit_id.clone())
652                .collect();
653        }
654        MoveCommitsTarget::Roots(root_ids) => {
655            if root_ids.is_empty() {
656                return Ok(ComputedMoveCommits::empty());
657            }
658
659            target_commit_ids = RevsetExpression::commits(root_ids.clone())
660                .descendants()
661                .evaluate(repo)
662                .map_err(|err| err.into_backend_error())?
663                .stream()
664                .try_collect()
665                .await
666                .map_err(|err| err.into_backend_error())?;
667
668            connected_target_commits = try_join_all(
669                target_commit_ids
670                    .iter()
671                    .map(|id| repo.store().get_commit_async(id)),
672            )
673            .await?;
674            // We don't have to compute the internal parents for the connected target set,
675            // since the connected target set is the same as the target set.
676            connected_target_commits_internal_parents = HashMap::new();
677            target_roots = root_ids.iter().cloned().collect();
678        }
679    }
680
681    // If a commit outside the target set has a commit in the target set as a
682    // parent, then - after the transformation - it should have that commit's
683    // ancestors which are not in the target set as parents.
684    let mut target_commits_external_parents: HashMap<CommitId, IndexSet<CommitId>> = HashMap::new();
685    for id in target_commit_ids.iter().rev() {
686        let commit = repo.store().get_commit_async(id).await?;
687        let mut new_parents = IndexSet::new();
688        for old_parent in commit.parent_ids() {
689            if let Some(parents) = target_commits_external_parents.get(old_parent) {
690                new_parents.extend(parents.iter().cloned());
691            } else {
692                new_parents.insert(old_parent.clone());
693            }
694        }
695        target_commits_external_parents.insert(commit.id().clone(), new_parents);
696    }
697
698    // If the new parents include a commit in the target set, replace it with the
699    // commit's ancestors which are outside the set.
700    // e.g. `jj rebase -r A --before A`
701    let new_parent_ids: Vec<_> = loc
702        .new_parent_ids
703        .iter()
704        .flat_map(|parent_id| {
705            if let Some(parent_ids) = target_commits_external_parents.get(parent_id) {
706                parent_ids.iter().cloned().collect_vec()
707            } else {
708                vec![parent_id.clone()]
709            }
710        })
711        .collect();
712
713    // If the new children include a commit in the target set, replace it with the
714    // commit's descendants which are outside the set.
715    // e.g. `jj rebase -r A --after A`
716    let new_children: Vec<_> = if loc
717        .new_child_ids
718        .iter()
719        .any(|id| target_commit_ids.contains(id))
720    {
721        let target_commits_descendants: Vec<_> =
722            RevsetExpression::commits(target_commit_ids.iter().cloned().collect_vec())
723                .union(
724                    &RevsetExpression::commits(target_commit_ids.iter().cloned().collect_vec())
725                        .children(),
726                )
727                .evaluate(repo)
728                .map_err(|err| err.into_backend_error())?
729                .stream()
730                .commits(repo.store())
731                .try_collect()
732                .await
733                .map_err(|err| err.into_backend_error())?;
734
735        // For all commits in the target set, compute its transitive descendant commits
736        // which are outside of the target set by up to 1 generation.
737        let mut target_commit_external_descendants: HashMap<CommitId, IndexSet<Commit>> =
738            HashMap::new();
739        // Iterate through all descendants of the target set, going through children
740        // before parents.
741        for commit in &target_commits_descendants {
742            if !target_commit_external_descendants.contains_key(commit.id()) {
743                let children = if target_commit_ids.contains(commit.id()) {
744                    IndexSet::new()
745                } else {
746                    IndexSet::from([commit.clone()])
747                };
748                target_commit_external_descendants.insert(commit.id().clone(), children);
749            }
750
751            let children = target_commit_external_descendants
752                .get(commit.id())
753                .unwrap()
754                .iter()
755                .cloned()
756                .collect_vec();
757            for parent_id in commit.parent_ids() {
758                if target_commit_ids.contains(parent_id) {
759                    if let Some(target_children) =
760                        target_commit_external_descendants.get_mut(parent_id)
761                    {
762                        target_children.extend(children.iter().cloned());
763                    } else {
764                        target_commit_external_descendants
765                            .insert(parent_id.clone(), children.iter().cloned().collect());
766                    }
767                }
768            }
769        }
770
771        let mut new_children = Vec::new();
772        for id in &loc.new_child_ids {
773            if let Some(children) = target_commit_external_descendants.get(id) {
774                new_children.extend(children.iter().cloned());
775            } else {
776                new_children.push(repo.store().get_commit_async(id).await?);
777            }
778        }
779        new_children
780    } else {
781        try_join_all(
782            loc.new_child_ids
783                .iter()
784                .map(|id| repo.store().get_commit_async(id)),
785        )
786        .await?
787    };
788
789    // Compute the parents of the new children, which will include the heads of the
790    // target set.
791    let new_children_parents: HashMap<_, _> = if !new_children.is_empty() {
792        // Compute the heads of the target set, which will be used as the parents of
793        // `new_children`.
794        let target_heads = compute_commits_heads(&target_commit_ids, &connected_target_commits);
795
796        new_children
797            .iter()
798            .map(|child_commit| {
799                let mut new_child_parent_ids = IndexSet::new();
800                for old_child_parent_id in child_commit.parent_ids() {
801                    // Replace target commits with their parents outside the target set.
802                    let old_child_parent_ids = if let Some(parents) =
803                        target_commits_external_parents.get(old_child_parent_id)
804                    {
805                        parents.iter().collect_vec()
806                    } else {
807                        vec![old_child_parent_id]
808                    };
809
810                    // If the original parents of the new children are the new parents of the
811                    // `target_heads`, replace them with the target heads since we are "inserting"
812                    // the target commits in between the new parents and the new children.
813                    for id in old_child_parent_ids {
814                        if new_parent_ids.contains(id) {
815                            new_child_parent_ids.extend(target_heads.clone());
816                        } else {
817                            new_child_parent_ids.insert(id.clone());
818                        }
819                    }
820                }
821
822                // If not already present, add `target_heads` as parents of the new child
823                // commit.
824                new_child_parent_ids.extend(target_heads.clone());
825
826                (
827                    child_commit.id().clone(),
828                    new_child_parent_ids.into_iter().collect_vec(),
829                )
830            })
831            .collect()
832    } else {
833        HashMap::new()
834    };
835
836    // Compute the set of commits to visit, which includes the target commits, the
837    // new children commits (if any), and their descendants.
838    let mut roots = target_roots.iter().cloned().collect_vec();
839    roots.extend(new_children.iter().ids().cloned());
840
841    let descendants = repo.find_descendants_for_rebase(roots.clone()).await?;
842    let commit_new_parents_map = descendants
843        .iter()
844        .map(|commit| -> BackendResult<_> {
845            let commit_id = commit.id();
846            let new_parent_ids =
847                if let Some(new_child_parents) = new_children_parents.get(commit_id) {
848                    // New child of the rebased target commits.
849                    new_child_parents.clone()
850                } else if target_commit_ids.contains(commit_id) {
851                    // Commit is in the target set.
852                    if target_roots.contains(commit_id) {
853                        // If the commit is a root of the target set, it should be rebased onto the
854                        // new destination.
855                        new_parent_ids.clone()
856                    } else {
857                        // Otherwise:
858                        // 1. Keep parents which are within the target set.
859                        // 2. Replace parents which are outside the target set but are part of the
860                        //    connected target set with their ancestor commits which are in the
861                        //    target set.
862                        // 3. Keep other parents outside the target set if they are not descendants
863                        //    of the new children of the target set.
864                        let mut new_parents = vec![];
865                        for parent_id in commit.parent_ids() {
866                            if target_commit_ids.contains(parent_id) {
867                                new_parents.push(parent_id.clone());
868                            } else if let Some(parents) =
869                                connected_target_commits_internal_parents.get(parent_id)
870                            {
871                                new_parents.extend(parents.iter().cloned());
872                            } else if !fallible_any(&new_children, |child| {
873                                repo.index().is_ancestor(child.id(), parent_id)
874                            })
875                            // TODO: indexing error shouldn't be a "BackendError"
876                            .map_err(|err| BackendError::Other(err.into()))?
877                            {
878                                new_parents.push(parent_id.clone());
879                            }
880                        }
881                        new_parents
882                    }
883                } else if commit
884                    .parent_ids()
885                    .iter()
886                    .any(|id| target_commits_external_parents.contains_key(id))
887                {
888                    // Commits outside the target set should have references to commits inside the
889                    // set replaced.
890                    let mut new_parents = vec![];
891                    for parent in commit.parent_ids() {
892                        if let Some(parents) = target_commits_external_parents.get(parent) {
893                            new_parents.extend(parents.iter().cloned());
894                        } else {
895                            new_parents.push(parent.clone());
896                        }
897                    }
898                    new_parents
899                } else {
900                    commit.parent_ids().iter().cloned().collect_vec()
901                };
902            Ok((commit.id().clone(), new_parent_ids))
903        })
904        .try_collect()?;
905
906    Ok(ComputedMoveCommits {
907        target_commit_ids,
908        descendants,
909        commit_new_parents_map,
910        to_abandon: HashSet::new(),
911    })
912}
913
914async fn apply_move_commits(
915    mut_repo: &mut MutableRepo,
916    commits: ComputedMoveCommits,
917    options: &RebaseOptions,
918) -> BackendResult<MoveCommitsStats> {
919    let mut num_rebased_targets = 0;
920    let mut num_rebased_descendants = 0;
921    let mut num_skipped_rebases = 0;
922    let mut num_abandoned_empty = 0;
923
924    // Always keep empty commits and don't simplify merges when rebasing
925    // descendants.
926    let rebase_descendant_options = &RebaseOptions {
927        empty: EmptyBehavior::Keep,
928        rewrite_refs: options.rewrite_refs.clone(),
929        simplify_ancestor_merge: false,
930    };
931
932    let mut rebased_commits: HashMap<CommitId, RebasedCommit> = HashMap::new();
933    mut_repo
934        .transform_commits(
935            commits.descendants,
936            &commits.commit_new_parents_map,
937            &options.rewrite_refs,
938            async |rewriter| {
939                let old_commit_id = rewriter.old_commit().id().clone();
940                if commits.to_abandon.contains(&old_commit_id) {
941                    rewriter.abandon();
942                } else if rewriter.parents_changed() {
943                    let is_target_commit = commits.target_commit_ids.contains(&old_commit_id);
944                    let rebased_commit = rebase_commit_with_options(
945                        rewriter,
946                        if is_target_commit {
947                            options
948                        } else {
949                            rebase_descendant_options
950                        },
951                    )
952                    .await?;
953                    if let RebasedCommit::Abandoned { .. } = rebased_commit {
954                        num_abandoned_empty += 1;
955                    } else if is_target_commit {
956                        num_rebased_targets += 1;
957                    } else {
958                        num_rebased_descendants += 1;
959                    }
960                    rebased_commits.insert(old_commit_id, rebased_commit);
961                } else {
962                    num_skipped_rebases += 1;
963                }
964
965                Ok(())
966            },
967        )
968        .await?;
969
970    Ok(MoveCommitsStats {
971        num_rebased_targets,
972        num_rebased_descendants,
973        num_skipped_rebases,
974        num_abandoned_empty,
975        rebased_commits,
976    })
977}
978
979#[derive(Debug, Default)]
980pub struct DuplicateCommitsStats {
981    /// Map of original commit ID to newly duplicated commit.
982    pub duplicated_commits: IndexMap<CommitId, Commit>,
983    /// The number of descendant commits which were rebased onto the duplicated
984    /// commits.
985    pub num_rebased: u32,
986}
987
988/// Duplicates the given `target_commit_ids` onto a new location in the graph.
989///
990/// The roots of `target_commit_ids` are duplicated on top of the new
991/// `parent_commit_ids`, whilst other commits in `target_commit_ids` are
992/// duplicated on top of the newly duplicated commits in the target set. If
993/// `children_commit_ids` is not empty, the `children_commit_ids` will be
994/// rebased onto the heads of the duplicated target commits.
995///
996/// If `target_descriptions` is not empty, it will be consulted to retrieve the
997/// new descriptions of the target commits, falling back to the original if the
998/// map does not contain an entry for a given commit.
999///
1000/// This assumes that commits in `children_commit_ids` can be rewritten. There
1001/// should also be no cycles in the resulting graph, i.e. `children_commit_ids`
1002/// should not be ancestors of `parent_commit_ids`. Commits in
1003/// `target_commit_ids` should be in reverse topological order (children before
1004/// parents).
1005pub async fn duplicate_commits(
1006    mut_repo: &mut MutableRepo,
1007    target_commit_ids: &[CommitId],
1008    target_descriptions: &HashMap<CommitId, String>,
1009    parent_commit_ids: &[CommitId],
1010    children_commit_ids: &[CommitId],
1011) -> BackendResult<DuplicateCommitsStats> {
1012    if target_commit_ids.is_empty() {
1013        return Ok(DuplicateCommitsStats::default());
1014    }
1015
1016    let mut duplicated_old_to_new: IndexMap<CommitId, Commit> = IndexMap::new();
1017    let mut num_rebased = 0;
1018
1019    let target_commit_ids: IndexSet<_> = target_commit_ids.iter().cloned().collect();
1020
1021    let connected_target_commits: Vec<_> =
1022        RevsetExpression::commits(target_commit_ids.iter().cloned().collect_vec())
1023            .connected()
1024            .evaluate(mut_repo)
1025            .map_err(|err| err.into_backend_error())?
1026            .stream()
1027            .commits(mut_repo.store())
1028            .try_collect()
1029            .await
1030            .map_err(|err| err.into_backend_error())?;
1031
1032    // Commits in the target set should only have other commits in the set as
1033    // parents, except the roots of the set, which persist their original
1034    // parents.
1035    // If a commit in the target set has a parent which is not in the set, but has
1036    // an ancestor which is in the set, then the commit will have that ancestor
1037    // as a parent instead.
1038    let target_commits_internal_parents = {
1039        let mut target_commits_internal_parents =
1040            compute_internal_parents_within(&target_commit_ids, &connected_target_commits);
1041        target_commits_internal_parents.retain(|id, _| target_commit_ids.contains(id));
1042        target_commits_internal_parents
1043    };
1044
1045    // Compute the roots of `target_commits`.
1046    let target_root_ids: HashSet<_> = target_commits_internal_parents
1047        .iter()
1048        .filter(|(_, parents)| parents.is_empty())
1049        .map(|(commit_id, _)| commit_id.clone())
1050        .collect();
1051
1052    // Compute the heads of the target set, which will be used as the parents of
1053    // the children commits.
1054    let target_head_ids = if !children_commit_ids.is_empty() {
1055        compute_commits_heads(&target_commit_ids, &connected_target_commits)
1056    } else {
1057        vec![]
1058    };
1059
1060    // Topological order ensures that any parents of the original commit are
1061    // either not in `target_commits` or were already duplicated.
1062    for original_commit_id in target_commit_ids.iter().rev() {
1063        let original_commit = mut_repo
1064            .store()
1065            .get_commit_async(original_commit_id)
1066            .await?;
1067        let new_parent_ids = if target_root_ids.contains(original_commit_id) {
1068            parent_commit_ids.to_vec()
1069        } else {
1070            target_commits_internal_parents
1071                .get(original_commit_id)
1072                .unwrap()
1073                .iter()
1074                // Replace parent IDs with their new IDs if they were duplicated.
1075                .map(|id| {
1076                    duplicated_old_to_new
1077                        .get(id)
1078                        .map_or(id, |commit| commit.id())
1079                        .clone()
1080                })
1081                .collect()
1082        };
1083        let mut new_commit_builder = CommitRewriter::new(mut_repo, original_commit, new_parent_ids)
1084            .rebase()
1085            .await?
1086            .clear_rewrite_source()
1087            .generate_new_change_id();
1088        if let Some(desc) = target_descriptions.get(original_commit_id) {
1089            new_commit_builder = new_commit_builder.set_description(desc);
1090        }
1091        duplicated_old_to_new.insert(
1092            original_commit_id.clone(),
1093            new_commit_builder.write().await?,
1094        );
1095    }
1096
1097    // Replace the original commit IDs in `target_head_ids` with the duplicated
1098    // commit IDs.
1099    let target_head_ids = target_head_ids
1100        .into_iter()
1101        .map(|commit_id| {
1102            duplicated_old_to_new
1103                .get(&commit_id)
1104                .map_or(commit_id, |commit| commit.id().clone())
1105        })
1106        .collect_vec();
1107
1108    // Rebase new children onto the target heads.
1109    let children_commit_ids_set: HashSet<CommitId> = children_commit_ids.iter().cloned().collect();
1110    mut_repo
1111        .transform_descendants(children_commit_ids.to_vec(), async |mut rewriter| {
1112            if children_commit_ids_set.contains(rewriter.old_commit().id()) {
1113                let mut child_new_parent_ids = IndexSet::new();
1114                for old_parent_id in rewriter.old_commit().parent_ids() {
1115                    // If the original parents of the new children are the new parents of
1116                    // `target_head_ids`, replace them with `target_head_ids` since we are
1117                    // "inserting" the target commits in between the new parents and the new
1118                    // children.
1119                    if parent_commit_ids.contains(old_parent_id) {
1120                        child_new_parent_ids.extend(target_head_ids.clone());
1121                    } else {
1122                        child_new_parent_ids.insert(old_parent_id.clone());
1123                    }
1124                }
1125                // If not already present, add `target_head_ids` as parents of the new child
1126                // commit.
1127                child_new_parent_ids.extend(target_head_ids.clone());
1128                rewriter.set_new_parents(child_new_parent_ids.into_iter().collect());
1129            }
1130            num_rebased += 1;
1131            rewriter.rebase().await?.write().await?;
1132            Ok(())
1133        })
1134        .await?;
1135
1136    Ok(DuplicateCommitsStats {
1137        duplicated_commits: duplicated_old_to_new,
1138        num_rebased,
1139    })
1140}
1141
1142/// Duplicates the given `target_commits` onto their original parents or other
1143/// duplicated commits.
1144///
1145/// Commits in `target_commits` should be in reverse topological order (children
1146/// before parents).
1147///
1148/// If `target_descriptions` is not empty, it will be consulted to retrieve the
1149/// new descriptions of the target commits, falling back to the original if
1150/// the map does not contain an entry for a given commit.
1151pub async fn duplicate_commits_onto_parents(
1152    mut_repo: &mut MutableRepo,
1153    target_commits: &[CommitId],
1154    target_descriptions: &HashMap<CommitId, String>,
1155) -> BackendResult<DuplicateCommitsStats> {
1156    if target_commits.is_empty() {
1157        return Ok(DuplicateCommitsStats::default());
1158    }
1159
1160    let mut duplicated_old_to_new: IndexMap<CommitId, Commit> = IndexMap::new();
1161
1162    // Topological order ensures that any parents of the original commit are
1163    // either not in `target_commits` or were already duplicated.
1164    for original_commit_id in target_commits.iter().rev() {
1165        let original_commit = mut_repo
1166            .store()
1167            .get_commit_async(original_commit_id)
1168            .await?;
1169        let new_parent_ids = original_commit
1170            .parent_ids()
1171            .iter()
1172            .map(|id| {
1173                duplicated_old_to_new
1174                    .get(id)
1175                    .map_or(id, |commit| commit.id())
1176                    .clone()
1177            })
1178            .collect();
1179        let mut new_commit_builder = mut_repo
1180            .rewrite_commit(&original_commit)
1181            .clear_rewrite_source()
1182            .generate_new_change_id()
1183            .set_parents(new_parent_ids);
1184        if let Some(desc) = target_descriptions.get(original_commit_id) {
1185            new_commit_builder = new_commit_builder.set_description(desc);
1186        }
1187        duplicated_old_to_new.insert(
1188            original_commit_id.clone(),
1189            new_commit_builder.write().await?,
1190        );
1191    }
1192
1193    Ok(DuplicateCommitsStats {
1194        duplicated_commits: duplicated_old_to_new,
1195        num_rebased: 0,
1196    })
1197}
1198
1199/// Computes the internal parents of all commits in a connected commit graph,
1200/// allowing only commits in the target set as parents.
1201///
1202/// The parents of each commit are identical to the ones found using a preorder
1203/// DFS of the node's ancestors, starting from the node itself, and avoiding
1204/// traversing an edge if the parent is in the target set. `graph_commits`
1205/// should be in reverse topological order.
1206fn compute_internal_parents_within(
1207    target_commit_ids: &IndexSet<CommitId>,
1208    graph_commits: &[Commit],
1209) -> HashMap<CommitId, IndexSet<CommitId>> {
1210    let mut internal_parents: HashMap<CommitId, IndexSet<CommitId>> = HashMap::new();
1211    for commit in graph_commits.iter().rev() {
1212        // The roots of the set will not have any parents found in `internal_parents`,
1213        // and will be stored as an empty vector.
1214        let mut new_parents = IndexSet::new();
1215        for old_parent in commit.parent_ids() {
1216            if target_commit_ids.contains(old_parent) {
1217                new_parents.insert(old_parent.clone());
1218            } else if let Some(parents) = internal_parents.get(old_parent) {
1219                new_parents.extend(parents.iter().cloned());
1220            }
1221        }
1222        internal_parents.insert(commit.id().clone(), new_parents);
1223    }
1224    internal_parents
1225}
1226
1227/// Computes the heads of commits in the target set, given the list of
1228/// `target_commit_ids` and a connected graph of commits.
1229///
1230/// `connected_target_commits` should be in reverse topological order (children
1231/// before parents).
1232fn compute_commits_heads(
1233    target_commit_ids: &IndexSet<CommitId>,
1234    connected_target_commits: &[Commit],
1235) -> Vec<CommitId> {
1236    let mut target_head_ids: HashSet<CommitId> = HashSet::new();
1237    for commit in connected_target_commits.iter().rev() {
1238        target_head_ids.insert(commit.id().clone());
1239        for old_parent in commit.parent_ids() {
1240            target_head_ids.remove(old_parent);
1241        }
1242    }
1243    connected_target_commits
1244        .iter()
1245        .rev()
1246        .filter(|commit| {
1247            target_head_ids.contains(commit.id()) && target_commit_ids.contains(commit.id())
1248        })
1249        .map(|commit| commit.id().clone())
1250        .collect_vec()
1251}
1252
1253#[derive(Debug)]
1254pub struct CommitWithSelection {
1255    pub commit: Commit,
1256    pub selected_tree: MergedTree,
1257    pub parent_tree: MergedTree,
1258}
1259
1260impl CommitWithSelection {
1261    /// Returns true if the selection contains all changes in the commit.
1262    pub fn is_full_selection(&self) -> bool {
1263        self.selected_tree.tree_ids() == self.commit.tree_ids()
1264    }
1265
1266    /// Returns true if the selection matches the parent tree (contains no
1267    /// changes from the commit).
1268    ///
1269    /// Both `is_full_selection()` and `is_empty_selection()`
1270    /// can be true if the commit is itself empty.
1271    pub fn is_empty_selection(&self) -> bool {
1272        self.selected_tree.tree_ids() == self.parent_tree.tree_ids()
1273    }
1274
1275    /// Returns a diff of labeled trees which represents the selected changes.
1276    /// This can be used with `MergedTree::merge` and `Merge::from_diffs` to
1277    /// apply the selected changes to a tree.
1278    pub async fn diff_with_labels(
1279        &self,
1280        parent_tree_label: &str,
1281        selected_tree_label: &str,
1282        full_selection_label: &str,
1283    ) -> BackendResult<Diff<(MergedTree, String)>> {
1284        let parent_tree_label = format!(
1285            "{} ({parent_tree_label})",
1286            self.commit.parents_conflict_label().await?
1287        );
1288
1289        let commit_label = self.commit.conflict_label();
1290        let selected_tree_label = if self.is_full_selection() {
1291            format!("{commit_label} ({full_selection_label})")
1292        } else {
1293            format!("{selected_tree_label} (from {commit_label})")
1294        };
1295
1296        Ok(Diff::new(
1297            (self.parent_tree.clone(), parent_tree_label),
1298            (self.selected_tree.clone(), selected_tree_label),
1299        ))
1300    }
1301}
1302
1303/// Resulting commit builder and stats to be returned by [`squash_commits()`].
1304#[must_use]
1305pub struct SquashedCommit<'repo> {
1306    /// New destination commit will be created by this builder.
1307    pub commit_builder: CommitBuilder<'repo>,
1308    /// List of abandoned source commits.
1309    pub abandoned_commits: Vec<Commit>,
1310}
1311
1312/// Squash `sources` into `destination` and return a [`SquashedCommit`] for the
1313/// resulting commit. Caller is responsible for setting the description and
1314/// finishing the commit.
1315pub async fn squash_commits<'repo>(
1316    repo: &'repo mut MutableRepo,
1317    sources: &[CommitWithSelection],
1318    destination: &Commit,
1319    keep_emptied: bool,
1320) -> BackendResult<Option<SquashedCommit<'repo>>> {
1321    struct SourceCommit<'a> {
1322        commit: &'a CommitWithSelection,
1323        diff: Diff<(MergedTree, String)>,
1324        abandon: bool,
1325    }
1326    let mut source_commits = vec![];
1327    for source in sources {
1328        let abandon = !keep_emptied && source.is_full_selection();
1329        if !abandon && source.is_empty_selection() {
1330            // Nothing selected from this commit. If it's abandoned (i.e. already empty), we
1331            // still include it so `jj squash` can be used for abandoning an empty commit in
1332            // the middle of a stack.
1333            continue;
1334        }
1335
1336        // TODO: Do we want to optimize the case of moving to the parent commit (`jj
1337        // squash -r`)? The source tree will be unchanged in that case.
1338        source_commits.push(SourceCommit {
1339            commit: source,
1340            diff: source
1341                .diff_with_labels(
1342                    "parents of squashed revision",
1343                    "selected changes for squash",
1344                    "squashed revision",
1345                )
1346                .await?,
1347            abandon,
1348        });
1349    }
1350
1351    if source_commits.is_empty() {
1352        return Ok(None);
1353    }
1354
1355    let mut abandoned_commits = vec![];
1356    for source in &source_commits {
1357        if source.abandon {
1358            repo.record_abandoned_commit(&source.commit.commit);
1359            abandoned_commits.push(source.commit.commit.clone());
1360        } else {
1361            let source_tree = source.commit.commit.tree();
1362            // Apply the reverse of the selected changes onto the source
1363            let new_source_tree = MergedTree::merge(Merge::from_diffs(
1364                (source_tree, source.commit.commit.conflict_label()),
1365                [source.diff.clone().invert()],
1366            ))
1367            .await?;
1368            repo.rewrite_commit(&source.commit.commit)
1369                .set_tree(new_source_tree)
1370                .write()
1371                .await?;
1372        }
1373    }
1374
1375    let mut rewritten_destination = destination.clone();
1376    if fallible_any(sources, |source| {
1377        repo.index()
1378            .is_ancestor(source.commit.id(), destination.id())
1379    })
1380    // TODO: indexing error shouldn't be a "BackendError"
1381    .map_err(|err| BackendError::Other(err.into()))?
1382    {
1383        // If we're moving changes to a descendant, first rebase descendants onto the
1384        // rewritten sources. Otherwise it will likely already have the content
1385        // changes we're moving, so applying them will have no effect and the
1386        // changes will disappear.
1387        let options = RebaseOptions::default();
1388        repo.rebase_descendants_with_options(&options, |old_commit, rebased_commit| {
1389            if old_commit.id() != destination.id() {
1390                return;
1391            }
1392            rewritten_destination = match rebased_commit {
1393                RebasedCommit::Rewritten(commit) => commit,
1394                RebasedCommit::Abandoned { .. } => panic!("all commits should be kept"),
1395            };
1396        })
1397        .await?;
1398    }
1399    let mut predecessors = vec![destination.id().clone()];
1400    predecessors.extend(
1401        source_commits
1402            .iter()
1403            .map(|source| source.commit.commit.id().clone()),
1404    );
1405    // Apply the selected changes onto the destination
1406    let destination_tree = MergedTree::merge(Merge::from_diffs(
1407        (
1408            rewritten_destination.tree(),
1409            format!("{} (squash destination)", destination.conflict_label()),
1410        ),
1411        source_commits.into_iter().map(|source| source.diff),
1412    ))
1413    .await?;
1414
1415    let commit_builder = repo
1416        .rewrite_commit(&rewritten_destination)
1417        .set_tree(destination_tree)
1418        .set_predecessors(predecessors);
1419    Ok(Some(SquashedCommit {
1420        commit_builder,
1421        abandoned_commits,
1422    }))
1423}
1424
1425/// Find divergent commits from the target that are already present with
1426/// identical contents in the destination. These commits should be able to be
1427/// safely abandoned.
1428pub async fn find_duplicate_divergent_commits(
1429    repo: &dyn Repo,
1430    new_parent_ids: &[CommitId],
1431    target: &MoveCommitsTarget,
1432) -> BackendResult<Vec<Commit>> {
1433    let target_commits: Vec<Commit> = match target {
1434        MoveCommitsTarget::Commits(commit_ids) => {
1435            try_join_all(
1436                commit_ids
1437                    .iter()
1438                    .map(|commit_id| repo.store().get_commit_async(commit_id)),
1439            )
1440            .await?
1441        }
1442        MoveCommitsTarget::Roots(root_ids) => RevsetExpression::commits(root_ids.clone())
1443            .descendants()
1444            .evaluate(repo)
1445            .map_err(|err| err.into_backend_error())?
1446            .stream()
1447            .commits(repo.store())
1448            .try_collect()
1449            .await
1450            .map_err(|err| err.into_backend_error())?,
1451    };
1452    let target_commit_ids: HashSet<&CommitId> = target_commits.iter().map(Commit::id).collect();
1453
1454    // For each divergent change being rebased, we want to find all of the other
1455    // commits with the same change ID which are not being rebased.
1456    let divergent_changes: Vec<(&Commit, Vec<CommitId>)> = target_commits
1457        .iter()
1458        .map(|target_commit| -> Result<_, BackendError> {
1459            let mut ancestor_candidates = repo
1460                .resolve_change_id(target_commit.change_id())
1461                // TODO: indexing error shouldn't be a "BackendError"
1462                .map_err(|err| BackendError::Other(err.into()))?
1463                .and_then(ResolvedChangeTargets::into_visible)
1464                .unwrap_or_default();
1465            ancestor_candidates.retain(|commit_id| !target_commit_ids.contains(commit_id));
1466            Ok((target_commit, ancestor_candidates))
1467        })
1468        .filter_ok(|(_, candidates)| !candidates.is_empty())
1469        .try_collect()?;
1470    if divergent_changes.is_empty() {
1471        return Ok(Vec::new());
1472    }
1473
1474    let target_root_ids = match target {
1475        MoveCommitsTarget::Commits(commit_ids) => commit_ids,
1476        MoveCommitsTarget::Roots(root_ids) => root_ids,
1477    };
1478
1479    // We only care about divergent changes which are new ancestors of the rebased
1480    // commits, not ones which were already ancestors of the rebased commits.
1481    let is_new_ancestor = RevsetExpression::commits(target_root_ids.clone())
1482        .range(&RevsetExpression::commits(new_parent_ids.to_owned()))
1483        .evaluate(repo)
1484        .map_err(|err| err.into_backend_error())?
1485        .containing_fn();
1486
1487    let mut duplicate_divergent = Vec::new();
1488    // Checking every pair of commits between these two sets could be expensive if
1489    // there are several commits with the same change ID. However, it should be
1490    // uncommon to have more than a couple commits with the same change ID being
1491    // rebased at the same time, so it should be good enough in practice.
1492    for (target_commit, ancestor_candidates) in divergent_changes {
1493        for ancestor_candidate_id in ancestor_candidates {
1494            if !is_new_ancestor(&ancestor_candidate_id).map_err(|err| err.into_backend_error())? {
1495                continue;
1496            }
1497
1498            let ancestor_candidate = repo
1499                .store()
1500                .get_commit_async(&ancestor_candidate_id)
1501                .await?;
1502            let new_tree =
1503                rebase_to_dest_parent(repo, slice::from_ref(target_commit), &ancestor_candidate)
1504                    .await?;
1505            // Check whether the rebased commit would have the same tree as the existing
1506            // commit if they had the same parents. If so, we can skip this rebased commit.
1507            if new_tree.tree_ids() == ancestor_candidate.tree_ids() {
1508                duplicate_divergent.push(target_commit.clone());
1509                break;
1510            }
1511        }
1512    }
1513    Ok(duplicate_divergent)
1514}