M4.8: merge conflicts with a three-pane resolve view

Backend (crates/vcs/src/merge.rs, cmd/git_merge.rs via start_with):
git.merge {branch} -> {result: merged|upToDate|conflicts, conflicts},
git.mergeAbort, git.conflictVersions {path} -> {base?, ours, theirs,
binary, tooLarge} from the index stages :1:/:2:/:3:, git.markResolved
{paths}. Repo::lock becomes pub(crate) so merge and abort hold the
mutation lock.

UI (ui/src/components/vcs/merge/): merge dialog with branch picker,
conflicts list from the shared status store, a three-pane resolve view
(ours / editable result / theirs) with accept left/right per chunk,
accept all, previous/next conflict, Apply through the file's buffer then
mark resolved, keep-a-side for modify/delete, abort after confirmation.
Own three-way line merge on @codemirror/merge's diff. UI commands
vcs.merge, vcs.resolveConflicts, vcs.abortMerge (no default shortcuts);
the Changes window opens conflicted rows in the resolve view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-29 17:48:24 +01:00
parent 74c674ed12
commit d82e57b3ac
26 changed files with 3872 additions and 16 deletions

View file

@ -42,3 +42,7 @@ pub use repo::{
};
pub use runner::{Cancel, ProgressSink, redact_urls};
pub use watch::{RepoWatch, fingerprint};
mod merge;
pub use merge::{
CheckLine, ConflictVersions, MergeOutcome, MergeResult, parse_check_line, parse_unmerged,
};

339
crates/vcs/src/merge.rs Normal file
View file

@ -0,0 +1,339 @@
//! Merges and merge conflicts (M4.8): merging a branch into the current
//! one, aborting a merge, the three versions of a conflicted file and
//! marking files resolved.
//!
//! - [`Repo::merge`] runs `git merge --no-edit` (hooks run, 120 s). A merge
//! that stops on conflicts is not an error: it returns the conflicted
//! paths, read from the index's unmerged entries (`ls-files -u -z`).
//! - [`Repo::conflict_versions`] reads the index stages of a conflicted
//! file: `:1:` (the common ancestor), `:2:` (ours, the current branch) and
//! `:3:` (theirs, the branch being merged), as stored, like
//! [`Repo::show`].
//! - [`Repo::mark_resolved`] stages the files (`add -A`), which removes the
//! unmerged entries; a file deleted in the work tree is staged as deleted.
//! - [`Repo::merge_abort`] runs `git merge --abort`.
use crate::VcsError;
use crate::repo::{Contents, FILE_CAP, Repo, SMALL_CAP, check_name, decode};
use crate::runner::{Call, HOOK_TIMEOUT};
/// How a merge ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MergeResult {
/// HEAD moved: a merge commit or a fast-forward.
Merged,
/// Nothing to merge: the branch is already contained in HEAD.
UpToDate,
/// The merge stopped on conflicts; resolve them and commit, or abort.
Conflicts,
}
/// What [`Repo::merge`] did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeOutcome {
/// How it ended.
pub result: MergeResult,
/// Project-relative conflicted paths, sorted; empty unless
/// [`MergeResult::Conflicts`].
pub conflicts: Vec<String>,
}
/// The versions of a conflicted file in the index.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ConflictVersions {
/// The common ancestor (`:1:`); `None` when the file was added on both
/// sides.
pub base: Option<String>,
/// The current branch's version (`:2:`); `None` when deleted there.
pub ours: Option<String>,
/// The merged branch's version (`:3:`); `None` when deleted there.
pub theirs: Option<String>,
/// One of the versions is binary (texts are then all `None`).
pub binary: bool,
/// One of the versions is larger than [`FILE_CAP`] (texts are then all
/// `None`).
pub too_large: bool,
}
/// One line of `git cat-file --batch-check`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CheckLine {
/// The object does not exist.
Missing,
/// An object: its id, type and size in bytes.
Object {
/// The object id.
oid: String,
/// `blob`, `tree`, `commit` (a submodule) or `tag`.
kind: String,
/// Size in bytes.
size: usize,
},
}
/// Reads one line of `git cat-file --batch-check` (`<oid> <type> <size>`,
/// or `<name> missing`).
///
/// # Returns
/// `None` when the line is neither.
pub fn parse_check_line(line: &str) -> Option<CheckLine> {
let line = line.trim_end_matches(['\r', '\n']);
if line.ends_with(" missing") || line.ends_with(" ambiguous") {
return Some(CheckLine::Missing);
}
let mut fields = line.rsplitn(3, ' ');
let size = fields.next()?.parse().ok()?;
let kind = fields.next()?.to_string();
let oid = fields.next()?.to_string();
if oid.is_empty() || oid.contains(' ') || kind.is_empty() {
return None;
}
Some(CheckLine::Object { oid, kind, size })
}
/// The paths of `git ls-files -u -z` output (`<mode> <oid> <stage>\t<path>`
/// records), each once, sorted.
pub fn parse_unmerged(bytes: &[u8]) -> Vec<String> {
let mut paths: Vec<String> = bytes
.split(|b| *b == 0)
.filter_map(|record| {
let tab = record.iter().position(|b| *b == b'\t')?;
let path = record.get(tab + 1..)?;
(!path.is_empty()).then(|| String::from_utf8_lossy(path).into_owned())
})
.collect();
paths.sort();
paths.dedup();
paths
}
impl Repo {
/// The commit HEAD points to; `None` before the first commit.
fn head_commit(&self) -> Result<Option<String>, VcsError> {
let output = self.run(Call::read(
self.root(),
&["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
4096,
))?;
Ok(output
.success()
.then(|| String::from_utf8_lossy(&output.stdout).trim().to_string()))
}
/// Whether a merge is in progress (`MERGE_HEAD` exists).
///
/// # Errors
/// The runner's errors.
pub fn merging(&self) -> Result<bool, VcsError> {
Ok(self
.run(Call::read(
self.root(),
&["rev-parse", "--verify", "--quiet", "MERGE_HEAD"],
4096,
))?
.success())
}
/// Unmerged paths in the index, project-relative and sorted (paths
/// outside the project are left out).
///
/// # Errors
/// The runner's errors or git's refusal.
pub fn unmerged(&self) -> Result<Vec<String>, VcsError> {
let output = self
.run(Call::read(
self.root(),
&["ls-files", "-u", "-z"],
SMALL_CAP,
))?
.checked()?;
Ok(parse_unmerged(&output.stdout)
.into_iter()
.filter_map(|path| self.from_repo_path(&path))
.collect())
}
/// Merges `branch` into the current branch (`git merge --no-edit`; a
/// fast-forward when possible, git's default). Hooks run (120 s).
///
/// # Returns
/// [`MergeResult::Conflicts`] with the conflicted paths when git stopped
/// on conflicts; the work tree then holds the conflict markers.
///
/// # Errors
/// [`VcsError::InvalidName`]; [`VcsError::Git`] when a merge is already
/// in progress or files are unmerged, or when git refuses (an unknown
/// branch, local changes that would be overwritten, no commit yet);
/// git's message is passed on.
pub fn merge(&self, branch: &str) -> Result<MergeOutcome, VcsError> {
check_name(branch)?;
let _guard = self.lock();
if self.merging()? || !self.unmerged()?.is_empty() {
return Err(VcsError::Git(
"a merge is in progress: resolve its conflicts and commit, or abort it first"
.into(),
));
}
let before = self.head_commit()?;
let output = self.run(
Call::write(
self.root(),
&[
"merge",
"--no-edit",
"--no-progress",
"--end-of-options",
branch,
],
)
.timeout(HOOK_TIMEOUT),
)?;
if output.success() {
let result = if self.head_commit()? == before {
MergeResult::UpToDate
} else {
MergeResult::Merged
};
return Ok(MergeOutcome {
result,
conflicts: Vec::new(),
});
}
let conflicts = self.unmerged()?;
if conflicts.is_empty() && !self.merging()? {
return Err(VcsError::Git(output.message()));
}
Ok(MergeOutcome {
result: MergeResult::Conflicts,
conflicts,
})
}
/// Aborts the merge in progress (`git merge --abort`): the work tree
/// and index go back to the state before the merge.
///
/// # Errors
/// [`VcsError::Git`] when no merge is in progress, or git's refusal.
pub fn merge_abort(&self) -> Result<(), VcsError> {
let _guard = self.lock();
self.run(Call::write(self.root(), &["merge", "--abort"]))?
.checked()?;
Ok(())
}
/// The three index versions of a conflicted file, as stored (no
/// filters, no line-ending conversion).
///
/// # Errors
/// [`VcsError::InvalidPath`]; [`VcsError::Git`] when the file is not in
/// conflict; the runner's errors.
pub fn conflict_versions(&self, path: &str) -> Result<ConflictVersions, VcsError> {
let repo_path = self.to_repo_path(path)?;
let objects = format!(":1:{repo_path}\n:2:{repo_path}\n:3:{repo_path}\n");
let output = self
.run(
Call::read(self.root(), &["cat-file", "--batch-check"], SMALL_CAP)
.stdin(objects.into_bytes()),
)?
.checked()?;
let text = String::from_utf8_lossy(&output.stdout);
let lines: Vec<CheckLine> = text
.lines()
.map(|line| parse_check_line(line).ok_or_else(|| VcsError::BadOutput(line.to_string())))
.collect::<Result<_, _>>()?;
if lines.len() != 3 {
return Err(VcsError::BadOutput(text.to_string()));
}
if lines.iter().all(|line| *line == CheckLine::Missing) {
return Err(VcsError::Git(format!("{path} is not in conflict")));
}
let mut versions = ConflictVersions::default();
let mut texts = Vec::with_capacity(3);
for line in &lines {
let CheckLine::Object { oid, kind, size } = line else {
texts.push(None);
continue;
};
if kind != "blob" {
versions.binary = true;
texts.push(None);
continue;
}
if *size > FILE_CAP {
versions.too_large = true;
texts.push(None);
continue;
}
let blob = self
.run(Call::read(
self.root(),
&["cat-file", "blob", oid],
FILE_CAP,
))?
.checked()?;
let Contents { text, binary, .. } = decode(blob.stdout);
versions.binary |= binary;
texts.push(text);
}
if versions.binary || versions.too_large {
return Ok(versions);
}
let mut texts = texts.into_iter();
versions.base = texts.next().flatten();
versions.ours = texts.next().flatten();
versions.theirs = texts.next().flatten();
Ok(versions)
}
/// Marks files resolved by staging them (`add -A`): the unmerged index
/// entries go away; a file deleted in the work tree is staged as
/// deleted. Committing then concludes the merge.
///
/// # Errors
/// [`VcsError::InvalidPath`], or git's refusal.
pub fn mark_resolved(&self, paths: &[String]) -> Result<(), VcsError> {
self.stage(paths)
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use proptest::prelude::*;
#[test]
fn reads_check_lines() {
assert_eq!(
parse_check_line(":1:a b.php missing"),
Some(CheckLine::Missing)
);
assert_eq!(
parse_check_line("0123abcd blob 42\n"),
Some(CheckLine::Object {
oid: "0123abcd".into(),
kind: "blob".into(),
size: 42
})
);
assert_eq!(parse_check_line("garbage"), None);
assert_eq!(parse_check_line("a b c d"), None);
}
#[test]
fn reads_unmerged_paths_once_each() {
let out = b"100644 aaa 1\tsrc/a b.php\x00100644 bbb 2\tsrc/a b.php\x00100644 ccc 3\tsrc/a b.php\x00100644 ddd 2\tREADME\x00";
assert_eq!(parse_unmerged(out), vec!["README", "src/a b.php"]);
assert!(parse_unmerged(b"").is_empty());
assert!(parse_unmerged(b"no tab here\0").is_empty());
}
proptest! {
#[test]
fn parsers_never_panic(bytes in proptest::collection::vec(any::<u8>(), 0..256)) {
let _ = parse_unmerged(&bytes);
let _ = parse_check_line(&String::from_utf8_lossy(&bytes));
}
}
}

View file

@ -244,7 +244,7 @@ impl Repo {
/// Serialises changes: the guard of [`Repo::mutations`]. A poisoned
/// lock is taken over: the lock guards no data.
fn lock(&self) -> MutexGuard<'_, ()> {
pub(crate) fn lock(&self) -> MutexGuard<'_, ()> {
self.mutations
.lock()
.unwrap_or_else(PoisonError::into_inner)

248
crates/vcs/tests/merge.rs Normal file
View file

@ -0,0 +1,248 @@
//! Merges against real temp repositories: a clean merge, a fast-forward,
//! already up to date, a content conflict with its three versions, an
//! add/add conflict without a base, a modify/delete conflict, marking files
//! resolved and committing, aborting, a refused merge (local changes) and a
//! second merge while one is in progress. Every test skips with a message
//! when git is not installed.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use std::path::Path;
use std::process::Command;
use lutra_vcs::{FileState, Git, MergeResult, Repo, VcsError};
/// The installed git, or `None` (with a message) when there is none.
fn installed() -> Option<Git> {
match Git::detect("") {
Ok(git) => Some(git),
Err(e) => {
eprintln!("skipped: no usable git installed ({e})");
None
}
}
}
/// Runs git in `dir` for test setup and asserts it succeeded.
fn git(dir: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.args(args)
.current_dir(dir)
.env_remove("GIT_DIR")
.env_remove("GIT_WORK_TREE")
.env_remove("GIT_INDEX_FILE")
.output()
.unwrap();
assert!(
out.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
/// Writes a file.
fn write(dir: &Path, path: &str, text: &str) {
std::fs::write(dir.join(path), text).unwrap();
}
/// Stages everything and commits.
fn commit(dir: &Path, message: &str) {
git(dir, &["add", "-A"]);
git(dir, &["commit", "-q", "-m", message]);
}
/// A repository on `main` with `a.php` committed, and a branch `feature`
/// at that commit.
fn init(dir: &Path) {
git(dir, &["init", "-q", "-b", "main"]);
for (key, value) in [
("user.name", "Lutra Test"),
("user.email", "test@lutra.invalid"),
("commit.gpgsign", "false"),
("core.autocrlf", "false"),
("core.hooksPath", ".git/hooks"),
("merge.conflictStyle", "merge"),
] {
git(dir, &["config", key, value]);
}
write(dir, "a.php", "<?php\none\ntwo\nthree\n");
commit(dir, "base");
git(dir, &["branch", "feature"]);
}
/// Opens the repository at `dir`.
fn open(git: &Git, dir: &Path) -> Repo {
git.open(dir).unwrap().expect("a repository")
}
/// `a.php` changed on both branches in the same line.
fn conflicting(dir: &Path) {
write(dir, "a.php", "<?php\none\nTWO (main)\nthree\n");
commit(dir, "main side");
git(dir, &["switch", "-q", "feature"]);
write(dir, "a.php", "<?php\none\nTWO (feature)\nthree\n");
commit(dir, "feature side");
git(dir, &["switch", "-q", "main"]);
}
#[test]
fn clean_merge_fast_forward_and_up_to_date() {
let Some(cli) = installed() else { return };
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
init(root);
git(root, &["switch", "-q", "feature"]);
write(root, "b.php", "<?php // b\n");
commit(root, "feature b");
git(root, &["switch", "-q", "main"]);
let repo = open(&cli, root);
let ff = repo.merge("feature").unwrap();
assert_eq!(ff.result, MergeResult::Merged);
assert!(ff.conflicts.is_empty());
assert!(root.join("b.php").exists());
assert_eq!(repo.merge("feature").unwrap().result, MergeResult::UpToDate);
git(root, &["switch", "-q", "feature"]);
write(root, "c.php", "<?php // c\n");
commit(root, "feature c");
git(root, &["switch", "-q", "main"]);
write(root, "d.php", "<?php // d\n");
commit(root, "main d");
let merged = repo.merge("feature").unwrap();
assert_eq!(merged.result, MergeResult::Merged);
assert_eq!(git(root, &["rev-list", "--count", "--merges", "HEAD"]), "1");
assert!(!repo.merging().unwrap());
}
#[test]
fn a_conflict_its_versions_resolving_and_committing() {
let Some(cli) = installed() else { return };
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
init(root);
conflicting(root);
let repo = open(&cli, root);
let outcome = repo.merge("feature").unwrap();
assert_eq!(outcome.result, MergeResult::Conflicts);
assert_eq!(outcome.conflicts, vec!["a.php"]);
assert!(repo.merging().unwrap());
let status = repo.status().unwrap();
let file = status.files.iter().find(|f| f.path == "a.php").unwrap();
assert_eq!(file.worktree, FileState::Conflicted);
let versions = repo.conflict_versions("a.php").unwrap();
assert_eq!(versions.base.as_deref(), Some("<?php\none\ntwo\nthree\n"));
assert_eq!(
versions.ours.as_deref(),
Some("<?php\none\nTWO (main)\nthree\n")
);
assert_eq!(
versions.theirs.as_deref(),
Some("<?php\none\nTWO (feature)\nthree\n")
);
assert!(!versions.binary && !versions.too_large);
let on_disk = std::fs::read_to_string(root.join("a.php")).unwrap();
assert!(on_disk.contains("<<<<<<<"));
assert!(matches!(
repo.merge("feature"),
Err(VcsError::Git(message)) if message.contains("in progress")
));
write(root, "a.php", "<?php\none\nTWO (both)\nthree\n");
repo.mark_resolved(&["a.php".to_string()]).unwrap();
assert!(repo.unmerged().unwrap().is_empty());
assert!(matches!(
repo.conflict_versions("a.php"),
Err(VcsError::Git(message)) if message.contains("not in conflict")
));
repo.commit("Merge feature", false).unwrap();
assert!(!repo.merging().unwrap());
assert_eq!(git(root, &["rev-list", "--count", "--merges", "HEAD"]), "1");
}
#[test]
fn add_add_and_modify_delete_conflicts() {
let Some(cli) = installed() else { return };
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
init(root);
write(root, "new file.php", "<?php // main\n");
git(root, &["rm", "-q", "a.php"]);
commit(root, "main adds, deletes a");
git(root, &["switch", "-q", "feature"]);
write(root, "new file.php", "<?php // feature\n");
write(root, "a.php", "<?php\none\nchanged\nthree\n");
commit(root, "feature adds, changes a");
git(root, &["switch", "-q", "main"]);
let repo = open(&cli, root);
let outcome = repo.merge("feature").unwrap();
assert_eq!(outcome.result, MergeResult::Conflicts);
assert_eq!(outcome.conflicts, vec!["a.php", "new file.php"]);
let added = repo.conflict_versions("new file.php").unwrap();
assert_eq!(added.base, None);
assert_eq!(added.ours.as_deref(), Some("<?php // main\n"));
assert_eq!(added.theirs.as_deref(), Some("<?php // feature\n"));
let deleted = repo.conflict_versions("a.php").unwrap();
assert!(deleted.base.is_some());
assert_eq!(deleted.ours, None);
assert_eq!(
deleted.theirs.as_deref(),
Some("<?php\none\nchanged\nthree\n")
);
std::fs::remove_file(root.join("a.php")).unwrap();
repo.mark_resolved(&["a.php".to_string(), "new file.php".to_string()])
.unwrap();
assert!(repo.unmerged().unwrap().is_empty());
}
#[test]
fn abort_restores_the_state_before_the_merge() {
let Some(cli) = installed() else { return };
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
init(root);
conflicting(root);
let repo = open(&cli, root);
let head = git(root, &["rev-parse", "HEAD"]);
assert_eq!(
repo.merge("feature").unwrap().result,
MergeResult::Conflicts
);
repo.merge_abort().unwrap();
assert!(!repo.merging().unwrap());
assert!(repo.unmerged().unwrap().is_empty());
assert_eq!(git(root, &["rev-parse", "HEAD"]), head);
assert_eq!(
std::fs::read_to_string(root.join("a.php")).unwrap(),
"<?php\none\nTWO (main)\nthree\n"
);
assert!(matches!(repo.merge_abort(), Err(VcsError::Git(_))));
}
#[test]
fn refusals_pass_on_gits_message() {
let Some(cli) = installed() else { return };
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
init(root);
conflicting(root);
write(root, "a.php", "<?php\nlocal edit\n");
let repo = open(&cli, root);
assert!(matches!(repo.merge("feature"), Err(VcsError::Git(_))));
assert!(!repo.merging().unwrap());
assert!(matches!(
repo.merge("no-such-branch"),
Err(VcsError::Git(_))
));
assert!(matches!(
repo.merge("--abort"),
Err(VcsError::InvalidName(_))
));
assert!(matches!(
repo.conflict_versions("../x"),
Err(VcsError::InvalidPath(_))
));
}