1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
27
28use crate::change_id::change_id;
29use crate::diff::{diff_trees, unified_diff, IndentHeuristic, UnifiedDiffOptions};
30use crate::error::Result;
31use crate::merge_base::{
32 is_ancestor, merge_bases_first_vs_rest, walk_commits_reachable_excluding_ancestors_of,
33 ReachableWalkLimit,
34};
35use crate::merge_file::MergeFavor;
36use crate::merge_trees::{
37 merge_trees_three_way, DirectoryRenameMode, TreeMergeConflictPresentation,
38 WhitespaceMergeOptions,
39};
40use crate::objects::ObjectId;
41use crate::patch_ids::{compute_patch_id, PatchIdMode};
42use crate::refs::store::RefName;
43use crate::repo::Repository;
44use crate::repo_relpath::StoredRelPath;
45use crate::revwalk::RevWalk;
46
47const MAX_COMMITS: usize = 500;
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
53pub enum Scenario {
54 Same,
57 Ahead,
59 Behind,
61 SameContent,
64 SameRewrite,
66
67 AddedBoth,
70 RewroteOne,
73 AmendedBothCompatible,
75 AmendedOneReorderedOther,
77 AmendedDifferent,
79 RebasedOne,
81 RebasedBoth,
83 DroppedOne,
85 DroppedBoth,
87 SquashedOneAddedOther,
89 SplitOne,
91 SquashedOneAmendedOther,
93 SplitOneAmendedOther,
95
96 AmendedBothConflicting,
99 AddedBothConflict,
101 DroppedOneAmendedOther,
103 ReorderedBoth,
105 SplitBoth,
107 SplitOneAmendedOtherSpanning,
109 SquashedBothDifferently,
111 ResetOne,
113 MergeCommit,
115 NoChangeIds,
117}
118
119impl Scenario {
120 #[must_use]
122 pub fn code(self) -> &'static str {
123 match self {
124 Self::Same => "same",
125 Self::Ahead => "ahead",
126 Self::Behind => "behind",
127 Self::SameContent => "same_content",
128 Self::SameRewrite => "same_rewrite",
129 Self::AddedBoth => "added_both",
130 Self::RewroteOne => "rewrote_one",
131 Self::AmendedBothCompatible => "amended_both_compatible",
132 Self::AmendedOneReorderedOther => "amended_one_reordered_other",
133 Self::AmendedDifferent => "amended_different",
134 Self::RebasedOne => "rebased_one",
135 Self::RebasedBoth => "rebased_both",
136 Self::DroppedOne => "dropped_one",
137 Self::DroppedBoth => "dropped_both",
138 Self::SquashedOneAddedOther => "squashed_one_added_other",
139 Self::SplitOne => "split_one",
140 Self::SquashedOneAmendedOther => "squashed_one_amended_other",
141 Self::SplitOneAmendedOther => "split_one_amended_other",
142 Self::AmendedBothConflicting => "amended_both_conflicting",
143 Self::AddedBothConflict => "added_both_conflict",
144 Self::DroppedOneAmendedOther => "dropped_one_amended_other",
145 Self::ReorderedBoth => "reordered_both",
146 Self::SplitBoth => "split_both",
147 Self::SplitOneAmendedOtherSpanning => "split_one_amended_other_spanning",
148 Self::SquashedBothDifferently => "squashed_both_differently",
149 Self::ResetOne => "reset_one",
150 Self::MergeCommit => "merge_commit",
151 Self::NoChangeIds => "no_change_ids",
152 }
153 }
154
155 fn priority(self) -> usize {
157 const ORDER: [Scenario; 28] = [
158 Scenario::MergeCommit,
159 Scenario::ResetOne,
160 Scenario::AmendedBothConflicting,
161 Scenario::DroppedOneAmendedOther,
162 Scenario::SplitBoth,
163 Scenario::SplitOneAmendedOtherSpanning,
164 Scenario::SquashedBothDifferently,
165 Scenario::ReorderedBoth,
166 Scenario::AddedBothConflict,
167 Scenario::NoChangeIds,
168 Scenario::AmendedBothCompatible,
169 Scenario::AmendedOneReorderedOther,
170 Scenario::SplitOneAmendedOther,
171 Scenario::SquashedOneAmendedOther,
172 Scenario::AmendedDifferent,
173 Scenario::RebasedBoth,
174 Scenario::RebasedOne,
175 Scenario::DroppedBoth,
176 Scenario::DroppedOne,
177 Scenario::SplitOne,
178 Scenario::SquashedOneAddedOther,
179 Scenario::RewroteOne,
180 Scenario::AddedBoth,
181 Scenario::SameRewrite,
182 Scenario::SameContent,
183 Scenario::Ahead,
184 Scenario::Behind,
185 Scenario::Same,
186 ];
187 ORDER.iter().position(|s| *s == self).unwrap_or(ORDER.len())
188 }
189
190 #[must_use]
192 pub fn all() -> Vec<Self> {
193 let mut all = vec![
194 Self::Same,
195 Self::Ahead,
196 Self::Behind,
197 Self::SameContent,
198 Self::SameRewrite,
199 Self::AddedBoth,
200 Self::RewroteOne,
201 Self::AmendedBothCompatible,
202 Self::AmendedOneReorderedOther,
203 Self::AmendedDifferent,
204 Self::RebasedOne,
205 Self::RebasedBoth,
206 Self::DroppedOne,
207 Self::DroppedBoth,
208 Self::SquashedOneAddedOther,
209 Self::SplitOne,
210 Self::SquashedOneAmendedOther,
211 Self::SplitOneAmendedOther,
212 Self::AmendedBothConflicting,
213 Self::AddedBothConflict,
214 Self::DroppedOneAmendedOther,
215 Self::ReorderedBoth,
216 Self::SplitBoth,
217 Self::SplitOneAmendedOtherSpanning,
218 Self::SquashedBothDifferently,
219 Self::ResetOne,
220 Self::MergeCommit,
221 Self::NoChangeIds,
222 ];
223 all.sort_by_key(|s| s.priority());
224 all
225 }
226
227 #[must_use]
229 pub fn diverged(self) -> bool {
230 !matches!(
231 self,
232 Self::Same | Self::Ahead | Self::Behind | Self::SameContent | Self::SameRewrite
233 )
234 }
235
236 #[must_use]
238 pub fn needs_decision(self) -> bool {
239 matches!(
240 self,
241 Self::AmendedBothConflicting
242 | Self::AddedBothConflict
243 | Self::DroppedOneAmendedOther
244 | Self::ReorderedBoth
245 | Self::SplitBoth
246 | Self::SplitOneAmendedOtherSpanning
247 | Self::SquashedBothDifferently
248 | Self::ResetOne
249 | Self::MergeCommit
250 | Self::NoChangeIds
251 )
252 }
253}
254
255#[derive(Debug, Clone, PartialEq, Eq)]
257pub enum Did {
258 Unchanged,
260 Moved,
262 Reworded,
264 Amended,
266 Dropped,
268 SquashedInto(String),
270 Split(Vec<String>),
273 New,
275 SplitFrom(String),
277 Absent,
279}
280
281impl Did {
282 #[must_use]
284 pub fn word(&self) -> &'static str {
285 match self {
286 Self::Unchanged => "unchanged",
287 Self::Moved => "moved",
288 Self::Reworded => "reworded",
289 Self::Amended => "amended",
290 Self::Dropped => "dropped",
291 Self::SquashedInto(_) => "squashed",
292 Self::Split(_) => "split",
293 Self::New => "new",
294 Self::SplitFrom(_) => "split_piece",
295 Self::Absent => "absent",
296 }
297 }
298
299 fn changed(&self) -> bool {
300 !matches!(self, Self::Unchanged | Self::Absent)
301 }
302
303 fn rewrote(&self) -> bool {
304 matches!(
305 self,
306 Self::Moved
307 | Self::Reworded
308 | Self::Amended
309 | Self::Dropped
310 | Self::SquashedInto(_)
311 | Self::Split(_)
312 )
313 }
314}
315
316#[derive(Debug, Clone, PartialEq, Eq)]
318pub struct Change {
319 pub key: String,
321 pub subject: String,
323 pub ours: Did,
325 pub theirs: Did,
327 pub ours_commit: Option<ObjectId>,
329 pub theirs_commit: Option<ObjectId>,
331 pub paths: Vec<String>,
333}
334
335#[derive(Debug, Clone, PartialEq, Eq)]
337pub struct Divergence {
338 pub scenario: Scenario,
341 pub scenarios: Vec<Scenario>,
343 pub base: Option<ObjectId>,
345 pub changes: Vec<Change>,
347 pub conflicts: Vec<StoredRelPath>,
349 pub matched_without_ids: bool,
351}
352
353impl Divergence {
354 fn simple(scenario: Scenario, base: Option<ObjectId>) -> Self {
355 Self {
356 scenario,
357 scenarios: vec![scenario],
358 base,
359 changes: Vec::new(),
360 conflicts: Vec::new(),
361 matched_without_ids: false,
362 }
363 }
364
365 #[must_use]
367 pub fn summary(&self, them: &str) -> String {
368 let subject = |pred: &dyn Fn(&Change) -> bool| {
369 self.changes
370 .iter()
371 .find(|c| pred(c))
372 .map(|c| format!("\"{}\"", c.subject))
373 .unwrap_or_else(|| "a commit".to_owned())
374 };
375 let both = |a: &Did, b: &Did| a == b;
376 match self.scenario {
377 Scenario::Same => format!("Your head and {them}'s are the same."),
378 Scenario::Ahead => format!("Your head builds on {them}'s."),
379 Scenario::Behind => format!("{them}'s head builds on yours."),
380 Scenario::SameContent => {
381 format!("Your head and {them}'s have the same changes, as different commits.")
382 }
383 Scenario::SameRewrite => format!("You and {them} made the same rewrite."),
384 Scenario::AddedBoth => format!(
385 "You and {them} both added commits on top of the same base; they don't conflict."
386 ),
387 Scenario::AddedBothConflict => format!(
388 "You and {them} both added commits, and they conflict in {}.",
389 self.conflict_paths()
390 ),
391 Scenario::RewroteOne if self.scenarios.contains(&Scenario::SameRewrite) => format!(
392 "You and {them} made the same rewrite, and one of you added commits on top."
393 ),
394 Scenario::RewroteOne => format!(
395 "One of you rewrote commits ({}); the other only added on top.",
396 self.rewrite_words()
397 ),
398 Scenario::AmendedBothCompatible => format!(
399 "You and {them} both amended {}; the edits don't overlap.",
400 subject(&|c| c.ours == Did::Amended && c.theirs == Did::Amended)
401 ),
402 Scenario::AmendedBothConflicting => format!(
403 "You and {them} both amended {}, and the edits overlap in {}.",
404 subject(&|c| matches!(c.ours, Did::Amended | Did::Reworded)
405 && matches!(c.theirs, Did::Amended | Did::Reworded)),
406 self.conflict_paths()
407 ),
408 Scenario::AmendedOneReorderedOther => format!(
409 "One of you reordered commits, and the other amended {}.",
410 subject(&|c| c.ours == Did::Amended || c.theirs == Did::Amended)
411 ),
412 Scenario::AmendedDifferent => {
413 format!("You and {them} amended different commits.")
414 }
415 Scenario::RebasedOne => {
416 "One of you rebased the branch onto a newer target; the other only changed commits on it."
417 .to_owned()
418 }
419 Scenario::RebasedBoth => {
420 format!("You and {them} both rebased the branch, onto different target commits.")
421 }
422 Scenario::DroppedOne => format!(
423 "One of you dropped {}; the other didn't touch it.",
424 subject(&|c| c.ours == Did::Dropped || c.theirs == Did::Dropped)
425 ),
426 Scenario::DroppedBoth => format!(
427 "You and {them} both dropped {}.",
428 subject(&|c| both(&c.ours, &Did::Dropped) && both(&c.theirs, &Did::Dropped))
429 ),
430 Scenario::DroppedOneAmendedOther => {
431 let mine = self
432 .changes
433 .iter()
434 .find(|c| c.ours == Did::Dropped && matches!(c.theirs, Did::Amended | Did::Reworded));
435 match mine {
436 Some(c) => format!(
437 "You dropped \"{}\", and {them} amended it.",
438 c.subject
439 ),
440 None => format!(
441 "{them} dropped {}, and you amended it.",
442 subject(&|c| c.theirs == Did::Dropped)
443 ),
444 }
445 }
446 Scenario::ReorderedBoth => {
447 format!("You and {them} both reordered the commits, into different orders.")
448 }
449 Scenario::SplitOne => format!(
450 "One of you split {}; the other didn't touch it.",
451 subject(&|c| matches!(c.ours, Did::Split(_)) || matches!(c.theirs, Did::Split(_)))
452 ),
453 Scenario::SplitBoth => format!(
454 "You and {them} both split {}, differently.",
455 subject(&|c| matches!(c.ours, Did::Split(_)) && matches!(c.theirs, Did::Split(_)))
456 ),
457 Scenario::SplitOneAmendedOther => format!(
458 "One of you split {}, and the other amended it; the amendment fits one piece.",
459 subject(&|c| matches!(c.ours, Did::Split(_)) || matches!(c.theirs, Did::Split(_)))
460 ),
461 Scenario::SplitOneAmendedOtherSpanning => format!(
462 "One of you split {}, and the other's amendment of it spans the pieces.",
463 subject(&|c| matches!(c.ours, Did::Split(_)) || matches!(c.theirs, Did::Split(_)))
464 ),
465 Scenario::SquashedOneAddedOther => {
466 "One of you squashed commits; the other only added on top.".to_owned()
467 }
468 Scenario::SquashedOneAmendedOther => format!(
469 "One of you squashed {} into another commit, and the other amended it.",
470 subject(&|c| matches!(c.ours, Did::SquashedInto(_))
471 || matches!(c.theirs, Did::SquashedInto(_)))
472 ),
473 Scenario::SquashedBothDifferently => {
474 format!("You and {them} both squashed commits, differently.")
475 }
476 Scenario::ResetOne => {
477 "One head drops most of the branch's commits: perhaps an accidental reset."
478 .to_owned()
479 }
480 Scenario::MergeCommit => {
481 "One head has a merge commit, so the two can't be compared commit by commit."
482 .to_owned()
483 }
484 Scenario::NoChangeIds => format!(
485 "Some commits have no change ids (made or rebased with plain git), so your head and {them}'s were matched by patch, which can't follow an amend."
486 ),
487 }
488 }
489
490 fn conflict_paths(&self) -> String {
491 match self.conflicts.as_slice() {
492 [] => "the same files".to_owned(),
493 [one] => one.as_str().to_owned(),
494 [first, rest @ ..] => format!("{} and {} more", first.as_str(), rest.len()),
495 }
496 }
497
498 fn rewrite_words(&self) -> String {
499 let mut words = BTreeSet::new();
500 for c in &self.changes {
501 for did in [&c.ours, &c.theirs] {
502 if did.rewrote() {
503 words.insert(did.word());
504 }
505 }
506 }
507 words.into_iter().collect::<Vec<_>>().join(", ")
508 }
509}
510
511#[derive(Debug, Clone)]
513struct Version {
514 oid: ObjectId,
515 key: String,
516 by_patch: bool,
517 subject: String,
518 message: String,
519 patch: Option<ObjectId>,
520 tree: ObjectId,
521 parent: Option<ObjectId>,
522 merge: bool,
523 time: i64,
525 lines: Option<HashSet<(String, char, String)>>,
527 paths: Vec<String>,
528}
529
530fn sequence(repo: &Repository, head: ObjectId, floor: &[ObjectId]) -> Result<Vec<Version>> {
533 let (_, reachable) = walk_commits_reachable_excluding_ancestors_of(
534 repo,
535 &[head],
536 floor,
537 ReachableWalkLimit::StopAfter(MAX_COMMITS * 4),
538 )?;
539 let reachable: HashSet<ObjectId> = reachable.into_iter().collect();
540 let mut out = Vec::new();
541 let mut at = Some(head);
542 while let Some(oid) = at {
543 if !reachable.contains(&oid) || out.len() >= MAX_COMMITS {
544 break;
545 }
546 let data = repo.odb().read_commit(&oid)?;
547 let (key, by_patch, patch) = match change_id(&data) {
548 Some(id) => (id.as_str().to_owned(), false, None),
549 None => {
550 let patch = compute_patch_id(
551 repo.odb().hash_algo(),
552 repo.odb(),
553 &oid,
554 PatchIdMode::Stable,
555 )?;
556 let key = match patch {
557 Some(p) => format!("patch:{}", p.to_hex()),
558 None => format!("commit:{}", oid.to_hex()),
559 };
560 (key, true, patch)
561 }
562 };
563 out.push(Version {
564 oid,
565 key,
566 by_patch,
567 subject: data.message.lines().next().unwrap_or_default().to_owned(),
568 message: data.message.clone(),
569 patch,
570 tree: data.tree,
571 parent: data.parents.first().copied(),
572 merge: data.parents.len() > 1,
573 time: crate::ident::committer_timestamp_for_until_filter(&data.committer),
574 lines: None,
575 paths: Vec::new(),
576 });
577 at = data.parents.first().copied();
578 }
579 out.reverse();
580 Ok(out)
581}
582
583fn load_changes(repo: &Repository, v: &mut Version) -> Result<()> {
585 if v.lines.is_some() {
586 return Ok(());
587 }
588 if v.patch.is_none() {
589 v.patch = compute_patch_id(
590 repo.odb().hash_algo(),
591 repo.odb(),
592 &v.oid,
593 PatchIdMode::Stable,
594 )?;
595 }
596 let odb = repo.odb();
597 let parent_tree = match v.parent {
598 Some(p) => Some(odb.commit_tree(&p)?),
599 None => None,
600 };
601 let mut lines = HashSet::new();
602 let mut paths = BTreeSet::new();
603 for entry in diff_trees(odb, parent_tree.as_ref(), Some(&v.tree), "")? {
604 let path = entry
605 .new_path
606 .clone()
607 .or_else(|| entry.old_path.clone())
608 .unwrap_or_default();
609 paths.insert(path.clone());
610 let text = |oid: &ObjectId| -> String {
611 if oid.is_zero() {
612 return String::new();
613 }
614 odb.read(oid)
615 .ok()
616 .filter(|o| o.data.len() <= 1 << 20 && !o.data.contains(&0))
617 .map(|o| String::from_utf8_lossy(&o.data).into_owned())
618 .unwrap_or_default()
619 };
620 let patch = unified_diff(
621 &text(&entry.old_oid),
622 &text(&entry.new_oid),
623 &UnifiedDiffOptions::new()
624 .with_context_lines(0)
625 .with_indent_heuristic(IndentHeuristic::Disabled),
626 );
627 for line in patch.lines() {
628 if let Some(rest) = line.strip_prefix('+') {
629 lines.insert((path.clone(), '+', rest.to_owned()));
630 } else if let Some(rest) = line.strip_prefix('-') {
631 lines.insert((path.clone(), '-', rest.to_owned()));
632 }
633 }
634 lines.insert((path.clone(), '=', entry.new_oid.to_hex()));
636 }
637 v.lines = Some(lines);
638 v.paths = paths.into_iter().collect();
639 Ok(())
640}
641
642fn lines_of(v: &Version) -> HashSet<(String, char, String)> {
643 v.lines
644 .clone()
645 .unwrap_or_default()
646 .into_iter()
647 .filter(|(_, sign, _)| *sign != '=')
648 .collect()
649}
650
651fn within(inner: &Version, outer: &Version) -> bool {
653 let a = lines_of(inner);
654 !a.is_empty() && a.is_subset(&lines_of(outer))
655}
656
657fn extend_base(base: &mut Vec<Version>, ours: &[Version], theirs: &[Version]) {
662 let known: HashSet<String> = base.iter().map(|v| v.key.clone()).collect();
663 for o in ours {
664 if known.contains(&o.key) || o.by_patch {
665 continue;
666 }
667 if let Some(t) = theirs.iter().find(|t| t.key == o.key) {
668 base.push(if t.time < o.time {
669 t.clone()
670 } else {
671 o.clone()
672 });
673 }
674 }
675}
676
677fn holds_all(repo: &Repository, big: &mut [Version], small: &mut [Version]) -> Result<bool> {
680 if small.is_empty() {
681 return Ok(false);
682 }
683 for v in big.iter_mut().chain(small.iter_mut()) {
684 load_changes(repo, v)?;
685 }
686 Ok(small.iter().all(|s| {
687 big.iter()
688 .any(|b| b.key == s.key && b.patch == s.patch && b.message == s.message)
689 }))
690}
691
692fn rebase_on_held(
697 repo: &Repository,
698 base: Option<ObjectId>,
699 base_seq: &mut Vec<Version>,
700 ours: ObjectId,
701 ours_seq: &mut [Version],
702 theirs: ObjectId,
703 theirs_seq: &mut [Version],
704) -> Result<Option<ObjectId>> {
705 let added = |seq: &[Version], base_seq: &[Version]| {
706 seq.iter().any(|v| !base_seq.iter().any(|b| b.key == v.key))
707 };
708 if added(ours_seq, base_seq) && holds_all(repo, theirs_seq, ours_seq)? {
709 *base_seq = ours_seq.to_vec();
710 return Ok(Some(ours));
711 }
712 if added(theirs_seq, base_seq) && holds_all(repo, ours_seq, theirs_seq)? {
713 *base_seq = theirs_seq.to_vec();
714 return Ok(Some(theirs));
715 }
716 Ok(base)
717}
718
719fn resets(base: &[Version], seq: &[Version]) -> bool {
722 let kept: HashSet<&str> = seq.iter().map(|v| v.key.as_str()).collect();
723 let gone = base
724 .iter()
725 .filter(|b| !kept.contains(b.key.as_str()))
726 .count();
727 gone >= 2 && gone * 2 > base.len()
728}
729
730struct Side {
732 did: BTreeMap<String, Did>,
733 new: Vec<String>,
734 rebased: bool,
735}
736
737fn compare_side(repo: &Repository, base: &mut [Version], side: &mut [Version]) -> Result<Side> {
738 let base_parent = base.first().and_then(|v| v.parent);
739 let side_parent = side.first().and_then(|v| v.parent);
740 let rebased = !base.is_empty() && !side.is_empty() && base_parent != side_parent;
741 let side_index: HashMap<String, usize> = side
742 .iter()
743 .enumerate()
744 .map(|(i, v)| (v.key.clone(), i))
745 .collect();
746 let base_keys: HashSet<String> = base.iter().map(|v| v.key.clone()).collect();
747 for v in base.iter_mut().chain(side.iter_mut()) {
748 load_changes(repo, v)?;
749 }
750 let mut did = BTreeMap::new();
751 let common: Vec<(usize, usize)> = base
754 .iter()
755 .enumerate()
756 .filter_map(|(bi, v)| side_index.get(&v.key).map(|si| (bi, *si)))
757 .collect();
758 let kept = longest_increasing(&common.iter().map(|(_, si)| *si).collect::<Vec<_>>());
759 let moved: HashSet<usize> = common
760 .iter()
761 .enumerate()
762 .filter(|(i, _)| !kept.contains(i))
763 .map(|(_, (bi, _))| *bi)
764 .collect();
765 let new_keys: Vec<String> = side
766 .iter()
767 .filter(|v| !base_keys.contains(&v.key))
768 .map(|v| v.key.clone())
769 .collect();
770 let mut pieces_taken: HashSet<String> = HashSet::new();
771 for (bi, b) in base.iter().enumerate() {
772 let entry = match side_index.get(&b.key) {
773 Some(si) => {
774 let s = &side[*si];
775 let same_patch = b.patch == s.patch;
776 let same_message = b.message == s.message;
777 let pieces: Vec<String> = side
780 .iter()
781 .filter(|n| !base_keys.contains(&n.key) && within(n, b))
782 .map(|n| n.key.clone())
783 .collect();
784 if !same_patch && !pieces.is_empty() && within(s, b) {
785 let mut all = vec![b.key.clone()];
786 all.extend(pieces.iter().cloned());
787 pieces_taken.extend(pieces);
788 Did::Split(all)
789 } else if !same_patch {
790 Did::Amended
791 } else if !same_message {
792 Did::Reworded
793 } else if moved.contains(&bi) {
794 Did::Moved
795 } else {
796 Did::Unchanged
797 }
798 }
799 None => {
800 let pieces: Vec<String> = side
801 .iter()
802 .filter(|n| !base_keys.contains(&n.key) && within(n, b))
803 .map(|n| n.key.clone())
804 .collect();
805 let into = side
806 .iter()
807 .filter(|n| base_keys.contains(&n.key) && n.key != b.key)
808 .find(|n| within(b, n))
809 .map(|n| n.key.clone());
810 if pieces.len() >= 2 {
811 pieces_taken.extend(pieces.iter().cloned());
812 Did::Split(pieces)
813 } else if let Some(into) = into {
814 Did::SquashedInto(into)
815 } else {
816 Did::Dropped
817 }
818 }
819 };
820 did.insert(b.key.clone(), entry);
821 }
822 let mut new = Vec::new();
823 for key in new_keys {
824 if pieces_taken.contains(&key) {
825 let from = did
826 .iter()
827 .find(|(_, d)| matches!(d, Did::Split(p) if p.contains(&key)))
828 .map(|(k, _)| k.clone())
829 .unwrap_or_default();
830 did.insert(key.clone(), Did::SplitFrom(from));
831 } else {
832 new.push(key);
833 }
834 }
835 Ok(Side { did, new, rebased })
836}
837
838fn longest_increasing(seq: &[usize]) -> HashSet<usize> {
840 let n = seq.len();
841 let mut len = vec![1usize; n];
842 let mut prev = vec![usize::MAX; n];
843 for i in 0..n {
844 for j in 0..i {
845 if seq[j] < seq[i] && len[j] + 1 > len[i] {
846 len[i] = len[j] + 1;
847 prev[i] = j;
848 }
849 }
850 }
851 let mut out = HashSet::new();
852 let Some(mut at) = (0..n).max_by_key(|i| len[*i]) else {
853 return out;
854 };
855 loop {
856 out.insert(at);
857 if prev[at] == usize::MAX {
858 break;
859 }
860 at = prev[at];
861 }
862 out
863}
864
865fn tree_conflicts(
868 repo: &Repository,
869 base: ObjectId,
870 ours: ObjectId,
871 theirs: ObjectId,
872) -> Result<Vec<StoredRelPath>> {
873 let merged = merge_trees_three_way(
874 repo,
875 base,
876 ours,
877 theirs,
878 MergeFavor::default(),
879 WhitespaceMergeOptions::default(),
880 None,
881 TreeMergeConflictPresentation::default(),
882 DirectoryRenameMode::from_repo(repo)?,
883 )?;
884 let mut paths: Vec<StoredRelPath> = crate::operation::conflicts_from_tree_merge(&merged)
885 .into_iter()
886 .map(|c| StoredRelPath::new(c.path))
887 .collect();
888 paths.sort();
889 paths.dedup();
890 Ok(paths)
891}
892
893#[must_use]
896pub(crate) fn heads_seen(repo: &Repository, refname: &str) -> Vec<ObjectId> {
897 crate::reflog::read_reflog(repo.git_dir(), refname)
898 .map(|entries| entries.into_iter().rev().map(|e| e.new_oid).collect())
899 .unwrap_or_default()
900}
901
902pub(crate) fn common_base(
910 repo: &Repository,
911 ours: ObjectId,
912 theirs: ObjectId,
913 ours_seen: &[ObjectId],
914 theirs_seen: &[ObjectId],
915) -> Result<Option<ObjectId>> {
916 let theirs_set: HashSet<&ObjectId> = theirs_seen.iter().chain([&theirs]).collect();
917 for oid in [ours].iter().chain(ours_seen.iter()) {
918 if theirs_set.contains(oid) {
919 return Ok(Some(*oid));
920 }
921 }
922 Ok(merge_bases_first_vs_rest(repo, ours, &[theirs])?
923 .first()
924 .copied())
925}
926
927pub(crate) fn classify(
939 repo: &Repository,
940 floor: &[ObjectId],
941 base: Option<ObjectId>,
942 ours: ObjectId,
943 theirs: ObjectId,
944) -> Result<Divergence> {
945 if ours == theirs {
946 return Ok(Divergence::simple(Scenario::Same, Some(ours)));
947 }
948 if is_ancestor(repo, theirs, ours)? {
949 return Ok(Divergence::simple(Scenario::Ahead, Some(theirs)));
950 }
951 if is_ancestor(repo, ours, theirs)? {
952 return Ok(Divergence::simple(Scenario::Behind, Some(ours)));
953 }
954 let base = match base {
955 Some(b) => Some(b),
956 None => merge_bases_first_vs_rest(repo, ours, &[theirs])?
957 .first()
958 .copied(),
959 };
960 let mut base_seq = match base {
961 Some(b) => sequence(repo, b, floor)?,
962 None => Vec::new(),
963 };
964 let mut ours_seq = sequence(repo, ours, floor)?;
965 let mut theirs_seq = sequence(repo, theirs, floor)?;
966 let base = rebase_on_held(
967 repo,
968 base,
969 &mut base_seq,
970 ours,
971 &mut ours_seq,
972 theirs,
973 &mut theirs_seq,
974 )?;
975 extend_base(&mut base_seq, &ours_seq, &theirs_seq);
976
977 let mut scenarios = BTreeSet::new();
978 if ours_seq.iter().chain(&theirs_seq).any(|v| v.merge) {
979 let reset = |seq: &[Version]| resets(&base_seq, seq) && !seq.iter().any(|v| v.merge);
982 let scenario = if reset(&ours_seq) || reset(&theirs_seq) {
983 Scenario::ResetOne
984 } else {
985 Scenario::MergeCommit
986 };
987 let mut d = Divergence::simple(scenario, base);
988 if scenario == Scenario::ResetOne {
989 d.scenarios = vec![Scenario::ResetOne, Scenario::MergeCommit];
990 let has = |seq: &[Version], key: &str| seq.iter().any(|v| v.key == key);
991 for b in &base_seq {
992 let did = |seq: &[Version]| {
993 if has(seq, &b.key) {
994 Did::Unchanged
995 } else {
996 Did::Dropped
997 }
998 };
999 let (o, t) = (did(&ours_seq), did(&theirs_seq));
1000 if o.changed() || t.changed() {
1001 d.changes.push(Change {
1002 key: b.key.clone(),
1003 subject: b.subject.clone(),
1004 ours: o,
1005 theirs: t,
1006 ours_commit: None,
1007 theirs_commit: None,
1008 paths: Vec::new(),
1009 });
1010 }
1011 }
1012 for (seq, mine) in [(&ours_seq, true), (&theirs_seq, false)] {
1013 for v in seq.iter().filter(|v| !has(&base_seq, &v.key)) {
1014 if d.changes.iter().any(|c| c.key == v.key) {
1015 continue;
1016 }
1017 let other = if mine { &theirs_seq } else { &ours_seq };
1018 let there = if has(other, &v.key) {
1019 Did::New
1020 } else {
1021 Did::Absent
1022 };
1023 let (o, t) = if mine {
1024 (Did::New, there)
1025 } else {
1026 (there, Did::New)
1027 };
1028 d.changes.push(Change {
1029 key: v.key.clone(),
1030 subject: v.subject.clone(),
1031 ours: o,
1032 theirs: t,
1033 ours_commit: None,
1034 theirs_commit: None,
1035 paths: Vec::new(),
1036 });
1037 }
1038 }
1039 }
1040 return Ok(d);
1041 }
1042 let same_content = ours_seq.len() == theirs_seq.len()
1043 && ours_seq
1044 .iter()
1045 .zip(&theirs_seq)
1046 .all(|(a, b)| a.key == b.key && a.message == b.message)
1047 && {
1048 let mut same = true;
1049 for (a, b) in ours_seq.iter_mut().zip(theirs_seq.iter_mut()) {
1050 load_changes(repo, a)?;
1051 load_changes(repo, b)?;
1052 same &= a.patch == b.patch;
1053 }
1054 same
1055 };
1056 if same_content {
1057 return Ok(Divergence::simple(Scenario::SameContent, base));
1058 }
1059
1060 let ours_side = compare_side(repo, &mut base_seq, &mut ours_seq)?;
1061 let theirs_side = compare_side(repo, &mut base_seq, &mut theirs_seq)?;
1062 let find = |seq: &[Version], key: &str| seq.iter().find(|v| v.key == key).cloned();
1063
1064 let mut keys: Vec<String> = Vec::new();
1067 for v in base_seq.iter().chain(&ours_seq).chain(&theirs_seq) {
1068 if !keys.contains(&v.key) {
1069 keys.push(v.key.clone());
1070 }
1071 }
1072 let did_of = |side: &Side, seq: &[Version], key: &str| -> Did {
1073 if let Some(d) = side.did.get(key) {
1074 return d.clone();
1075 }
1076 if side.new.iter().any(|k| k == key) {
1077 return Did::New;
1078 }
1079 if seq.iter().any(|v| v.key == key) {
1080 return Did::New;
1081 }
1082 Did::Absent
1083 };
1084 let mut changes = Vec::new();
1085 let mut conflicts = Vec::new();
1086 for key in &keys {
1087 let ours_did = did_of(&ours_side, &ours_seq, key);
1088 let theirs_did = did_of(&theirs_side, &theirs_seq, key);
1089 let o = find(&ours_seq, key);
1090 let t = find(&theirs_seq, key);
1091 let b = find(&base_seq, key);
1092 let newest = o.as_ref().or(t.as_ref()).or(b.as_ref());
1093 let mut paths: BTreeSet<String> = BTreeSet::new();
1094 for v in [&o, &t, &b].into_iter().flatten() {
1095 paths.extend(v.paths.iter().cloned());
1096 }
1097 match (&ours_did, &theirs_did) {
1098 (Did::Amended | Did::Reworded, Did::Amended | Did::Reworded) => {
1099 let (Some(o), Some(t)) = (o.clone(), t.clone()) else {
1101 continue;
1102 };
1103 if o.patch == t.patch && o.message == t.message {
1104 scenarios.insert(Scenario::SameRewrite);
1105 } else if ours_did == Did::Reworded || theirs_did == Did::Reworded {
1106 if o.patch == t.patch {
1108 scenarios.insert(Scenario::AmendedBothConflicting);
1110 } else {
1111 scenarios.insert(Scenario::AmendedBothCompatible);
1112 }
1113 } else {
1114 let base_tree = match &b {
1115 Some(b) => b.tree,
1116 None => o
1117 .parent
1118 .map_or(Ok(o.tree), |p| repo.odb().commit_tree(&p))?,
1119 };
1120 let found = tree_conflicts(repo, base_tree, o.tree, t.tree)?;
1121 if found.is_empty() {
1122 scenarios.insert(Scenario::AmendedBothCompatible);
1123 } else {
1124 conflicts.extend(found);
1125 scenarios.insert(Scenario::AmendedBothConflicting);
1126 }
1127 }
1128 }
1129 (Did::Dropped, Did::Dropped) => {
1130 scenarios.insert(Scenario::DroppedBoth);
1131 }
1132 (Did::Dropped, Did::Amended | Did::Reworded)
1133 | (Did::Amended | Did::Reworded, Did::Dropped) => {
1134 scenarios.insert(Scenario::DroppedOneAmendedOther);
1135 }
1136 (Did::Split(a), Did::Split(b2)) => {
1137 scenarios.insert(if a == b2 {
1138 Scenario::SameRewrite
1139 } else {
1140 Scenario::SplitBoth
1141 });
1142 }
1143 (Did::Split(pieces), Did::Amended) | (Did::Amended, Did::Split(pieces)) => {
1144 let (amended, split_seq) = if matches!(ours_did, Did::Amended) {
1145 (o.clone(), &theirs_seq)
1146 } else {
1147 (t.clone(), &ours_seq)
1148 };
1149 let Some(amended) = amended else {
1150 continue;
1151 };
1152 let base_lines = b.as_ref().map(lines_of).unwrap_or_default();
1153 let delta: HashSet<_> = lines_of(&amended)
1154 .difference(&base_lines)
1155 .cloned()
1156 .collect();
1157 let fits = split_seq
1158 .iter()
1159 .filter(|v| pieces.contains(&v.key))
1160 .any(|piece| {
1161 let touched: HashSet<String> = piece.paths.iter().cloned().collect();
1162 delta.iter().all(|(p, _, _)| touched.contains(p))
1163 });
1164 scenarios.insert(if fits {
1165 Scenario::SplitOneAmendedOther
1166 } else {
1167 Scenario::SplitOneAmendedOtherSpanning
1168 });
1169 }
1170 (Did::SquashedInto(a), Did::SquashedInto(b2)) => {
1171 scenarios.insert(if a == b2 {
1172 Scenario::SameRewrite
1173 } else {
1174 Scenario::SquashedBothDifferently
1175 });
1176 }
1177 (Did::SquashedInto(_), Did::Amended | Did::Reworded)
1178 | (Did::Amended | Did::Reworded, Did::SquashedInto(_)) => {
1179 scenarios.insert(Scenario::SquashedOneAmendedOther);
1180 }
1181 _ => {}
1182 }
1183 let agreed = matches!(ours_did, Did::Amended | Did::Reworded)
1185 && matches!(theirs_did, Did::Amended | Did::Reworded)
1186 && matches!((&o, &t), (Some(o), Some(t)) if o.patch == t.patch && o.message == t.message);
1187 if (ours_did.changed() || theirs_did.changed()) && !agreed {
1188 changes.push(Change {
1189 key: key.clone(),
1190 subject: newest.map(|v| v.subject.clone()).unwrap_or_default(),
1191 ours: ours_did,
1192 theirs: theirs_did,
1193 ours_commit: o.map(|v| v.oid),
1194 theirs_commit: t.map(|v| v.oid),
1195 paths: paths.into_iter().collect(),
1196 });
1197 }
1198 }
1199
1200 let moved = |side: &Side| side.did.values().any(|d| *d == Did::Moved);
1201 let amended = |side: &Side| side.did.values().any(|d| *d == Did::Amended);
1202 let rewrote = |side: &Side| side.did.values().any(Did::rewrote);
1203 let dropped = |side: &Side| side.did.values().filter(|d| **d == Did::Dropped).count();
1204 if moved(&ours_side) && moved(&theirs_side) {
1205 let order = |seq: &[Version]| -> Vec<String> {
1206 seq.iter()
1207 .filter(|v| base_seq.iter().any(|b| b.key == v.key))
1208 .map(|v| v.key.clone())
1209 .collect()
1210 };
1211 if order(&ours_seq) != order(&theirs_seq) {
1212 scenarios.insert(Scenario::ReorderedBoth);
1213 }
1214 }
1215 if (moved(&ours_side) && amended(&theirs_side)) || (moved(&theirs_side) && amended(&ours_side))
1216 {
1217 scenarios.insert(Scenario::AmendedOneReorderedOther);
1218 }
1219 for side in [&ours_side, &theirs_side] {
1220 let n = dropped(side);
1221 let only_drops = side
1222 .did
1223 .values()
1224 .all(|d| matches!(d, Did::Dropped | Did::Unchanged));
1225 if n >= 2 && n * 2 > base_seq.len() && only_drops {
1227 scenarios.insert(Scenario::ResetOne);
1228 }
1229 }
1230 match (ours_side.rebased, theirs_side.rebased) {
1231 (true, true) => {
1232 let first_parent = |seq: &[Version]| seq.first().and_then(|v| v.parent);
1233 if first_parent(&ours_seq) != first_parent(&theirs_seq) {
1234 scenarios.insert(Scenario::RebasedBoth);
1235 }
1236 }
1237 (true, false) | (false, true) => {
1238 scenarios.insert(Scenario::RebasedOne);
1239 }
1240 _ => {}
1241 }
1242 let ours_rewrote = rewrote(&ours_side);
1243 let theirs_rewrote = rewrote(&theirs_side);
1244 if !ours_side.new.is_empty() && !theirs_side.new.is_empty() {
1245 let tip_tree =
1246 |seq: &[Version], fallback: ObjectId| seq.last().map_or(fallback, |v| v.tree);
1247 let base_tree = match base {
1248 Some(b) => repo.odb().commit_tree(&b)?,
1249 None => ours_seq
1250 .first()
1251 .and_then(|v| v.parent)
1252 .map_or(Ok(ours_seq[0].tree), |p| repo.odb().commit_tree(&p))?,
1253 };
1254 let found = tree_conflicts(
1255 repo,
1256 base_tree,
1257 tip_tree(&ours_seq, base_tree),
1258 tip_tree(&theirs_seq, base_tree),
1259 )?;
1260 if found.is_empty() {
1261 scenarios.insert(Scenario::AddedBoth);
1262 } else if !scenarios.contains(&Scenario::AmendedBothConflicting) {
1263 conflicts.extend(found);
1264 scenarios.insert(Scenario::AddedBothConflict);
1265 }
1266 }
1267 if ours_rewrote != theirs_rewrote {
1268 let side = if ours_rewrote {
1269 &ours_side
1270 } else {
1271 &theirs_side
1272 };
1273 let other = if ours_rewrote {
1274 &theirs_side
1275 } else {
1276 &ours_side
1277 };
1278 let only = |pred: &dyn Fn(&Did) -> bool| {
1279 side.did
1280 .values()
1281 .all(|d| pred(d) || matches!(d, Did::Unchanged | Did::SplitFrom(_)))
1282 };
1283 if only(&|d| *d == Did::Dropped) {
1284 scenarios.insert(Scenario::DroppedOne);
1285 } else if only(&|d| matches!(d, Did::Split(_))) {
1286 scenarios.insert(Scenario::SplitOne);
1287 } else if only(&|d| matches!(d, Did::SquashedInto(_))) && !other.new.is_empty() {
1288 scenarios.insert(Scenario::SquashedOneAddedOther);
1289 } else {
1290 scenarios.insert(Scenario::RewroteOne);
1291 }
1292 } else if ours_rewrote && theirs_rewrote {
1293 let amended_keys = |side: &Side| -> BTreeSet<String> {
1294 side.did
1295 .iter()
1296 .filter(|(_, d)| matches!(d, Did::Amended | Did::Reworded))
1297 .map(|(k, _)| k.clone())
1298 .collect()
1299 };
1300 let (a, b2) = (amended_keys(&ours_side), amended_keys(&theirs_side));
1301 if !a.is_empty() && !b2.is_empty() && a.is_disjoint(&b2) {
1302 scenarios.insert(Scenario::AmendedDifferent);
1303 }
1304 }
1305 let matched_without_ids = ours_seq
1306 .iter()
1307 .chain(&theirs_seq)
1308 .chain(&base_seq)
1309 .any(|v| v.by_patch);
1310 let unmatched_patch = changes.iter().any(|c| {
1311 c.key.starts_with("patch:")
1312 && matches!(
1313 (&c.ours, &c.theirs),
1314 (Did::Dropped, _)
1315 | (_, Did::Dropped)
1316 | (Did::New, Did::Absent)
1317 | (Did::Absent, Did::New)
1318 )
1319 });
1320 if matched_without_ids && unmatched_patch && (ours_rewrote || theirs_rewrote) {
1321 scenarios.insert(Scenario::NoChangeIds);
1322 }
1323 if !scenarios.is_empty()
1326 && scenarios.iter().all(|s| !s.diverged())
1327 && (!ours_side.new.is_empty() || !theirs_side.new.is_empty())
1328 {
1329 scenarios.insert(Scenario::RewroteOne);
1330 }
1331 if scenarios.is_empty() {
1332 scenarios.insert(if changes.is_empty() {
1333 Scenario::SameContent
1334 } else {
1335 Scenario::AddedBoth
1336 });
1337 }
1338 let mut ordered: Vec<Scenario> = scenarios.into_iter().collect();
1340 ordered.sort_by_key(|s| s.priority());
1341 conflicts.sort();
1342 conflicts.dedup();
1343 Ok(Divergence {
1344 scenario: ordered[0],
1345 scenarios: ordered,
1346 base,
1347 changes,
1348 conflicts,
1349 matched_without_ids,
1350 })
1351}
1352
1353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1355pub enum Choice {
1356 Combine,
1359 KeepMine,
1361 KeepTheirs,
1363 KeepBoth,
1366 KeepAmended,
1369 Drop,
1371 MyOrder,
1373 TheirOrder,
1375 MySplit,
1377 TheirSplit,
1379 Restore,
1381 Resolve,
1383}
1384
1385impl Choice {
1386 #[must_use]
1388 pub fn id(self) -> &'static str {
1389 match self {
1390 Self::Combine => "combine",
1391 Self::KeepMine => "keep_mine",
1392 Self::KeepTheirs => "keep_theirs",
1393 Self::KeepBoth => "keep_both",
1394 Self::KeepAmended => "keep_amended",
1395 Self::Drop => "drop",
1396 Self::MyOrder => "my_order",
1397 Self::TheirOrder => "their_order",
1398 Self::MySplit => "my_split",
1399 Self::TheirSplit => "their_split",
1400 Self::Restore => "restore",
1401 Self::Resolve => "resolve",
1402 }
1403 }
1404
1405 #[must_use]
1407 pub fn parse(id: &str) -> Option<Self> {
1408 [
1409 Self::Combine,
1410 Self::KeepMine,
1411 Self::KeepTheirs,
1412 Self::KeepBoth,
1413 Self::KeepAmended,
1414 Self::Drop,
1415 Self::MyOrder,
1416 Self::TheirOrder,
1417 Self::MySplit,
1418 Self::TheirSplit,
1419 Self::Restore,
1420 Self::Resolve,
1421 ]
1422 .into_iter()
1423 .find(|c| c.id() == id)
1424 }
1425}
1426
1427#[derive(Debug, Clone, PartialEq, Eq)]
1429pub struct ResolveOption {
1430 pub choice: Choice,
1432 pub label: String,
1434 pub loses: Option<String>,
1437}
1438
1439impl Divergence {
1440 #[must_use]
1442 pub fn options(&self, them: &str) -> Vec<ResolveOption> {
1443 let opt = |choice, label: &str, loses: Option<String>| ResolveOption {
1444 choice,
1445 label: label.to_owned(),
1446 loses,
1447 };
1448 let theirs_lost = Some(format!("{them}'s changes since you last agreed"));
1449 let mine_lost = Some("your changes since you last agreed".to_owned());
1450 let keep_mine = opt(Choice::KeepMine, "keep yours", theirs_lost.clone());
1451 let keep_theirs = opt(
1452 Choice::KeepTheirs,
1453 &format!("keep {them}'s"),
1454 mine_lost.clone(),
1455 );
1456 let resolve = opt(
1457 Choice::Resolve,
1458 &format!("rebase onto {them}'s head and resolve the conflicts yourself"),
1459 None,
1460 );
1461 if !self.scenario.diverged() {
1462 return Vec::new();
1463 }
1464 match self.scenario {
1465 Scenario::AmendedBothConflicting => vec![
1466 opt(
1467 Choice::KeepBoth,
1468 &format!("keep both: {them}'s version, then yours as a commit on top"),
1469 None,
1470 ),
1471 resolve,
1472 keep_mine,
1473 keep_theirs,
1474 ],
1475 Scenario::AddedBothConflict
1476 | Scenario::SplitOneAmendedOtherSpanning
1477 | Scenario::NoChangeIds
1478 | Scenario::MergeCommit => vec![resolve, keep_mine, keep_theirs],
1479 Scenario::DroppedOneAmendedOther => vec![
1480 opt(Choice::KeepAmended, "keep the amended commit", None),
1481 opt(
1482 Choice::Drop,
1483 "drop it",
1484 Some("the amendment to the dropped commit".to_owned()),
1485 ),
1486 keep_mine,
1487 keep_theirs,
1488 ],
1489 Scenario::ReorderedBoth => vec![
1490 opt(Choice::MyOrder, "your order", None),
1491 opt(Choice::TheirOrder, &format!("{them}'s order"), None),
1492 keep_mine,
1493 keep_theirs,
1494 ],
1495 Scenario::SplitBoth => vec![
1496 opt(Choice::MySplit, "your split", None),
1497 opt(Choice::TheirSplit, &format!("{them}'s split"), None),
1498 keep_mine,
1499 keep_theirs,
1500 ],
1501 Scenario::SquashedBothDifferently => vec![keep_mine, keep_theirs],
1502 Scenario::ResetOne => vec![
1503 opt(Choice::Restore, "bring the dropped commits back", None),
1504 keep_mine,
1505 keep_theirs,
1506 ],
1507 _ => vec![
1508 opt(Choice::Combine, "combine both", None),
1509 keep_mine,
1510 keep_theirs,
1511 ],
1512 }
1513 }
1514}
1515
1516#[derive(Debug, Clone, PartialEq, Eq)]
1518pub struct Combined {
1519 pub head: Option<ObjectId>,
1521 pub conflicts: Vec<StoredRelPath>,
1523 pub stopped_at: Option<String>,
1525}
1526
1527struct Step {
1530 version: Version,
1531 fold: Option<(Version, Version)>,
1533 message: Option<String>,
1535 new_change: bool,
1537 against: Option<Version>,
1539}
1540
1541pub(crate) fn combine(
1550 repo: &Repository,
1551 floor: &[ObjectId],
1552 base: Option<ObjectId>,
1553 ours: ObjectId,
1554 theirs: ObjectId,
1555 choice: Choice,
1556) -> Result<Combined> {
1557 let done = |head| Combined {
1558 head: Some(head),
1559 conflicts: Vec::new(),
1560 stopped_at: None,
1561 };
1562 match choice {
1563 Choice::KeepMine => return Ok(done(ours)),
1564 Choice::KeepTheirs => return Ok(done(theirs)),
1565 Choice::Resolve => {
1566 return Ok(Combined {
1567 head: None,
1568 conflicts: Vec::new(),
1569 stopped_at: None,
1570 })
1571 }
1572 _ => {}
1573 }
1574 if is_ancestor(repo, theirs, ours)? {
1575 return Ok(done(ours));
1576 }
1577 if is_ancestor(repo, ours, theirs)? {
1578 return Ok(done(theirs));
1579 }
1580 let base = match base {
1581 Some(b) => Some(b),
1582 None => merge_bases_first_vs_rest(repo, ours, &[theirs])?
1583 .first()
1584 .copied(),
1585 };
1586 let mut base_seq = match base {
1587 Some(b) => sequence(repo, b, floor)?,
1588 None => Vec::new(),
1589 };
1590 let mut ours_seq = sequence(repo, ours, floor)?;
1591 let mut theirs_seq = sequence(repo, theirs, floor)?;
1592 rebase_on_held(
1593 repo,
1594 base,
1595 &mut base_seq,
1596 ours,
1597 &mut ours_seq,
1598 theirs,
1599 &mut theirs_seq,
1600 )?;
1601 extend_base(&mut base_seq, &ours_seq, &theirs_seq);
1602 let ours_side = compare_side(repo, &mut base_seq, &mut ours_seq)?;
1603 let theirs_side = compare_side(repo, &mut base_seq, &mut theirs_seq)?;
1604
1605 let moved = |side: &Side| side.did.values().any(|d| *d == Did::Moved);
1608 let ours_lead = match choice {
1609 Choice::MyOrder => true,
1610 Choice::TheirOrder => false,
1611 _ => moved(&ours_side) && !moved(&theirs_side),
1612 };
1613 let (lead_seq, lead, follow_seq, follow) = if ours_lead {
1614 (&ours_seq, &ours_side, &theirs_seq, &theirs_side)
1615 } else {
1616 (&theirs_seq, &theirs_side, &ours_seq, &ours_side)
1617 };
1618 let lead_split = match choice {
1620 Choice::MySplit => ours_lead,
1621 Choice::TheirSplit => !ours_lead,
1622 _ => true,
1623 };
1624 let find = |seq: &[Version], key: &str| seq.iter().find(|v| v.key == key).cloned();
1625 let base_has = |key: &str| base_seq.iter().any(|v| v.key == key);
1626
1627 if matches!(choice, Choice::KeepBoth | Choice::Restore) {
1633 let drops = |side: &Side| side.did.values().filter(|d| **d == Did::Dropped).count();
1634 let ours_keeps = choice == Choice::Restore && drops(&ours_side) < drops(&theirs_side);
1635 let (keep, keep_seq, add_seq, add_side) = if ours_keeps {
1636 (ours, &ours_seq, &theirs_seq, &theirs_side)
1637 } else {
1638 (theirs, &theirs_seq, &ours_seq, &ours_side)
1639 };
1640 let mut tip = keep;
1641 for v in add_seq {
1642 let kept = keep_seq.iter().find(|k| k.key == v.key);
1643 let step = if !base_has(&v.key) {
1644 if kept.is_some() {
1645 continue;
1646 }
1647 Step {
1648 version: v.clone(),
1649 fold: None,
1650 message: None,
1651 new_change: false,
1652 against: None,
1653 }
1654 } else if matches!(add_side.did.get(&v.key), Some(Did::Amended)) {
1655 let Some(against) = kept.cloned().or_else(|| find(&base_seq, &v.key)) else {
1656 continue;
1657 };
1658 Step {
1659 version: v.clone(),
1660 fold: None,
1661 message: None,
1662 new_change: true,
1663 against: Some(against),
1664 }
1665 } else {
1666 continue;
1667 };
1668 match replay(repo, tip, &step)? {
1669 Ok(Some(next)) => tip = next,
1670 Ok(None) => {}
1671 Err(conflicts) => {
1672 return Ok(Combined {
1673 head: None,
1674 conflicts,
1675 stopped_at: Some(step.version.subject.clone()),
1676 })
1677 }
1678 }
1679 }
1680 return Ok(done(tip));
1681 }
1682 let dropped = |side: &Side, other: &Side, key: &str| -> bool {
1684 let gone = matches!(side.did.get(key), Some(Did::Dropped));
1685 let other_amended = matches!(other.did.get(key), Some(Did::Amended | Did::Reworded));
1686 match choice {
1687 Choice::Restore => false,
1688 Choice::KeepAmended => gone && !other_amended,
1689 _ => gone,
1690 }
1691 };
1692
1693 let mut steps: Vec<Step> = Vec::new();
1694 let mut placed: HashSet<String> = HashSet::new();
1695 for v in lead_seq {
1696 if placed.contains(&v.key) {
1697 continue;
1698 }
1699 let key = v.key.clone();
1700 if !base_has(&key) {
1701 if let Some(Did::SplitFrom(from)) = lead.did.get(&key) {
1703 if !lead_split && matches!(follow.did.get(from), Some(Did::Split(_))) {
1704 continue;
1705 }
1706 }
1707 placed.insert(key);
1708 steps.push(Step {
1709 version: v.clone(),
1710 fold: None,
1711 message: None,
1712 new_change: false,
1713 against: None,
1714 });
1715 continue;
1716 }
1717 if dropped(follow, lead, &key) {
1718 placed.insert(key);
1719 continue;
1720 }
1721 let lead_did = lead.did.get(&key).cloned().unwrap_or(Did::Unchanged);
1722 let follow_did = follow.did.get(&key).cloned().unwrap_or(Did::Unchanged);
1723 let base_v = find(&base_seq, &key);
1724 let follow_v = find(follow_seq, &key);
1725 match (&lead_did, &follow_did) {
1726 (_, Did::SquashedInto(_)) => {
1728 placed.insert(key);
1729 continue;
1730 }
1731 (
1734 Did::Unchanged | Did::Moved | Did::Amended | Did::Reworded | Did::Split(_),
1735 Did::Split(pieces),
1736 ) if !lead_split || !matches!(lead_did, Did::Split(_)) => {
1737 for piece in follow_seq.iter().filter(|p| pieces.contains(&p.key)) {
1738 if placed.insert(piece.key.clone()) {
1739 steps.push(Step {
1740 version: piece.clone(),
1741 fold: None,
1742 message: None,
1743 new_change: false,
1744 against: None,
1745 });
1746 }
1747 }
1748 if let (Did::Amended, Some(base_v)) = (&lead_did, &base_v) {
1749 if let Some(last) = steps.last_mut() {
1750 last.fold = Some((base_v.clone(), v.clone()));
1751 }
1752 }
1753 placed.insert(key);
1754 continue;
1755 }
1756 _ => {}
1757 }
1758 let mut step = Step {
1759 version: v.clone(),
1760 fold: None,
1761 message: None,
1762 new_change: false,
1763 against: None,
1764 };
1765 match (&lead_did, &follow_did, &follow_v, &base_v) {
1766 (Did::Unchanged | Did::Moved, Did::Amended | Did::Reworded, Some(fv), _) => {
1768 step.version = fv.clone();
1769 }
1770 (Did::Amended | Did::Reworded, Did::Amended | Did::Reworded, Some(fv), Some(bv)) => {
1772 if choice == Choice::KeepBoth {
1773 steps.push(step);
1774 steps.push(Step {
1775 version: fv.clone(),
1776 fold: None,
1777 message: None,
1778 new_change: true,
1779 against: Some(v.clone()),
1780 });
1781 placed.insert(key);
1782 continue;
1783 }
1784 if fv.patch != bv.patch {
1785 step.fold = Some((bv.clone(), fv.clone()));
1786 }
1787 if fv.message != bv.message && v.message == bv.message {
1788 step.message = Some(fv.message.clone());
1789 }
1790 }
1791 (_, Did::Unchanged, Some(fv), _) if fv.patch != v.patch => {
1794 if lead_did == Did::Unchanged {
1795 step.version = fv.clone();
1796 } else if let Some(bv) = &base_v {
1797 step.fold = Some((bv.clone(), fv.clone()));
1798 }
1799 }
1800 _ => {}
1801 }
1802 placed.insert(key);
1803 steps.push(step);
1804 }
1805 for v in follow_seq {
1808 if placed.contains(&v.key) {
1809 continue;
1810 }
1811 if base_has(&v.key) {
1812 let lead_dropped = dropped(lead, follow, &v.key);
1813 let lead_squashed = matches!(lead.did.get(&v.key), Some(Did::SquashedInto(_)));
1814 if lead_dropped || lead_squashed {
1815 continue;
1816 }
1817 }
1818 if let Some(Did::SplitFrom(from)) = follow.did.get(&v.key) {
1819 if lead_split && matches!(lead.did.get(from), Some(Did::Split(_))) {
1820 continue;
1821 }
1822 }
1823 placed.insert(v.key.clone());
1824 steps.push(Step {
1825 version: v.clone(),
1826 fold: None,
1827 message: None,
1828 new_change: false,
1829 against: None,
1830 });
1831 }
1832 if choice == Choice::Restore {
1833 for b in &base_seq {
1834 if !placed.contains(&b.key) {
1835 placed.insert(b.key.clone());
1836 steps.push(Step {
1837 version: b.clone(),
1838 fold: None,
1839 message: None,
1840 new_change: false,
1841 against: None,
1842 });
1843 }
1844 }
1845 }
1846
1847 let root = |seq: &[Version]| seq.first().and_then(|v| v.parent);
1849 let mut tip = match (root(&ours_seq), root(&theirs_seq)) {
1850 (Some(a), Some(b)) if a != b => {
1851 if is_ancestor(repo, a, b)? {
1852 b
1853 } else {
1854 a
1855 }
1856 }
1857 (Some(a), _) | (None, Some(a)) => a,
1858 (None, None) => return Ok(done(ours)),
1859 };
1860 for step in steps {
1861 match replay(repo, tip, &step)? {
1862 Ok(Some(next)) => tip = next,
1863 Ok(None) => {}
1864 Err(conflicts) => {
1865 return Ok(Combined {
1866 head: None,
1867 conflicts,
1868 stopped_at: Some(step.version.subject.clone()),
1869 })
1870 }
1871 }
1872 }
1873 Ok(done(tip))
1874}
1875
1876fn replay(
1879 repo: &Repository,
1880 tip: ObjectId,
1881 step: &Step,
1882) -> Result<std::result::Result<Option<ObjectId>, Vec<StoredRelPath>>> {
1883 let v = &step.version;
1884 if v.parent == Some(tip) && step.fold.is_none() && step.message.is_none() && !step.new_change {
1885 return Ok(Ok(Some(v.oid)));
1886 }
1887 let odb = repo.odb();
1888 let tip_tree = odb.commit_tree(&tip)?;
1889 let parent_tree = match (&step.against, v.parent) {
1890 (Some(against), _) => against.tree,
1891 (None, Some(p)) => odb.commit_tree(&p)?,
1892 (None, None) => tip_tree,
1893 };
1894 let mut tree = if v.parent == Some(tip) && step.against.is_none() {
1895 v.tree
1896 } else {
1897 let found = tree_conflicts_with_result(repo, parent_tree, tip_tree, v.tree)?;
1898 match found {
1899 Ok(tree) => tree,
1900 Err(paths) => return Ok(Err(paths)),
1901 }
1902 };
1903 if let Some((from, other)) = &step.fold {
1904 match tree_conflicts_with_result(repo, from.tree, tree, other.tree)? {
1905 Ok(t) => tree = t,
1906 Err(paths) => return Ok(Err(paths)),
1907 }
1908 }
1909 if step.new_change {
1910 if tree == tip_tree {
1912 return Ok(Ok(None));
1913 }
1914 } else if tree == tip_tree && !v.lines.as_ref().is_some_and(HashSet::is_empty) {
1915 return Ok(Ok(None));
1917 }
1918 let mut data = odb.read_commit(&v.oid)?;
1919 data.tree = tree;
1920 data.parents = vec![tip];
1921 if let Some(message) = &step.message {
1922 data.message = message.clone();
1923 }
1924 data.extra_headers = crate::objects::remove_header_lines(&data.extra_headers, |key| {
1925 key == b"gpgsig" || key == b"gpgsig-sha256" || key == b"mergetag"
1926 });
1927 if step.new_change {
1928 let id = crate::change_id::ChangeId::derived_from_commit_id(&v.oid);
1929 crate::change_id::set_change_id(&mut data, &id);
1930 }
1931 let oid = odb.write(
1932 crate::objects::ObjectKind::Commit,
1933 &crate::objects::serialize_commit(&data),
1934 )?;
1935 Ok(Ok(Some(oid)))
1936}
1937
1938fn tree_conflicts_with_result(
1941 repo: &Repository,
1942 base: ObjectId,
1943 ours: ObjectId,
1944 theirs: ObjectId,
1945) -> Result<std::result::Result<ObjectId, Vec<StoredRelPath>>> {
1946 let merged = merge_trees_three_way(
1947 repo,
1948 base,
1949 ours,
1950 theirs,
1951 MergeFavor::default(),
1952 WhitespaceMergeOptions::default(),
1953 None,
1954 TreeMergeConflictPresentation::default(),
1955 DirectoryRenameMode::from_repo(repo)?,
1956 )?;
1957 let mut paths: Vec<StoredRelPath> = crate::operation::conflicts_from_tree_merge(&merged)
1958 .into_iter()
1959 .map(|c| StoredRelPath::new(c.path))
1960 .collect();
1961 if paths.is_empty() {
1962 return Ok(Ok(merged.result_tree));
1963 }
1964 paths.sort();
1965 paths.dedup();
1966 Ok(Err(paths))
1967}
1968
1969#[derive(Debug, Clone, PartialEq, Eq)]
1971pub struct Keyed {
1972 pub key: String,
1974 pub commit: ObjectId,
1976 pub subject: String,
1978}
1979
1980pub(crate) fn keyed_commits(
1987 repo: &Repository,
1988 head: ObjectId,
1989 floor: &[ObjectId],
1990) -> Result<Vec<Keyed>> {
1991 Ok(sequence(repo, head, floor)?
1992 .into_iter()
1993 .map(|v| Keyed {
1994 key: v.key,
1995 commit: v.oid,
1996 subject: v.subject,
1997 })
1998 .collect())
1999}
2000
2001pub(crate) fn missing_from(
2009 repo: &Repository,
2010 floor: &[ObjectId],
2011 ours: ObjectId,
2012 theirs: ObjectId,
2013) -> Result<Vec<Keyed>> {
2014 if is_ancestor(repo, theirs, ours)? {
2015 return Ok(Vec::new());
2016 }
2017 let have: HashSet<String> = sequence(repo, ours, floor)?
2018 .into_iter()
2019 .map(|v| v.key)
2020 .collect();
2021 Ok(keyed_commits(repo, theirs, floor)?
2022 .into_iter()
2023 .filter(|k| !have.contains(&k.key))
2024 .collect())
2025}
2026
2027#[derive(Debug, Clone, PartialEq, Eq)]
2029pub enum ReplayOntoOutcome {
2030 Ok {
2032 tip: ObjectId,
2034 },
2035 Conflict {
2037 paths: Vec<StoredRelPath>,
2039 },
2040}
2041
2042pub(crate) fn replay_onto(
2050 repo: &Repository,
2051 head: ObjectId,
2052 floor: &[ObjectId],
2053 onto: ObjectId,
2054 skip: &HashSet<String>,
2055) -> Result<ReplayOntoOutcome> {
2056 let mut tip = onto;
2057 for mut version in sequence(repo, head, floor)? {
2058 if skip.contains(&version.key) || version.merge {
2059 continue;
2060 }
2061 load_changes(repo, &mut version)?;
2062 let step = Step {
2063 version,
2064 fold: None,
2065 message: None,
2066 new_change: false,
2067 against: None,
2068 };
2069 match replay(repo, tip, &step)? {
2070 Ok(Some(next)) => tip = next,
2071 Ok(None) => {}
2072 Err(paths) => return Ok(ReplayOntoOutcome::Conflict { paths }),
2073 }
2074 }
2075 Ok(ReplayOntoOutcome::Ok { tip })
2076}
2077
2078impl RevWalk<'_> {
2079 #[must_use]
2082 pub fn heads_seen(&self, ref_name: &RefName) -> Vec<ObjectId> {
2083 heads_seen(self.repository(), ref_name.as_str())
2084 }
2085
2086 pub fn divergence_base(
2094 &self,
2095 ours: ObjectId,
2096 theirs: ObjectId,
2097 ours_seen: &[ObjectId],
2098 theirs_seen: &[ObjectId],
2099 ) -> Result<Option<ObjectId>> {
2100 common_base(self.repository(), ours, theirs, ours_seen, theirs_seen)
2101 }
2102
2103 pub fn classify_divergence(
2115 &self,
2116 floor: &[ObjectId],
2117 base: Option<ObjectId>,
2118 ours: ObjectId,
2119 theirs: ObjectId,
2120 ) -> Result<Divergence> {
2121 classify(self.repository(), floor, base, ours, theirs)
2122 }
2123
2124 pub fn combine_divergence(
2133 &self,
2134 floor: &[ObjectId],
2135 base: Option<ObjectId>,
2136 ours: ObjectId,
2137 theirs: ObjectId,
2138 choice: Choice,
2139 ) -> Result<Combined> {
2140 combine(self.repository(), floor, base, ours, theirs, choice)
2141 }
2142
2143 pub fn keyed_commits(&self, head: ObjectId, floor: &[ObjectId]) -> Result<Vec<Keyed>> {
2150 keyed_commits(self.repository(), head, floor)
2151 }
2152
2153 pub fn missing_from(
2160 &self,
2161 floor: &[ObjectId],
2162 ours: ObjectId,
2163 theirs: ObjectId,
2164 ) -> Result<Vec<Keyed>> {
2165 missing_from(self.repository(), floor, ours, theirs)
2166 }
2167
2168 pub fn replay_onto(
2176 &self,
2177 head: ObjectId,
2178 floor: &[ObjectId],
2179 onto: ObjectId,
2180 skip: &HashSet<String>,
2181 ) -> Result<ReplayOntoOutcome> {
2182 replay_onto(self.repository(), head, floor, onto, skip)
2183 }
2184}