PM: merge M4.8 merge conflicts with a three-pane resolve view
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
65907d925a
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(_))
|
||||
));
|
||||
}
|
||||
|
|
@ -697,6 +697,16 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
|||
- `crates/engine/tests/git_remote.rs`: 3 tests. Clone without a project, remotes, push with upstream and `gitChanged`, fetch and pull; cancel and the one-call rule; bad params.
|
||||
- `ui/tests/vcs/Remote.test.ts`: 11 Vitest tests.
|
||||
|
||||
### Merge conflicts (M4.8)
|
||||
|
||||
- **Backend (`crates/vcs/src/merge.rs`, an `impl Repo` append):** `merge(branch)` runs `git merge --no-edit --no-progress --end-of-options <branch>` (fast-forward when possible, hooks run, 120 s) under the mutation lock (`Repo::lock`, now `pub(crate)`); it refuses while `MERGE_HEAD` exists or the index has unmerged entries. A merge that stops on conflicts is not an error: the conflicted paths come from `ls-files -u -z`. Success compares HEAD before and after (merged or up to date); a failure without unmerged entries or `MERGE_HEAD` is git's refusal (local changes would be overwritten, unknown branch). `merge_abort()` is `git merge --abort`. `conflict_versions(path)` reads the stages `:1:` (base), `:2:` (ours), `:3:` (theirs) with one `cat-file --batch-check` and the blobs as stored, through M4.1's `decode` (binary, over 32 MiB, missing per side). `mark_resolved(paths)` is `stage` (`add -A`, so a file deleted on disk is staged as deleted). `merging()` and `unmerged()` are public. The `--batch-check` and `ls-files -u` parsers are property-tested.
|
||||
- **Commands (`crates/engine/src/cmd/git_merge.rs`, through `git::start_with`):** `git.merge {branch}` → `{result: "merged"|"upToDate"|"conflicts", conflicts: [path]}`; `git.mergeAbort` → `{}`; `git.conflictVersions {path}` → `{base?, ours: string|null, theirs: string|null, binary, tooLarge}` (`base` absent when the file was added on both sides, a side `null` when deleted there, all texts `null` when binary or too large); `git.markResolved {paths}` → `{}`. Merge, abort and mark resolved send `gitChanged`.
|
||||
- **Three-way line merge (`ui/src/components/vcs/merge/diff3.ts`):** texts become lines that keep their `\n`; each distinct line is encoded as one BMP character so `@codemirror/merge`'s character `diff` (2 s limit) gives line changes. The changes of ours and theirs against the base are grouped where they overlap or touch on the base (as git does): one side changed takes it, both changed alike takes it once, else a conflict. Without a base every difference of ours and theirs is a conflict. The result starts with every non-conflicting change applied and the base's lines in each conflict.
|
||||
- **Dialog (`MergeDialog.vue`, store `merge.ts`, editors `resolveView.ts`):** an exclusive modal. UI commands (menu Git, no default shortcuts): `vcs.merge {branch?}` lists the other branches with a filter (or merges the given one) after `flushDirty()`, toasts the outcome and opens the conflicts list on conflicts; `vcs.resolveConflicts {path?}` shows the conflicted files (from the shared status store) or one file's resolve view; `vcs.abortMerge` asks first, then runs `git.mergeAbort` (git's refusal stays in the dialog). The Changes window opens a conflicted row through `vcs.resolveConflicts {path}`. With no conflicts left the list offers Commit (`vcs.commit`).
|
||||
- **Resolve view:** three CodeMirror editors, ours (read-only), the result (editable), theirs (read-only), with the file's language. A state field maps each chunk's range in the result through edits; a chunk is open while its text is still the base's, taken from a side while it equals that side, edited otherwise, so undo reopens it without bookkeeping. » / « buttons in the side gutters accept a chunk; the toolbar has previous/next conflict (wrapping, scrolling all three), accept left/right for the current chunk, accept all left/right and a counter. Apply (enabled once no chunk is open) writes the result into the file's engine buffer (so its line ending, the journal and an open tab stay right), saves it and runs `git.markResolved`. A file deleted on one side offers to keep the other side's version; binary and too large files can only be marked resolved as they are on disk. Colours: `--lt-vcs-conflicted` for open chunks, `--lt-vcs-modified` for taken ones and non-conflicting changes. Escape closes, except in a changed resolve view.
|
||||
- **Not yet:** an "ignore" action, a compare menu, reverting a resolution, prefilling the commit message from `MERGE_MSG`, rebase and cherry-pick conflicts, synchronised scrolling.
|
||||
- **Tests:** `crates/vcs/tests/merge.rs` (5 against real temp repositories: clean merge, fast-forward, up to date, a content conflict with its versions, resolve and commit, add/add and modify/delete, abort, refusals); unit and property tests in `merge.rs`; `crates/engine/tests/git_merge.rs` (2: the command shapes, `gitChanged`, bad params, no project); Vitest `ui/tests/vcs/Merge.test.ts` (22: the merge on fixed and 300 random texts, layout, parsing, merging after `flushDirty`, the dialog's branches, list, resolve view, apply through the buffer, deleted and binary files, abort, the Changes entry point, registration).
|
||||
|
||||
## Decisions (M0)
|
||||
|
||||
| Question | Decision | Why |
|
||||
|
|
@ -716,6 +726,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
|||
|---|---|---|
|
||||
| 2026-10-28 | minor | M4.6: history backend (`git.log`, `git.showCommit`, `git.showAt`), the shared hook for new git commands, the Log tab, diffs at a commit |
|
||||
| 2026-10-28 | minor | M4.10: remotes (`Call::network` with progress and cancel, URL redaction, `git.fetch/pull/push/clone/cancel/remotes/remoteAdd/remoteSetUrl/remoteRemove`, `gitProgress`, `git.pull.mode`, the clone and remotes dialogs) |
|
||||
| 2026-10-28 | minor | M4.8: merge conflicts (`git.merge`, `git.mergeAbort`, `git.conflictVersions`, `git.markResolved`, the merge dialog with a three-pane resolve view) |
|
||||
| 2026-10-27 | minor | F3: `lutra_proc::spawn_suspended` (Phpactor) and `adopt` (ConPTY shell in a job), cancel superseded completions, syntax proptests compare leaf kinds |
|
||||
| 2026-10-27 | minor | C6 F1: remote branch checkout without a configured remote (`--no-track`), `git.lastMessage` and the Amend prefill, one shared git status store |
|
||||
| 2026-10-27 | minor | F2: `ui.screenshot` through WebView2 `CapturePreview` without focus; region fallback elsewhere; `--control` windows open unfocused |
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Gaps
|
||||
|
||||
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3; branch widget and popup, M4.5; remotes, M4.10); G14 English UI catalog in place · **Last updated:** 2026-10-26
|
||||
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3; branch widget and popup, M4.5; merge conflicts, M4.8; remotes, M4.10); G14 English UI catalog in place · **Last updated:** 2026-10-26
|
||||
|
||||
Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated.
|
||||
|
||||
|
|
@ -13,7 +13,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
|
|||
| G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h |
|
||||
| G6 | Language server: completion, definition, hover, rename via Phpactor (~~PHP detection and Phpactor download~~, M3.1; ~~engine wiring and diagnostics~~, M3.3; ~~completion, hover, signature help~~, M3.4; ~~definition, references, rename~~, M3.5) | M3 | ~15 h |
|
||||
| G7 | ~~Terminal~~ (M3.6: PTY sessions, xterm.js sub-tabs in the bottom panel; settings, persistence, links and search still open), ~~`lutra` CLI and single instance~~ (M3.7: open folders and files at a line, `--wait`, forwarding a second start, token-protected rendezvous), ~~MCP server~~ (M3.8: `lutra mcp` with list/execute every command, screenshot, read buffer, recent events, open buffers as resources; still missing: resource and tool change notifications, progress for long commands), files outside the open project (the CLI refuses them; needs out-of-project buffers or a second window), `lutra diff` | M3 | ~16 h |
|
||||
| G8 | Git integration: ~~backend through the installed git~~ (M4.1: status, stage/unstage, commit and amend, file contents at HEAD/index, branches, checkout, branch creation, `gitChanged`), ~~Changes window~~ (M4.2: staged/changes/untracked groups, stage and unstage per file and group, commit and amend after saving, amend prefilled with the last message (C6 F1), no chunk staging), ~~gutter markers and status colours~~ (M4.4: added/modified/deleted against the index, tree and tab colours; no chunk actions), ~~diff viewer~~ (M4.3: side by side against the index or HEAD, editable working copy, next/previous change; no unified view, chunk actions or other revisions), ~~branch popup~~ (M4.5: status-bar branch, popup with local and remote branches and a filter, checkout after saving, new branch from HEAD; no merge, rebase, rename or delete), ~~log~~ (M4.6: Log tab with graph lanes, filters, paging, commit details, diffs at a commit, file history; no date or branch filters, no actions on commits), ~~remotes~~ (M4.10: fetch, pull by merge or rebase, push with the upstream set on the first push, clone, manage remotes, progress and cancel, explained refusals, any HTTPS or SSH server through git's credential helper and the ssh agent; no force push, tags, per-branch push targets or hosting features such as pull requests), blame, conflicts, stash | M4 | ~122 h |
|
||||
| G8 | Git integration: ~~backend through the installed git~~ (M4.1: status, stage/unstage, commit and amend, file contents at HEAD/index, branches, checkout, branch creation, `gitChanged`), ~~Changes window~~ (M4.2: staged/changes/untracked groups, stage and unstage per file and group, commit and amend after saving, amend prefilled with the last message (C6 F1), no chunk staging), ~~gutter markers and status colours~~ (M4.4: added/modified/deleted against the index, tree and tab colours; no chunk actions), ~~diff viewer~~ (M4.3: side by side against the index or HEAD, editable working copy, next/previous change; no unified view, chunk actions or other revisions), ~~branch popup~~ (M4.5: status-bar branch, popup with local and remote branches and a filter, checkout after saving, new branch from HEAD; no merge, rebase, rename or delete), ~~log~~ (M4.6: Log tab with graph lanes, filters, paging, commit details, diffs at a commit, file history; no date or branch filters, no actions on commits), ~~remotes~~ (M4.10: fetch, pull by merge or rebase, push with the upstream set on the first push, clone, manage remotes, progress and cancel, explained refusals, any HTTPS or SSH server through git's credential helper and the ssh agent; no force push, tags, per-branch push targets or hosting features such as pull requests), blame, ~~conflicts~~ (M4.8: `git.merge`, conflicts list, three-pane resolve view with accept left/right per chunk, mark resolved, abort; no ignore action, compare menu or rebase conflicts), stash | M4 | ~122 h |
|
||||
| G9 | Debugger, test runner, Composer, run configurations | M5 | ~300 h |
|
||||
| G10 | Own indexer, type inference, inspections, refactorings | M6 | ~800 h |
|
||||
| G11 | Stability: crash-free operation on real projects and machines (~~recovery journal~~, M1.7) | ongoing | ~95 h |
|
||||
|
|
@ -57,6 +57,7 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin
|
|||
| 2026-10-28 | patch | G8: log and file history (M4.6) |
|
||||
| 2026-10-28 | minor | G8 shrunk: remotes (M4.10) |
|
||||
| 2026-10-27 | minor | G11 note: suspended Phpactor start, terminal shell in a job, completion cancel, syntax proptest (F3) |
|
||||
| 2026-10-28 | minor | G8 shrunk: merge conflicts (M4.8) |
|
||||
| 2026-10-27 | patch | G8: amend prefill, remote checkout fix, shared status store (C6 F1) |
|
||||
| 2026-10-27 | minor | Screenshot item shrunk: webview capture without focus on Windows (F2) |
|
||||
| 2026-10-26 | minor | G8 shrunk: branch widget and popup (M4.5) |
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, t
|
|||
| M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | done 2026-10-16 (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups, M1.8 command palette and keymap, M1.14 app icon, M1.9b settings dialog; C2 live checks pending, gaming mode) | ~5.6 (measured: C1 2.5, C2 3.1) |
|
||||
| M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | done 2026-10-17 (C3: M2.1 tree-sitter syntax, M2.2 highlighting + `editor.reveal`, M2.3 search backend, M2.4 Find tool window, M2.5 symbol index + go-to commands, M2.6 go-to popup, M2.7 Structure tool window) | ~6.1 (measured) |
|
||||
| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | done 2026-10-22 (C4: M3.1 PHP detection and Phpactor download, M3.2 LSP client, M3.3 engine wiring and diagnostics, M3.4 completion, hover and signature help, M3.5 definition, references and rename, M3.6 integrated terminal, M3.7 CLI and single instance, M3.8 MCP server, M3.9 app menu, M3.10 autosave; live check with real key presses pending) | ~14 (measured) |
|
||||
| M4 | Git: status, diff, commit, branches, log, blame, conflicts | in progress (C5: M4.1 backend, M4.2 Changes window, M4.4 gutter markers and status colours, M4.3 diff viewer, M4.5 branches done; C6: M4.6 log, M4.10 remotes done) | ~122 |
|
||||
| M4 | Git: status, diff, commit, branches, log, blame, conflicts | in progress (C5: M4.1 backend, M4.2 Changes window, M4.4 gutter markers and status colours, M4.3 diff viewer, M4.5 branches done; C6: M4.6 log, M4.8 merge conflicts, M4.10 remotes done) | ~122 |
|
||||
| M5 | Debugger (Xdebug via DAP), PHPUnit/Pest runner, Composer, run configurations | not started | ~300 |
|
||||
| M6 | Own indexer and inspections; Symfony, Laravel, Shopware, WordPress support | not started | ~1,100 |
|
||||
| M7 | Workbench and tools: Deployment (FTP/SFTP/local mappings, upload/download, compare with server, save before deploy, optional upload on save per server), Local History, diff tool (files/folders), scratch files, macros, keymap editor, user themes, plug-in system, Database tools and SQL, HTTP Client, SSH/Docker/Vagrant/WSL, File Watchers, external tools, TODO view, tasks and contexts | not started | ~900 |
|
||||
|
|
@ -36,6 +36,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati
|
|||
|---|---|---|
|
||||
| 2026-10-28 | minor | M4.6 log and file history |
|
||||
| 2026-10-28 | minor | M4.10 remotes (fetch, pull, push, clone, manage remotes) |
|
||||
| 2026-10-28 | minor | M4.8 merge conflicts |
|
||||
| 2026-10-26 | minor | M4.5 branch widget and popup |
|
||||
| 2026-10-26 | minor | M4.3 diff viewer |
|
||||
| 2026-10-25 | minor | M4.4 gutter markers and status colours |
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -10,6 +10,7 @@
|
|||
- M4.5 (2026-10-26): current branch in the status bar, switch to a local or remote branch (saving open files first, git's refusal shown) and create a branch from HEAD in the branches popup. Missing: merge, rebase, rename, delete, push/pull, log, blame, conflicts, stash.
|
||||
- M4.6 (2026-10-28): Log tab with graph lanes, message and author filters and lazy paging; commit details with each file's diff at that commit; history of a file from the tree, the editor or the menu. Missing: date and branch filters, actions on commits (cherry-pick, revert, reset, checkout), comparing two commits, blame, conflicts, stash, push/pull.
|
||||
- M4.10 (2026-10-28): fetch, pull (merge or rebase, setting `git.pull.mode`; open files saved first) and push (upstream set on the first push), each with progress and Cancel in the status bar and explained refusals; Clone Repository… from any HTTPS or SSH URL or a path, then the project opens; Manage Remotes… (list with redacted URLs, add, change URL, remove). Sign-in stays with git's credential helper (its own window is allowed) and the ssh agent; terminal prompts are off, so a missing credential fails with a message. Tested against local bare repositories only. Missing: force push, tags, pushing to another branch name, fetch/pull of one branch, prune options, hosting features (pull requests, issues), checked against a real GitHub/GitLab/Forgejo server.
|
||||
- M4.8 (2026-10-28): merge a branch into the current one (Git › Merge…), list the conflicted files, resolve each in a three-pane view (current branch / result / merged branch) with accept left or right per chunk and accept all, apply and mark resolved, abort the merge after a confirmation. Missing: an ignore action, comparing base/local/remote, reverting a resolution, rebase and cherry-pick conflicts, merge-message prefill.
|
||||
- [ ] Composer: install, update, require, scripts
|
||||
- [ ] PHP interpreters: local, Docker
|
||||
- [ ] Xdebug via DAP: breakpoints, stepping, variables, watches
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
* Root component: mounts the main window layout with the editor area; the
|
||||
* slogan shows while no tab is open, and the restore dialog for unsaved
|
||||
* texts from the recovery journal, the toast stack, the command palette,
|
||||
* the go-to popup and the settings dialog. Loads product information from the engine on
|
||||
* the go-to popup, the settings dialog and the merge dialog. Loads product information from the engine on
|
||||
* mount, starts showing notifications, following the theme (see
|
||||
* `theme.ts`; a failed theme report raises an error toast) and the global
|
||||
* keymap with the UI commands (see `commands/store.ts`), and loads the settings so the
|
||||
|
|
@ -21,6 +21,7 @@ import NavLayer from "./components/editor/nav/NavLayer.vue";
|
|||
import NotificationStack from "./components/notifications/NotificationStack.vue";
|
||||
import RecoveryDialog from "./components/recovery/RecoveryDialog.vue";
|
||||
import SettingsDialog from "./components/settings/SettingsDialog.vue";
|
||||
import MergeDialog from "./components/vcs/merge/MergeDialog.vue";
|
||||
import { useAppStore } from "./stores/app";
|
||||
import { useAutosaveStore } from "./stores/autosave";
|
||||
import { useNotificationsStore } from "./stores/notifications";
|
||||
|
|
@ -71,6 +72,7 @@ onUnmounted(() => {
|
|||
<CommandPalette />
|
||||
<GotoPopup />
|
||||
<SettingsDialog />
|
||||
<MergeDialog />
|
||||
<NavLayer />
|
||||
<NotificationStack />
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -19,7 +19,8 @@
|
|||
* command but `menu.open` closes it.
|
||||
* - **Navigation (M3.5):** the definition picker and the inline rename field
|
||||
* are exclusive modals too. So is the branches popup (M4.5), and so are
|
||||
* "Clone Repository…" and "Manage Remotes…" (M4.10).
|
||||
* "Clone Repository…" and "Manage Remotes…" (M4.10) and the merge
|
||||
* dialog (M4.8).
|
||||
*/
|
||||
import { defineStore } from "pinia";
|
||||
import { ref, watch } from "vue";
|
||||
|
|
@ -36,7 +37,8 @@ export type ModalId =
|
|||
| "rename"
|
||||
| "branches"
|
||||
| "clone"
|
||||
| "remotes";
|
||||
| "remotes"
|
||||
| "merge";
|
||||
|
||||
/** Store of the open exclusive modal. */
|
||||
export const useModalsStore = defineStore("modals", () => {
|
||||
|
|
|
|||
|
|
@ -42,6 +42,9 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
|
|||
{ id: "vcs.fetch", labelKey: "command.vcs.fetch", menuPath: "Git/Fetch" },
|
||||
{ id: "vcs.manageRemotes", labelKey: "command.vcs.manageRemotes", menuPath: "Git/Manage Remotes…" },
|
||||
{ id: "vcs.newBranch", labelKey: "command.vcs.newBranch", menuPath: "Git/New Branch…" },
|
||||
{ id: "vcs.merge", labelKey: "command.vcs.merge", menuPath: "Git/Merge…" },
|
||||
{ id: "vcs.resolveConflicts", labelKey: "command.vcs.resolveConflicts", menuPath: "Git/Resolve Conflicts…" },
|
||||
{ id: "vcs.abortMerge", labelKey: "command.vcs.abortMerge", menuPath: "Git/Abort Merge…" },
|
||||
{ id: "vcs.openChanges", labelKey: "command.vcs.openChanges", menuPath: "Git/Changes", defaultShortcut: "Mod+Alt+Shift+G" },
|
||||
{ id: "vcs.pull", labelKey: "command.vcs.pull", menuPath: "Git/Pull" },
|
||||
{ id: "vcs.push", labelKey: "command.vcs.push", menuPath: "Git/Push" },
|
||||
|
|
|
|||
|
|
@ -14,9 +14,11 @@
|
|||
* (`--lt-vcs-*`), its directory and its state. Up/Down, Page Up/Down,
|
||||
* Home and End move the selection, Space stages or unstages it, Enter or
|
||||
* a double-click opens it.
|
||||
* - **Opening:** through the UI command `vcs.showDiff {path, staged}` when
|
||||
* something provides it (the diff viewer, M4.3); until then the file
|
||||
* opens in the editor (`file.open`), unless it was deleted.
|
||||
* - **Opening:** a conflicted file through `vcs.resolveConflicts {path}`
|
||||
* (the merge dialog, M4.8); others through the UI command
|
||||
* `vcs.showDiff {path, staged}` when something provides it (the diff
|
||||
* viewer, M4.3); until then the file opens in the editor (`file.open`),
|
||||
* unless it was deleted.
|
||||
* - **Commit box:** the message, an Amend checkbox and Commit. Commit
|
||||
* saves dirty buffers first (`flushDirty`); `Mod+Enter` in the box
|
||||
* commits too.
|
||||
|
|
@ -204,12 +206,18 @@ function groupToggleLabel(group: GroupId): string {
|
|||
}
|
||||
|
||||
/**
|
||||
* Opens a row: the diff when `vcs.showDiff` is provided, else the file.
|
||||
* Opens a row: a conflicted file's resolve view when `vcs.resolveConflicts`
|
||||
* is provided (M4.8), else the diff when `vcs.showDiff` is provided, else
|
||||
* the file.
|
||||
*
|
||||
* @param row - the row.
|
||||
*/
|
||||
async function openRow(row: ChangeRow): Promise<void> {
|
||||
changes.select(row.key);
|
||||
if (row.state === "conflicted" && commands.isEnabled("vcs.resolveConflicts")) {
|
||||
await commands.execute("vcs.resolveConflicts", { path: row.file.path });
|
||||
return;
|
||||
}
|
||||
const staged = row.group === "staged";
|
||||
if (commands.isEnabled("vcs.showDiff")) {
|
||||
await commands.execute("vcs.showDiff", { path: row.file.path, staged });
|
||||
|
|
|
|||
917
ui/src/components/vcs/merge/MergeDialog.vue
Normal file
917
ui/src/components/vcs/merge/MergeDialog.vue
Normal file
|
|
@ -0,0 +1,917 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* The merge dialog (M4.8), an exclusive modal (`commands/modals.ts`).
|
||||
*
|
||||
* - **Merge** (`vcs.merge`): the branches other than the current one, with
|
||||
* a filter; choosing one merges it into the current branch.
|
||||
* - **Conflicts** (`vcs.resolveConflicts`): the conflicted files, each with
|
||||
* Resolve; Abort merge; with none left, a hint to commit and a Commit
|
||||
* button (`vcs.commit`).
|
||||
* - **Resolve** (`vcs.resolveConflicts {path}`, or Resolve in the list): three
|
||||
* editors, ours (the current branch) left, the result in the middle,
|
||||
* theirs right (`resolveView.ts`). Per chunk: the » / « buttons in the side
|
||||
* gutters, or Accept left / Accept right in the toolbar for the chunk
|
||||
* navigated to (Previous / Next conflict). Accept all left / right. Apply
|
||||
* (enabled once no chunk is open) writes the result and marks the file
|
||||
* resolved. Files deleted on one side offer the other side's version;
|
||||
* binary and too large files can only be marked resolved as they are.
|
||||
* - **Abort** (`vcs.abortMerge`, or Abort merge in the list): a confirmation
|
||||
* first; git's refusal shows in the dialog.
|
||||
* - **Keys:** Escape closes the dialog, except in the resolve view once the
|
||||
* result was changed (Back or Apply then); Tab stays inside. No default
|
||||
* shortcuts.
|
||||
*/
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { useModalsStore } from "../../../commands/modals";
|
||||
import { useCommandsStore } from "../../../commands/store";
|
||||
import { t } from "../../../i18n";
|
||||
import { useProjectStore } from "../../../stores/project";
|
||||
import { useVcsStatusStore } from "../../../stores/vcsStatus";
|
||||
import { ABORT_COMMAND, MERGE_COMMAND, RESOLVE_COMMAND, useMergeStore } from "./merge";
|
||||
import { ResolveView } from "./resolveView";
|
||||
|
||||
const merge = useMergeStore();
|
||||
const modals = useModalsStore();
|
||||
const commands = useCommandsStore();
|
||||
const project = useProjectStore();
|
||||
const status = useVcsStatusStore();
|
||||
|
||||
/** The dialog element. */
|
||||
const dialog = ref<HTMLElement | null>(null);
|
||||
/** The branch filter. */
|
||||
const filterInput = ref<HTMLInputElement | null>(null);
|
||||
/** Hosts of the three editors. */
|
||||
const oursHost = ref<HTMLElement | null>(null);
|
||||
const resultHost = ref<HTMLElement | null>(null);
|
||||
const theirsHost = ref<HTMLElement | null>(null);
|
||||
/** The branch filter text. */
|
||||
const filter = ref("");
|
||||
/** Chunks still open in the resolve view. */
|
||||
const open = ref(0);
|
||||
/** How many chunks the file has. */
|
||||
const total = ref(0);
|
||||
/** Whether the result was changed since it was built. */
|
||||
const changed = ref(false);
|
||||
/** The three editors, while the resolve view shows a text file. */
|
||||
let view: ResolveView | null = null;
|
||||
/** The element that had the focus before the dialog opened. */
|
||||
let returnFocus: HTMLElement | null = null;
|
||||
/** Withdraws the command handlers. */
|
||||
let withdraw: (() => void)[] = [];
|
||||
|
||||
/** Whether the dialog shows. */
|
||||
const visible = computed(() => merge.mode !== "closed");
|
||||
|
||||
/** Branches matching the filter (every word, ignoring case). */
|
||||
const shownBranches = computed(() => {
|
||||
const words = filter.value.toLowerCase().split(/\s+/).filter(Boolean);
|
||||
return merge.branches.filter((name) => words.every((word) => name.toLowerCase().includes(word)));
|
||||
});
|
||||
|
||||
/** The dialog's title. */
|
||||
const title = computed(() => {
|
||||
switch (merge.mode) {
|
||||
case "branches":
|
||||
return merge.currentBranch === null ? t("vcs.merge.titleMerge") : t("vcs.merge.titleMergeInto", { branch: merge.currentBranch });
|
||||
case "resolve":
|
||||
return t("vcs.merge.titleResolve", { path: merge.path ?? "" });
|
||||
case "abort":
|
||||
return t("vcs.merge.titleAbort");
|
||||
default:
|
||||
return t("vcs.merge.titleConflicts");
|
||||
}
|
||||
});
|
||||
|
||||
/** The ours column's caption. */
|
||||
const oursCaption = computed(() =>
|
||||
merge.currentBranch === null ? t("vcs.merge.ours") : t("vcs.merge.oursBranch", { branch: merge.currentBranch }),
|
||||
);
|
||||
|
||||
/** The line about a file deleted on one side. */
|
||||
const deletedNotice = computed(() => {
|
||||
const v = merge.versions;
|
||||
if (!v) {
|
||||
return "";
|
||||
}
|
||||
return v.ours === null ? t("vcs.merge.deletedOurs") : t("vcs.merge.deletedTheirs");
|
||||
});
|
||||
|
||||
/** The counter of the resolve toolbar. */
|
||||
const counter = computed(() =>
|
||||
open.value === 0 ? t("vcs.merge.allResolved") : t("vcs.merge.openCount", { open: String(open.value), total: String(total.value) }),
|
||||
);
|
||||
|
||||
/** Destroys the editors. */
|
||||
function destroyView(): void {
|
||||
view?.destroy();
|
||||
view = null;
|
||||
open.value = 0;
|
||||
total.value = 0;
|
||||
changed.value = false;
|
||||
}
|
||||
|
||||
/** Builds the editors for the loaded text file. */
|
||||
function buildView(): void {
|
||||
destroyView();
|
||||
const v = merge.versions;
|
||||
if (merge.mode !== "resolve" || merge.phase !== "text" || !v || v.ours === null || v.theirs === null) {
|
||||
return;
|
||||
}
|
||||
if (!oursHost.value || !resultHost.value || !theirsHost.value || merge.path === null) {
|
||||
return;
|
||||
}
|
||||
view = new ResolveView({
|
||||
path: merge.path,
|
||||
base: v.base,
|
||||
ours: v.ours,
|
||||
theirs: v.theirs,
|
||||
oursHost: oursHost.value,
|
||||
resultHost: resultHost.value,
|
||||
theirsHost: theirsHost.value,
|
||||
labels: { acceptOurs: t("vcs.merge.acceptLeft"), acceptTheirs: t("vcs.merge.acceptRight") },
|
||||
onChange: (count) => {
|
||||
open.value = count;
|
||||
changed.value = true;
|
||||
},
|
||||
});
|
||||
total.value = view.layout.chunks.length;
|
||||
open.value = view.open;
|
||||
view.go(1);
|
||||
}
|
||||
|
||||
/** Closes the dialog and gives the focus back. */
|
||||
function close(): void {
|
||||
if (merge.mode === "closed") {
|
||||
return;
|
||||
}
|
||||
destroyView();
|
||||
merge.close();
|
||||
}
|
||||
|
||||
watch(
|
||||
() => merge.mode !== "closed",
|
||||
async (shown) => {
|
||||
if (shown) {
|
||||
const active = document.activeElement;
|
||||
returnFocus = active instanceof HTMLElement && !dialog.value?.contains(active) ? active : returnFocus;
|
||||
modals.opened("merge", close);
|
||||
await nextTick();
|
||||
focusFirst();
|
||||
} else {
|
||||
destroyView();
|
||||
modals.closed("merge");
|
||||
returnFocus?.focus();
|
||||
returnFocus = null;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
watch(
|
||||
() => [merge.mode, merge.phase, merge.versions, merge.path] as const,
|
||||
async () => {
|
||||
await nextTick();
|
||||
buildView();
|
||||
focusFirst();
|
||||
},
|
||||
);
|
||||
|
||||
/** Focuses the first useful element of the current mode. */
|
||||
function focusFirst(): void {
|
||||
if (merge.mode === "branches") {
|
||||
filterInput.value?.focus();
|
||||
return;
|
||||
}
|
||||
if (view) {
|
||||
view.resultView.focus();
|
||||
return;
|
||||
}
|
||||
dialog.value?.querySelector<HTMLElement>("button:not(:disabled)")?.focus();
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges a branch from the list.
|
||||
*
|
||||
* @param branch - its name.
|
||||
*/
|
||||
async function mergeBranch(branch: string): Promise<void> {
|
||||
filter.value = "";
|
||||
await merge.merge(branch);
|
||||
}
|
||||
|
||||
/** Merges the first branch matching the filter (Enter in the filter). */
|
||||
async function mergeFirst(): Promise<void> {
|
||||
const first = shownBranches.value[0];
|
||||
if (first !== undefined) {
|
||||
await mergeBranch(first);
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes the result and marks the file resolved. */
|
||||
async function apply(): Promise<void> {
|
||||
if (!view || merge.path === null || open.value > 0) {
|
||||
return;
|
||||
}
|
||||
const ok = await merge.resolve(merge.path, view.result);
|
||||
if (ok) {
|
||||
destroyView();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps one side's whole file (one side deleted it).
|
||||
*
|
||||
* @param side - the side to keep.
|
||||
*/
|
||||
async function keep(side: "ours" | "theirs"): Promise<void> {
|
||||
const v = merge.versions;
|
||||
const text = side === "ours" ? v?.ours : v?.theirs;
|
||||
if (merge.path === null || text === null || text === undefined) {
|
||||
return;
|
||||
}
|
||||
await merge.resolve(merge.path, text);
|
||||
}
|
||||
|
||||
/** Marks the file resolved as it is on disk. */
|
||||
async function markAsIs(): Promise<void> {
|
||||
if (merge.path !== null) {
|
||||
await merge.resolve(merge.path, null);
|
||||
}
|
||||
}
|
||||
|
||||
/** Goes back from the resolve view to the list. */
|
||||
function back(): void {
|
||||
destroyView();
|
||||
merge.showConflicts();
|
||||
}
|
||||
|
||||
/** Runs `vcs.commit` to conclude the merge. */
|
||||
async function commit(): Promise<void> {
|
||||
close();
|
||||
await commands.execute("vcs.commit", {});
|
||||
}
|
||||
|
||||
/** The elements Tab reaches inside the dialog, in order. */
|
||||
function focusables(): HTMLElement[] {
|
||||
const root = dialog.value;
|
||||
if (!root) {
|
||||
return [];
|
||||
}
|
||||
return [...root.querySelectorAll<HTMLElement>("button:not(:disabled), input, .cm-content[contenteditable=true]")];
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape and the Tab cycle.
|
||||
*
|
||||
* @param event - the key event.
|
||||
*/
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (merge.mode === "resolve" && changed.value) {
|
||||
return;
|
||||
}
|
||||
close();
|
||||
return;
|
||||
}
|
||||
if (event.key !== "Tab") {
|
||||
return;
|
||||
}
|
||||
const list = focusables();
|
||||
const first = list[0];
|
||||
const last = list.at(-1);
|
||||
if (!first || !last) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
const active = document.activeElement;
|
||||
const inside = active instanceof HTMLElement && list.some((el) => el === active || el.contains(active));
|
||||
if (event.shiftKey && (active === first || !inside)) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
} else if (!event.shiftKey && (active === last || !inside)) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
const inRepo = (): boolean => project.root !== null && status.repo;
|
||||
withdraw = [
|
||||
commands.provide(MERGE_COMMAND, { run: (params) => merge.mergeCommand(params), enabled: inRepo }),
|
||||
commands.provide(RESOLVE_COMMAND, { run: (params) => merge.resolveCommand(params), enabled: inRepo }),
|
||||
commands.provide(ABORT_COMMAND, {
|
||||
run: () => {
|
||||
merge.askAbort();
|
||||
},
|
||||
enabled: inRepo,
|
||||
}),
|
||||
];
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
for (const undo of withdraw) {
|
||||
undo();
|
||||
}
|
||||
withdraw = [];
|
||||
destroyView();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="visible"
|
||||
class="merge"
|
||||
data-test="merge"
|
||||
@mousedown.self.prevent="merge.mode === 'resolve' && changed ? undefined : close()"
|
||||
>
|
||||
<div
|
||||
ref="dialog"
|
||||
class="merge__dialog"
|
||||
:class="{ 'merge__dialog--wide': merge.mode === 'resolve' }"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="lt-merge-title"
|
||||
data-test="merge-dialog"
|
||||
@keydown="onKeydown"
|
||||
>
|
||||
<header class="merge__header">
|
||||
<h2
|
||||
id="lt-merge-title"
|
||||
class="merge__title"
|
||||
data-test="merge-title"
|
||||
>
|
||||
{{ title }}
|
||||
</h2>
|
||||
</header>
|
||||
|
||||
<section
|
||||
v-if="merge.mode === 'branches'"
|
||||
class="merge__body"
|
||||
>
|
||||
<input
|
||||
ref="filterInput"
|
||||
v-model="filter"
|
||||
class="merge__filter"
|
||||
type="search"
|
||||
spellcheck="false"
|
||||
:aria-label="t('vcs.merge.filter')"
|
||||
:placeholder="t('vcs.merge.filter')"
|
||||
data-test="merge-filter"
|
||||
@keydown.enter.prevent="mergeFirst()"
|
||||
>
|
||||
<p
|
||||
v-if="merge.branchesError !== null"
|
||||
class="merge__error"
|
||||
>
|
||||
{{ t("vcs.branches.loadFailed", { reason: merge.branchesError }) }}
|
||||
</p>
|
||||
<p
|
||||
v-else-if="shownBranches.length === 0"
|
||||
class="merge__hint"
|
||||
>
|
||||
{{ t("vcs.merge.noBranches") }}
|
||||
</p>
|
||||
<ul
|
||||
class="merge__list"
|
||||
:aria-label="t('vcs.merge.branchesLabel')"
|
||||
>
|
||||
<li
|
||||
v-for="name in shownBranches"
|
||||
:key="name"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="merge__row"
|
||||
:disabled="merge.busy"
|
||||
data-test="merge-branch"
|
||||
:data-branch="name"
|
||||
@click="mergeBranch(name)"
|
||||
>
|
||||
{{ name }}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-else-if="merge.mode === 'conflicts'"
|
||||
class="merge__body"
|
||||
>
|
||||
<template v-if="merge.conflicts.length > 0">
|
||||
<p class="merge__hint">
|
||||
{{ t("vcs.merge.conflictsHint") }}
|
||||
</p>
|
||||
<ul
|
||||
class="merge__list"
|
||||
:aria-label="t('vcs.merge.conflictsLabel')"
|
||||
>
|
||||
<li
|
||||
v-for="file in merge.conflicts"
|
||||
:key="file"
|
||||
class="merge__file"
|
||||
data-test="merge-conflict"
|
||||
:data-path="file"
|
||||
@dblclick="merge.openFile(file)"
|
||||
>
|
||||
<span class="merge__path">{{ file }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button"
|
||||
data-test="merge-resolve"
|
||||
:aria-label="t('vcs.merge.resolveFile', { path: file })"
|
||||
@click="merge.openFile(file)"
|
||||
>
|
||||
{{ t("vcs.merge.resolve") }}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
<template v-else>
|
||||
<p
|
||||
class="merge__hint"
|
||||
data-test="merge-none"
|
||||
>
|
||||
{{ t("vcs.merge.noConflicts") }}
|
||||
</p>
|
||||
</template>
|
||||
<p
|
||||
v-if="merge.error !== null"
|
||||
class="merge__error"
|
||||
>
|
||||
{{ merge.error }}
|
||||
</p>
|
||||
<footer class="merge__footer">
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button"
|
||||
data-test="merge-ask-abort"
|
||||
@click="merge.askAbort()"
|
||||
>
|
||||
{{ t("vcs.merge.abort") }}
|
||||
</button>
|
||||
<button
|
||||
v-if="merge.conflicts.length === 0"
|
||||
type="button"
|
||||
class="merge__button merge__button--primary"
|
||||
data-test="merge-commit"
|
||||
@click="commit()"
|
||||
>
|
||||
{{ t("vcs.merge.commit") }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button"
|
||||
data-test="merge-close"
|
||||
@click="close()"
|
||||
>
|
||||
{{ t("vcs.merge.close") }}
|
||||
</button>
|
||||
</footer>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-else-if="merge.mode === 'abort'"
|
||||
class="merge__body"
|
||||
>
|
||||
<p class="merge__hint">
|
||||
{{ t("vcs.merge.abortQuestion") }}
|
||||
</p>
|
||||
<p
|
||||
v-if="merge.error !== null"
|
||||
class="merge__error"
|
||||
data-test="merge-error"
|
||||
>
|
||||
{{ merge.error }}
|
||||
</p>
|
||||
<footer class="merge__footer">
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button merge__button--danger"
|
||||
:disabled="merge.busy"
|
||||
data-test="merge-abort"
|
||||
@click="merge.abort()"
|
||||
>
|
||||
{{ t("vcs.merge.abortConfirm") }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button"
|
||||
data-test="merge-abort-cancel"
|
||||
@click="merge.showConflicts()"
|
||||
>
|
||||
{{ t("vcs.merge.keep") }}
|
||||
</button>
|
||||
</footer>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-else
|
||||
class="merge__body merge__body--resolve"
|
||||
>
|
||||
<p
|
||||
v-if="merge.phase === 'loading'"
|
||||
class="merge__hint"
|
||||
>
|
||||
{{ t("vcs.merge.loading") }}
|
||||
</p>
|
||||
<p
|
||||
v-else-if="merge.phase === 'error'"
|
||||
class="merge__error"
|
||||
data-test="merge-error"
|
||||
>
|
||||
{{ t("vcs.merge.loadFailed", { reason: merge.error ?? "" }) }}
|
||||
</p>
|
||||
<template v-else-if="merge.phase === 'deleted'">
|
||||
<p
|
||||
class="merge__hint"
|
||||
data-test="merge-deleted"
|
||||
>
|
||||
{{ deletedNotice }}
|
||||
</p>
|
||||
<footer class="merge__footer">
|
||||
<button
|
||||
v-if="merge.versions?.ours !== null"
|
||||
type="button"
|
||||
class="merge__button"
|
||||
:disabled="merge.busy"
|
||||
data-test="merge-keep-ours"
|
||||
@click="keep('ours')"
|
||||
>
|
||||
{{ t("vcs.merge.keepOurs") }}
|
||||
</button>
|
||||
<button
|
||||
v-if="merge.versions?.theirs !== null"
|
||||
type="button"
|
||||
class="merge__button"
|
||||
:disabled="merge.busy"
|
||||
data-test="merge-keep-theirs"
|
||||
@click="keep('theirs')"
|
||||
>
|
||||
{{ t("vcs.merge.keepTheirs") }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button"
|
||||
:disabled="merge.busy"
|
||||
data-test="merge-mark-as-is"
|
||||
@click="markAsIs()"
|
||||
>
|
||||
{{ t("vcs.merge.markAsIs") }}
|
||||
</button>
|
||||
</footer>
|
||||
</template>
|
||||
<template v-else-if="merge.phase === 'binary' || merge.phase === 'tooLarge'">
|
||||
<p
|
||||
class="merge__hint"
|
||||
data-test="merge-binary"
|
||||
>
|
||||
{{ merge.phase === "binary" ? t("vcs.merge.binary") : t("vcs.merge.tooLarge") }}
|
||||
</p>
|
||||
<footer class="merge__footer">
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button"
|
||||
:disabled="merge.busy"
|
||||
data-test="merge-mark-as-is"
|
||||
@click="markAsIs()"
|
||||
>
|
||||
{{ t("vcs.merge.markAsIs") }}
|
||||
</button>
|
||||
</footer>
|
||||
</template>
|
||||
<template v-if="merge.phase === 'text'">
|
||||
<div
|
||||
class="merge__toolbar"
|
||||
role="toolbar"
|
||||
:aria-label="t('vcs.merge.toolbar')"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button"
|
||||
:disabled="open === 0"
|
||||
data-test="merge-previous"
|
||||
@click="view?.go(-1)"
|
||||
>
|
||||
{{ t("vcs.merge.previous") }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button"
|
||||
:disabled="open === 0"
|
||||
data-test="merge-next"
|
||||
@click="view?.go(1)"
|
||||
>
|
||||
{{ t("vcs.merge.next") }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button"
|
||||
:disabled="open === 0"
|
||||
data-test="merge-accept-left"
|
||||
@click="view?.acceptCurrent('ours')"
|
||||
>
|
||||
{{ t("vcs.merge.acceptLeft") }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button"
|
||||
:disabled="open === 0"
|
||||
data-test="merge-accept-right"
|
||||
@click="view?.acceptCurrent('theirs')"
|
||||
>
|
||||
{{ t("vcs.merge.acceptRight") }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button"
|
||||
:disabled="open === 0"
|
||||
data-test="merge-all-left"
|
||||
@click="view?.acceptAll('ours')"
|
||||
>
|
||||
{{ t("vcs.merge.allLeft") }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button"
|
||||
:disabled="open === 0"
|
||||
data-test="merge-all-right"
|
||||
@click="view?.acceptAll('theirs')"
|
||||
>
|
||||
{{ t("vcs.merge.allRight") }}
|
||||
</button>
|
||||
<span
|
||||
class="merge__counter"
|
||||
role="status"
|
||||
data-test="merge-counter"
|
||||
>{{ counter }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button merge__button--primary"
|
||||
:disabled="open > 0 || merge.busy"
|
||||
:title="open > 0 ? t('vcs.merge.applyHint') : undefined"
|
||||
data-test="merge-apply"
|
||||
@click="apply()"
|
||||
>
|
||||
{{ t("vcs.merge.apply") }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button"
|
||||
data-test="merge-back"
|
||||
@click="back()"
|
||||
>
|
||||
{{ t("vcs.merge.back") }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
<div
|
||||
v-show="merge.phase === 'text'"
|
||||
class="merge__panes"
|
||||
>
|
||||
<div class="merge__pane">
|
||||
<span class="merge__caption">{{ oursCaption }}</span>
|
||||
<div
|
||||
ref="oursHost"
|
||||
class="merge__editor"
|
||||
data-test="merge-ours"
|
||||
/>
|
||||
</div>
|
||||
<div class="merge__pane">
|
||||
<span class="merge__caption">{{ t("vcs.merge.result") }}</span>
|
||||
<div
|
||||
ref="resultHost"
|
||||
class="merge__editor"
|
||||
data-test="merge-result"
|
||||
/>
|
||||
</div>
|
||||
<div class="merge__pane">
|
||||
<span class="merge__caption">{{ t("vcs.merge.theirs") }}</span>
|
||||
<div
|
||||
ref="theirsHost"
|
||||
class="merge__editor"
|
||||
data-test="merge-theirs"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p
|
||||
v-if="merge.error !== null && merge.phase !== 'error'"
|
||||
class="merge__error"
|
||||
data-test="merge-error"
|
||||
>
|
||||
{{ merge.error }}
|
||||
</p>
|
||||
<footer
|
||||
v-if="merge.phase !== 'text'"
|
||||
class="merge__footer"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="merge__button"
|
||||
data-test="merge-back"
|
||||
@click="back()"
|
||||
>
|
||||
{{ t("vcs.merge.back") }}
|
||||
</button>
|
||||
</footer>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.merge {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: color-mix(in srgb, var(--lt-bg) 40%, transparent);
|
||||
z-index: 30;
|
||||
}
|
||||
|
||||
.merge__dialog {
|
||||
width: min(560px, 92vw);
|
||||
max-height: 84vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--lt-bg);
|
||||
color: var(--lt-fg);
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.merge__dialog--wide {
|
||||
width: 96vw;
|
||||
height: 90vh;
|
||||
max-height: none;
|
||||
}
|
||||
|
||||
.merge__header {
|
||||
padding: var(--lt-space-s, 8px) var(--lt-space-m, 12px);
|
||||
border-bottom: 1px solid var(--lt-border);
|
||||
}
|
||||
|
||||
.merge__title {
|
||||
margin: 0;
|
||||
font-size: var(--lt-font-size-ui);
|
||||
font-weight: 600;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.merge__body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--lt-space-s, 8px);
|
||||
padding: var(--lt-space-m, 12px);
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.merge__body--resolve {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.merge__filter {
|
||||
padding: var(--lt-space-xs, 2px) var(--lt-space-s, 8px);
|
||||
color: var(--lt-fg);
|
||||
background: var(--lt-editor-bg);
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: var(--lt-radius, 4px);
|
||||
}
|
||||
|
||||
.merge__list {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
overflow: auto;
|
||||
max-height: 50vh;
|
||||
}
|
||||
|
||||
.merge__row {
|
||||
width: 100%;
|
||||
padding: var(--lt-space-xs, 2px) var(--lt-space-s, 8px);
|
||||
text-align: left;
|
||||
color: var(--lt-fg);
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: var(--lt-radius, 4px);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.merge__row:hover,
|
||||
.merge__row:focus-visible {
|
||||
background: var(--lt-editor-selection-bg);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.merge__file {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--lt-space-s, 8px);
|
||||
padding: var(--lt-space-xs, 2px) 0;
|
||||
}
|
||||
|
||||
.merge__path {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--lt-vcs-conflicted);
|
||||
}
|
||||
|
||||
.merge__hint {
|
||||
margin: 0;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.merge__error {
|
||||
margin: 0;
|
||||
color: var(--lt-error);
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.merge__toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--lt-space-xs, 4px);
|
||||
}
|
||||
|
||||
.merge__counter {
|
||||
margin-left: auto;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.merge__panes {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr 1fr;
|
||||
gap: var(--lt-space-xs, 4px);
|
||||
}
|
||||
|
||||
.merge__pane {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.merge__caption {
|
||||
padding: var(--lt-space-xs, 2px) 0;
|
||||
color: var(--lt-fg-muted);
|
||||
font-size: var(--lt-font-size-small);
|
||||
}
|
||||
|
||||
.merge__editor {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--lt-border);
|
||||
background: var(--lt-editor-bg);
|
||||
}
|
||||
|
||||
.merge__editor :deep(.cm-editor) {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.merge__footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: var(--lt-space-s, 8px);
|
||||
}
|
||||
|
||||
.merge__button {
|
||||
padding: var(--lt-space-xs, 2px) var(--lt-space-m, 12px);
|
||||
color: var(--lt-fg);
|
||||
background: transparent;
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: var(--lt-radius, 4px);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.merge__button--primary {
|
||||
background: color-mix(in srgb, var(--lt-accent) 18%, transparent);
|
||||
border-color: var(--lt-accent);
|
||||
}
|
||||
|
||||
.merge__button--danger {
|
||||
border-color: var(--lt-error);
|
||||
}
|
||||
|
||||
.merge__button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.merge__button:focus-visible,
|
||||
.merge__filter:focus-visible {
|
||||
outline: 2px solid var(--lt-accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
</style>
|
||||
276
ui/src/components/vcs/merge/diff3.ts
Normal file
276
ui/src/components/vcs/merge/diff3.ts
Normal file
|
|
@ -0,0 +1,276 @@
|
|||
/**
|
||||
* The three-way line merge of the resolve view (M4.8).
|
||||
*
|
||||
* - **Units:** texts are split into lines that keep their `\n`
|
||||
* ({@link splitUnits}), so joining units gives the text back and a block
|
||||
* inserted at a unit boundary carries its own line breaks. Line breaks
|
||||
* are normalised to `\n` before (git returns blobs as stored).
|
||||
* - **Line diff:** every distinct line becomes one character of the Basic
|
||||
* Multilingual Plane outside the surrogates, and `@codemirror/merge`'s
|
||||
* character `diff` (with a time limit) compares the two strings; so a
|
||||
* change is a run of whole lines. Texts with more distinct lines than
|
||||
* there are such characters fall back to one change covering both.
|
||||
* - **Merge ({@link merge3}):** the changes of ours and of theirs against
|
||||
* the base are grouped where they overlap or touch on the base (as git
|
||||
* does). A group changed on one side takes that side; one changed alike
|
||||
* on both takes it once; otherwise it is a conflict. Without a base (a
|
||||
* file added on both sides) ours and theirs are compared directly, and
|
||||
* every difference is a conflict ({@link merge2}).
|
||||
* - **Result:** {@link initialResult} applies every non-conflicting change
|
||||
* and keeps the base's lines in each conflict, so the result starts like
|
||||
* git's merge without the markers.
|
||||
*/
|
||||
import { diff } from "@codemirror/merge";
|
||||
|
||||
/** What a block of the merge is. */
|
||||
export type BlockKind = "stable" | "ours" | "theirs" | "both" | "conflict";
|
||||
|
||||
/** One block of a three-way merge, as units (lines with their `\n`). */
|
||||
export interface MergeBlock {
|
||||
/** What it is. */
|
||||
kind: BlockKind;
|
||||
/** The base's units. */
|
||||
base: string[];
|
||||
/** Our units (the current branch). */
|
||||
ours: string[];
|
||||
/** Their units (the merged branch). */
|
||||
theirs: string[];
|
||||
}
|
||||
|
||||
/** A change between two unit lists: `[fromA, toA)` became `[fromB, toB)`. */
|
||||
export interface UnitChange {
|
||||
/** Start in the first list. */
|
||||
fromA: number;
|
||||
/** End in the first list. */
|
||||
toA: number;
|
||||
/** Start in the second list. */
|
||||
fromB: number;
|
||||
/** End in the second list. */
|
||||
toB: number;
|
||||
}
|
||||
|
||||
/** Time limit of one line diff, in milliseconds. */
|
||||
const DIFF_TIMEOUT = 2000;
|
||||
|
||||
/** First code unit used to encode lines (after the C0/C1 controls and Latin-1). */
|
||||
const CODE_START = 0x100;
|
||||
|
||||
/** How many lines can be encoded: the BMP above {@link CODE_START} without the surrogates. */
|
||||
const CODE_COUNT = 0xd800 - CODE_START + (0x10000 - 0xe000);
|
||||
|
||||
/**
|
||||
* Turns every line break into `\n`.
|
||||
*
|
||||
* @param text - text with any mix of `\r\n`, `\r` and `\n`.
|
||||
*/
|
||||
export function normaliseEol(text: string): string {
|
||||
return text.replace(/\r\n?/g, "\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a text into lines that keep their `\n`; the last one lacks it when
|
||||
* the text does not end in a line break.
|
||||
*
|
||||
* @param text - text with `\n` breaks.
|
||||
*/
|
||||
export function splitUnits(text: string): string[] {
|
||||
return text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* The code unit of the `index`th distinct line.
|
||||
*
|
||||
* @param index - below {@link CODE_COUNT}.
|
||||
*/
|
||||
function codeOf(index: number): string {
|
||||
const code = CODE_START + index;
|
||||
return String.fromCharCode(code < 0xd800 ? code : code + (0xe000 - 0xd800));
|
||||
}
|
||||
|
||||
/**
|
||||
* The changes from one unit list to another.
|
||||
*
|
||||
* @param a - the first list.
|
||||
* @param b - the second list.
|
||||
* @returns changes in order, each a run of whole units.
|
||||
*/
|
||||
export function diffUnits(a: readonly string[], b: readonly string[]): UnitChange[] {
|
||||
const codes = new Map<string, string>();
|
||||
const encode = (units: readonly string[]): string | null => {
|
||||
let out = "";
|
||||
for (const unit of units) {
|
||||
let code = codes.get(unit);
|
||||
if (code === undefined) {
|
||||
if (codes.size >= CODE_COUNT) {
|
||||
return null;
|
||||
}
|
||||
code = codeOf(codes.size);
|
||||
codes.set(unit, code);
|
||||
}
|
||||
out += code;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
const left = encode(a);
|
||||
const right = encode(b);
|
||||
if (left === null || right === null) {
|
||||
return a.length === 0 && b.length === 0 ? [] : [{ fromA: 0, toA: a.length, fromB: 0, toB: b.length }];
|
||||
}
|
||||
return diff(left, right, { timeout: DIFF_TIMEOUT }).map((c) => ({ fromA: c.fromA, toA: c.toA, fromB: c.fromB, toB: c.toB }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether two unit lists are equal.
|
||||
*
|
||||
* @param a - one list.
|
||||
* @param b - the other.
|
||||
*/
|
||||
function same(a: readonly string[], b: readonly string[]): boolean {
|
||||
return a.length === b.length && a.every((unit, i) => unit === b[i]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pushes a block, merging stable runs.
|
||||
*
|
||||
* @param blocks - the blocks so far.
|
||||
* @param block - the next block; empty stable blocks are dropped.
|
||||
*/
|
||||
function push(blocks: MergeBlock[], block: MergeBlock): void {
|
||||
const last = blocks[blocks.length - 1];
|
||||
if (block.kind === "stable") {
|
||||
if (block.base.length === 0) {
|
||||
return;
|
||||
}
|
||||
if (last?.kind === "stable") {
|
||||
last.base.push(...block.base);
|
||||
last.ours.push(...block.ours);
|
||||
last.theirs.push(...block.theirs);
|
||||
return;
|
||||
}
|
||||
}
|
||||
blocks.push(block);
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges ours and theirs without a base: equal runs are stable, every
|
||||
* difference is a conflict with an empty base.
|
||||
*
|
||||
* @param ours - our units.
|
||||
* @param theirs - their units.
|
||||
*/
|
||||
export function merge2(ours: readonly string[], theirs: readonly string[]): MergeBlock[] {
|
||||
const blocks: MergeBlock[] = [];
|
||||
let a = 0;
|
||||
let b = 0;
|
||||
for (const change of diffUnits(ours, theirs)) {
|
||||
const stable = ours.slice(a, change.fromA);
|
||||
push(blocks, { kind: "stable", base: stable, ours: [...stable], theirs: [...stable] });
|
||||
push(blocks, {
|
||||
kind: "conflict",
|
||||
base: [],
|
||||
ours: ours.slice(change.fromA, change.toA),
|
||||
theirs: theirs.slice(change.fromB, change.toB),
|
||||
});
|
||||
a = change.toA;
|
||||
b = change.toB;
|
||||
}
|
||||
const rest = ours.slice(a);
|
||||
push(blocks, { kind: "stable", base: rest, ours: [...rest], theirs: theirs.slice(b) });
|
||||
return blocks;
|
||||
}
|
||||
|
||||
/** A change of one side against the base, tagged with its side. */
|
||||
interface SideChange extends UnitChange {
|
||||
/** 0 for ours, 1 for theirs. */
|
||||
side: 0 | 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges ours and theirs against their common base.
|
||||
*
|
||||
* @param base - the base's units; null when there is none (added on both
|
||||
* sides), see {@link merge2}.
|
||||
* @param ours - our units.
|
||||
* @param theirs - their units.
|
||||
* @returns the blocks in order; joining one side's units of every block
|
||||
* gives that side's text.
|
||||
*/
|
||||
export function merge3(base: readonly string[] | null, ours: readonly string[], theirs: readonly string[]): MergeBlock[] {
|
||||
if (base === null) {
|
||||
return merge2(ours, theirs);
|
||||
}
|
||||
const changes: SideChange[] = [
|
||||
...diffUnits(base, ours).map((c) => ({ ...c, side: 0 as const })),
|
||||
...diffUnits(base, theirs).map((c) => ({ ...c, side: 1 as const })),
|
||||
].sort((x, y) => x.fromA - y.fromA || x.toA - y.toA);
|
||||
const blocks: MergeBlock[] = [];
|
||||
const sides = [ours, theirs] as const;
|
||||
const delta = [0, 0];
|
||||
let at = 0;
|
||||
let i = 0;
|
||||
while (i < changes.length) {
|
||||
const first = changes[i];
|
||||
if (!first) {
|
||||
break;
|
||||
}
|
||||
const group: SideChange[] = [first];
|
||||
let lo = first.fromA;
|
||||
let hi = first.toA;
|
||||
i += 1;
|
||||
for (let next = changes[i]; next && next.fromA <= hi; next = changes[i]) {
|
||||
group.push(next);
|
||||
lo = Math.min(lo, next.fromA);
|
||||
hi = Math.max(hi, next.toA);
|
||||
i += 1;
|
||||
}
|
||||
const stable = base.slice(at, lo);
|
||||
push(blocks, { kind: "stable", base: stable, ours: [...stable], theirs: [...stable] });
|
||||
const ranges = ([0, 1] as const).map((side) => {
|
||||
const own = group.filter((c) => c.side === side);
|
||||
const firstOwn = own[0];
|
||||
const lastOwn = own[own.length - 1];
|
||||
const from = firstOwn ? firstOwn.fromB - (firstOwn.fromA - lo) : lo + (delta[side] ?? 0);
|
||||
const to = lastOwn ? lastOwn.toB + (hi - lastOwn.toA) : hi + (delta[side] ?? 0);
|
||||
delta[side] = to - hi;
|
||||
return { changed: own.length > 0, units: sides[side].slice(from, to) };
|
||||
});
|
||||
const [mine, yours] = ranges;
|
||||
if (!mine || !yours) {
|
||||
break;
|
||||
}
|
||||
const kind: BlockKind =
|
||||
mine.changed && yours.changed ? (same(mine.units, yours.units) ? "both" : "conflict") : mine.changed ? "ours" : "theirs";
|
||||
blocks.push({ kind, base: base.slice(lo, hi), ours: mine.units, theirs: yours.units });
|
||||
at = hi;
|
||||
}
|
||||
const rest = base.slice(at);
|
||||
push(blocks, { kind: "stable", base: rest, ours: [...rest], theirs: [...rest] });
|
||||
return blocks;
|
||||
}
|
||||
|
||||
/**
|
||||
* The units a block contributes to the initial result: the changed side,
|
||||
* or the base for stable blocks and conflicts.
|
||||
*
|
||||
* @param block - the block.
|
||||
*/
|
||||
export function resultUnits(block: MergeBlock): string[] {
|
||||
switch (block.kind) {
|
||||
case "ours":
|
||||
case "both":
|
||||
return block.ours;
|
||||
case "theirs":
|
||||
return block.theirs;
|
||||
default:
|
||||
return block.base;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The result text before any conflict is resolved.
|
||||
*
|
||||
* @param blocks - the merge.
|
||||
*/
|
||||
export function initialResult(blocks: readonly MergeBlock[]): string {
|
||||
return blocks.map((block) => resultUnits(block).join("")).join("");
|
||||
}
|
||||
458
ui/src/components/vcs/merge/merge.ts
Normal file
458
ui/src/components/vcs/merge/merge.ts
Normal file
|
|
@ -0,0 +1,458 @@
|
|||
/**
|
||||
* The merge dialog's state (M4.8): merging a branch, the list of
|
||||
* conflicted files, resolving one file and aborting the merge.
|
||||
*
|
||||
* - **Merge:** `git.merge {branch}` after `flushDirty()` (a failed save
|
||||
* cancels it, as for checkout). A clean merge or "already up to date"
|
||||
* toasts; a merge that stops on conflicts opens the conflicts list.
|
||||
* - **Conflicts:** the files whose index or work tree state is
|
||||
* `conflicted` in the shared status store (`stores/vcsStatus.ts`, the only
|
||||
* caller of `git.status`). The list follows the store, so files resolved
|
||||
* elsewhere leave it.
|
||||
* - **Resolving a file:** `git.conflictVersions {path}` gives the base, ours
|
||||
* and theirs; the view merges them (`diff3.ts`). Applying writes the result
|
||||
* into the file's engine buffer (so its line endings, the journal and open
|
||||
* tabs stay right), saves it and runs `git.markResolved {paths}`. A file
|
||||
* deleted on one side offers to keep the other side's version; binary and
|
||||
* too large files can only be marked resolved as they are on disk.
|
||||
* - **Abort:** `git.mergeAbort` after a confirmation in the dialog.
|
||||
* - **Untrusted input:** every result is checked field by field.
|
||||
*/
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, ref, shallowRef } from "vue";
|
||||
import { t } from "../../../i18n";
|
||||
import { runWaiting, type JsonValue } from "../../../ipc";
|
||||
import { useAutosaveStore } from "../../../stores/autosave";
|
||||
import { useEditorStore } from "../../../stores/editor";
|
||||
import { useNotificationsStore } from "../../../stores/notifications";
|
||||
import { useVcsStatusStore } from "../../../stores/vcsStatus";
|
||||
import { normaliseEol } from "./diff3";
|
||||
|
||||
/** Command id that merges a branch into the current one. */
|
||||
export const MERGE_COMMAND = "vcs.merge";
|
||||
|
||||
/** Command id that opens the conflicts (optionally one file's resolve view). */
|
||||
export const RESOLVE_COMMAND = "vcs.resolveConflicts";
|
||||
|
||||
/** Command id that asks to abort the merge. */
|
||||
export const ABORT_COMMAND = "vcs.abortMerge";
|
||||
|
||||
/** What the dialog shows. */
|
||||
export type MergeMode = "closed" | "branches" | "conflicts" | "resolve" | "abort";
|
||||
|
||||
/** How `git.merge` ended. */
|
||||
export type MergeResultKind = "merged" | "upToDate" | "conflicts";
|
||||
|
||||
/** A `git.merge` result, checked. */
|
||||
export interface MergeAnswer {
|
||||
/** How it ended. */
|
||||
result: MergeResultKind;
|
||||
/** Conflicted paths. */
|
||||
conflicts: string[];
|
||||
}
|
||||
|
||||
/** A `git.conflictVersions` result, checked; texts with `\n` breaks. */
|
||||
export interface ConflictVersions {
|
||||
/** The common ancestor; null when added on both sides. */
|
||||
base: string | null;
|
||||
/** Ours (the current branch); null when deleted there. */
|
||||
ours: string | null;
|
||||
/** Theirs (the merged branch); null when deleted there. */
|
||||
theirs: string | null;
|
||||
/** A version is binary. */
|
||||
binary: boolean;
|
||||
/** A version is too large. */
|
||||
tooLarge: boolean;
|
||||
}
|
||||
|
||||
/** What the resolve view of a file shows. */
|
||||
export type ResolvePhase = "loading" | "text" | "deleted" | "binary" | "tooLarge" | "error";
|
||||
|
||||
/**
|
||||
* Reads a `git.merge` result; null when malformed.
|
||||
*
|
||||
* @param raw - untrusted.
|
||||
*/
|
||||
export function toMergeAnswer(raw: unknown): MergeAnswer | null {
|
||||
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
||||
return null;
|
||||
}
|
||||
const r = raw as Record<string, unknown>;
|
||||
if (r.result !== "merged" && r.result !== "upToDate" && r.result !== "conflicts") {
|
||||
return null;
|
||||
}
|
||||
const conflicts = Array.isArray(r.conflicts) ? r.conflicts.filter((p): p is string => typeof p === "string" && p !== "") : [];
|
||||
return { result: r.result, conflicts };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a `git.conflictVersions` result; null when malformed. Line breaks
|
||||
* become `\n`.
|
||||
*
|
||||
* @param raw - untrusted.
|
||||
*/
|
||||
export function toConflictVersions(raw: unknown): ConflictVersions | null {
|
||||
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
||||
return null;
|
||||
}
|
||||
const r = raw as Record<string, unknown>;
|
||||
const text = (value: unknown): string | null | undefined =>
|
||||
value === null || value === undefined ? null : typeof value === "string" ? normaliseEol(value) : undefined;
|
||||
const base = text(r.base);
|
||||
const ours = text(r.ours);
|
||||
const theirs = text(r.theirs);
|
||||
if (base === undefined || ours === undefined || theirs === undefined) {
|
||||
return null;
|
||||
}
|
||||
return { base, ours, theirs, binary: r.binary === true, tooLarge: r.tooLarge === true };
|
||||
}
|
||||
|
||||
/**
|
||||
* The phase a file's versions call for.
|
||||
*
|
||||
* @param versions - the checked versions.
|
||||
*/
|
||||
export function phaseOf(versions: ConflictVersions): ResolvePhase {
|
||||
if (versions.binary) {
|
||||
return "binary";
|
||||
}
|
||||
if (versions.tooLarge) {
|
||||
return "tooLarge";
|
||||
}
|
||||
return versions.ours === null || versions.theirs === null ? "deleted" : "text";
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the params of `vcs.resolveConflicts`; undefined when malformed.
|
||||
*
|
||||
* @param params - untrusted (`{}` from the palette).
|
||||
* @returns the path, or null for the list.
|
||||
*/
|
||||
export function parseResolveParams(params: unknown): string | null | undefined {
|
||||
const p = typeof params === "object" && params !== null && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
|
||||
if (p.path === undefined || p.path === null) {
|
||||
return null;
|
||||
}
|
||||
return typeof p.path === "string" && p.path !== "" ? p.path : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* A short reason for a toast: git's message, or `?` when empty.
|
||||
*
|
||||
* @param message - the error text.
|
||||
*/
|
||||
function reasonOf(message: string): string {
|
||||
return message.trim() === "" ? "?" : message.trim();
|
||||
}
|
||||
|
||||
/** The merge store. */
|
||||
export const useMergeStore = defineStore("merge", () => {
|
||||
const notifications = useNotificationsStore();
|
||||
const status = useVcsStatusStore();
|
||||
const editor = useEditorStore();
|
||||
|
||||
/** What the dialog shows. */
|
||||
const mode = ref<MergeMode>("closed");
|
||||
/** The branches offered for a merge (not the current one). */
|
||||
const branches = ref<string[]>([]);
|
||||
/** Why the branches could not be read; null if they could. */
|
||||
const branchesError = ref<string | null>(null);
|
||||
/** The file being resolved. */
|
||||
const path = ref<string | null>(null);
|
||||
/** What its view shows. */
|
||||
const phase = ref<ResolvePhase>("loading");
|
||||
/** Its versions, once loaded. */
|
||||
const versions = shallowRef<ConflictVersions | null>(null);
|
||||
/** Error text of the resolve view or the last action; null if none. */
|
||||
const error = ref<string | null>(null);
|
||||
/** A git call or save runs. */
|
||||
const busy = ref(false);
|
||||
/** Bumped on every load, so only the newest one lands. */
|
||||
let generation = 0;
|
||||
|
||||
/** The conflicted files, sorted by path. */
|
||||
const conflicts = computed(() =>
|
||||
(status.snapshot?.files ?? [])
|
||||
.filter((file) => file.index === "conflicted" || file.worktree === "conflicted")
|
||||
.map((file) => file.path),
|
||||
);
|
||||
|
||||
/** The current branch, null when detached or unknown. */
|
||||
const currentBranch = computed(() => status.snapshot?.repo?.branch ?? null);
|
||||
|
||||
/** Closes the dialog. */
|
||||
function close(): void {
|
||||
mode.value = "closed";
|
||||
error.value = null;
|
||||
generation += 1;
|
||||
}
|
||||
|
||||
/** Shows the branches to merge and reads them. */
|
||||
async function showBranches(): Promise<void> {
|
||||
mode.value = "branches";
|
||||
error.value = null;
|
||||
branchesError.value = null;
|
||||
const result = await runWaiting("git.branches", {});
|
||||
if (!result.ok) {
|
||||
branchesError.value = reasonOf(result.error.message);
|
||||
branches.value = [];
|
||||
return;
|
||||
}
|
||||
const raw = result.value as Record<string, unknown> | null;
|
||||
const current = typeof raw?.current === "string" ? raw.current : null;
|
||||
const names = (list: unknown): string[] =>
|
||||
Array.isArray(list)
|
||||
? list
|
||||
.map((entry: unknown) =>
|
||||
typeof entry === "object" && entry !== null ? (entry as Record<string, unknown>).name : undefined,
|
||||
)
|
||||
.filter((name): name is string => typeof name === "string" && name !== "" && name !== current)
|
||||
: [];
|
||||
branches.value = [...names(raw?.local), ...names(raw?.remote)];
|
||||
}
|
||||
|
||||
/** Shows the list of conflicted files. */
|
||||
function showConflicts(): void {
|
||||
mode.value = "conflicts";
|
||||
path.value = null;
|
||||
error.value = null;
|
||||
generation += 1;
|
||||
}
|
||||
|
||||
/** Shows the abort confirmation. */
|
||||
function askAbort(): void {
|
||||
mode.value = "abort";
|
||||
error.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges a branch into the current one.
|
||||
*
|
||||
* @param branch - the branch name.
|
||||
* @returns how it ended, or null when it did not run or git refused.
|
||||
*/
|
||||
async function merge(branch: string): Promise<MergeResultKind | null> {
|
||||
if (busy.value) {
|
||||
return null;
|
||||
}
|
||||
busy.value = true;
|
||||
try {
|
||||
const flushed = await useAutosaveStore().flushDirty();
|
||||
if (flushed.error !== null || flushed.failed.length > 0) {
|
||||
notifications.notify({ level: "warning", messageKey: "notification.vcs.mergeNotSaved", params: { branch } });
|
||||
return null;
|
||||
}
|
||||
const result = await runWaiting("git.merge", { branch });
|
||||
if (!result.ok) {
|
||||
const reason = reasonOf(result.error.message);
|
||||
notifications.notify({ level: "error", messageKey: "notification.vcs.mergeFailed", message: reason, params: { branch, reason } });
|
||||
return null;
|
||||
}
|
||||
const answer = toMergeAnswer(result.value);
|
||||
if (!answer) {
|
||||
notifications.notify({ level: "error", messageKey: "common.error.unexpectedResult", params: { command: "git.merge" } });
|
||||
return null;
|
||||
}
|
||||
await status.refresh();
|
||||
if (answer.result === "conflicts") {
|
||||
notifications.notify({
|
||||
level: "warning",
|
||||
messageKey: "notification.vcs.mergeConflicts",
|
||||
params: { branch, count: String(answer.conflicts.length) },
|
||||
});
|
||||
showConflicts();
|
||||
} else {
|
||||
notifications.notify({
|
||||
level: "info",
|
||||
messageKey: answer.result === "merged" ? "notification.vcs.merged" : "notification.vcs.mergeUpToDate",
|
||||
params: { branch },
|
||||
});
|
||||
close();
|
||||
}
|
||||
return answer.result;
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Aborts the merge in progress.
|
||||
*
|
||||
* @returns whether git aborted it.
|
||||
*/
|
||||
async function abort(): Promise<boolean> {
|
||||
if (busy.value) {
|
||||
return false;
|
||||
}
|
||||
busy.value = true;
|
||||
try {
|
||||
const result = await runWaiting("git.mergeAbort", {});
|
||||
if (!result.ok) {
|
||||
error.value = reasonOf(result.error.message);
|
||||
return false;
|
||||
}
|
||||
await status.refresh();
|
||||
notifications.notify({ level: "info", messageKey: "notification.vcs.mergeAborted" });
|
||||
close();
|
||||
return true;
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the resolve view of a file and reads its versions.
|
||||
*
|
||||
* @param file - project-relative path.
|
||||
*/
|
||||
async function openFile(file: string): Promise<void> {
|
||||
generation += 1;
|
||||
const mine = generation;
|
||||
mode.value = "resolve";
|
||||
path.value = file;
|
||||
phase.value = "loading";
|
||||
versions.value = null;
|
||||
error.value = null;
|
||||
const result = await runWaiting("git.conflictVersions", { path: file });
|
||||
if (mine !== generation) {
|
||||
return;
|
||||
}
|
||||
if (!result.ok) {
|
||||
phase.value = "error";
|
||||
error.value = reasonOf(result.error.message);
|
||||
return;
|
||||
}
|
||||
const checked = toConflictVersions(result.value);
|
||||
if (!checked) {
|
||||
phase.value = "error";
|
||||
error.value = t("common.error.unexpectedResult", { command: "git.conflictVersions" });
|
||||
return;
|
||||
}
|
||||
versions.value = checked;
|
||||
phase.value = phaseOf(checked);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a text into a file through its engine buffer and saves it.
|
||||
*
|
||||
* @param file - project-relative path.
|
||||
* @param text - the new text with `\n` breaks (the buffer keeps the
|
||||
* file's line ending on save).
|
||||
* @returns null when saved, else why not.
|
||||
*/
|
||||
async function write(file: string, text: string): Promise<string | null> {
|
||||
const before = editor.lastError;
|
||||
const id = await editor.openFile(file);
|
||||
if (id === null) {
|
||||
const reason = editor.lastError?.message ?? "?";
|
||||
editor.lastError = before;
|
||||
return reason;
|
||||
}
|
||||
const sync = editor.syncOf(id);
|
||||
if (!sync) {
|
||||
return "?";
|
||||
}
|
||||
await sync.idle();
|
||||
const doc = sync.state.doc;
|
||||
if (doc.toString() !== text) {
|
||||
sync.dispatch({ changes: { from: 0, to: doc.length, insert: text } });
|
||||
}
|
||||
const saved = await editor.save(id);
|
||||
return saved ? null : (editor.lastError?.message ?? "?");
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a file resolved, optionally writing its result first, then goes
|
||||
* back to the list.
|
||||
*
|
||||
* @param file - project-relative path.
|
||||
* @param text - the result to write; null to keep the file on disk as it is.
|
||||
* @returns whether it was marked resolved.
|
||||
*/
|
||||
async function resolve(file: string, text: string | null): Promise<boolean> {
|
||||
if (busy.value) {
|
||||
return false;
|
||||
}
|
||||
busy.value = true;
|
||||
try {
|
||||
if (text !== null) {
|
||||
const failed = await write(file, text);
|
||||
if (failed !== null) {
|
||||
error.value = t("vcs.merge.saveFailed", { reason: failed });
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const result = await runWaiting("git.markResolved", { paths: [file] } satisfies JsonValue);
|
||||
if (!result.ok) {
|
||||
error.value = reasonOf(result.error.message);
|
||||
return false;
|
||||
}
|
||||
await status.refresh();
|
||||
notifications.notify({ level: "info", messageKey: "notification.vcs.resolved", params: { path: file } });
|
||||
showConflicts();
|
||||
return true;
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `vcs.resolveConflicts {path?}`.
|
||||
*
|
||||
* @param params - untrusted params.
|
||||
* @throws Error with a catalog message when the params are malformed.
|
||||
*/
|
||||
async function resolveCommand(params: JsonValue): Promise<void> {
|
||||
const file = parseResolveParams(params);
|
||||
if (file === undefined) {
|
||||
throw new Error(t("vcs.merge.invalidParams"));
|
||||
}
|
||||
if (file === null) {
|
||||
showConflicts();
|
||||
return;
|
||||
}
|
||||
await openFile(file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `vcs.merge {branch?}`: merges the branch, or shows the branches.
|
||||
*
|
||||
* @param params - untrusted params.
|
||||
* @throws Error with a catalog message when the params are malformed.
|
||||
*/
|
||||
async function mergeCommand(params: JsonValue): Promise<void> {
|
||||
const p = typeof params === "object" && params !== null && !Array.isArray(params) ? params : {};
|
||||
const branch = p.branch;
|
||||
if (branch === undefined || branch === null) {
|
||||
await showBranches();
|
||||
return;
|
||||
}
|
||||
if (typeof branch !== "string" || branch.trim() === "") {
|
||||
throw new Error(t("vcs.merge.invalidMergeParams"));
|
||||
}
|
||||
await merge(branch.trim());
|
||||
}
|
||||
|
||||
return {
|
||||
mode,
|
||||
branches,
|
||||
branchesError,
|
||||
path,
|
||||
phase,
|
||||
versions,
|
||||
error,
|
||||
busy,
|
||||
conflicts,
|
||||
currentBranch,
|
||||
close,
|
||||
showBranches,
|
||||
showConflicts,
|
||||
askAbort,
|
||||
merge,
|
||||
abort,
|
||||
openFile,
|
||||
resolve,
|
||||
resolveCommand,
|
||||
mergeCommand,
|
||||
};
|
||||
});
|
||||
513
ui/src/components/vcs/merge/resolveView.ts
Normal file
513
ui/src/components/vcs/merge/resolveView.ts
Normal file
|
|
@ -0,0 +1,513 @@
|
|||
/**
|
||||
* The three editors of the resolve view (M4.8): ours (left, read-only),
|
||||
* the result (middle, editable) and theirs (right, read-only).
|
||||
*
|
||||
* - **Blocks:** built by `merge3` (`diff3.ts`). Non-conflicting changes are
|
||||
* in the result from the start; each conflict is a chunk whose range in
|
||||
* the result starts as the base's lines.
|
||||
* - **Chunks in the result:** a state field keeps each chunk's range,
|
||||
* mapped through every edit (the start sticks before text inserted at it,
|
||||
* the end after, so typing at a chunk's edge extends it). Its state comes
|
||||
* from its text: open while it is the base's, taken from ours or theirs
|
||||
* while it equals that side, edited by hand otherwise.
|
||||
* - **Accepting:** {@link ResolveView.accept} replaces a chunk's range with
|
||||
* that side's lines; it is one undoable change of the result, and undo
|
||||
* opens the chunk again. The side
|
||||
* panes show a button in the gutter at the first line of every open
|
||||
* chunk ("»" left, "«" right); a click accepts it.
|
||||
* - **Colours:** only `--lt-*` tokens: open conflicts tinted with
|
||||
* `--lt-vcs-conflicted`, accepted chunks and non-conflicting changes with
|
||||
* `--lt-vcs-modified`.
|
||||
* - **Navigation:** {@link ResolveView.go} moves to the next or previous
|
||||
* open chunk (wrapping), selects it in the result and scrolls all three
|
||||
* editors to it.
|
||||
*/
|
||||
import { EditorState, RangeSetBuilder, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
|
||||
import { Decoration, EditorView, GutterMarker, gutter, type DecorationSet } from "@codemirror/view";
|
||||
import { basicSetup } from "codemirror";
|
||||
import { lutraEditorTheme } from "../../editor/extensions";
|
||||
import { languageExtensions } from "../../editor/language";
|
||||
import { merge3, resultUnits, splitUnits, type MergeBlock } from "./diff3";
|
||||
|
||||
/** Which side a chunk was taken from, or how else it was settled. */
|
||||
export type ChunkState = "open" | "ours" | "theirs" | "edited";
|
||||
|
||||
/** A conflict chunk: its text on each side and its place in each document. */
|
||||
export interface Chunk {
|
||||
/** Our text. */
|
||||
ours: string;
|
||||
/** Their text. */
|
||||
theirs: string;
|
||||
/** Range in the ours document. */
|
||||
oursFrom: number;
|
||||
/** End in the ours document. */
|
||||
oursTo: number;
|
||||
/** Range in the theirs document. */
|
||||
theirsFrom: number;
|
||||
/** End in the theirs document. */
|
||||
theirsTo: number;
|
||||
}
|
||||
|
||||
/** A chunk's live range in the result. */
|
||||
interface Range {
|
||||
/** Start in the result. */
|
||||
from: number;
|
||||
/** End in the result. */
|
||||
to: number;
|
||||
}
|
||||
|
||||
/** A chunk's live range and state in the result. */
|
||||
export interface Live extends Range {
|
||||
/** Its state, read from the text in its range. */
|
||||
state: ChunkState;
|
||||
}
|
||||
|
||||
/** A highlighted range of a side document. */
|
||||
interface Marked {
|
||||
/** Start. */
|
||||
from: number;
|
||||
/** End. */
|
||||
to: number;
|
||||
/** A conflict (else a non-conflicting change). */
|
||||
conflict: boolean;
|
||||
}
|
||||
|
||||
/** The laid-out merge: documents, chunks and highlights. */
|
||||
export interface Layout {
|
||||
/** The ours document. */
|
||||
ours: string;
|
||||
/** The theirs document. */
|
||||
theirs: string;
|
||||
/** The initial result. */
|
||||
result: string;
|
||||
/** The conflict chunks in order. */
|
||||
chunks: Chunk[];
|
||||
/** Initial result range of each chunk. */
|
||||
resultRanges: { from: number; to: number }[];
|
||||
/** Highlights of the ours document. */
|
||||
oursMarks: Marked[];
|
||||
/** Highlights of the theirs document. */
|
||||
theirsMarks: Marked[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Lays out a merge of the three texts.
|
||||
*
|
||||
* @param base - the base text, null when there is none.
|
||||
* @param ours - our text.
|
||||
* @param theirs - their text.
|
||||
*/
|
||||
export function layout(base: string | null, ours: string, theirs: string): Layout {
|
||||
const blocks: MergeBlock[] = merge3(base === null ? null : splitUnits(base), splitUnits(ours), splitUnits(theirs));
|
||||
const out: Layout = { ours: "", theirs: "", result: "", chunks: [], resultRanges: [], oursMarks: [], theirsMarks: [] };
|
||||
for (const block of blocks) {
|
||||
const oursText = block.ours.join("");
|
||||
const theirsText = block.theirs.join("");
|
||||
const resultText = resultUnits(block).join("");
|
||||
const oursFrom = out.ours.length;
|
||||
const theirsFrom = out.theirs.length;
|
||||
const resultFrom = out.result.length;
|
||||
out.ours += oursText;
|
||||
out.theirs += theirsText;
|
||||
out.result += resultText;
|
||||
if (block.kind === "conflict") {
|
||||
out.chunks.push({
|
||||
ours: oursText,
|
||||
theirs: theirsText,
|
||||
oursFrom,
|
||||
oursTo: out.ours.length,
|
||||
theirsFrom,
|
||||
theirsTo: out.theirs.length,
|
||||
});
|
||||
out.resultRanges.push({ from: resultFrom, to: out.result.length });
|
||||
}
|
||||
if (block.kind === "conflict" || block.kind === "ours" || block.kind === "both") {
|
||||
out.oursMarks.push({ from: oursFrom, to: out.ours.length, conflict: block.kind === "conflict" });
|
||||
}
|
||||
if (block.kind === "conflict" || block.kind === "theirs" || block.kind === "both") {
|
||||
out.theirsMarks.push({ from: theirsFrom, to: out.theirs.length, conflict: block.kind === "conflict" });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Marks the chunks resolved in a side pane (`true` = open). */
|
||||
const setOpen = StateEffect.define<boolean[]>();
|
||||
|
||||
/** Line decorations by class. */
|
||||
const lineDecos = {
|
||||
conflict: Decoration.line({ class: "lt-merge-conflict" }),
|
||||
change: Decoration.line({ class: "lt-merge-change" }),
|
||||
resolved: Decoration.line({ class: "lt-merge-resolved" }),
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds line decorations for the lines a range covers (one line for an
|
||||
* empty range).
|
||||
*
|
||||
* @param doc - the document.
|
||||
* @param from - start of the range.
|
||||
* @param to - end of the range.
|
||||
* @param add - receives each line start.
|
||||
*/
|
||||
function eachLine(doc: Text, from: number, to: number, add: (lineStart: number) => void): void {
|
||||
const first = doc.lineAt(Math.min(from, doc.length));
|
||||
const last = to > from ? doc.lineAt(Math.min(Math.max(to - 1, from), doc.length)) : first;
|
||||
for (let n = first.number; n <= last.number; n += 1) {
|
||||
add(doc.line(n).from);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds line decorations from ranges.
|
||||
*
|
||||
* @param doc - the document.
|
||||
* @param ranges - ranges with their decoration, in document order.
|
||||
*/
|
||||
function lineSet(doc: Text, ranges: { from: number; to: number; deco: Decoration }[]): DecorationSet {
|
||||
const builder = new RangeSetBuilder<Decoration>();
|
||||
let last = -1;
|
||||
for (const range of ranges) {
|
||||
eachLine(doc, range.from, range.to, (start) => {
|
||||
if (start > last) {
|
||||
builder.add(start, start, range.deco);
|
||||
last = start;
|
||||
}
|
||||
});
|
||||
}
|
||||
return builder.finish();
|
||||
}
|
||||
|
||||
/** The accept button in a side pane's gutter. */
|
||||
class AcceptMarker extends GutterMarker {
|
||||
/**
|
||||
* @param glyph - `»` or `«`.
|
||||
* @param label - its accessible name.
|
||||
*/
|
||||
constructor(
|
||||
readonly glyph: string,
|
||||
readonly label: string,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
/** @param other - another marker. */
|
||||
override eq(other: GutterMarker): boolean {
|
||||
return other instanceof AcceptMarker && other.glyph === this.glyph && other.label === this.label;
|
||||
}
|
||||
|
||||
/** The button. */
|
||||
override toDOM(): Node {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "lt-merge-accept";
|
||||
button.textContent = this.glyph;
|
||||
button.title = this.label;
|
||||
button.setAttribute("aria-label", this.label);
|
||||
button.tabIndex = -1;
|
||||
return button;
|
||||
}
|
||||
}
|
||||
|
||||
/** Colours of the three editors, from tokens only. */
|
||||
export const resolveTheme: Extension = EditorView.theme({
|
||||
".lt-merge-conflict": { backgroundColor: "color-mix(in srgb, var(--lt-vcs-conflicted) 18%, var(--lt-editor-bg))" },
|
||||
".lt-merge-change": { backgroundColor: "color-mix(in srgb, var(--lt-vcs-modified) 12%, var(--lt-editor-bg))" },
|
||||
".lt-merge-resolved": { backgroundColor: "color-mix(in srgb, var(--lt-vcs-modified) 18%, var(--lt-editor-bg))" },
|
||||
".lt-merge-accept": {
|
||||
font: "inherit",
|
||||
lineHeight: "1",
|
||||
padding: "0 4px",
|
||||
border: "1px solid var(--lt-border)",
|
||||
borderRadius: "3px",
|
||||
color: "var(--lt-fg)",
|
||||
background: "var(--lt-bg)",
|
||||
cursor: "pointer",
|
||||
},
|
||||
".lt-merge-accept:hover": { background: "color-mix(in srgb, var(--lt-accent) 25%, var(--lt-bg))" },
|
||||
});
|
||||
|
||||
/** Labels of the gutter buttons. */
|
||||
export interface ResolveLabels {
|
||||
/** The ours pane's button. */
|
||||
acceptOurs: string;
|
||||
/** The theirs pane's button. */
|
||||
acceptTheirs: string;
|
||||
}
|
||||
|
||||
/** Where the three editors go and what they report. */
|
||||
export interface ResolveOptions {
|
||||
/** The file's path, for its language. */
|
||||
path: string;
|
||||
/** The base text, null when there is none. */
|
||||
base: string | null;
|
||||
/** Our text. */
|
||||
ours: string;
|
||||
/** Their text. */
|
||||
theirs: string;
|
||||
/** Element of the ours editor. */
|
||||
oursHost: HTMLElement;
|
||||
/** Element of the result editor. */
|
||||
resultHost: HTMLElement;
|
||||
/** Element of the theirs editor. */
|
||||
theirsHost: HTMLElement;
|
||||
/** Gutter button labels. */
|
||||
labels: ResolveLabels;
|
||||
/** Called after every change of a chunk's state, with the open count. */
|
||||
onChange: (open: number) => void;
|
||||
}
|
||||
|
||||
/** The three editors of one file. */
|
||||
export class ResolveView {
|
||||
/** The ours editor. */
|
||||
readonly oursView: EditorView;
|
||||
/** The result editor. */
|
||||
readonly resultView: EditorView;
|
||||
/** The theirs editor. */
|
||||
readonly theirsView: EditorView;
|
||||
/** The laid-out merge. */
|
||||
readonly layout: Layout;
|
||||
/** The chunk navigated to last; -1 before any. */
|
||||
current = -1;
|
||||
/** Reports changes. */
|
||||
private readonly onChange: (open: number) => void;
|
||||
/** The chunks' field in the result. */
|
||||
private readonly field: StateField<Range[]>;
|
||||
/** Each chunk's initial text in the result (the base's lines). */
|
||||
private readonly bases: string[];
|
||||
/** The open flags' field of the side panes. */
|
||||
private readonly openField: StateField<boolean[]>;
|
||||
|
||||
/** @param options - hosts, texts and callbacks. */
|
||||
constructor(options: ResolveOptions) {
|
||||
this.onChange = options.onChange;
|
||||
const lay = layout(options.base, options.ours, options.theirs);
|
||||
this.layout = lay;
|
||||
const base = lay.resultRanges.map((r) => lay.result.slice(r.from, r.to));
|
||||
this.bases = base;
|
||||
const field = StateField.define<Range[]>({
|
||||
create: () => lay.resultRanges.map((r) => ({ ...r })),
|
||||
update(ranges, tr) {
|
||||
if (!tr.docChanged) {
|
||||
return ranges;
|
||||
}
|
||||
return ranges.map((range) => {
|
||||
const from = tr.changes.mapPos(range.from, -1);
|
||||
return { from, to: Math.max(from, tr.changes.mapPos(range.to, 1)) };
|
||||
});
|
||||
},
|
||||
provide: (f) =>
|
||||
EditorView.decorations.from(f, (ranges) => (view: EditorView) =>
|
||||
lineSet(
|
||||
view.state.doc,
|
||||
ranges.map((r, i) => ({
|
||||
from: r.from,
|
||||
to: r.to,
|
||||
deco: view.state.doc.sliceString(r.from, r.to) === base[i] ? lineDecos.conflict : lineDecos.resolved,
|
||||
})),
|
||||
),
|
||||
),
|
||||
});
|
||||
this.field = field;
|
||||
const openField = StateField.define<boolean[]>({
|
||||
create: () => lay.chunks.map(() => true),
|
||||
update(flags, tr) {
|
||||
for (const effect of tr.effects) {
|
||||
if (effect.is(setOpen)) {
|
||||
return effect.value;
|
||||
}
|
||||
}
|
||||
return flags;
|
||||
},
|
||||
});
|
||||
this.openField = openField;
|
||||
const language = languageExtensions(options.path);
|
||||
const readOnly = [EditorState.readOnly.of(true), EditorView.editable.of(false)];
|
||||
const side = (which: "ours" | "theirs"): Extension => {
|
||||
const marks = which === "ours" ? lay.oursMarks : lay.theirsMarks;
|
||||
const marker = new AcceptMarker(which === "ours" ? "»" : "«", which === "ours" ? options.labels.acceptOurs : options.labels.acceptTheirs);
|
||||
const starts = lay.chunks.map((c) => (which === "ours" ? c.oursFrom : c.theirsFrom));
|
||||
return [
|
||||
basicSetup,
|
||||
lutraEditorTheme,
|
||||
language,
|
||||
resolveTheme,
|
||||
readOnly,
|
||||
openField,
|
||||
StateField.define<DecorationSet>({
|
||||
create: (state) =>
|
||||
lineSet(
|
||||
state.doc,
|
||||
marks.map((m) => ({ from: m.from, to: m.to, deco: m.conflict ? lineDecos.conflict : lineDecos.change })),
|
||||
),
|
||||
update: (set) => set,
|
||||
provide: (f) => EditorView.decorations.from(f),
|
||||
}),
|
||||
gutter({
|
||||
class: "lt-merge-gutter",
|
||||
lineMarker: (view, line) => {
|
||||
const flags = view.state.field(openField);
|
||||
const index = starts.findIndex(
|
||||
(start, i) => flags[i] === true && view.state.doc.lineAt(Math.min(start, view.state.doc.length)).from === line.from,
|
||||
);
|
||||
return index >= 0 ? marker : null;
|
||||
},
|
||||
lineMarkerChange: (update) => update.transactions.some((tr) => tr.effects.some((e) => e.is(setOpen))),
|
||||
domEventHandlers: {
|
||||
mousedown: (view, line) => {
|
||||
const flags = view.state.field(openField);
|
||||
const index = starts.findIndex(
|
||||
(start, i) => flags[i] === true && view.state.doc.lineAt(Math.min(start, view.state.doc.length)).from === line.from,
|
||||
);
|
||||
if (index < 0) {
|
||||
return false;
|
||||
}
|
||||
this.accept(index, which);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
};
|
||||
this.oursView = new EditorView({ parent: options.oursHost, state: EditorState.create({ doc: lay.ours, extensions: side("ours") }) });
|
||||
this.theirsView = new EditorView({ parent: options.theirsHost, state: EditorState.create({ doc: lay.theirs, extensions: side("theirs") }) });
|
||||
this.resultView = new EditorView({
|
||||
parent: options.resultHost,
|
||||
state: EditorState.create({
|
||||
doc: lay.result,
|
||||
extensions: [
|
||||
basicSetup,
|
||||
lutraEditorTheme,
|
||||
language,
|
||||
resolveTheme,
|
||||
field,
|
||||
EditorView.updateListener.of((update) => {
|
||||
if (update.docChanged) {
|
||||
this.report();
|
||||
}
|
||||
}),
|
||||
],
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The chunks' live ranges and states. A chunk is open while its text is
|
||||
* still the base's, taken from a side while it equals that side's, and
|
||||
* edited otherwise; so undo and redo need no bookkeeping.
|
||||
*/
|
||||
get chunks(): readonly Live[] {
|
||||
const state = this.resultView.state;
|
||||
return state.field(this.field).map((range, i) => {
|
||||
const text = state.doc.sliceString(range.from, range.to);
|
||||
const chunk = this.layout.chunks[i];
|
||||
const kind: ChunkState =
|
||||
text === this.bases[i] ? "open" : text === chunk?.ours ? "ours" : text === chunk?.theirs ? "theirs" : "edited";
|
||||
return { ...range, state: kind };
|
||||
});
|
||||
}
|
||||
|
||||
/** How many chunks are still open. */
|
||||
get open(): number {
|
||||
return this.chunks.filter((c) => c.state === "open").length;
|
||||
}
|
||||
|
||||
/** The result text. */
|
||||
get result(): string {
|
||||
return this.resultView.state.doc.toString();
|
||||
}
|
||||
|
||||
/** Tells the side panes which chunks are open and reports the count. */
|
||||
private report(): void {
|
||||
const flags = this.chunks.map((c) => c.state === "open");
|
||||
for (const view of [this.oursView, this.theirsView]) {
|
||||
const before = view.state.field(this.openField);
|
||||
if (before.length !== flags.length || before.some((f, i) => f !== flags[i])) {
|
||||
view.dispatch({ effects: setOpen.of(flags) });
|
||||
}
|
||||
}
|
||||
this.onChange(this.open);
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes one side's text for a chunk.
|
||||
*
|
||||
* @param index - the chunk.
|
||||
* @param side - which side.
|
||||
*/
|
||||
accept(index: number, side: "ours" | "theirs"): void {
|
||||
const live = this.chunks[index];
|
||||
const chunk = this.layout.chunks[index];
|
||||
if (!live || !chunk) {
|
||||
return;
|
||||
}
|
||||
const insert = side === "ours" ? chunk.ours : chunk.theirs;
|
||||
this.resultView.dispatch({
|
||||
changes: { from: live.from, to: live.to, insert },
|
||||
userEvent: "input.merge",
|
||||
});
|
||||
this.current = index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes one side's text for every open chunk, last first so earlier
|
||||
* ranges stay valid.
|
||||
*
|
||||
* @param side - which side.
|
||||
*/
|
||||
acceptAll(side: "ours" | "theirs"): void {
|
||||
const open = this.chunks.map((c, i) => ({ c, i })).filter(({ c }) => c.state === "open");
|
||||
for (const { i } of open.reverse()) {
|
||||
this.accept(i, side);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes one side for the chunk navigated to last, else the first open one.
|
||||
*
|
||||
* @param side - which side.
|
||||
*/
|
||||
acceptCurrent(side: "ours" | "theirs"): void {
|
||||
const chunks = this.chunks;
|
||||
const index = chunks[this.current]?.state === "open" ? this.current : chunks.findIndex((c) => c.state === "open");
|
||||
if (index >= 0) {
|
||||
this.accept(index, side);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves to the next or previous open chunk, wrapping.
|
||||
*
|
||||
* @param direction - 1 or -1.
|
||||
* @returns whether there was one.
|
||||
*/
|
||||
go(direction: 1 | -1): boolean {
|
||||
const chunks = this.chunks;
|
||||
const count = chunks.length;
|
||||
for (let step = 1; step <= count; step += 1) {
|
||||
const index = (((this.current < 0 && direction < 0 ? 0 : this.current) + direction * step) % count + count) % count;
|
||||
const live = chunks[index];
|
||||
const chunk = this.layout.chunks[index];
|
||||
if (live?.state === "open" && chunk) {
|
||||
this.current = index;
|
||||
this.resultView.dispatch({
|
||||
selection: { anchor: live.from, head: live.to },
|
||||
effects: EditorView.scrollIntoView(live.from, { y: "center" }),
|
||||
});
|
||||
this.oursView.dispatch({ effects: EditorView.scrollIntoView(Math.min(chunk.oursFrom, this.oursView.state.doc.length), { y: "center" }) });
|
||||
this.theirsView.dispatch({
|
||||
effects: EditorView.scrollIntoView(Math.min(chunk.theirsFrom, this.theirsView.state.doc.length), { y: "center" }),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Destroys the three editors. */
|
||||
destroy(): void {
|
||||
this.oursView.destroy();
|
||||
this.resultView.destroy();
|
||||
this.theirsView.destroy();
|
||||
}
|
||||
}
|
||||
|
|
@ -19,12 +19,14 @@
|
|||
"command.settings.open": "Settings…",
|
||||
"command.terminal.open": "Terminal",
|
||||
"command.unavailable": "{command} cannot run right now",
|
||||
"command.vcs.abortMerge": "Abort Merge…",
|
||||
"command.vcs.branches": "Branches…",
|
||||
"command.vcs.checkout": "Check Out Branch",
|
||||
"command.vcs.clone": "Clone Repository…",
|
||||
"command.vcs.commit": "Commit…",
|
||||
"command.vcs.fetch": "Fetch",
|
||||
"command.vcs.manageRemotes": "Manage Remotes…",
|
||||
"command.vcs.merge": "Merge…",
|
||||
"command.vcs.newBranch": "New Branch…",
|
||||
"command.vcs.nextChange": "Next Change",
|
||||
"command.vcs.openChanges": "Changes",
|
||||
|
|
@ -32,6 +34,7 @@
|
|||
"command.vcs.pull": "Pull",
|
||||
"command.vcs.push": "Push",
|
||||
"command.vcs.refresh": "Refresh Changes",
|
||||
"command.vcs.resolveConflicts": "Resolve Conflicts…",
|
||||
"command.vcs.showDiff": "Show Diff",
|
||||
"command.vcs.showHistory": "Show History",
|
||||
"command.vcs.showLog": "Log",
|
||||
|
|
@ -172,6 +175,12 @@
|
|||
"notification.vcs.fetchFailed": "Fetch failed: {reason}",
|
||||
"notification.vcs.fetched": "Fetched from every remote",
|
||||
"notification.vcs.historyNoFile": "Open a file or pass a path to show its history",
|
||||
"notification.vcs.mergeAborted": "Merge aborted",
|
||||
"notification.vcs.mergeConflicts": "Merging {branch} stopped on conflicts (conflicted files: {count}). Resolve them, then commit.",
|
||||
"notification.vcs.mergeFailed": "Git did not merge {branch}: {reason}",
|
||||
"notification.vcs.mergeNotSaved": "Merge of {branch} cancelled: not every file could be saved first.",
|
||||
"notification.vcs.mergeUpToDate": "Already up to date with {branch}",
|
||||
"notification.vcs.merged": "Merged {branch}",
|
||||
"notification.vcs.newBranchFailed": "Branch {branch} was not created: {reason}",
|
||||
"notification.vcs.pullFailed": "Pull failed: {reason}",
|
||||
"notification.vcs.pullNotSaved": "Pull cancelled: not every file could be saved first.",
|
||||
|
|
@ -180,6 +189,7 @@
|
|||
"notification.vcs.pushed": "Pushed {branch} to {remote}",
|
||||
"notification.vcs.pushedUpstream": "Pushed {branch} to {remote} and set it as the upstream",
|
||||
"notification.vcs.remoteCancelled": "Git operation cancelled",
|
||||
"notification.vcs.resolved": "Marked {path} as resolved",
|
||||
"notification.vfs.pumpFailed": "Applying changes on disk failed: {reason}",
|
||||
"notification.watch.failed": "Lutra stopped watching the project for changes on disk: {reason}",
|
||||
"palette.label": "Command palette",
|
||||
|
|
@ -388,6 +398,53 @@
|
|||
"vcs.log.refresh": "Reload the history",
|
||||
"vcs.log.toolWindow.title": "Log",
|
||||
"vcs.log.truncated": "More files changed than are listed here.",
|
||||
"vcs.merge.abort": "Abort merge…",
|
||||
"vcs.merge.abortConfirm": "Abort merge",
|
||||
"vcs.merge.abortQuestion": "Abort the merge? The files and the index return to how they were before it; resolutions made so far are lost.",
|
||||
"vcs.merge.acceptLeft": "Accept left",
|
||||
"vcs.merge.acceptRight": "Accept right",
|
||||
"vcs.merge.allLeft": "Accept all left",
|
||||
"vcs.merge.allResolved": "No open conflicts",
|
||||
"vcs.merge.allRight": "Accept all right",
|
||||
"vcs.merge.apply": "Apply and mark resolved",
|
||||
"vcs.merge.applyHint": "Resolve every conflict first",
|
||||
"vcs.merge.back": "Back",
|
||||
"vcs.merge.binary": "Binary file: it cannot be merged here. Put the version you want on disk, then mark it resolved.",
|
||||
"vcs.merge.branchesLabel": "Branches to merge",
|
||||
"vcs.merge.close": "Close",
|
||||
"vcs.merge.commit": "Commit…",
|
||||
"vcs.merge.conflictsHint": "These files have conflicts. Resolve each one, then commit to finish the merge.",
|
||||
"vcs.merge.conflictsLabel": "Conflicted files",
|
||||
"vcs.merge.deletedOurs": "The current branch deleted this file and the merged branch changed it. Keep the merged branch's version, or delete the file and mark it resolved.",
|
||||
"vcs.merge.deletedTheirs": "The merged branch deleted this file and the current branch changed it. Keep the current branch's version, or delete the file and mark it resolved.",
|
||||
"vcs.merge.filter": "Filter branches",
|
||||
"vcs.merge.invalidMergeParams": "vcs.merge takes {branch?: string}",
|
||||
"vcs.merge.invalidParams": "vcs.resolveConflicts takes {path?: string}",
|
||||
"vcs.merge.keep": "Keep merging",
|
||||
"vcs.merge.keepOurs": "Keep the current branch's version",
|
||||
"vcs.merge.keepTheirs": "Keep the merged branch's version",
|
||||
"vcs.merge.loadFailed": "The conflict cannot be read: {reason}",
|
||||
"vcs.merge.loading": "Reading the conflict from Git…",
|
||||
"vcs.merge.markAsIs": "Mark resolved as on disk",
|
||||
"vcs.merge.next": "Next conflict",
|
||||
"vcs.merge.noBranches": "No other branch to merge",
|
||||
"vcs.merge.noConflicts": "No conflicts left. Commit to finish the merge.",
|
||||
"vcs.merge.openCount": "{open} of {total} conflicts open",
|
||||
"vcs.merge.ours": "Current branch",
|
||||
"vcs.merge.oursBranch": "Current branch ({branch})",
|
||||
"vcs.merge.previous": "Previous conflict",
|
||||
"vcs.merge.resolve": "Resolve…",
|
||||
"vcs.merge.resolveFile": "Resolve {path}",
|
||||
"vcs.merge.result": "Result",
|
||||
"vcs.merge.saveFailed": "The result could not be saved: {reason}",
|
||||
"vcs.merge.theirs": "Merged branch",
|
||||
"vcs.merge.titleAbort": "Abort merge",
|
||||
"vcs.merge.titleConflicts": "Merge conflicts",
|
||||
"vcs.merge.titleMerge": "Merge a branch",
|
||||
"vcs.merge.titleMergeInto": "Merge into {branch}",
|
||||
"vcs.merge.titleResolve": "Resolve {path}",
|
||||
"vcs.merge.tooLarge": "The file is too large to merge here. Put the version you want on disk, then mark it resolved.",
|
||||
"vcs.merge.toolbar": "Conflict actions",
|
||||
"vcs.remote.cancel": "Cancel the Git operation",
|
||||
"vcs.remote.operation.clone": "Cloning",
|
||||
"vcs.remote.operation.fetch": "Fetching",
|
||||
|
|
|
|||
|
|
@ -45,8 +45,8 @@ const usedKeys = sourceFiles(SRC).flatMap((file) =>
|
|||
* `settings.list`, the `messageKey` of
|
||||
* `notification` events (engine and desktop host), the keys the
|
||||
* notifications store passes through a constant, and the Changes
|
||||
* window's commit toasts (M4.2), the branch toasts (M4.5) and the remote
|
||||
* toasts (M4.10), passed as
|
||||
* window's commit toasts (M4.2), the branch toasts (M4.5), the merge
|
||||
* toasts (M4.8) and the remote toasts (M4.10), passed as
|
||||
* `messageKey`.
|
||||
*/
|
||||
const RUNTIME_KEYS = new Set([
|
||||
|
|
@ -68,6 +68,12 @@ const RUNTIME_KEYS = new Set([
|
|||
"notification.vcs.historyNoFile",
|
||||
"notification.vcs.commitNotSaved",
|
||||
"notification.vcs.committed",
|
||||
"notification.vcs.mergeAborted",
|
||||
"notification.vcs.mergeConflicts",
|
||||
"notification.vcs.mergeFailed",
|
||||
"notification.vcs.mergeNotSaved",
|
||||
"notification.vcs.mergeUpToDate",
|
||||
"notification.vcs.merged",
|
||||
"notification.vcs.newBranchFailed",
|
||||
"notification.vcs.cloned",
|
||||
"notification.vcs.fetchFailed",
|
||||
|
|
@ -79,6 +85,7 @@ const RUNTIME_KEYS = new Set([
|
|||
"notification.vcs.pushed",
|
||||
"notification.vcs.pushedUpstream",
|
||||
"notification.vcs.remoteCancelled",
|
||||
"notification.vcs.resolved",
|
||||
"notification.settings.corrupt",
|
||||
"notification.settings.corruptNotMoved",
|
||||
"notification.settings.unavailable",
|
||||
|
|
|
|||
|
|
@ -275,6 +275,7 @@ describe("AppMenu", () => {
|
|||
"goto.fileOpen",
|
||||
"goto.classOpen",
|
||||
"goto.symbolOpen",
|
||||
"vcs.abortMerge",
|
||||
"vcs.branches",
|
||||
"vcs.openChanges",
|
||||
"vcs.clone",
|
||||
|
|
@ -282,12 +283,14 @@ describe("AppMenu", () => {
|
|||
"vcs.fetch",
|
||||
"vcs.showLog",
|
||||
"vcs.manageRemotes",
|
||||
"vcs.merge",
|
||||
"vcs.newBranch",
|
||||
"vcs.nextChange",
|
||||
"vcs.previousChange",
|
||||
"vcs.pull",
|
||||
"vcs.push",
|
||||
"vcs.refresh",
|
||||
"vcs.resolveConflicts",
|
||||
"vcs.showDiff",
|
||||
"vcs.showHistory",
|
||||
"app.about",
|
||||
|
|
|
|||
|
|
@ -258,6 +258,7 @@ describe("CommandPalette", () => {
|
|||
expect(wrapper.find("[data-test=palette]").exists()).toBe(true);
|
||||
expect(document.activeElement).toBe(wrapper.find("[data-test=palette-input]").element);
|
||||
expect(rows(wrapper)).toEqual([
|
||||
"vcs.abortMerge",
|
||||
"vcs.branches",
|
||||
"vcs.openChanges",
|
||||
"vcs.checkout",
|
||||
|
|
@ -273,6 +274,7 @@ describe("CommandPalette", () => {
|
|||
"goto.symbolOpen",
|
||||
"vcs.showLog",
|
||||
"vcs.manageRemotes",
|
||||
"vcs.merge",
|
||||
"vcs.newBranch",
|
||||
"vcs.nextChange",
|
||||
"project.openDialog",
|
||||
|
|
@ -285,6 +287,7 @@ describe("CommandPalette", () => {
|
|||
"editor.quickDocumentation",
|
||||
"app.quit",
|
||||
"vcs.refresh",
|
||||
"vcs.resolveConflicts",
|
||||
"editor.reveal",
|
||||
"settings.open",
|
||||
"vcs.showDiff",
|
||||
|
|
@ -325,7 +328,7 @@ describe("CommandPalette", () => {
|
|||
await press({ key: "ArrowUp" });
|
||||
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("terminal.open");
|
||||
await press({ key: "ArrowDown" });
|
||||
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("vcs.branches");
|
||||
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("vcs.abortMerge");
|
||||
});
|
||||
|
||||
it("dims disabled commands, which Enter and clicks do not run", async () => {
|
||||
|
|
|
|||
577
ui/tests/vcs/Merge.test.ts
Normal file
577
ui/tests/vcs/Merge.test.ts
Normal file
|
|
@ -0,0 +1,577 @@
|
|||
/**
|
||||
* Tests of merge conflicts (M4.8): the three-way line merge (one-sided,
|
||||
* identical and conflicting changes, touching changes, no base, missing
|
||||
* final line breaks, the initial result), the layout of the three
|
||||
* documents, reading untrusted `git.merge` and `git.conflictVersions`
|
||||
* results and the command params, merging with `flushDirty` first (clean,
|
||||
* up to date, conflicts, refusal, cancelled by a failed save), the dialog
|
||||
* (branches, the conflicts list from the shared status store, the resolve
|
||||
* view's three editors with accept left/right per chunk, accept all, a
|
||||
* chunk opening again when its base text is back, Apply writing the result through the file's buffer
|
||||
* then `git.markResolved`, deleted and binary files, abort with its
|
||||
* confirmation and git's refusal), the Changes window opening a
|
||||
* conflicted file in the resolve view, and the registration of the
|
||||
* commands. The engine is a fake behind the mocked Tauri `invoke` and
|
||||
* `listen`.
|
||||
*/
|
||||
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
|
||||
import { createPinia, setActivePinia, type Pinia } from "pinia";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
|
||||
const invoke = vi.hoisted(() => vi.fn());
|
||||
const listen = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
|
||||
vi.mock("@tauri-apps/api/event", () => ({ listen }));
|
||||
|
||||
import { useModalsStore } from "../../src/commands/modals";
|
||||
import { useCommandsStore } from "../../src/commands/store";
|
||||
import { UI_COMMANDS } from "../../src/commands/uiCommands";
|
||||
import ChangesToolWindow from "../../src/components/vcs/changes/ChangesToolWindow.vue";
|
||||
import { useChangesStore } from "../../src/components/vcs/changes/changes";
|
||||
import { initialResult, merge3, splitUnits, type MergeBlock } from "../../src/components/vcs/merge/diff3";
|
||||
import MergeDialog from "../../src/components/vcs/merge/MergeDialog.vue";
|
||||
import {
|
||||
parseResolveParams,
|
||||
phaseOf,
|
||||
toConflictVersions,
|
||||
toMergeAnswer,
|
||||
useMergeStore,
|
||||
} from "../../src/components/vcs/merge/merge";
|
||||
import { layout } from "../../src/components/vcs/merge/resolveView";
|
||||
import { useNotificationsStore } from "../../src/stores/notifications";
|
||||
import { useProjectStore } from "../../src/stores/project";
|
||||
import { useVcsStatusStore } from "../../src/stores/vcsStatus";
|
||||
|
||||
/** A buffer of the fake engine. */
|
||||
interface FakeBuffer {
|
||||
path: string;
|
||||
text: string;
|
||||
version: number;
|
||||
saved: string;
|
||||
}
|
||||
|
||||
/** A recorded engine call. */
|
||||
interface Call {
|
||||
/** Command id. */
|
||||
command: string;
|
||||
/** Its params. */
|
||||
params: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Every engine call, in order. */
|
||||
let calls: Call[];
|
||||
/** Fake engine buffers by id. */
|
||||
let buffers: Map<number, FakeBuffer>;
|
||||
/** Files on disk. */
|
||||
let disk: Record<string, string>;
|
||||
/** Next buffer id. */
|
||||
let nextId: number;
|
||||
/** What `git.status` answers. */
|
||||
let gitStatus: { available: boolean; repo: unknown; files: unknown[] };
|
||||
/** What `git.merge` answers. */
|
||||
let mergeAnswer: unknown;
|
||||
/** What `git.conflictVersions` answers, by path. */
|
||||
let versions: Record<string, unknown>;
|
||||
/** What `file.saveAll` answers. */
|
||||
let saveAll: unknown;
|
||||
/** Errors to throw, by command id. */
|
||||
let failures: Record<string, { code: string; message: string }>;
|
||||
/** Pinia of the current test. */
|
||||
let pinia: Pinia;
|
||||
/** Mounted components. */
|
||||
let mounted: VueWrapper[];
|
||||
|
||||
/** The conflicted status entry of a path. */
|
||||
function conflicted(path: string): unknown {
|
||||
return { path, index: "conflicted", worktree: "conflicted" };
|
||||
}
|
||||
|
||||
/**
|
||||
* The calls of a command.
|
||||
*
|
||||
* @param command - the command id.
|
||||
*/
|
||||
function callsOf(command: string): Call[] {
|
||||
return calls.filter((c) => c.command === command);
|
||||
}
|
||||
|
||||
/**
|
||||
* Describes a buffer as `file.open` does.
|
||||
*
|
||||
* @param id - its id.
|
||||
*/
|
||||
function describeBuffer(id: number): unknown {
|
||||
const b = buffers.get(id);
|
||||
return b ? { id, path: b.path, text: b.text, version: b.version, dirty: b.text !== b.saved, lineEnding: "lf" } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The fake engine.
|
||||
*
|
||||
* @param command - command id.
|
||||
* @param p - params.
|
||||
*/
|
||||
function execute(command: string, p: Record<string, unknown>): Promise<unknown> {
|
||||
const failure = failures[command];
|
||||
if (failure) {
|
||||
return Promise.reject(Object.assign(new Error(failure.message), failure));
|
||||
}
|
||||
const id = typeof p.id === "number" ? p.id : -1;
|
||||
const b = buffers.get(id);
|
||||
switch (command) {
|
||||
case "git.status":
|
||||
return Promise.resolve(gitStatus);
|
||||
case "git.branches":
|
||||
return Promise.resolve({
|
||||
current: "main",
|
||||
local: [{ name: "main", head: "1" }, { name: "feature", head: "2" }],
|
||||
remote: [{ name: "origin/release", head: "3" }],
|
||||
});
|
||||
case "git.merge":
|
||||
return Promise.resolve(mergeAnswer);
|
||||
case "git.conflictVersions":
|
||||
return Promise.resolve(versions[String(p.path)] ?? null);
|
||||
case "git.markResolved": {
|
||||
const paths = p.paths as string[];
|
||||
gitStatus = { ...gitStatus, files: gitStatus.files.filter((f) => !paths.includes((f as { path: string }).path)) };
|
||||
return Promise.resolve({});
|
||||
}
|
||||
case "file.saveAll":
|
||||
return Promise.resolve(saveAll);
|
||||
case "file.open": {
|
||||
const path = String(p.path);
|
||||
for (const [existing, buffer] of buffers) {
|
||||
if (buffer.path === path) {
|
||||
return Promise.resolve(describeBuffer(existing));
|
||||
}
|
||||
}
|
||||
const text = disk[path];
|
||||
if (text === undefined) {
|
||||
return Promise.reject(Object.assign(new Error(`${path}: not found`), { code: "failed", message: `${path}: not found` }));
|
||||
}
|
||||
const newId = nextId++;
|
||||
buffers.set(newId, { path, text, version: 1, saved: text });
|
||||
return Promise.resolve(describeBuffer(newId));
|
||||
}
|
||||
case "buffer.get":
|
||||
return Promise.resolve(describeBuffer(id));
|
||||
case "buffer.edit": {
|
||||
if (!b || p.baseVersion !== b.version) {
|
||||
return Promise.reject(Object.assign(new Error("stale"), { code: "stale_version", message: "stale" }));
|
||||
}
|
||||
let out = "";
|
||||
let pos = 0;
|
||||
for (const e of p.edits as { from: number; to: number; insert: string }[]) {
|
||||
out += b.text.slice(pos, e.from) + e.insert;
|
||||
pos = e.to;
|
||||
}
|
||||
b.text = out + b.text.slice(pos);
|
||||
b.version += 1;
|
||||
return Promise.resolve({ id, version: b.version, dirty: true });
|
||||
}
|
||||
case "file.save":
|
||||
if (b) {
|
||||
b.saved = b.text;
|
||||
disk[b.path] = b.text;
|
||||
}
|
||||
return Promise.resolve({ id, version: b?.version ?? 0, dirty: false });
|
||||
default:
|
||||
return Promise.resolve({});
|
||||
}
|
||||
}
|
||||
|
||||
/** jsdom has no layout; CodeMirror measures text ranges, so give ranges empty rectangles. */
|
||||
function stubRangeGeometry(): void {
|
||||
const empty = (): DOMRectList => Object.assign([] as DOMRect[], { item: () => null });
|
||||
Range.prototype.getClientRects = empty;
|
||||
Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
/** Mounts the dialog with the status store, commands and a project. */
|
||||
async function mountDialog(): Promise<VueWrapper> {
|
||||
useProjectStore(pinia).root = { path: "/p", name: "p" };
|
||||
useVcsStatusStore(pinia).start();
|
||||
const wrapper = mount(MergeDialog, { attachTo: document.body, global: { plugins: [pinia] } });
|
||||
mounted.push(wrapper);
|
||||
await useCommandsStore(pinia).start();
|
||||
await flushPromises();
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a command through the command store and waits.
|
||||
*
|
||||
* @param id - command id.
|
||||
* @param params - its params.
|
||||
*/
|
||||
async function runCommand(id: string, params: Record<string, unknown> = {}): Promise<void> {
|
||||
await useCommandsStore(pinia).execute(id, params as never);
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
/** Kinds of the blocks of a merge. */
|
||||
function kinds(blocks: MergeBlock[]): string[] {
|
||||
return blocks.map((b) => b.kind);
|
||||
}
|
||||
|
||||
/** Lines of a text. */
|
||||
function lines(...items: string[]): string {
|
||||
return items.map((l) => `${l}\n`).join("");
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
stubRangeGeometry();
|
||||
Element.prototype.scrollIntoView = () => undefined;
|
||||
pinia = createPinia();
|
||||
setActivePinia(pinia);
|
||||
calls = [];
|
||||
buffers = new Map();
|
||||
nextId = 1;
|
||||
mounted = [];
|
||||
failures = {};
|
||||
saveAll = { saved: [], failed: [], skipped: [] };
|
||||
mergeAnswer = { result: "conflicts", conflicts: ["a.php"] };
|
||||
gitStatus = {
|
||||
available: true,
|
||||
repo: { root: "C:/p", branch: "main", detached: false, head: "0123456789" },
|
||||
files: [conflicted("a.php"), { path: "b.php", index: "modified", worktree: "unmodified" }],
|
||||
};
|
||||
disk = { "a.php": "<<<<<<< markers\n" };
|
||||
versions = {
|
||||
"a.php": {
|
||||
base: lines("<?php", "one", "two", "three", "four", "five"),
|
||||
ours: lines("<?php", "ONE", "two", "three", "four (main)", "five"),
|
||||
theirs: "<?php\r\none\r\ntwo\r\nthree (feature)\r\nfour (feature)\r\nfive\r\n",
|
||||
binary: false,
|
||||
tooLarge: false,
|
||||
},
|
||||
};
|
||||
invoke.mockReset();
|
||||
listen.mockReset();
|
||||
listen.mockImplementation(() => Promise.resolve(() => undefined));
|
||||
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
|
||||
if (cmd === "engine_list_commands") {
|
||||
return Promise.resolve([{ id: "git.status", label: "Git Status", enabled: true }]);
|
||||
}
|
||||
if ((cmd === "engine_execute" || cmd === "engine_execute_waiting") && args) {
|
||||
calls.push({ command: args.command, params: args.params });
|
||||
return execute(args.command, args.params);
|
||||
}
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await flushPromises();
|
||||
for (const wrapper of mounted) {
|
||||
wrapper.unmount();
|
||||
}
|
||||
useCommandsStore(pinia).stop();
|
||||
useVcsStatusStore(pinia).stop();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
describe("the three-way merge", () => {
|
||||
it("takes one-sided and identical changes and conflicts on different ones", () => {
|
||||
const base = splitUnits(lines("a", "b", "c", "d", "e", "f", "g"));
|
||||
const ours = splitUnits(lines("A", "b", "c", "D", "e", "f", "g", "h"));
|
||||
const theirs = splitUnits(lines("a", "b", "C", "d2", "e", "F", "g", "h"));
|
||||
const blocks = merge3(base, ours, theirs);
|
||||
expect(kinds(blocks)).toEqual(["ours", "stable", "conflict", "stable", "theirs", "stable", "both"]);
|
||||
expect(blocks[2]).toMatchObject({ base: ["c\n", "d\n"], ours: ["c\n", "D\n"], theirs: ["C\n", "d2\n"] });
|
||||
expect(initialResult(blocks)).toBe(lines("A", "b", "c", "d", "e", "F", "g", "h"));
|
||||
});
|
||||
|
||||
it("joins every side's units back to its text", () => {
|
||||
const base = lines("1", "2", "3", "4");
|
||||
const ours = lines("1", "x", "3", "4", "5");
|
||||
const theirs = lines("0", "1", "2", "3", "4");
|
||||
const blocks = merge3(splitUnits(base), splitUnits(ours), splitUnits(theirs));
|
||||
expect(blocks.map((b) => b.base.join("")).join("")).toBe(base);
|
||||
expect(blocks.map((b) => b.ours.join("")).join("")).toBe(ours);
|
||||
expect(blocks.map((b) => b.theirs.join("")).join("")).toBe(theirs);
|
||||
expect(blocks.some((b) => b.kind === "conflict")).toBe(false);
|
||||
expect(initialResult(blocks)).toBe(lines("0", "1", "x", "3", "4", "5"));
|
||||
});
|
||||
|
||||
it("gives every side back for random texts, and equals a side changed alone", () => {
|
||||
let seed = 7;
|
||||
const next = (n: number): number => {
|
||||
seed = (seed * 1103515245 + 12345) % 2147483648;
|
||||
return seed % n;
|
||||
};
|
||||
const mutate = (units: string[]): string[] => {
|
||||
const out = [...units];
|
||||
for (let k = next(4); k > 0; k -= 1) {
|
||||
const at = next(out.length + 1);
|
||||
if (next(2) === 0) {
|
||||
out.splice(at, 1);
|
||||
} else {
|
||||
out.splice(at, 0, `${String(next(5))}\n`);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
for (let round = 0; round < 300; round += 1) {
|
||||
const base = Array.from({ length: next(8) }, () => `${String(next(5))}\n`);
|
||||
const ours = mutate(base);
|
||||
const theirs = mutate(base);
|
||||
const blocks = merge3(base, ours, theirs);
|
||||
expect(blocks.map((b) => b.base.join("")).join("")).toBe(base.join(""));
|
||||
expect(blocks.map((b) => b.ours.join("")).join("")).toBe(ours.join(""));
|
||||
expect(blocks.map((b) => b.theirs.join("")).join("")).toBe(theirs.join(""));
|
||||
expect(initialResult(merge3(base, ours, base))).toBe(ours.join(""));
|
||||
expect(initialResult(merge3(base, base, theirs))).toBe(theirs.join(""));
|
||||
}
|
||||
});
|
||||
|
||||
it("treats touching changes as a conflict, as git does", () => {
|
||||
const blocks = merge3(splitUnits(lines("a", "b", "c")), splitUnits(lines("a", "B", "c")), splitUnits(lines("a", "b", "C")));
|
||||
expect(kinds(blocks)).toEqual(["stable", "conflict"]);
|
||||
});
|
||||
|
||||
it("compares ours and theirs directly without a base", () => {
|
||||
const blocks = merge3(null, splitUnits(lines("<?php", "main", "end")), splitUnits(lines("<?php", "feature", "end")));
|
||||
expect(kinds(blocks)).toEqual(["stable", "conflict", "stable"]);
|
||||
expect(blocks[1]).toMatchObject({ base: [], ours: ["main\n"], theirs: ["feature\n"] });
|
||||
expect(initialResult(blocks)).toBe(lines("<?php", "end"));
|
||||
});
|
||||
|
||||
it("keeps a missing final line break as a difference", () => {
|
||||
expect(splitUnits("a\nb")).toEqual(["a\n", "b"]);
|
||||
expect(splitUnits("")).toEqual([]);
|
||||
const blocks = merge3(splitUnits("a\nb"), splitUnits("a\nb\n"), splitUnits("a\nb"));
|
||||
expect(initialResult(blocks)).toBe("a\nb\n");
|
||||
});
|
||||
|
||||
it("lays out the documents with the chunks' places", () => {
|
||||
const lay = layout("x\nbase\ny\n", "x\nours\ny\n", "x\ntheirs\ny\n");
|
||||
expect(lay.result).toBe("x\nbase\ny\n");
|
||||
expect(lay.chunks).toEqual([{ ours: "ours\n", theirs: "theirs\n", oursFrom: 2, oursTo: 7, theirsFrom: 2, theirsTo: 9 }]);
|
||||
expect(lay.resultRanges).toEqual([{ from: 2, to: 7 }]);
|
||||
expect(lay.oursMarks).toEqual([{ from: 2, to: 7, conflict: true }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("reading results and params", () => {
|
||||
it("checks git.merge and git.conflictVersions", () => {
|
||||
expect(toMergeAnswer({ result: "conflicts", conflicts: ["a", 3, ""] })).toEqual({ result: "conflicts", conflicts: ["a"] });
|
||||
expect(toMergeAnswer({ result: "upToDate" })).toEqual({ result: "upToDate", conflicts: [] });
|
||||
expect(toMergeAnswer({ result: "weird" })).toBeNull();
|
||||
expect(toMergeAnswer([1])).toBeNull();
|
||||
const v = toConflictVersions({ ours: "a\r\nb", theirs: null, binary: false });
|
||||
expect(v).toEqual({ base: null, ours: "a\nb", theirs: null, binary: false, tooLarge: false });
|
||||
expect(v && phaseOf(v)).toBe("deleted");
|
||||
expect(toConflictVersions({ ours: 3, theirs: "x" })).toBeNull();
|
||||
expect(toConflictVersions(null)).toBeNull();
|
||||
expect(phaseOf({ base: null, ours: null, theirs: null, binary: true, tooLarge: false })).toBe("binary");
|
||||
expect(phaseOf({ base: null, ours: "", theirs: "", binary: false, tooLarge: false })).toBe("text");
|
||||
});
|
||||
|
||||
it("checks the params of vcs.resolveConflicts", () => {
|
||||
expect(parseResolveParams({})).toBeNull();
|
||||
expect(parseResolveParams(null)).toBeNull();
|
||||
expect(parseResolveParams({ path: "a.php" })).toBe("a.php");
|
||||
expect(parseResolveParams({ path: 3 })).toBeUndefined();
|
||||
expect(parseResolveParams({ path: "" })).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("merging", () => {
|
||||
it("saves first, merges and opens the conflicts list", async () => {
|
||||
const wrapper = await mountDialog();
|
||||
await runCommand("vcs.merge", { branch: "feature" });
|
||||
const order = calls.map((c) => c.command);
|
||||
expect(order.indexOf("file.saveAll")).toBeLessThan(order.indexOf("git.merge"));
|
||||
expect(callsOf("git.merge")[0]?.params).toEqual({ branch: "feature" });
|
||||
const merge = useMergeStore(pinia);
|
||||
expect(merge.mode).toBe("conflicts");
|
||||
expect(wrapper.findAll("[data-test=merge-conflict]").map((r) => r.attributes("data-path"))).toEqual(["a.php"]);
|
||||
expect(useNotificationsStore(pinia).toasts.at(-1)?.level).toBe("warning");
|
||||
expect(useModalsStore(pinia).current).toBe("merge");
|
||||
});
|
||||
|
||||
it("toasts a clean merge and an up-to-date one, and closes", async () => {
|
||||
await mountDialog();
|
||||
mergeAnswer = { result: "merged", conflicts: [] };
|
||||
await runCommand("vcs.merge", { branch: "feature" });
|
||||
expect(useMergeStore(pinia).mode).toBe("closed");
|
||||
expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("Merged feature");
|
||||
mergeAnswer = { result: "upToDate", conflicts: [] };
|
||||
await runCommand("vcs.merge", { branch: "feature" });
|
||||
expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("up to date");
|
||||
});
|
||||
|
||||
it("toasts git's refusal and a failed save cancels the merge", async () => {
|
||||
await mountDialog();
|
||||
failures["git.merge"] = { code: "failed", message: "Your local changes would be overwritten" };
|
||||
await runCommand("vcs.merge", { branch: "feature" });
|
||||
expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("Your local changes would be overwritten");
|
||||
delete failures["git.merge"];
|
||||
calls = [];
|
||||
saveAll = { saved: [], failed: [{ id: 1, path: "x.php", message: "denied" }], skipped: [] };
|
||||
await runCommand("vcs.merge", { branch: "feature" });
|
||||
expect(callsOf("git.merge")).toHaveLength(0);
|
||||
expect(useNotificationsStore(pinia).toasts.some((n) => n.text.includes("cancelled"))).toBe(true);
|
||||
});
|
||||
|
||||
it("lists the other branches and merges the one chosen", async () => {
|
||||
const wrapper = await mountDialog();
|
||||
await runCommand("vcs.merge");
|
||||
expect(wrapper.get("[data-test=merge-title]").text()).toBe("Merge into main");
|
||||
expect(wrapper.findAll("[data-test=merge-branch]").map((b) => b.text())).toEqual(["feature", "origin/release"]);
|
||||
await wrapper.get("[data-test=merge-filter]").setValue("rel");
|
||||
expect(wrapper.findAll("[data-test=merge-branch]").map((b) => b.text())).toEqual(["origin/release"]);
|
||||
await wrapper.get("[data-test=merge-filter]").trigger("keydown", { key: "Enter" });
|
||||
await flushPromises();
|
||||
expect(callsOf("git.merge")[0]?.params).toEqual({ branch: "origin/release" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolving a file", () => {
|
||||
/** Opens the resolve view of a.php. */
|
||||
async function openResolve(): Promise<VueWrapper> {
|
||||
const wrapper = await mountDialog();
|
||||
await runCommand("vcs.resolveConflicts", { path: "a.php" });
|
||||
await flushPromises();
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* The text of one of the three editors.
|
||||
*
|
||||
* @param wrapper - the dialog.
|
||||
* @param pane - ours, result or theirs.
|
||||
*/
|
||||
function paneText(wrapper: VueWrapper, pane: "ours" | "result" | "theirs"): string {
|
||||
return [...wrapper.get(`[data-test=merge-${pane}]`).element.querySelectorAll(".cm-line")].map((l) => l.textContent).join("\n");
|
||||
}
|
||||
|
||||
it("shows ours, the merged result and theirs with the conflict open", async () => {
|
||||
const wrapper = await openResolve();
|
||||
expect(callsOf("git.conflictVersions")[0]?.params).toEqual({ path: "a.php" });
|
||||
expect(paneText(wrapper, "ours")).toContain("four (main)");
|
||||
expect(paneText(wrapper, "theirs")).toContain("three (feature)");
|
||||
expect(paneText(wrapper, "result")).toContain("ONE");
|
||||
expect(paneText(wrapper, "result")).toContain("three");
|
||||
expect(wrapper.get("[data-test=merge-counter]").text()).toBe("1 of 1 conflicts open");
|
||||
expect(wrapper.get("[data-test=merge-apply]").attributes("disabled")).toBeDefined();
|
||||
expect(wrapper.findAll(".lt-merge-accept")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("accepts right per chunk, undo reopens it, and Apply writes and marks resolved", async () => {
|
||||
const wrapper = await openResolve();
|
||||
await wrapper.get("[data-test=merge-accept-right]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(paneText(wrapper, "result")).toContain("three (feature)");
|
||||
expect(wrapper.get("[data-test=merge-counter]").text()).toBe("No open conflicts");
|
||||
expect(wrapper.findAll(".lt-merge-accept")).toHaveLength(0);
|
||||
await wrapper.get("[data-test=merge-accept-left]").trigger("click");
|
||||
await wrapper.get("[data-test=merge-apply]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(disk["a.php"]).toBe(lines("<?php", "ONE", "two", "three (feature)", "four (feature)", "five"));
|
||||
const order = calls.map((c) => c.command);
|
||||
expect(order.lastIndexOf("file.save")).toBeLessThan(order.indexOf("git.markResolved"));
|
||||
expect(callsOf("git.markResolved")[0]?.params).toEqual({ paths: ["a.php"] });
|
||||
expect(useMergeStore(pinia).mode).toBe("conflicts");
|
||||
expect(wrapper.find("[data-test=merge-none]").exists()).toBe(true);
|
||||
expect(wrapper.find("[data-test=merge-commit]").exists()).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts all left, and restoring the base's text opens the chunk again", async () => {
|
||||
const wrapper = await openResolve();
|
||||
await wrapper.get("[data-test=merge-all-left]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(paneText(wrapper, "result")).toContain("four (main)");
|
||||
expect(wrapper.get("[data-test=merge-counter]").text()).toBe("No open conflicts");
|
||||
const dom = wrapper.get("[data-test=merge-result]").element.querySelector(".cm-editor");
|
||||
const view = dom ? EditorView.findFromDOM(dom as HTMLElement) : null;
|
||||
expect(view).not.toBeNull();
|
||||
if (view) {
|
||||
const text = view.state.doc.toString();
|
||||
const taken = "three\nfour (main)\n";
|
||||
const from = text.indexOf(taken);
|
||||
view.dispatch({ changes: { from, to: from + taken.length, insert: "three\nfour\n" } });
|
||||
}
|
||||
await flushPromises();
|
||||
expect(wrapper.get("[data-test=merge-counter]").text()).toBe("1 of 1 conflicts open");
|
||||
expect(wrapper.findAll(".lt-merge-accept")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("keeps the side that was not deleted, and marks binary files resolved as they are", async () => {
|
||||
versions["a.php"] = { base: "x\n", ours: null, theirs: "y\n", binary: false, tooLarge: false };
|
||||
const wrapper = await openResolve();
|
||||
expect(wrapper.find("[data-test=merge-deleted]").exists()).toBe(true);
|
||||
expect(wrapper.find("[data-test=merge-keep-ours]").exists()).toBe(false);
|
||||
await wrapper.get("[data-test=merge-keep-theirs]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(disk["a.php"]).toBe("y\n");
|
||||
gitStatus = { ...gitStatus, files: [conflicted("img.png")] };
|
||||
versions["img.png"] = { ours: null, theirs: null, binary: true, tooLarge: false };
|
||||
await useVcsStatusStore(pinia).refresh();
|
||||
await runCommand("vcs.resolveConflicts", { path: "img.png" });
|
||||
expect(wrapper.find("[data-test=merge-binary]").exists()).toBe(true);
|
||||
await wrapper.get("[data-test=merge-mark-as-is]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(callsOf("git.markResolved").at(-1)?.params).toEqual({ paths: ["img.png"] });
|
||||
expect(callsOf("file.open").filter((c) => c.params.path === "img.png")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("shows git's error for a file that is not in conflict", async () => {
|
||||
failures["git.conflictVersions"] = { code: "failed", message: "a.php is not in conflict" };
|
||||
const wrapper = await openResolve();
|
||||
expect(wrapper.get("[data-test=merge-error]").text()).toContain("a.php is not in conflict");
|
||||
});
|
||||
});
|
||||
|
||||
describe("aborting", () => {
|
||||
it("asks first, then aborts; git's refusal stays in the dialog", async () => {
|
||||
const wrapper = await mountDialog();
|
||||
await runCommand("vcs.abortMerge");
|
||||
expect(callsOf("git.mergeAbort")).toHaveLength(0);
|
||||
failures["git.mergeAbort"] = { code: "failed", message: "There is no merge to abort (MERGE_HEAD missing)." };
|
||||
await wrapper.get("[data-test=merge-abort]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(wrapper.get("[data-test=merge-error]").text()).toContain("MERGE_HEAD missing");
|
||||
delete failures["git.mergeAbort"];
|
||||
await wrapper.get("[data-test=merge-abort]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(callsOf("git.mergeAbort")).toHaveLength(2);
|
||||
expect(useMergeStore(pinia).mode).toBe("closed");
|
||||
expect(wrapper.find("[data-test=merge]").exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("Escape closes the list", async () => {
|
||||
const wrapper = await mountDialog();
|
||||
await runCommand("vcs.resolveConflicts");
|
||||
await wrapper.get("[data-test=merge-dialog]").trigger("keydown", { key: "Escape" });
|
||||
expect(useMergeStore(pinia).mode).toBe("closed");
|
||||
expect(useModalsStore(pinia).current).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("entry points", () => {
|
||||
it("registers the merge commands without default shortcuts", () => {
|
||||
for (const id of ["vcs.merge", "vcs.resolveConflicts", "vcs.abortMerge"]) {
|
||||
const spec = UI_COMMANDS.find((c) => c.id === id);
|
||||
expect(spec?.menuPath?.startsWith("Git/")).toBe(true);
|
||||
expect(spec?.defaultShortcut).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it("opens a conflicted file from the Changes window in the resolve view", async () => {
|
||||
await mountDialog();
|
||||
useChangesStore(pinia).start();
|
||||
const changes = mount(ChangesToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
|
||||
mounted.push(changes);
|
||||
await flushPromises();
|
||||
const row = changes.findAll("[data-test=changes-row]").find((r) => r.text().includes("a.php"));
|
||||
expect(row).toBeDefined();
|
||||
await row?.trigger("dblclick");
|
||||
await flushPromises();
|
||||
expect(useMergeStore(pinia).mode).toBe("resolve");
|
||||
expect(useMergeStore(pinia).path).toBe("a.php");
|
||||
useChangesStore(pinia).stop();
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue