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(_))
|
||||
));
|
||||
}
|
||||
|
|
@ -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
339
crates/vcs/src/merge.rs
Normal 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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
248
crates/vcs/tests/merge.rs
Normal 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(_))
|
||||
));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue