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:
parent
74c674ed12
commit
d82e57b3ac
26 changed files with 3872 additions and 16 deletions
210
crates/engine/src/cmd/git_merge.rs
Normal file
210
crates/engine/src/cmd/git_merge.rs
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
//! Merge commands (M4.8): `git.merge`, `git.mergeAbort`,
|
||||
//! `git.conflictVersions` and `git.markResolved`, on top of
|
||||
//! `lutra_vcs::Repo`'s merge calls.
|
||||
//!
|
||||
//! Each runs through [`super::git::start_with`]: a pending outcome, git and
|
||||
//! the repository detected and cached as for every `git.*` command, and
|
||||
//! `gitChanged` after the calls that change the repository (merge, abort,
|
||||
//! mark resolved). A merge that stops on conflicts is a success with the
|
||||
//! conflicted paths, so `gitChanged` follows it too.
|
||||
|
||||
use lutra_vcs::MergeResult;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::git::{rel_path, start_with};
|
||||
use super::params::parse;
|
||||
use crate::{Command, CommandSpec, EngineError, Outcome, Registry, State};
|
||||
|
||||
/// Registers the merge commands.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`EngineError::Internal`] if an id is taken.
|
||||
pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
|
||||
registry.register(Box::new(Merge))?;
|
||||
registry.register(Box::new(MergeAbort))?;
|
||||
registry.register(Box::new(ConflictVersionsCommand))?;
|
||||
registry.register(Box::new(MarkResolved))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The wire name of a merge result.
|
||||
fn result_name(result: MergeResult) -> &'static str {
|
||||
match result {
|
||||
MergeResult::Merged => "merged",
|
||||
MergeResult::UpToDate => "upToDate",
|
||||
MergeResult::Conflicts => "conflicts",
|
||||
}
|
||||
}
|
||||
|
||||
/// Params of `git.merge`.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct MergeParams {
|
||||
/// The branch (or revision) to merge into the current branch.
|
||||
branch: String,
|
||||
}
|
||||
|
||||
/// `git.merge`.
|
||||
struct Merge;
|
||||
|
||||
impl Command for Merge {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "git.merge",
|
||||
label: "Git: Merge Branch into Current",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "{ branch: local or remote branch }; git merge --no-edit (fast-forward when possible, hooks run, 120 s); returns { result: \"merged\" | \"upToDate\" | \"conflicts\", conflicts: [project-relative path] }; stopping on conflicts is not an error. Refused while a merge is in progress; git's refusal (local changes would be overwritten) is the error text. Save dirty buffers first.",
|
||||
}
|
||||
}
|
||||
|
||||
fn enabled(&self, state: &State) -> bool {
|
||||
state.has_project()
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let command = self.spec().id;
|
||||
let p: MergeParams = parse(command, params)?;
|
||||
let branch = p.branch;
|
||||
start_with(
|
||||
state,
|
||||
command,
|
||||
true,
|
||||
Box::new(move |repo| {
|
||||
let outcome = repo.merge(&branch)?;
|
||||
Ok(json!({
|
||||
"result": result_name(outcome.result),
|
||||
"conflicts": outcome.conflicts,
|
||||
}))
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// `git.mergeAbort`.
|
||||
struct MergeAbort;
|
||||
|
||||
impl Command for MergeAbort {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "git.mergeAbort",
|
||||
label: "Git: Abort Merge",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "none; git merge --abort: the work tree and index return to the state before the merge; returns {}; fails with git's message when no merge is in progress",
|
||||
}
|
||||
}
|
||||
|
||||
fn enabled(&self, state: &State) -> bool {
|
||||
state.has_project()
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let command = self.spec().id;
|
||||
let _: serde_json::Map<String, Value> = parse(command, params)?;
|
||||
start_with(
|
||||
state,
|
||||
command,
|
||||
true,
|
||||
Box::new(|repo| repo.merge_abort().map(|()| json!({}))),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Params of `git.conflictVersions`.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct PathParams {
|
||||
/// The conflicted file.
|
||||
path: String,
|
||||
}
|
||||
|
||||
/// `git.conflictVersions`.
|
||||
struct ConflictVersionsCommand;
|
||||
|
||||
impl Command for ConflictVersionsCommand {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "git.conflictVersions",
|
||||
label: "Git: Conflict Versions",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "{ path: project-relative path of a conflicted file }; returns { base?: string, ours: string | null, theirs: string | null, binary, tooLarge }: the index stages :1: (common ancestor; absent when added on both sides), :2: (current branch) and :3: (merged branch) as stored; null when deleted on that side; all texts null when one version is binary or over 32 MiB. Fails when the file is not in conflict.",
|
||||
}
|
||||
}
|
||||
|
||||
fn enabled(&self, state: &State) -> bool {
|
||||
state.has_project()
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let command = self.spec().id;
|
||||
let p: PathParams = parse(command, params)?;
|
||||
let path = rel_path(state, command, &p.path)?;
|
||||
start_with(
|
||||
state,
|
||||
command,
|
||||
false,
|
||||
Box::new(move |repo| {
|
||||
let v = repo.conflict_versions(&path)?;
|
||||
let mut value = json!({
|
||||
"ours": v.ours,
|
||||
"theirs": v.theirs,
|
||||
"binary": v.binary,
|
||||
"tooLarge": v.too_large,
|
||||
});
|
||||
if let (Some(base), Some(map)) = (v.base, value.as_object_mut()) {
|
||||
map.insert("base".into(), Value::String(base));
|
||||
}
|
||||
Ok(value)
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Params of `git.markResolved`.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct PathsParams {
|
||||
/// The resolved files.
|
||||
paths: Vec<String>,
|
||||
}
|
||||
|
||||
/// `git.markResolved`.
|
||||
struct MarkResolved;
|
||||
|
||||
impl Command for MarkResolved {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "git.markResolved",
|
||||
label: "Git: Mark Resolved",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "{ paths: [project-relative path] }; stages the files as they are on disk (a file missing from disk is staged as deleted), which clears their conflict; returns {}. Save the result first.",
|
||||
}
|
||||
}
|
||||
|
||||
fn enabled(&self, state: &State) -> bool {
|
||||
state.has_project()
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let command = self.spec().id;
|
||||
let p: PathsParams = parse(command, params)?;
|
||||
if p.paths.is_empty() {
|
||||
return Err(EngineError::invalid_params(command, "paths is empty"));
|
||||
}
|
||||
let paths = p
|
||||
.paths
|
||||
.iter()
|
||||
.map(|path| rel_path(state, command, path))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
start_with(
|
||||
state,
|
||||
command,
|
||||
true,
|
||||
Box::new(move |repo| repo.mark_resolved(&paths).map(|()| json!({}))),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -6,6 +6,7 @@ mod file;
|
|||
pub mod git;
|
||||
pub mod git_lines;
|
||||
pub mod git_log;
|
||||
pub mod git_merge;
|
||||
pub mod git_remote;
|
||||
pub mod goto;
|
||||
mod lsp_assist;
|
||||
|
|
@ -72,5 +73,6 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
|
|||
git_lines::register(registry)?;
|
||||
git_log::register(registry)?;
|
||||
git_remote::register(registry)?;
|
||||
git_merge::register(registry)?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -486,11 +486,15 @@ mod tests {
|
|||
"git.checkout",
|
||||
"git.clone",
|
||||
"git.commit",
|
||||
"git.conflictVersions",
|
||||
"git.createBranch",
|
||||
"git.fetch",
|
||||
"git.lastMessage",
|
||||
"git.lineChanges",
|
||||
"git.log",
|
||||
"git.markResolved",
|
||||
"git.merge",
|
||||
"git.mergeAbort",
|
||||
"git.pull",
|
||||
"git.push",
|
||||
"git.remoteAdd",
|
||||
|
|
|
|||
208
crates/engine/tests/git_merge.rs
Normal file
208
crates/engine/tests/git_merge.rs
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
//! The merge commands through the engine with pending outcomes:
|
||||
//! `git.merge` up to date, with conflicts and refused; `git.conflictVersions`;
|
||||
//! `git.markResolved` and `git.mergeAbort`, each followed by `gitChanged`;
|
||||
//! bad params. 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 std::sync::Mutex;
|
||||
|
||||
use lutra_engine::{Engine, EngineError, Event, run_waiting};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Whether git is installed; prints why a test is skipped.
|
||||
fn have_git() -> bool {
|
||||
let ok = Command::new("git")
|
||||
.arg("--version")
|
||||
.output()
|
||||
.is_ok_and(|o| o.status.success());
|
||||
if !ok {
|
||||
eprintln!("skipped: git is not installed");
|
||||
}
|
||||
ok
|
||||
}
|
||||
|
||||
/// Runs git for test setup.
|
||||
fn git(dir: &Path, args: &[&str]) -> String {
|
||||
let out = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"git {args:?}: {}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
String::from_utf8_lossy(&out.stdout).trim().to_string()
|
||||
}
|
||||
|
||||
/// Commits everything.
|
||||
fn commit(dir: &Path, file: &str, text: &str, message: &str) {
|
||||
std::fs::write(dir.join(file), text).unwrap();
|
||||
git(dir, &["add", "-A"]);
|
||||
git(dir, &["commit", "-q", "-m", message]);
|
||||
}
|
||||
|
||||
/// A repository where `main` and `feature` changed the same line of
|
||||
/// `a.php`.
|
||||
fn conflicting(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"),
|
||||
] {
|
||||
git(dir, &["config", key, value]);
|
||||
}
|
||||
commit(dir, "a.php", "<?php\nbase\n", "base");
|
||||
git(dir, &["branch", "feature"]);
|
||||
commit(dir, "a.php", "<?php\nmain\n", "main side");
|
||||
git(dir, &["switch", "-q", "feature"]);
|
||||
commit(dir, "a.php", "<?php\nfeature\n", "feature side");
|
||||
git(dir, &["switch", "-q", "main"]);
|
||||
}
|
||||
|
||||
/// An engine behind a lock, like a host, recording every event.
|
||||
struct Host {
|
||||
/// The engine.
|
||||
engine: Mutex<Engine>,
|
||||
/// Events published so far.
|
||||
events: Mutex<Vec<Event>>,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// An engine with `root` open as the project.
|
||||
fn open(root: &Path) -> Self {
|
||||
let host = Self {
|
||||
engine: Mutex::new(Engine::new().unwrap()),
|
||||
events: Mutex::new(Vec::new()),
|
||||
};
|
||||
host.run("project.open", json!({"path": root})).unwrap();
|
||||
host
|
||||
}
|
||||
|
||||
/// Runs a command the way hosts do, waiting without the lock.
|
||||
fn run(&self, command: &str, params: Value) -> Result<Value, EngineError> {
|
||||
run_waiting(
|
||||
|| self.engine.lock().unwrap(),
|
||||
command,
|
||||
params,
|
||||
|events| self.events.lock().unwrap().extend_from_slice(events),
|
||||
)
|
||||
.map(|o| o.value)
|
||||
}
|
||||
|
||||
/// How many `gitChanged` events arrived since the last call.
|
||||
fn git_changes(&self) -> usize {
|
||||
let mut events = self.events.lock().unwrap();
|
||||
let count = events
|
||||
.iter()
|
||||
.filter(|e| matches!(e, Event::GitChanged(_)))
|
||||
.count();
|
||||
events.clear();
|
||||
count
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_conflict_versions_resolve_and_abort() {
|
||||
if !have_git() {
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
conflicting(root);
|
||||
let host = Host::open(root);
|
||||
host.git_changes();
|
||||
|
||||
let merged = host.run("git.merge", json!({"branch": "feature"})).unwrap();
|
||||
assert_eq!(
|
||||
merged,
|
||||
json!({"result": "conflicts", "conflicts": ["a.php"]})
|
||||
);
|
||||
assert_eq!(host.git_changes(), 1);
|
||||
|
||||
let versions = host
|
||||
.run("git.conflictVersions", json!({"path": "a.php"}))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
versions,
|
||||
json!({
|
||||
"base": "<?php\nbase\n",
|
||||
"ours": "<?php\nmain\n",
|
||||
"theirs": "<?php\nfeature\n",
|
||||
"binary": false,
|
||||
"tooLarge": false,
|
||||
})
|
||||
);
|
||||
assert_eq!(host.git_changes(), 0);
|
||||
|
||||
let again = host.run("git.merge", json!({"branch": "feature"}));
|
||||
assert!(matches!(again, Err(EngineError::Failed(m)) if m.contains("in progress")));
|
||||
|
||||
host.run("git.mergeAbort", Value::Null).unwrap();
|
||||
assert_eq!(host.git_changes(), 1);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(root.join("a.php")).unwrap(),
|
||||
"<?php\nmain\n"
|
||||
);
|
||||
|
||||
host.run("git.merge", json!({"branch": "feature"})).unwrap();
|
||||
std::fs::write(root.join("a.php"), "<?php\nboth\n").unwrap();
|
||||
host.git_changes();
|
||||
host.run("git.markResolved", json!({"paths": ["a.php"]}))
|
||||
.unwrap();
|
||||
assert_eq!(host.git_changes(), 1);
|
||||
let status = host.run("git.status", Value::Null).unwrap();
|
||||
assert_eq!(status["files"][0]["index"], "modified");
|
||||
assert!(
|
||||
host.run("git.conflictVersions", json!({"path": "a.php"}))
|
||||
.is_err()
|
||||
);
|
||||
host.run("git.commit", json!({"message": "Merge feature"}))
|
||||
.unwrap();
|
||||
let up_to_date = host.run("git.merge", json!({"branch": "feature"})).unwrap();
|
||||
assert_eq!(up_to_date, json!({"result": "upToDate", "conflicts": []}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_and_no_project() {
|
||||
if !have_git() {
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
conflicting(dir.path());
|
||||
let host = Host::open(dir.path());
|
||||
for (command, params) in [
|
||||
("git.merge", json!({})),
|
||||
("git.merge", json!({"branch": "-x"})),
|
||||
("git.markResolved", json!({"paths": []})),
|
||||
("git.conflictVersions", json!({"path": 3})),
|
||||
] {
|
||||
assert!(
|
||||
matches!(
|
||||
host.run(command, params.clone()),
|
||||
Err(EngineError::InvalidParams { .. })
|
||||
),
|
||||
"{command} {params}"
|
||||
);
|
||||
}
|
||||
let bare = Host {
|
||||
engine: Mutex::new(Engine::new().unwrap()),
|
||||
events: Mutex::new(Vec::new()),
|
||||
};
|
||||
assert!(matches!(
|
||||
bare.run("git.mergeAbort", Value::Null),
|
||||
Err(EngineError::Disabled(_))
|
||||
));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue