diff --git a/crates/engine/src/cmd/git_merge.rs b/crates/engine/src/cmd/git_merge.rs new file mode 100644 index 0000000..838efd0 --- /dev/null +++ b/crates/engine/src/cmd/git_merge.rs @@ -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 { + 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 { + let command = self.spec().id; + let _: serde_json::Map = 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 { + 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, +} + +/// `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 { + 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::, _>>()?; + start_with( + state, + command, + true, + Box::new(move |repo| repo.mark_resolved(&paths).map(|()| json!({}))), + ) + } +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 50f47af..c17b70a 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -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(()) } diff --git a/crates/engine/src/engine.rs b/crates/engine/src/engine.rs index 54fe8b0..09fb30c 100644 --- a/crates/engine/src/engine.rs +++ b/crates/engine/src/engine.rs @@ -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", diff --git a/crates/engine/tests/git_merge.rs b/crates/engine/tests/git_merge.rs new file mode 100644 index 0000000..b2ab00e --- /dev/null +++ b/crates/engine/tests/git_merge.rs @@ -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", ", + /// Events published so far. + events: Mutex>, +} + +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 { + 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": ", +} + +/// 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, + /// The current branch's version (`:2:`); `None` when deleted there. + pub ours: Option, + /// The merged branch's version (`:3:`); `None` when deleted there. + pub theirs: Option, + /// 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` (` `, +/// or ` missing`). +/// +/// # Returns +/// `None` when the line is neither. +pub fn parse_check_line(line: &str) -> Option { + 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 (` \t` +/// records), each once, sorted. +pub fn parse_unmerged(bytes: &[u8]) -> Vec { + let mut paths: Vec = 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, 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 { + 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, 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 { + 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 { + 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 = text + .lines() + .map(|line| parse_check_line(line).ok_or_else(|| VcsError::BadOutput(line.to_string()))) + .collect::>()?; + 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::(), 0..256)) { + let _ = parse_unmerged(&bytes); + let _ = parse_check_line(&String::from_utf8_lossy(&bytes)); + } + } +} diff --git a/crates/vcs/src/repo.rs b/crates/vcs/src/repo.rs index 211d098..b63afe9 100644 --- a/crates/vcs/src/repo.rs +++ b/crates/vcs/src/repo.rs @@ -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) diff --git a/crates/vcs/tests/merge.rs b/crates/vcs/tests/merge.rs new file mode 100644 index 0000000..50d5a97 --- /dev/null +++ b/crates/vcs/tests/merge.rs @@ -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 { + 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", " 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", "` (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 | diff --git a/docs/gaps.md b/docs/gaps.md index c4b7e8e..4fe0bec 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -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) | diff --git a/docs/roadmap.md b/docs/roadmap.md index 71ca717..4e3fa07 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -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 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e44f040..1f16cc7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity -> **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and the go-to popup, the Structure tool window; M3 started: the integrated terminal, go to definition, find references and rename through Phpactor; M4 started: Git backend (M4.1), Changes tool window (M4.2), diff viewer (M4.3), branches (M4.5), remotes (M4.10) · **Last updated:** 2026-10-28 · **Target:** PhpStorm 2026.x +> **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and the go-to popup, the Structure tool window; M3 started: the integrated terminal, go to definition, find references and rename through Phpactor; M4 started: Git backend (M4.1), Changes tool window (M4.2), diff viewer (M4.3), branches (M4.5), merge conflicts (M4.8), remotes (M4.10) · **Last updated:** 2026-10-28 · **Target:** PhpStorm 2026.x ## How this is measured @@ -22,7 +22,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour | Inspections and quick-fixes | 8 | 5% (est.) | Lutra's own inspections and their settings, severities per inspection, quick-fixes (LSP code actions), suppression, inspection profiles, running inspections on a scope, the editor's problem counter and scrollbar marks, next/previous problem, a current-file Problems view and severity filters, external tools (PHPStan, Psalm, PHP_CodeSniffer) | ~287 (est.) | H3: PHP syntax errors on Windows from Lutra's own `php -l` (on open and save, off the engine lock, killed with Lutra), merged into the editor underlines and the Problems tab with source `php -l`; the language server's messages as notifications and its log as `lsp.log`. Tests: `crates/engine/tests/lsp_ux.rs`, unit tests incl. a parser proptest. M3.3: diagnostics from Phpactor (worse reflection: missing members, unknown classes, …) as wavy underlines, gutter markers and hover messages in the editor (`ui/src/components/editor/lint.ts`, tokens only), and a Problems tab in the bottom panel grouped by file with click to reveal (`ui/src/components/problems/`, `problems.open` `Mod+Alt+P`); engine `diagnosticsChanged`, `diagnostics.list`, `lspStatus` (`crates/engine/src/lsp/`). Tests: 10 engine tests against a fake server incl. a sync proptest, a TCP test, 16 Vitest tests, an ignored test against the real PHAR. Checked in the app on Windows 11 with the real Phpactor (port 7933): five errors underlined and listed; first diagnostics 2.7 s after `file.open`, 2.7–2.9 s after an edit (debug build, measured, incl. Phpactor's 1 s debounce). Graded against `plan/phpstorm/11-problems.md`: the depth comes from Phpactor, Lutra has no inspections of its own | | Refactoring | 7 | 3% (est.) | rename: preview of all changes, comments/strings and text occurrences, scope, renaming files with classes, one undo across files (closed files written on disk are not undone by the editor); extract variable/method/constant, inline, move, change signature, safe delete, pull up/push down, introduce parameter | ~244 (est.) | M3.5: Rename (`lsp.prepareRename` then `lsp.rename`, F2) through Phpactor with an inline field over the symbol that shows how many uses in how many files change. The workspace edit is checked completely first (inside the project, ranges fit, open buffers unchanged since the request, no file operations); then closed files are written atomically through the VFS (written ones restored if a later write fails), open buffers change through `buffer.edit` (dirty, one undo step each in the editor), Phpactor reindexes the written files (sent as `didOpen`/`didSave`/`didClose`; its index followed in 140 ms, measured) and a summary notification follows. Live: renaming a method used in 3 files took 28 ms (open buffer + 2 closed files, CRLF kept). Tests: `crates/engine/tests/lsp_nav.rs` (multi-file rename incl. a closed CRLF file, an edit outside the project refused, a bad range refused, a buffer edited meanwhile refused; ignored real-Phpactor rename and rename back), Vitest `ui/tests/nav/`. | | Code style and formatting | 4 | 0% | everything | ~120 (est.) | — | -| Git | 8 | 11% (est.) | Changes window: chunk and line staging, changelists, recent messages and a message template, pre-commit checks, skipping hooks, commit-and-push, a tree view and grouping, a context menu (rollback, delete, ignore); gutter markers: actions (show the old text, revert or stage a chunk, next/previous change), markers against HEAD; directory status colours; diff viewer: a unified view, three-way merge, revert or stage a chunk from the diff, comparing with any revision or branch, ignore-whitespace options, folders; branches: merge, rebase, rename, delete, compare, favourites, incoming/outgoing markers, a branch from another start point; log: date and branch filters, several selected commits, cherry-pick, revert, reset, checkout or new branch from a commit, compare two commits, history of a selection; blame, conflicts, stash (C6); remotes: force push, tags, a push dialog with the outgoing commits and a target branch, hosting features (pull requests, issues), a check against a real hosted server; ignored files in the status | ~122 (est.) | M4.10: fetch, pull (merge or rebase per `git.pull.mode`, open files saved first) and push (upstream set on the first push) as `git.fetch/pull/push` and Git › Fetch / Pull / Push, with `gitProgress` in the status bar, Cancel (`git.cancel`, git and its children killed) and explained refusals (rejected push, sign-in, unknown host key, not found, unreachable, no upstream, conflicts); Git › Clone Repository… (`git.clone`, then `project.open`) and Git › Manage Remotes… (`git.remotes/remoteAdd/remoteSetUrl/remoteRemove`). Any HTTPS or SSH server through git's credential helper (its window allowed) and the ssh agent; no terminal prompts, `ext::` refused, URL userinfo redacted everywhere (D23). Tests against local bare repositories only (`crates/vcs/tests/remote.rs` 8, `crates/engine/tests/git_remote.rs` 3, Vitest `ui/tests/vcs/Remote.test.ts` 11); not checked against a hosted server. C6 M4.6: a Log tab in the bottom panel (`vcs.showLog`, menu Git › Log) lists all branches' commits in topological order with graph lanes, ref badges, author and date, 100 per page loaded as the list scrolls; message and author filters; the selected commit's message and changed files, each opening a read-only "Diff: ()" at that commit against its parent (renames followed); history of a file or folder (`vcs.showHistory`: menu, the tree's context menu, or the active editor tab) follows renames. Backend `git.log`, `git.showCommit`, `git.showAt`. Tests: `crates/vcs/tests/log.rs`, `crates/engine/tests/git_log.rs`, Vitest `ui/tests/vcs/Log.test.ts` (21). C6 F1: Amend fills an empty message box with the last commit message (`git.lastMessage`); checking out a remote branch whose remote is not configured gives an untracked local branch and a clean tree instead of a half-done checkout; one shared status store, so a `gitChanged` costs one `git.status` for the Changes window, the colours and the branch item. M4.5: a status-bar item shows the current branch, or the short hash when detached (`ui/src/components/vcs/branches/`); clicking it or `vcs.branches` (menu Git › Branches…) opens a popup with a filter field, "New branch…", the local branches (current marked, upstream shown) and the remote branches, keyboard-driven; choosing one runs `vcs.checkout {branch}`, which saves dirty buffers through `flushDirty()` first, cancels when a save fails and toasts git's refusal with the branch name; a remote branch checks out its tracking branch. "New branch…" / `vcs.newBranch {name?, checkout?}` creates one from HEAD (checked out by default) and keeps git's refusal next to the name. Tests: 16 Vitest tests (`ui/tests/vcs/Branches.test.ts`). M4.3: `vcs.showDiff {path, staged?}` (`Mod+Alt+Shift+D`, menu Git › Show Diff, double-click in Changes, the project tree's context menu, the palette) opens a "Diff: " tab in the editor area: `@codemirror/merge` side by side, the staged version (or the last commit for a staged row) read-only on the left, the working copy editable on the right through its normal engine buffer (saves, autosave, the journal), changed lines and words tinted with `--lt-vcs-*`, unchanged stretches collapsed, the left side re-read on `gitChanged`; next/previous change (`Alt+Shift+]` / `Alt+Shift+[`); notices for binary, too large, failed and deleted files (`ui/src/components/vcs/diff/`, 21 Vitest tests). M4.2: Changes tab in the bottom panel (`ui/src/components/vcs/changes/`): Staged / Changes / Untracked groups from `git.status` (re-read on `gitChanged`), stage and unstage per file and per group with checkboxes (a staged rename passes both paths), keyboard navigation with Space to stage, double-click or Enter opens through `vcs.showDiff` when the diff viewer provides it, else the file; a commit message box with Amend and Commit (also `Mod+Enter`), which runs `flushDirty()` first, cancels when a save fails and toasts the short hash; hints for a missing git and a folder without a repository; `vcs.openChanges` `Mod+Alt+Shift+G`, `vcs.commit` `Mod+Alt+Shift+M`, `vcs.refresh`. Tests: 19 Vitest tests (`ui/tests/vcs/ChangesToolWindow.test.ts`). M4.4: change markers in the editor gutter (added, modified, deleted against the index, 150 ms after typing and on every `gitChanged`, CRLF-safe) through `git.lineChanges` (line diff in Rust off the lock, index text cached and dropped on `gitChanged`); file names in the project tree and the editor tabs coloured by Git status (`--lt-vcs-*`), ignored entries in the ignored colour inside a repository. Tests: `crates/engine/tests/git_lines.rs` (real temp repositories), unit and property tests, Vitest (`ui/tests/editor/gitGutter.test.ts`, `ui/tests/vcs/vcsStatus.test.ts`). M4.1 (backend, reachable through the palette, control channel and MCP): `git.status`, `git.stage`, `git.unstage` (also before the first commit), `git.commit {message, amend}` with hooks, `git.show` at HEAD or the index, `git.branches`, `git.checkout` (remote → tracking branch), `git.createBranch`; `gitChanged` after changes and from a `.git` poll plus the project watcher. Runs the installed git ≥ 2.30 (`git.executable`), porcelain v2 / `-z` only, no prompts, timeouts and caps, off the engine lock. Tests against real temp repositories (`crates/vcs/tests/repo.rs`, `crates/engine/tests/git.rs`). Graded against `plan/phpstorm/16-vcs-basics.md`: committing, staging and switching or creating branches work from the UI, and changed lines and files are marked (read-only markers, no chunk actions); diff, log, blame and remotes do not yet. | +| Git | 8 | 11% (est.) | Changes window: chunk and line staging, changelists, recent messages and a message template, pre-commit checks, skipping hooks, commit-and-push, a tree view and grouping, a context menu (rollback, delete, ignore); gutter markers: actions (show the old text, revert or stage a chunk, next/previous change), markers against HEAD; directory status colours; diff viewer: a unified view, three-way merge, revert or stage a chunk from the diff, comparing with any revision or branch, ignore-whitespace options, folders; branches: merge, rebase, rename, delete, compare, favourites, incoming/outgoing markers, a branch from another start point; log: date and branch filters, several selected commits, cherry-pick, revert, reset, checkout or new branch from a commit, compare two commits, history of a selection; blame, stash (C6); remotes: force push, tags, a push dialog with the outgoing commits and a target branch, hosting features (pull requests, issues), a check against a real hosted server; ignored files in the status | ~122 (est.) | M4.8: `vcs.merge` (Git › Merge…) merges a branch after saving and toasts merged, up to date or git's refusal; on conflicts the merge dialog lists the conflicted files (also from Changes and Git › Resolve Conflicts…); each opens a three-pane resolve view (current branch, the editable result starting from the base with non-conflicting changes applied, merged branch) with » / « per chunk, accept left/right, accept all and previous/next conflict; Apply writes the result through the file's buffer and runs `git.markResolved`; modify/delete keeps one side; Abort Merge after a confirmation. Backend `git.merge`, `git.mergeAbort`, `git.conflictVersions`, `git.markResolved`. Tests: `crates/vcs/tests/merge.rs`, `crates/engine/tests/git_merge.rs`, 22 Vitest tests (`ui/tests/vcs/Merge.test.ts`). M4.10: fetch, pull (merge or rebase per `git.pull.mode`, open files saved first) and push (upstream set on the first push) as `git.fetch/pull/push` and Git › Fetch / Pull / Push, with `gitProgress` in the status bar, Cancel (`git.cancel`, git and its children killed) and explained refusals (rejected push, sign-in, unknown host key, not found, unreachable, no upstream, conflicts); Git › Clone Repository… (`git.clone`, then `project.open`) and Git › Manage Remotes… (`git.remotes/remoteAdd/remoteSetUrl/remoteRemove`). Any HTTPS or SSH server through git's credential helper (its window allowed) and the ssh agent; no terminal prompts, `ext::` refused, URL userinfo redacted everywhere (D23). Tests against local bare repositories only (`crates/vcs/tests/remote.rs` 8, `crates/engine/tests/git_remote.rs` 3, Vitest `ui/tests/vcs/Remote.test.ts` 11); not checked against a hosted server. C6 M4.6: a Log tab in the bottom panel (`vcs.showLog`, menu Git › Log) lists all branches' commits in topological order with graph lanes, ref badges, author and date, 100 per page loaded as the list scrolls; message and author filters; the selected commit's message and changed files, each opening a read-only "Diff: ()" at that commit against its parent (renames followed); history of a file or folder (`vcs.showHistory`: menu, the tree's context menu, or the active editor tab) follows renames. Backend `git.log`, `git.showCommit`, `git.showAt`. Tests: `crates/vcs/tests/log.rs`, `crates/engine/tests/git_log.rs`, Vitest `ui/tests/vcs/Log.test.ts` (21). C6 F1: Amend fills an empty message box with the last commit message (`git.lastMessage`); checking out a remote branch whose remote is not configured gives an untracked local branch and a clean tree instead of a half-done checkout; one shared status store, so a `gitChanged` costs one `git.status` for the Changes window, the colours and the branch item. M4.5: a status-bar item shows the current branch, or the short hash when detached (`ui/src/components/vcs/branches/`); clicking it or `vcs.branches` (menu Git › Branches…) opens a popup with a filter field, "New branch…", the local branches (current marked, upstream shown) and the remote branches, keyboard-driven; choosing one runs `vcs.checkout {branch}`, which saves dirty buffers through `flushDirty()` first, cancels when a save fails and toasts git's refusal with the branch name; a remote branch checks out its tracking branch. "New branch…" / `vcs.newBranch {name?, checkout?}` creates one from HEAD (checked out by default) and keeps git's refusal next to the name. Tests: 16 Vitest tests (`ui/tests/vcs/Branches.test.ts`). M4.3: `vcs.showDiff {path, staged?}` (`Mod+Alt+Shift+D`, menu Git › Show Diff, double-click in Changes, the project tree's context menu, the palette) opens a "Diff: " tab in the editor area: `@codemirror/merge` side by side, the staged version (or the last commit for a staged row) read-only on the left, the working copy editable on the right through its normal engine buffer (saves, autosave, the journal), changed lines and words tinted with `--lt-vcs-*`, unchanged stretches collapsed, the left side re-read on `gitChanged`; next/previous change (`Alt+Shift+]` / `Alt+Shift+[`); notices for binary, too large, failed and deleted files (`ui/src/components/vcs/diff/`, 21 Vitest tests). M4.2: Changes tab in the bottom panel (`ui/src/components/vcs/changes/`): Staged / Changes / Untracked groups from `git.status` (re-read on `gitChanged`), stage and unstage per file and per group with checkboxes (a staged rename passes both paths), keyboard navigation with Space to stage, double-click or Enter opens through `vcs.showDiff` when the diff viewer provides it, else the file; a commit message box with Amend and Commit (also `Mod+Enter`), which runs `flushDirty()` first, cancels when a save fails and toasts the short hash; hints for a missing git and a folder without a repository; `vcs.openChanges` `Mod+Alt+Shift+G`, `vcs.commit` `Mod+Alt+Shift+M`, `vcs.refresh`. Tests: 19 Vitest tests (`ui/tests/vcs/ChangesToolWindow.test.ts`). M4.4: change markers in the editor gutter (added, modified, deleted against the index, 150 ms after typing and on every `gitChanged`, CRLF-safe) through `git.lineChanges` (line diff in Rust off the lock, index text cached and dropped on `gitChanged`); file names in the project tree and the editor tabs coloured by Git status (`--lt-vcs-*`), ignored entries in the ignored colour inside a repository. Tests: `crates/engine/tests/git_lines.rs` (real temp repositories), unit and property tests, Vitest (`ui/tests/editor/gitGutter.test.ts`, `ui/tests/vcs/vcsStatus.test.ts`). M4.1 (backend, reachable through the palette, control channel and MCP): `git.status`, `git.stage`, `git.unstage` (also before the first commit), `git.commit {message, amend}` with hooks, `git.show` at HEAD or the index, `git.branches`, `git.checkout` (remote → tracking branch), `git.createBranch`; `gitChanged` after changes and from a `.git` poll plus the project watcher. Runs the installed git ≥ 2.30 (`git.executable`), porcelain v2 / `-z` only, no prompts, timeouts and caps, off the engine lock. Tests against real temp repositories (`crates/vcs/tests/repo.rs`, `crates/engine/tests/git.rs`). Graded against `plan/phpstorm/16-vcs-basics.md`: committing, staging and switching or creating branches work from the UI, and changed lines and files are marked (read-only markers, no chunk actions); diff, log, blame and remotes do not yet. | | Terminal | 3 | 15% (est.) | renaming and splitting tabs, sessions kept across restarts, search in the output, clickable paths and links, drag and drop, command completion, terminal settings (shell path, start directory, environment, font, cursor shape, bell, copy on selection, middle-click paste), a key back to the editor, the PHP interpreter in `PATH`, a terminal in a file's directory, confirmation before killing a running process, moving a terminal into the editor | ~26 (est.) | M3.6: `crates/terminal` runs the shell in a pseudo terminal (`portable-pty`: ConPTY on Windows, Unix pty elsewhere) on its own reader, writer and waiter threads: UTF-8 split across reads joined, invalid bytes U+FFFD, a 1 MiB output buffer per session with backpressure (the shell waits, nothing is dropped while it runs), a non-blocking input queue, resize, kill, exit codes. Engine `terminal.create {cwd?, shell?, cols, rows}` / `terminal.input` / `terminal.resize` / `terminal.close`, events `terminalOutput` (≤ 64 KiB per terminal and 256 KiB per pump, round-robin) and `terminalExited {code}`; terminals close with the project and on `app.quit`. UI: a Terminal tab in the bottom panel (tabs next to Find), xterm.js with the fit addon, several terminals as sub-tabs (Local, Local (2)…) with close and new buttons, output replayed after collapsing the panel, copy (`Mod+Shift+C`, `Ctrl+C` with a selection) and paste (`Mod+Shift+V`, `Ctrl+V`), a focus rule that leaves plain Ctrl keys to the shell, Lutra's own ANSI colours (`--lt-terminal-*`, all text colours ≥ 4.5:1), `terminal.open` `Mod+Shift+T`. Tests: 8 session tests with real `cmd.exe` (echo, exit code, input, 6,000 multibyte characters without U+FFFD, 30,000 lines through a full buffer without losing a line, resize, kill, spawn errors) and UTF-8 proptests (`crates/terminal`), 3 engine tests (`crates/engine/tests/terminal.rs`), a TCP control test create → output → input → exit (`crates/control/tests/terminal.rs`), 20 Vitest tests with a mocked xterm (`ui/tests/terminal/`). Live check (Windows 11, debug build with bundled UI, control port 7936, temp project): `terminal.open` showed a pwsh prompt in the project root, first `terminalOutput` 0.2–0.5 s after the command; `php -v` printed PHP 8.4.24 within 0.5–1.5 s; `dir` listed the project; resizing the window changed the shell's width 144 → 190 → 105 → 142 columns (pwsh `WindowSize`); a second terminal as sub-tab "Local (2)"; Find and Terminal as bottom tabs; dark and light screenshots read; `exit 3` gave `terminalExited {code: 3}`; `app.quit` ended the app and its shells (measured). The live check found two bugs, fixed before the commit: xterm's own black viewport background showed as a bar under the last row, and programs printing ANSI white (PSReadLine) were unreadable on the light theme, so xterm now enforces a 4.5:1 minimum contrast. Typing, clicking and copy/paste were not driven in the app (the control channel has no input method); Vitest covers them. Graded against `plan/phpstorm/10-terminal.md` | | Run configurations | 2 | 0% | everything | ~50 (est.) | — | | Debugger | 5 | 0% | everything | ~120 (est.) | — | @@ -67,6 +67,7 @@ The project tree is the first user-visible feature (Project view 8%, estimated); |---|---|---| | 2026-10-28 | patch | M4.6 evidence in the Git row (Log tab, commit details, diff at a commit, file history); score left to the PM | | 2026-10-28 | minor | Git row: remotes (M4.10), 9% → 11% (est.) | +| 2026-10-28 | patch | M4.8 evidence in the Git row (merge conflicts); score left to the PM | | 2026-10-27 | patch | C6 F1 evidence in the Git row (Amend prefill, remote checkout fix, shared status store) | | 2026-10-26 | minor | C5 review: breadth 35/155 | | 2026-10-26 | minor | M4.5: Git 8% → 9% (est.), branch widget and popup; hours 128 → 122 | diff --git a/docs/tooling-parity.md b/docs/tooling-parity.md index f2cbbc5..511e23a 100644 --- a/docs/tooling-parity.md +++ b/docs/tooling-parity.md @@ -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 diff --git a/ui/src/App.vue b/ui/src/App.vue index cf36e82..45d3a01 100644 --- a/ui/src/App.vue +++ b/ui/src/App.vue @@ -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(() => { + diff --git a/ui/src/commands/modals.ts b/ui/src/commands/modals.ts index 24b55a6..5a41bce 100644 --- a/ui/src/commands/modals.ts +++ b/ui/src/commands/modals.ts @@ -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", () => { diff --git a/ui/src/commands/uiCommands.ts b/ui/src/commands/uiCommands.ts index 7a7e80a..23c7485 100644 --- a/ui/src/commands/uiCommands.ts +++ b/ui/src/commands/uiCommands.ts @@ -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" }, diff --git a/ui/src/components/vcs/changes/ChangesToolWindow.vue b/ui/src/components/vcs/changes/ChangesToolWindow.vue index f7956e7..06012f5 100644 --- a/ui/src/components/vcs/changes/ChangesToolWindow.vue +++ b/ui/src/components/vcs/changes/ChangesToolWindow.vue @@ -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 { 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 }); diff --git a/ui/src/components/vcs/merge/MergeDialog.vue b/ui/src/components/vcs/merge/MergeDialog.vue new file mode 100644 index 0000000..e0a1e11 --- /dev/null +++ b/ui/src/components/vcs/merge/MergeDialog.vue @@ -0,0 +1,917 @@ + + + + + diff --git a/ui/src/components/vcs/merge/diff3.ts b/ui/src/components/vcs/merge/diff3.ts new file mode 100644 index 0000000..7e246fb --- /dev/null +++ b/ui/src/components/vcs/merge/diff3.ts @@ -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(); + 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(""); +} diff --git a/ui/src/components/vcs/merge/merge.ts b/ui/src/components/vcs/merge/merge.ts new file mode 100644 index 0000000..ddab81d --- /dev/null +++ b/ui/src/components/vcs/merge/merge.ts @@ -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; + 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; + 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) : {}; + 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("closed"); + /** The branches offered for a merge (not the current one). */ + const branches = ref([]); + /** Why the branches could not be read; null if they could. */ + const branchesError = ref(null); + /** The file being resolved. */ + const path = ref(null); + /** What its view shows. */ + const phase = ref("loading"); + /** Its versions, once loaded. */ + const versions = shallowRef(null); + /** Error text of the resolve view or the last action; null if none. */ + const error = ref(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 { + 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 | 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).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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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, + }; +}); diff --git a/ui/src/components/vcs/merge/resolveView.ts b/ui/src/components/vcs/merge/resolveView.ts new file mode 100644 index 0000000..fb29331 --- /dev/null +++ b/ui/src/components/vcs/merge/resolveView.ts @@ -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(); + +/** 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(); + 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; + /** 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; + + /** @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({ + 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({ + 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({ + 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(); + } +} diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index c6e0ac5..78f8f68 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -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", diff --git a/ui/tests/i18n/catalog.test.ts b/ui/tests/i18n/catalog.test.ts index 1177847..21417c4 100644 --- a/ui/tests/i18n/catalog.test.ts +++ b/ui/tests/i18n/catalog.test.ts @@ -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", diff --git a/ui/tests/menu/AppMenu.test.ts b/ui/tests/menu/AppMenu.test.ts index 95ce7df..dd2753c 100644 --- a/ui/tests/menu/AppMenu.test.ts +++ b/ui/tests/menu/AppMenu.test.ts @@ -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", diff --git a/ui/tests/palette/CommandPalette.test.ts b/ui/tests/palette/CommandPalette.test.ts index 520e79a..484e17d 100644 --- a/ui/tests/palette/CommandPalette.test.ts +++ b/ui/tests/palette/CommandPalette.test.ts @@ -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 () => { diff --git a/ui/tests/vcs/Merge.test.ts b/ui/tests/vcs/Merge.test.ts new file mode 100644 index 0000000..a52dbb4 --- /dev/null +++ b/ui/tests/vcs/Merge.test.ts @@ -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; +} + +/** Every engine call, in order. */ +let calls: Call[]; +/** Fake engine buffers by id. */ +let buffers: Map; +/** Files on disk. */ +let disk: Record; +/** 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; +/** What `file.saveAll` answers. */ +let saveAll: unknown; +/** Errors to throw, by command id. */ +let failures: Record; +/** 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): Promise { + 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 { + 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 = {}): Promise { + 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(" Promise.resolve(() => undefined)); + invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { + 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(" { + 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 { + 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(" 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(); + }); +});