diff --git a/crates/engine/src/cmd/app.rs b/crates/engine/src/cmd/app.rs index 2f18e4e..8a04e75 100644 --- a/crates/engine/src/cmd/app.rs +++ b/crates/engine/src/cmd/app.rs @@ -53,3 +53,8 @@ impl Command for Quit { Ok(Outcome::effect(Effect::Quit)) } } + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &["app.about", "app.quit"]; diff --git a/crates/engine/src/cmd/buffer.rs b/crates/engine/src/cmd/buffer.rs index 68fb7ec..6dae200 100644 --- a/crates/engine/src/cmd/buffer.rs +++ b/crates/engine/src/cmd/buffer.rs @@ -258,3 +258,9 @@ impl Command for List { Ok(Outcome::value(Value::Array(list))) } } + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = + &["buffer.close", "buffer.edit", "buffer.get", "buffer.list"]; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 74d71aa..fc35781 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -201,3 +201,8 @@ impl Command for SaveAll { )) } } + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &["file.open", "file.save", "file.saveAll"]; diff --git a/crates/engine/src/cmd/git.rs b/crates/engine/src/cmd/git.rs index 3ad6f81..a5b72be 100644 --- a/crates/engine/src/cmd/git.rs +++ b/crates/engine/src/cmd/git.rs @@ -955,6 +955,21 @@ impl Command for CreateBranch { } } +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &[ + "git.branches", + "git.checkout", + "git.commit", + "git.createBranch", + "git.lastMessage", + "git.show", + "git.stage", + "git.status", + "git.unstage", +]; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/cmd/git_blame.rs b/crates/engine/src/cmd/git_blame.rs index 72fc4c4..3a1966e 100644 --- a/crates/engine/src/cmd/git_blame.rs +++ b/crates/engine/src/cmd/git_blame.rs @@ -114,3 +114,8 @@ impl Command for Blame { ) } } + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &["git.blame"]; diff --git a/crates/engine/src/cmd/git_ignore.rs b/crates/engine/src/cmd/git_ignore.rs new file mode 100644 index 0000000..c52a21c --- /dev/null +++ b/crates/engine/src/cmd/git_ignore.rs @@ -0,0 +1,80 @@ +//! `git.ignore` (C7 A3): adds literal patterns for chosen files to the +//! work tree's `.gitignore`, on top of `lutra_vcs::Repo::ignore`. +//! +//! It runs through [`super::git::start_with`] like the other `git.*` +//! commands and sends `gitChanged` afterwards, since the status changes. + +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}; + +/// Most paths one call takes. +const MAX_PATHS: usize = 10_000; + +/// Registers `git.ignore`. +/// +/// # Errors +/// [`EngineError::Internal`] if the id is taken. +pub fn register(registry: &mut Registry) -> Result<(), EngineError> { + registry.register(Box::new(Ignore)) +} + +/// Params of `git.ignore`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct IgnoreParams { + /// Project-relative or absolute paths inside the project. + paths: Vec, +} + +/// `git.ignore`. +struct Ignore; + +impl Command for Ignore { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "git.ignore", + label: "Git: Add to .gitignore", + menu_path: None, + default_shortcut: None, + params: "{ paths: [path inside the project] } (1 to 10000); appends one literal pattern per path to the .gitignore at the work tree's root (created when missing): anchored with /, with \\ * ? [ and trailing spaces escaped, so it matches exactly that file or folder; returns { patterns: [added pattern] }, leaving out patterns already in the file", + } + } + + 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: IgnoreParams = parse(command, params)?; + if p.paths.is_empty() || p.paths.len() > MAX_PATHS { + return Err(EngineError::invalid_params( + command, + format!("paths takes 1 to {MAX_PATHS} entries"), + )); + } + let paths = p + .paths + .iter() + .map(|path| rel_path(state, command, path)) + .collect::, _>>()?; + start_with( + state, + command, + true, + Box::new(move |repo| { + let patterns = repo.ignore(&paths)?; + Ok(json!({ "patterns": patterns })) + }), + ) + } +} + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &["git.ignore"]; diff --git a/crates/engine/src/cmd/git_lines.rs b/crates/engine/src/cmd/git_lines.rs index 7fb751d..48871ef 100644 --- a/crates/engine/src/cmd/git_lines.rs +++ b/crates/engine/src/cmd/git_lines.rs @@ -449,6 +449,11 @@ impl Command for LineChanges { } } +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &["git.lineChanges"]; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/cmd/git_log.rs b/crates/engine/src/cmd/git_log.rs index 64022d2..32ae371 100644 --- a/crates/engine/src/cmd/git_log.rs +++ b/crates/engine/src/cmd/git_log.rs @@ -221,3 +221,8 @@ impl Command for ShowAt { ) } } + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &["git.log", "git.showAt", "git.showCommit"]; diff --git a/crates/engine/src/cmd/git_merge.rs b/crates/engine/src/cmd/git_merge.rs index 838efd0..9962453 100644 --- a/crates/engine/src/cmd/git_merge.rs +++ b/crates/engine/src/cmd/git_merge.rs @@ -1,5 +1,5 @@ //! Merge commands (M4.8): `git.merge`, `git.mergeAbort`, -//! `git.conflictVersions` and `git.markResolved`, on top of +//! `git.conflictVersions`, `git.markResolved` and `git.mergeMessage`, on top of //! `lutra_vcs::Repo`'s merge calls. //! //! Each runs through [`super::git::start_with`]: a pending outcome, git and @@ -25,6 +25,7 @@ pub fn register(registry: &mut Registry) -> Result<(), EngineError> { registry.register(Box::new(MergeAbort))?; registry.register(Box::new(ConflictVersionsCommand))?; registry.register(Box::new(MarkResolved))?; + registry.register(Box::new(MergeMessage))?; Ok(()) } @@ -112,6 +113,36 @@ impl Command for MergeAbort { } } +/// `git.mergeMessage`. +struct MergeMessage; + +impl Command for MergeMessage { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "git.mergeMessage", + label: "Git: Prepared Merge Message", + menu_path: None, + default_shortcut: None, + params: "none; returns { message: string | null }: the message git prepared for the merge in progress (MERGE_MSG without its # comment lines), null when no merge is in progress; for prefilling the commit box", + } + } + + 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, + false, + Box::new(|repo| Ok(json!({ "message": repo.merge_message()? }))), + ) + } +} + /// Params of `git.conflictVersions`. #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] @@ -208,3 +239,14 @@ impl Command for MarkResolved { ) } } + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &[ + "git.conflictVersions", + "git.markResolved", + "git.merge", + "git.mergeAbort", + "git.mergeMessage", +]; diff --git a/crates/engine/src/cmd/git_remote.rs b/crates/engine/src/cmd/git_remote.rs index 827db5a..fe9f5ab 100644 --- a/crates/engine/src/cmd/git_remote.rs +++ b/crates/engine/src/cmd/git_remote.rs @@ -699,3 +699,18 @@ impl Command for RemoteRemove { start(state, command, Op::Remove(p.name)) } } + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &[ + "git.cancel", + "git.clone", + "git.fetch", + "git.pull", + "git.push", + "git.remoteAdd", + "git.remoteRemove", + "git.remoteSetUrl", + "git.remotes", +]; diff --git a/crates/engine/src/cmd/git_stash.rs b/crates/engine/src/cmd/git_stash.rs index cdefd97..3757251 100644 --- a/crates/engine/src/cmd/git_stash.rs +++ b/crates/engine/src/cmd/git_stash.rs @@ -219,3 +219,13 @@ impl Command for StashDrop { ) } } + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &[ + "git.stash", + "git.stashApply", + "git.stashDrop", + "git.stashList", +]; diff --git a/crates/engine/src/cmd/goto.rs b/crates/engine/src/cmd/goto.rs index 83bf2a9..22eb88d 100644 --- a/crates/engine/src/cmd/goto.rs +++ b/crates/engine/src/cmd/goto.rs @@ -516,3 +516,8 @@ fn symbol_item(hit: &SymbolHit<'_>, container: bool) -> Value { } item } + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &["goto.class", "goto.file", "goto.symbol", "index.status"]; diff --git a/crates/engine/src/cmd/lsp_assist.rs b/crates/engine/src/cmd/lsp_assist.rs index d45ae26..df1a313 100644 --- a/crates/engine/src/cmd/lsp_assist.rs +++ b/crates/engine/src/cmd/lsp_assist.rs @@ -841,6 +841,11 @@ fn cap(text: &str, max: usize) -> String { text.get(..end).unwrap_or("").to_string() } +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &["lsp.completion", "lsp.hover", "lsp.signatureHelp"]; + #[cfg(test)] mod tests { use serde_json::json; diff --git a/crates/engine/src/cmd/lsp_diagnostics.rs b/crates/engine/src/cmd/lsp_diagnostics.rs index 7f41623..ce8f784 100644 --- a/crates/engine/src/cmd/lsp_diagnostics.rs +++ b/crates/engine/src/cmd/lsp_diagnostics.rs @@ -135,3 +135,9 @@ impl Command for Log { Ok(Outcome::value(json!({ "lines": state.lsp.log() }))) } } + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = + &["diagnostics.list", "lsp.log", "lsp.restart", "lsp.status"]; diff --git a/crates/engine/src/cmd/lsp_nav.rs b/crates/engine/src/cmd/lsp_nav.rs index d2cc829..279b4e7 100644 --- a/crates/engine/src/cmd/lsp_nav.rs +++ b/crates/engine/src/cmd/lsp_nav.rs @@ -781,6 +781,16 @@ fn notify_summary(state: &mut State, new_name: &str, applied: &edit::Applied) { ); } +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &[ + "lsp.definition", + "lsp.prepareRename", + "lsp.references", + "lsp.rename", +]; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 1b82e60..812b351 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -5,6 +5,7 @@ mod buffer; mod file; pub mod git; pub mod git_blame; +pub mod git_ignore; pub mod git_lines; pub mod git_log; pub mod git_merge; @@ -78,5 +79,37 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> { git_remote::register(registry)?; git_merge::register(registry)?; git_stash::register(registry)?; + git_ignore::register(registry)?; Ok(()) } + +/// The id lists of every module that registers built-in commands, one entry +/// per module. Each module keeps its own list next to its commands, so new +/// commands in different modules never touch the same lines. +#[cfg(test)] +pub(crate) const BUILTIN_COMMAND_IDS: &[&[&str]] = &[ + app::COMMAND_IDS, + buffer::COMMAND_IDS, + file::COMMAND_IDS, + git::COMMAND_IDS, + git_blame::COMMAND_IDS, + git_ignore::COMMAND_IDS, + git_lines::COMMAND_IDS, + git_log::COMMAND_IDS, + git_merge::COMMAND_IDS, + git_remote::COMMAND_IDS, + git_stash::COMMAND_IDS, + goto::COMMAND_IDS, + lsp_assist::COMMAND_IDS, + lsp_diagnostics::COMMAND_IDS, + lsp_nav::COMMAND_IDS, + project::COMMAND_IDS, + recovery::COMMAND_IDS, + search::COMMAND_IDS, + settings::COMMAND_IDS, + syntax::COMMAND_IDS, + terminal::COMMAND_IDS, + theme::COMMAND_IDS, + toolchain::COMMAND_IDS, + ui::COMMAND_IDS, +]; diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index a94b379..102129e 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -230,3 +230,13 @@ impl Command for Children { }))) } } + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &[ + "project.children", + "project.close", + "project.open", + "project.openDialog", +]; diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index d81835a..ad8d43a 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -204,3 +204,8 @@ impl Command for Discard { Ok(Outcome::value(json!({ "discarded": discarded }))) } } + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &["recovery.discard", "recovery.list", "recovery.restore"]; diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index 91c92c2..d5f7ff7 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -302,3 +302,8 @@ impl From for SearchMatch { } } } + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &["search.cancel", "search.find"]; diff --git a/crates/engine/src/cmd/settings.rs b/crates/engine/src/cmd/settings.rs index 84c31a1..520e5c5 100644 --- a/crates/engine/src/cmd/settings.rs +++ b/crates/engine/src/cmd/settings.rs @@ -167,3 +167,13 @@ fn finish( .ok_or_else(|| EngineError::Internal(format!("setting vanished: {key}")))?; Ok(Outcome::value(json!({ "value": value }))) } + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &[ + "settings.get", + "settings.list", + "settings.reset", + "settings.set", +]; diff --git a/crates/engine/src/cmd/syntax.rs b/crates/engine/src/cmd/syntax.rs index 38d3cf6..2ea7253 100644 --- a/crates/engine/src/cmd/syntax.rs +++ b/crates/engine/src/cmd/syntax.rs @@ -581,6 +581,11 @@ impl Command for OutlineCommand { } } +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &["syntax.outline"]; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/cmd/terminal.rs b/crates/engine/src/cmd/terminal.rs index ee69dce..7a69c63 100644 --- a/crates/engine/src/cmd/terminal.rs +++ b/crates/engine/src/cmd/terminal.rs @@ -400,6 +400,16 @@ pub fn pump(state: &mut State) { } } +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &[ + "terminal.close", + "terminal.create", + "terminal.input", + "terminal.resize", +]; + #[cfg(test)] mod tests { use serde_json::json; diff --git a/crates/engine/src/cmd/theme.rs b/crates/engine/src/cmd/theme.rs index c6acc34..fb09f38 100644 --- a/crates/engine/src/cmd/theme.rs +++ b/crates/engine/src/cmd/theme.rs @@ -100,3 +100,8 @@ impl Command for SystemPreference { Ok(Outcome::value(Value::Object(fields))) } } + +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &["theme.list", "theme.systemPreference"]; diff --git a/crates/engine/src/cmd/toolchain.rs b/crates/engine/src/cmd/toolchain.rs index 0025290..b9ca990 100644 --- a/crates/engine/src/cmd/toolchain.rs +++ b/crates/engine/src/cmd/toolchain.rs @@ -639,6 +639,11 @@ impl Command for DownloadPhpactor { } } +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &["toolchain.downloadPhpactor", "toolchain.status"]; + #[cfg(test)] mod tests { use std::io::{Read, Write}; diff --git a/crates/engine/src/cmd/ui.rs b/crates/engine/src/cmd/ui.rs index 8999fd0..2af76c2 100644 --- a/crates/engine/src/cmd/ui.rs +++ b/crates/engine/src/cmd/ui.rs @@ -182,6 +182,11 @@ pub fn dispatch(state: &mut State, id: &str, params: Value) -> Option { Some(Outcome::value(Value::Null)) } +/// The ids of the commands this module registers, checked against the +/// registry by the engine's listing test. Add a new command's id here. +#[cfg(test)] +pub(crate) const COMMAND_IDS: &[&str] = &["ui.registerCommands"]; + #[cfg(test)] mod tests { use super::valid_id; diff --git a/crates/engine/src/engine.rs b/crates/engine/src/engine.rs index 51f856b..6cf84cb 100644 --- a/crates/engine/src/engine.rs +++ b/crates/engine/src/engine.rs @@ -467,91 +467,23 @@ mod tests { let mut engine = Engine::new().unwrap(); engine.register(Box::new(Disabled)).unwrap(); let list = engine.list_commands(); - let ids: Vec<_> = list.iter().map(|c| c.id.as_str()).collect(); - assert_eq!( - ids, - vec![ - "app.about", - "app.quit", - "buffer.close", - "buffer.edit", - "buffer.get", - "buffer.list", - "diagnostics.list", - "file.open", - "file.save", - "file.saveAll", - "git.blame", - "git.branches", - "git.cancel", - "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", - "git.remoteRemove", - "git.remoteSetUrl", - "git.remotes", - "git.show", - "git.showAt", - "git.showCommit", - "git.stage", - "git.stash", - "git.stashApply", - "git.stashDrop", - "git.stashList", - "git.status", - "git.unstage", - "goto.class", - "goto.file", - "goto.symbol", - "index.status", - "lsp.completion", - "lsp.definition", - "lsp.hover", - "lsp.log", - "lsp.prepareRename", - "lsp.references", - "lsp.rename", - "lsp.restart", - "lsp.signatureHelp", - "lsp.status", - "project.children", - "project.close", - "project.open", - "project.openDialog", - "recovery.discard", - "recovery.list", - "recovery.restore", - "search.cancel", - "search.find", - "settings.get", - "settings.list", - "settings.reset", - "settings.set", - "syntax.outline", - "terminal.close", - "terminal.create", - "terminal.input", - "terminal.resize", - "test.disabled", - "theme.list", - "theme.systemPreference", - "toolchain.downloadPhpactor", - "toolchain.status", - "ui.registerCommands", - ] + let ids: Vec<&str> = list.iter().map(|c| c.id.as_str()).collect(); + let mut sorted = ids.clone(); + sorted.sort_unstable(); + assert_eq!(ids, sorted, "the listing is sorted by id"); + let mut expected: Vec<&str> = cmd::BUILTIN_COMMAND_IDS + .iter() + .flat_map(|ids| ids.iter().copied()) + .chain(["test.disabled"]) + .collect(); + expected.sort_unstable(); + let missing: Vec<_> = expected.iter().filter(|id| !ids.contains(id)).collect(); + let extra: Vec<_> = ids.iter().filter(|id| !expected.contains(id)).collect(); + assert!( + missing.is_empty() && extra.is_empty(), + "registered but not in a module's COMMAND_IDS: {extra:?}; listed in COMMAND_IDS but not registered: {missing:?}" ); + assert_eq!(ids, expected, "no id is listed twice"); let by_id = |id: &str| list.iter().find(|c| c.id == id).unwrap(); let quit = by_id("app.quit"); assert_eq!(quit.default_shortcut.as_deref(), Some("Mod+Q")); diff --git a/crates/engine/tests/git_merge.rs b/crates/engine/tests/git_merge.rs index b2ab00e..7f658c9 100644 --- a/crates/engine/tests/git_merge.rs +++ b/crates/engine/tests/git_merge.rs @@ -1,7 +1,7 @@ //! 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. +//! `git.mergeMessage`; `git.ignore` (C7 A3); bad params. Skips with a message when git is not installed. #![allow( clippy::unwrap_used, @@ -147,11 +147,21 @@ fn merge_conflict_versions_resolve_and_abort() { ); assert_eq!(host.git_changes(), 0); + let prepared = host.run("git.mergeMessage", Value::Null).unwrap(); + let text = prepared["message"].as_str().unwrap(); + assert!(text.starts_with("Merge branch 'feature'"), "{text}"); + assert!(!text.contains('#'), "{text}"); + assert_eq!(host.git_changes(), 0); + let again = host.run("git.merge", json!({"branch": "feature"})); assert!(matches!(again, Err(EngineError::Failed(m)) if m.contains("in progress"))); host.run("git.mergeAbort", Value::Null).unwrap(); assert_eq!(host.git_changes(), 1); + assert_eq!( + host.run("git.mergeMessage", Value::Null).unwrap(), + json!({"message": null}) + ); assert_eq!( std::fs::read_to_string(root.join("a.php")).unwrap(), " = status["files"] + .as_array() + .unwrap() + .iter() + .map(|f| f["path"].as_str().unwrap()) + .collect(); + assert!(paths.contains(&"debug1.log"), "{paths:?}"); + assert!(paths.contains(&".gitignore"), "{paths:?}"); + assert!(!paths.contains(&"debug[1].log"), "{paths:?}"); +} diff --git a/crates/mcp/src/jsonrpc.rs b/crates/mcp/src/jsonrpc.rs index ab7d2ed..498d46f 100644 --- a/crates/mcp/src/jsonrpc.rs +++ b/crates/mcp/src/jsonrpc.rs @@ -53,7 +53,11 @@ pub enum Incoming { /// The error response line to send back: a parse error for invalid /// JSON, invalid request for anything that is not a single JSON-RPC 2.0 /// message, invalid params for params that are not an object. +/// +/// A leading byte order mark is dropped first: Windows PowerShell 5.1 +/// writes one when it pipes text into a native program. pub fn parse(line: &str) -> Result { + let line = line.strip_prefix('\u{feff}').unwrap_or(line); let value: Value = serde_json::from_str(line) .map_err(|e| error(&Value::Null, codes::PARSE_ERROR, &e.to_string(), None))?; let Value::Object(mut object) = value else { @@ -176,6 +180,10 @@ mod tests { }; assert_eq!(id, json!("a")); assert_eq!(params["k"], 1); + assert!(matches!( + parse("\u{feff}{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}"), + Ok(Incoming::Request { .. }) + )); assert_eq!( parse(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#).unwrap(), Incoming::Notification { diff --git a/crates/vcs/src/ignore.rs b/crates/vcs/src/ignore.rs new file mode 100644 index 0000000..8a540c8 --- /dev/null +++ b/crates/vcs/src/ignore.rs @@ -0,0 +1,115 @@ +//! Ignoring files (C7 A3): appending literal patterns for chosen paths to +//! the `.gitignore` at the work tree's root. +//! +//! Each path becomes one pattern that matches exactly that path: anchored +//! with a leading `/`, and with the characters gitignore treats specially +//! (`\`, `*`, `?`, `[`, and trailing spaces) escaped with a backslash, so a +//! file named `a*.php` ignores only itself. Patterns already in the file +//! are not added again. + +use std::fs::OpenOptions; +use std::io::{ErrorKind, Write}; + +use crate::Repo; +use crate::VcsError; +use crate::repo::SMALL_CAP; + +/// The literal, root-anchored gitignore pattern of a root-relative path. +/// +/// # Parameters +/// - `path`: a root-relative path with `/` separators, as +/// [`Repo::to_repo_path`] returns it. +pub fn ignore_pattern(path: &str) -> String { + let kept = path.trim_end_matches(' '); + let trailing = path.len() - kept.len(); + let mut out = String::with_capacity(path.len() + 8); + out.push('/'); + for c in kept.chars() { + if matches!(c, '\\' | '*' | '?' | '[') { + out.push('\\'); + } + out.push(c); + } + for _ in 0..trailing { + out.push_str("\\ "); + } + out +} + +impl Repo { + /// Appends a literal pattern for each path to the root's `.gitignore` + /// (created when missing), on a line of its own. + /// + /// # Parameters + /// - `paths`: project-relative paths of files or folders. + /// + /// # Returns + /// The patterns added, in the order given; patterns already in the + /// file are left out. + /// + /// # Errors + /// [`VcsError::InvalidPath`] for a bad path (nothing is written); + /// [`VcsError::Git`] when `.gitignore` cannot be read or written, or is + /// larger than 16 MiB. + pub fn ignore(&self, paths: &[String]) -> Result, VcsError> { + let mut patterns = Vec::with_capacity(paths.len()); + for path in paths { + let pattern = ignore_pattern(&self.to_repo_path(path)?); + if pattern != "/" && !patterns.contains(&pattern) { + patterns.push(pattern); + } + } + if patterns.is_empty() { + return Ok(patterns); + } + let _guard = self.lock(); + let file = self.root().join(".gitignore"); + let failed = |e: std::io::Error| VcsError::Git(format!("cannot update .gitignore: {e}")); + let existing = match std::fs::read(&file) { + Ok(bytes) => bytes, + Err(e) if e.kind() == ErrorKind::NotFound => Vec::new(), + Err(e) => return Err(failed(e)), + }; + if existing.len() > SMALL_CAP { + return Err(VcsError::Git( + "cannot update .gitignore: the file is too large".into(), + )); + } + let text = String::from_utf8_lossy(&existing); + let present: Vec<&str> = text.lines().collect(); + patterns.retain(|p| !present.contains(&p.as_str())); + if patterns.is_empty() { + return Ok(patterns); + } + let mut out = String::new(); + if !existing.is_empty() && !existing.ends_with(b"\n") { + out.push('\n'); + } + for pattern in &patterns { + out.push_str(pattern); + out.push('\n'); + } + OpenOptions::new() + .create(true) + .append(true) + .open(&file) + .and_then(|mut f| f.write_all(out.as_bytes())) + .map_err(failed)?; + Ok(patterns) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn patterns_are_anchored_and_literal() { + assert_eq!(ignore_pattern("tmp.txt"), "/tmp.txt"); + assert_eq!(ignore_pattern("a/b c.php"), "/a/b c.php"); + assert_eq!(ignore_pattern("x*?[y].php"), "/x\\*\\?\\[y].php"); + assert_eq!(ignore_pattern("#note!"), "/#note!"); + assert_eq!(ignore_pattern("back\\slash"), "/back\\\\slash"); + assert_eq!(ignore_pattern("end "), "/end\\ \\ "); + } +} diff --git a/crates/vcs/src/lib.rs b/crates/vcs/src/lib.rs index d6fbe4a..7d5c18f 100644 --- a/crates/vcs/src/lib.rs +++ b/crates/vcs/src/lib.rs @@ -12,6 +12,8 @@ //! git's credential helper and the ssh agent (see `remote.rs`). //! - Blame (M4.7): who last changed each line, of the working copy or an //! editor buffer (`blame.rs`). +//! - Ignoring files (C7 A3): literal patterns appended to `.gitignore` +//! (`ignore.rs`). //! - [`RepoWatch`] notices changes inside `.git` (HEAD, index, refs). //! //! Every call goes through [`runner::run`]: arguments as an array, never a @@ -25,6 +27,7 @@ pub mod blame; mod error; +mod ignore; pub mod log; pub mod porcelain; mod remote; @@ -35,6 +38,7 @@ mod watch; pub use blame::{BlameLine, UNCOMMITTED_AUTHOR, is_uncommitted}; pub use error::VcsError; +pub use ignore::ignore_pattern; pub use log::{CommitDetails, CommitFile, LOG_LIMIT, LogCommit, LogQuery}; pub use porcelain::{FileState, FileStatus, Head, Status, Version}; pub use remote::{ diff --git a/crates/vcs/src/merge.rs b/crates/vcs/src/merge.rs index 008720c..5cc9afc 100644 --- a/crates/vcs/src/merge.rs +++ b/crates/vcs/src/merge.rs @@ -12,11 +12,29 @@ //! - [`Repo::mark_resolved`] stages the files (`add -A`), which removes the //! unmerged entries; a file deleted in the work tree is staged as deleted. //! - [`Repo::merge_abort`] runs `git merge --abort`. +//! - [`Repo::merge_message`] reads the message git prepared for the merge +//! in progress (`MERGE_MSG`), for the commit box. + +use std::io::Read; use crate::VcsError; use crate::repo::{Contents, FILE_CAP, Repo, SMALL_CAP, check_name, decode}; use crate::runner::{Call, HOOK_TIMEOUT}; +/// The most of `MERGE_MSG` [`Repo::merge_message`] reads. +const MESSAGE_CAP: u64 = 64 * 1024; + +/// Removes comment lines (starting with `#`) and surrounding blank lines +/// from a prepared commit message; line endings become `\n`. +fn strip_comments(text: &str) -> String { + text.lines() + .filter(|line| !line.starts_with('#')) + .collect::>() + .join("\n") + .trim_matches(['\n', ' ', '\t']) + .to_string() +} + /// How a merge ended. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MergeResult { @@ -209,6 +227,35 @@ impl Repo { }) } + /// The message git prepared for the merge in progress: `MERGE_MSG` in + /// the repository directory, without its comment lines (those starting + /// with `#`, git's default comment character, such as the list of + /// conflicts) and without surrounding blank lines. + /// + /// A missing or unreadable file means there is no message: the box is + /// only a convenience, and the commit itself reports real failures. + /// + /// # Returns + /// `None` when no merge is in progress or git left no message. + /// + /// # Errors + /// The runner's errors. + pub fn merge_message(&self) -> Result, VcsError> { + if !self.merging()? { + return Ok(None); + } + let Ok(file) = std::fs::File::open(self.git_dir().join("MERGE_MSG")) else { + return Ok(None); + }; + let mut bytes = Vec::new(); + if file.take(MESSAGE_CAP).read_to_end(&mut bytes).is_err() { + return Ok(None); + } + let text = String::from_utf8_lossy(&bytes); + let message = strip_comments(&text); + Ok((!message.is_empty()).then_some(message)) + } + /// Aborts the merge in progress (`git merge --abort`): the work tree /// and index go back to the state before the merge. /// @@ -303,6 +350,16 @@ mod tests { use super::*; use proptest::prelude::*; + #[test] + fn strips_comment_lines_from_a_prepared_message() { + assert_eq!( + strip_comments("Merge branch 'f'\r\n\r\n# Conflicts:\r\n#\ta.php\r\n"), + "Merge branch 'f'" + ); + assert_eq!(strip_comments("\nA\n\nB\n#c\n\n"), "A\n\nB"); + assert_eq!(strip_comments("# only\n"), ""); + } + #[test] fn reads_check_lines() { assert_eq!( diff --git a/crates/vcs/tests/ignore.rs b/crates/vcs/tests/ignore.rs new file mode 100644 index 0000000..04959cd --- /dev/null +++ b/crates/vcs/tests/ignore.rs @@ -0,0 +1,86 @@ +//! Ignoring files against a real temp repository: literal patterns for +//! odd names, a project in a subfolder, no duplicates, a missing final line +//! break, and refused paths. Skips with a message when git is not +//! installed. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::Path; +use std::process::Command; + +use lutra_vcs::{Git, 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` and returns its stdout and whether it succeeded. +fn git(dir: &Path, args: &[&str]) -> (String, bool) { + 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(); + ( + String::from_utf8_lossy(&out.stdout).trim().to_string(), + out.status.success(), + ) +} + +/// Whether git ignores `path` (root-relative). +fn ignored(dir: &Path, path: &str) -> bool { + git(dir, &["check-ignore", "-q", "--no-index", "--", path]).1 +} + +#[test] +fn ignores_exactly_the_given_paths() { + let Some(cli) = installed() else { return }; + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + assert!(git(root, &["init", "-q", "-b", "main"]).1); + std::fs::create_dir_all(root.join("app/var")).unwrap(); + std::fs::write(root.join(".gitignore"), "vendor/").unwrap(); + for name in [ + "app/a[1].php", + "app/a1.php", + "app/var/cache.log", + "app/b.php", + ] { + std::fs::write(root.join(name), "x").unwrap(); + } + let repo = cli.open(&root.join("app")).unwrap().expect("a repository"); + + let added = repo + .ignore(&[ + "a[1].php".to_string(), + "var".to_string(), + "var/".to_string(), + ]) + .unwrap(); + assert_eq!(added, vec![r"/app/a\[1].php", "/app/var"]); + assert_eq!( + std::fs::read_to_string(root.join(".gitignore")).unwrap(), + "vendor/\n/app/a\\[1].php\n/app/var\n" + ); + assert!(ignored(root, "app/a[1].php")); + assert!(!ignored(root, "app/a1.php")); + assert!(ignored(root, "app/var/cache.log")); + assert!(!ignored(root, "app/b.php")); + + assert!(repo.ignore(&["a[1].php".to_string()]).unwrap().is_empty()); + assert!(matches!( + repo.ignore(&["../outside".to_string(), "b.php".to_string()]), + Err(VcsError::InvalidPath(_)) + )); + assert!(!ignored(root, "app/b.php")); +} diff --git a/crates/vcs/tests/merge.rs b/crates/vcs/tests/merge.rs index 50d5a97..8bc236c 100644 --- a/crates/vcs/tests/merge.rs +++ b/crates/vcs/tests/merge.rs @@ -127,10 +127,14 @@ fn a_conflict_its_versions_resolving_and_committing() { init(root); conflicting(root); let repo = open(&cli, root); + assert_eq!(repo.merge_message().unwrap(), None); let outcome = repo.merge("feature").unwrap(); assert_eq!(outcome.result, MergeResult::Conflicts); assert_eq!(outcome.conflicts, vec!["a.php"]); assert!(repo.merging().unwrap()); + let prepared = repo.merge_message().unwrap().unwrap(); + assert!(prepared.starts_with("Merge branch 'feature'"), "{prepared}"); + assert!(!prepared.contains('#'), "{prepared}"); let status = repo.status().unwrap(); let file = status.files.iter().find(|f| f.path == "a.php").unwrap(); assert_eq!(file.worktree, FileState::Conflicted); @@ -160,6 +164,7 @@ fn a_conflict_its_versions_resolving_and_committing() { )); repo.commit("Merge feature", false).unwrap(); assert!(!repo.merging().unwrap()); + assert_eq!(repo.merge_message().unwrap(), None); assert_eq!(git(root, &["rev-list", "--count", "--merges", "HEAD"]), "1"); } diff --git a/docs/architecture.md b/docs/architecture.md index 11378ac..3701e03 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -594,6 +594,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat - **Commands** (UI commands, menu group Git): `vcs.openChanges` `Mod+Alt+Shift+G` shows the tab; `vcs.commit` `Mod+Alt+Shift+M` shows it and focuses the message box; `vcs.refresh` re-reads the status (enabled while `git.status` is). The shortcuts are Lutra's own: checked against the public default keymaps (Windows and macOS) so they copy no default there, and against Lutra's registered shortcuts and CodeMirror's `basicSetup` keys (`Mod+Alt+G` is its go to line, which the global listener would swallow). - **Status:** read from the shared status store (`ui/src/stores/vcsStatus.ts`, since C6 F1), which runs `git.status` on start, on `projectOpened`, on `gitChanged` and on `vcs.refresh`; `projectClosed` clears it and with it the rows and the selection. The result is untrusted: unknown states and malformed entries are dropped, at most 50,000 files. - **Amend prefill (C6 F1):** checking Amend with an empty message box fills it from `git.lastMessage`; clearing Amend empties a box that still holds exactly that text. A message already typed is never replaced. The event type `gitChanged` is now part of `EngineEventPayload` in `ui/src/ipc.ts`. +- **Context menu and ignoring (C7 A3):** a right click on a row (or Shift+F10 / the context-menu key) opens `ChangesContextMenu.vue`: Open, and Add to .gitignore for untracked rows. That runs `git.ignore {paths}` (`cmd/git_ignore.rs`, `crates/vcs/src/ignore.rs`) → `{patterns}`: one pattern per path appended to the work tree root's `.gitignore`, anchored with `/` and with `\ * ? [` and trailing spaces escaped, so it matches only that path; patterns already present are skipped; `gitChanged` follows. - **Groups:** Staged (the index side changed), Changes (the work tree side changed, or conflicted), Untracked. A partly staged file is in Staged and Changes. Names are coloured with `--lt-vcs-*` (renamed and modified use `modified`, copied uses `added`); a deleted file is struck through. A staged rename shows "from ". - **Staging:** a checkbox per file and per group header: checked in Staged (clearing it unstages), clear elsewhere (checking it stages). `git.stage {paths}` / `git.unstage {paths}`, both through `runWaiting`; unstaging a staged rename passes both paths, as M4.1 requires. Keyboard: Up/Down, Page Up/Down, Home, End move; Space stages or unstages; Enter opens. Failures toast git's message (`notification.command.failed`). - **Opening:** Enter or a double-click runs the UI command `vcs.showDiff {path, staged}` when something provides it (the diff viewer, M4.3, registers and provides it); until then the file opens with `file.open`, and a deleted file does nothing. @@ -709,7 +710,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat ### Merge conflicts (M4.8) - **Backend (`crates/vcs/src/merge.rs`, an `impl Repo` append):** `merge(branch)` runs `git merge --no-edit --no-progress --end-of-options ` (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`. +- **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}` → `{}`; `git.mergeMessage` → `{message: string|null}` (git's prepared `MERGE_MSG` without `#` comment lines, null outside a merge; the Changes window offers it in an empty commit box once per merge and on `vcs.commit`). 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. @@ -756,6 +757,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | C7 A3: `git.mergeMessage` and the merge message prefill, `git.ignore` and the Changes context menu, gutter markers kept on their line, per-module `COMMAND_IDS` for the command listing test | | 2026-10-30 | minor | M4.7: blame (`git.blame` with `--contents` from the buffer, the annotation gutter by age, hover with the commit message, `vcs.toggleBlame`, `vcs.showCommit`) | | 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) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 465cf95..cda67b7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -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 | 16% (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 (C6); stash: stashing selected files, a stash's diff, unstash as a branch, restoring the index; 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.) | C6 M4.9: stash from the Git menu or the Changes window (`vcs.stash`, `vcs.showStashes`): a message and "Include untracked files", open files saved first; a list of entries (message or WIP text, branch, date) with apply, pop and drop after a question; refusals say what to do (nothing to stash, no commit yet, unresolved conflicts, conflicts after applying with the entry kept, files that would be overwritten, a stash changed meanwhile). Backend `git.stash`, `git.stashList`, `git.stashApply {index, pop, hash?}`, `git.stashDrop`. Tests: `crates/vcs/tests/stash.rs`, `crates/engine/tests/git_stash.rs`, `ui/tests/vcs/Stash.test.ts`. 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. | +| Git | 8 | 16% (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, context menu actions beyond Open and Add to .gitignore (rollback, delete); 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 (C6); stash: stashing selected files, a stash's diff, unstash as a branch, restoring the index; 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.) | C7 A3: a context menu on Changes rows (right click, Shift+F10 or the context-menu key) with Open and Add to .gitignore for untracked files (`git.ignore`: one anchored, escaped literal pattern per file in the root `.gitignore`); while a merge waits on conflicts, an empty commit box offers git's prepared merge message (`git.mergeMessage`); gutter markers stay on their line when text is inserted at its start. Tests: `crates/vcs/tests/ignore.rs`, `crates/vcs/tests/merge.rs`, `crates/engine/tests/git_merge.rs`, Vitest (`ui/tests/vcs/ChangesToolWindow.test.ts`, `ui/tests/editor/gitGutter.test.ts`). C6 M4.9: stash from the Git menu or the Changes window (`vcs.stash`, `vcs.showStashes`): a message and "Include untracked files", open files saved first; a list of entries (message or WIP text, branch, date) with apply, pop and drop after a question; refusals say what to do (nothing to stash, no commit yet, unresolved conflicts, conflicts after applying with the entry kept, files that would be overwritten, a stash changed meanwhile). Backend `git.stash`, `git.stashList`, `git.stashApply {index, pop, hash?}`, `git.stashDrop`. Tests: `crates/vcs/tests/stash.rs`, `crates/engine/tests/git_stash.rs`, `ui/tests/vcs/Stash.test.ts`. 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.) | — | @@ -65,6 +65,7 @@ The project tree is the first user-visible feature (Project view 8%, estimated); | Date | Change | Summary | |---|---|---| +| 2026-10-31 | patch | C7 A3 evidence in the Git row (Changes context menu with Add to .gitignore, merge message prefill, gutter markers on inserts); score left to the PM | | 2026-10-30 | minor | C6 review: Git 11% → 16% (est.): log, blame, merge conflicts, stash and remotes on top of the C5 core | | 2026-10-30 | patch | M4.9 evidence in the Git row (stash dialog, apply/pop/drop, refusals); score left to the PM | | 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 | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bf0a646..4a4a2da 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -41,7 +41,7 @@ - [ ] Terminal tool window - M3.6 (2026-10-18): a Terminal tab in the bottom panel (the panel shows Find and Terminal as tabs while both are open; Left/Right switch); xterm.js with the fit addon follows the panel size; several terminals as sub-tabs (Local, Local (2)…) with a close button each and a new-terminal button, Left/Right/Home/End/Delete on a sub-tab, an ended shell dims its tab and prints its exit code; output survives collapsing the panel; copy with `Mod+Shift+C` or `Ctrl+C` on a selection, paste with `Mod+Shift+V` or `Ctrl+V`; while a terminal has the focus plain Ctrl keys go to the shell and only Mod+Shift / Mod+Alt shortcuts reach Lutra; Lutra's own ANSI palette in both themes (text colours ≥ 4.5:1). `terminal.open` `Mod+Shift+T`. Missing: renaming and splitting tabs, a context menu, search, clickable links and paths, drag and drop, a key back to the editor, a confirmation before killing a running process, terminal settings. - [ ] Git tool window - - M4.2 (2026-10-25): a Changes tab in the bottom panel (`vcs.openChanges` `Mod+Alt+Shift+G`, menu Git › Changes): Staged, Changes and Untracked groups with counts, file names coloured by status (`--lt-vcs-*`, deleted struck through, a staged rename shows its old path), a checkbox per file and per group to stage or unstage, Up/Down/Page/Home/End and Space in the list, double-click or Enter opens the diff (M4.3) or the file; a commit message box with Amend and Commit (`Mod+Enter`; `vcs.commit` `Mod+Alt+Shift+M` focuses it), saving open files first; a refresh button (`vcs.refresh`); hints when git is missing or the folder is not a repository. Vitest (19 tests). Missing: a tree view and grouping by directory or module, changelists, chunk staging, a context menu (rollback, delete, add to .gitignore), recent commit messages, commit options (sign-off, author, skip hooks), commit and push, a commit preview of the diff. Behaviour notes: `plan/phpstorm/16-vcs-basics.md`. + - M4.2 (2026-10-25): a Changes tab in the bottom panel (`vcs.openChanges` `Mod+Alt+Shift+G`, menu Git › Changes): Staged, Changes and Untracked groups with counts, file names coloured by status (`--lt-vcs-*`, deleted struck through, a staged rename shows its old path), a checkbox per file and per group to stage or unstage, Up/Down/Page/Home/End and Space in the list, double-click or Enter opens the diff (M4.3) or the file; a commit message box with Amend and Commit (`Mod+Enter`; `vcs.commit` `Mod+Alt+Shift+M` focuses it), saving open files first; a refresh button (`vcs.refresh`); hints when git is missing or the folder is not a repository. Vitest (19 tests). C7 A3: a row context menu (right click, Shift+F10, the context-menu key) with Open and Add to .gitignore for untracked files, and git's prepared merge message offered in an empty box during a merge. Missing: a tree view and grouping by directory or module, changelists, chunk staging, context menu actions to roll back or delete, recent commit messages, commit options (sign-off, author, skip hooks), commit and push, a commit preview of the diff. Behaviour notes: `plan/phpstorm/16-vcs-basics.md`. - M4.4 (2026-10-25): the editor gutter shows a bar beside lines added or changed since the staged version and a notch where lines were deleted (tooltips from the catalog), updated 150 ms after typing and whenever Git changes; file names in the project tree and the tabs take the Git status colour (added, modified, deleted, untracked, conflicted; ignored entries inside a repository). Vitest. Missing: clicking a marker to see the old text, revert or stage the chunk, next/previous change, markers against HEAD, coloured directories. - M4.3 (2026-10-26): "Diff: " tabs in the editor area after the file tabs (`vcs.showDiff` `Mod+Alt+Shift+D`, menu Git › Show Diff; double-click or Enter in Changes; right click or Shift+F10 on a file in the project tree → Show Diff): the staged version or the last commit on the left, read-only, and the working copy on the right, editable like its own tab; a caption says what is compared; changed lines and words tinted with the VCS tokens, a change bar in each gutter, unchanged stretches collapsed to a clickable row; next/previous change `Alt+Shift+]` / `Alt+Shift+[` (wrapping); notices for binary, too large and deleted files and for git's errors. The project tree got its first context menu (Open, Show Diff; WAI-ARIA menu, keyboard). Vitest. Missing: unified view, revert/stage arrows between the sides, synchronised horizontal scrolling, whitespace and highlighting options, comparing with any revision, a diff window of its own, more tree context menu items. - M4.5 (2026-10-26): the status bar shows the current branch (Lucide `git-branch`), or the short hash when detached, hidden outside a repository. A click or `vcs.branches` (menu Git › Branches…) opens a popup above it: a filter field, "New branch…", Local (current one checked, upstream beside it) and Remote headings; Up/Down/Page keys, Enter or a click checks out, Escape or a click outside closes and returns the focus. "New branch…" switches to a name field with a "Check out" checkbox; git's refusal shows under the field. An exclusive modal. Vitest (16 tests). Missing: merge, rebase, rename, delete, compare with current, favourites, recent branches first, incoming/outgoing markers, a submenu per branch. @@ -51,6 +51,7 @@ | Date | Change | Summary | |---|---|---| +| 2026-10-31 | patch | Changes context menu with Add to .gitignore and the merge message prefill (C7 A3) | | 2026-10-28 | minor | Fetch/pull/push with progress, clone and remotes dialogs (M4.10) | | 2026-10-26 | minor | Branch widget and popup (M4.5) | | 2026-10-26 | minor | Diff viewer and the project tree's context menu (M4.3) | diff --git a/ui/src/components/editor/gitGutter.ts b/ui/src/components/editor/gitGutter.ts index b9f4006..cadff0e 100644 --- a/ui/src/components/editor/gitGutter.ts +++ b/ui/src/components/editor/gitGutter.ts @@ -108,6 +108,12 @@ class GitMarker extends GutterMarker { super(); } + /** Text inserted at the line's start pushes the marker down with the line. */ + override startSide = 1; + + /** Same side as the start, so the empty range survives mapping. */ + override endSide = 1; + override eq(other: GutterMarker): boolean { return other instanceof GitMarker && other.kind === this.kind; } diff --git a/ui/src/components/vcs/changes/ChangesContextMenu.vue b/ui/src/components/vcs/changes/ChangesContextMenu.vue new file mode 100644 index 0000000..5f8cb89 --- /dev/null +++ b/ui/src/components/vcs/changes/ChangesContextMenu.vue @@ -0,0 +1,200 @@ + + + + + diff --git a/ui/src/components/vcs/changes/ChangesToolWindow.vue b/ui/src/components/vcs/changes/ChangesToolWindow.vue index 8bc49ba..b8da5a6 100644 --- a/ui/src/components/vcs/changes/ChangesToolWindow.vue +++ b/ui/src/components/vcs/changes/ChangesToolWindow.vue @@ -20,6 +20,9 @@ * `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. + * - **Context menu (C7 A3):** a right click on a row, or Shift+F10 / the + * context-menu key on the selected one, opens `ChangesContextMenu.vue`: + * Open, and Add to .gitignore for untracked files. * - **Commit box:** the message, an Amend checkbox and Commit. Commit * saves dirty buffers first (`flushDirty`); `Mod+Enter` in the box * commits too. @@ -35,6 +38,7 @@ import { t } from "../../../i18n"; import { run } from "../../../ipc"; import { baseName } from "../../../stores/editor"; import { useNotificationsStore } from "../../../stores/notifications"; +import ChangesContextMenu from "./ChangesContextMenu.vue"; import { SHORT_HASH, useChangesStore, type ChangeRow, type FileState, type GroupId } from "./changes"; const changes = useChangesStore(); @@ -46,6 +50,27 @@ const list = ref(null); /** The commit message box. */ const messageBox = ref(null); +/** The open context menu: its row and where it shows; null when closed. */ +const menu = ref<{ row: ChangeRow; x: number; y: number } | null>(null); + +/** + * Opens the context menu of a row. + * + * @param row - the row; it becomes the selection. + * @param x - window x of the menu. + * @param y - window y of the menu. + */ +function openMenu(row: ChangeRow, x: number, y: number): void { + changes.select(row.key); + menu.value = { row, x, y }; +} + +/** Closes the context menu and gives the focus back to the list. */ +function closeMenu(): void { + menu.value = null; + list.value?.focus(); +} + /** Rows moved by Page Up and Page Down. */ const PAGE = 10; @@ -259,6 +284,10 @@ function onListKey(event: KeyboardEvent): void { } else if (event.key === " " && row) { event.preventDefault(); void changes.toggle(row); + } else if ((event.key === "ContextMenu" || (event.key === "F10" && event.shiftKey)) && row) { + event.preventDefault(); + const rect = document.getElementById(optionId(changes.selectedIndex))?.getBoundingClientRect(); + openMenu(row, rect ? rect.left + 24 : 0, rect ? rect.bottom : 0); } } @@ -399,6 +428,7 @@ watch( data-test="changes-row" @click="changes.select(row.key)" @dblclick="openRow(row)" + @contextmenu.prevent="openMenu(row, $event.clientX, $event.clientY)" > +
{ void onAmend(on); }); + /** Whether the box is empty and Amend is off, so a prepared message may fill it. */ + function boxFree(): boolean { + return !amend.value && message.value.trim() === ""; + } + + /** Whether the prepared merge message was offered for the merge in progress. */ + let mergeOffered = false; + + /** + * Fills an empty box (without Amend) with the message git prepared for + * the merge in progress. A failed call or no merge leaves the box as it + * is; no merge also ends the current offer. + */ + async function offerMergeMessage(): Promise { + if (!boxFree()) { + return; + } + const result = await runWaiting("git.mergeMessage"); + if (!result.ok) { + return; + } + const value = result.value; + const text = + typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.message === "string" + ? value.message + : null; + if (text === null) { + mergeOffered = false; + return; + } + mergeOffered = true; + if (boxFree()) { + message.value = text; + } + } + + watch(status, (s) => { + const conflicted = (s?.files ?? []).some((f) => f.index === "conflicted" || f.worktree === "conflicted"); + if (conflicted && !mergeOffered) { + void offerMergeMessage(); + } + }); + /** * Runs a mutating git command, toasting its failure. * @@ -301,6 +350,32 @@ export const useChangesStore = defineStore("changes", () => { return row.group === "staged" ? unstage([row]) : stage([row]); } + /** + * Adds untracked files to the root `.gitignore`, one literal pattern + * each, and toasts the result. + * + * @param list - rows; those not in Untracked are ignored. + */ + async function ignore(list: ChangeRow[]): Promise { + const paths = [...new Set(list.filter((row) => row.group === "untracked").map((row) => row.file.path))]; + if (paths.length === 0 || busy.value) { + return; + } + busy.value = true; + try { + if ((await mutate("git.ignore", { paths })) !== null) { + notifications.notify({ + level: "info", + messageKey: "notification.vcs.ignored", + params: { path: paths.join(", ") }, + }); + await refresh(); + } + } finally { + busy.value = false; + } + } + /** * Stages or unstages a whole group. * @@ -343,6 +418,7 @@ export const useChangesStore = defineStore("changes", () => { params: { hash: hash.slice(0, SHORT_HASH), summary }, }); prefilled = null; + mergeOffered = false; message.value = ""; amend.value = false; await refresh(); @@ -383,6 +459,9 @@ export const useChangesStore = defineStore("changes", () => { open(); focusPending.value = true; focusRequest.value += 1; + if (phase.value === "ready") { + void offerMergeMessage(); + } } /** Hides the tool window; the status and the message stay. */ @@ -436,6 +515,7 @@ export const useChangesStore = defineStore("changes", () => { unstage, toggle, toggleGroup, + ignore, commit, start, stop, diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index 09a6b9b..a96d816 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -183,6 +183,7 @@ "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.ignored": "Added to .gitignore: {path}", "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}", @@ -222,7 +223,7 @@ "problems.severity.hint": "Hint", "problems.severity.info": "Information", "problems.severity.warning": "Warning", - "problems.summary": "{errors} errors, {warnings} warnings, {infos} other", + "problems.summary": "Errors: {errors}, warnings: {warnings}, other: {infos}", "problems.toolWindow.title": "Problems", "project.empty.noFolder": "No folder is open.", "project.openFolder": "Open Folder…", @@ -347,6 +348,9 @@ "vcs.changes.group.untracked": "Untracked", "vcs.changes.list.label": "Changed files", "vcs.changes.loading": "Reading the Git status…", + "vcs.changes.menu.ignore": "Add to .gitignore", + "vcs.changes.menu.label": "Actions for {path}", + "vcs.changes.menu.open": "Open", "vcs.changes.noCommits": "no commits yet", "vcs.changes.noProject": "Open a project to see its changes", "vcs.changes.noRepo": "This project is not in a Git repository", diff --git a/ui/tests/editor/gitGutter.test.ts b/ui/tests/editor/gitGutter.test.ts index dc1f314..23168b3 100644 --- a/ui/tests/editor/gitGutter.test.ts +++ b/ui/tests/editor/gitGutter.test.ts @@ -220,6 +220,8 @@ describe("the gutter", () => { expect(markers(view)).toEqual({ 2: "modified" }); view.dispatch({ changes: { from: 0, insert: "new\n" } }); expect(markers(view)).toEqual({ 3: "modified" }); + view.dispatch({ changes: { from: view.state.doc.line(3).from, insert: "typed\n" } }); + expect(markers(view)).toEqual({ 4: "modified" }); engine.answer = { ranges: [], version: 2 }; refreshGitGutters(); await flush(); diff --git a/ui/tests/i18n/catalog.test.ts b/ui/tests/i18n/catalog.test.ts index 72f6166..617e6a2 100644 --- a/ui/tests/i18n/catalog.test.ts +++ b/ui/tests/i18n/catalog.test.ts @@ -38,108 +38,85 @@ const usedKeys = sourceFiles(SRC).flatMap((file) => })), ); +/** Root of the repository. */ +const REPO = join(SRC, "..", ".."); + +/** + * Lists the Rust files below a directory, leaving out `tests` directories + * and build output. + * + * @param dir - the directory. + */ +function rustFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const path = join(dir, entry.name); + if (entry.isDirectory()) { + return ["tests", "target", "node_modules"].includes(entry.name) ? [] : rustFiles(path); + } + return entry.name.endsWith(".rs") ? [path] : []; + }); +} + +/** + * The shipped part of a Rust file: everything before its unit test module. + * + * @param file - the path. + */ +function shippedRust(file: string): string { + return readFileSync(file, "utf8").replace(/\r\n/g, "\n").split("\n#[cfg(test)]\nmod tests")[0] ?? ""; +} + +/** + * Turns a settings enum value into its key segment (`lutra-dark` → + * `lutraDark`). + * + * @param value - the value as the engine stores it. + */ +function camel(value: string): string { + return value.replace(/-([a-z0-9])/g, (_, c: string) => c.toUpperCase()); +} + /** * Keys the source never passes to `t` literally because they arrive at - * runtime: theme labels from `theme.list`, the settings' `labelKey`, - * `descriptionKey`, section names and enum value names from - * `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), the merge - * toasts (M4.8) and the remote toasts (M4.10), passed as - * `messageKey`. + * runtime, derived from the source so new ones need no list here: + * + * - any `notification.*` literal: the `messageKey` of `notification` + * events (engine and desktop host) and of the toasts the frontend raises; + * - Rust `*_key: "…"` fields: theme labels and the settings' `labelKey` + * and `descriptionKey`; + * - per settings definition, its section name (`settings.section.`) and + * each enum value (`settings..value.`). */ -const RUNTIME_KEYS = new Set([ - "notification.command.failed", - "notification.lsp.failed", - "notification.lsp.message", - "notification.lsp.renamed", - "notification.project.notLocal", - "notification.project.openFailed", - "notification.project.unsavedChanges", - "notification.recovery.corrupt", - "notification.recovery.unavailable", - "notification.recovery.writeFailed", - "notification.save.failed", - "notification.vcs.branchCreated", - "notification.vcs.checkedOut", - "notification.vcs.checkoutFailed", - "notification.vcs.checkoutNotSaved", - "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", - "notification.vcs.fetched", - "notification.vcs.pullFailed", - "notification.vcs.pullNotSaved", - "notification.vcs.pulled", - "notification.vcs.pushFailed", - "notification.vcs.pushed", - "notification.vcs.pushedUpstream", - "notification.vcs.remoteCancelled", - "notification.vcs.resolved", - "notification.vcs.stashApplied", - "notification.vcs.stashDropped", - "notification.vcs.stashPopped", - "notification.vcs.stashed", - "notification.settings.corrupt", - "notification.settings.corruptNotMoved", - "notification.settings.unavailable", - "notification.toolchain.downloadDone", - "notification.toolchain.downloadFailed", - "notification.toolchain.downloadStarted", - "notification.toolchain.phpMissing", - "notification.vfs.pumpFailed", - "notification.watch.failed", - "settings.appearance.theme.description", - "settings.appearance.theme.label", - "settings.appearance.theme.value.lutraDark", - "settings.appearance.theme.value.lutraLight", - "settings.appearance.theme.value.system", - "settings.editor.autosave.idleSeconds.description", - "settings.editor.autosave.idleSeconds.label", - "settings.editor.autosave.onBlur.description", - "settings.editor.autosave.onBlur.label", - "settings.editor.autosave.onTabSwitch.description", - "settings.editor.autosave.onTabSwitch.label", - "settings.editor.completion.autoPopup.description", - "settings.editor.completion.autoPopup.label", - "settings.editor.completion.delayMs.description", - "settings.editor.completion.delayMs.label", - "settings.editor.fontSize.description", - "settings.editor.fontSize.label", - "settings.editor.hover.delayMs.description", - "settings.editor.hover.delayMs.label", - "settings.git.executable.description", - "settings.git.executable.label", - "settings.git.pull.mode.description", - "settings.git.pull.mode.label", - "settings.git.pull.mode.value.merge", - "settings.git.pull.mode.value.rebase", - "settings.php.executable.description", - "settings.php.executable.label", - "settings.phpactor.autoDownload.description", - "settings.phpactor.autoDownload.label", - "settings.phpactor.path.description", - "settings.phpactor.path.label", - "settings.section.appearance", - "settings.section.editor", - "settings.section.git", - "settings.section.php", - "settings.ui.language.description", - "settings.ui.language.label", - "settings.ui.language.value.en", - "theme.lutraDark", - "theme.lutraLight", -]); +const RUNTIME_KEYS = (() => { + const keys = new Set(); + const add = (text: string, pattern: RegExp): void => { + for (const m of text.matchAll(pattern)) { + keys.add(m[1] ?? ""); + } + }; + for (const file of sourceFiles(SRC)) { + add(readFileSync(file, "utf8"), /["'`](notification\.[A-Za-z0-9.]+)["'`]/g); + } + for (const file of [...rustFiles(join(REPO, "crates")), ...rustFiles(join(REPO, "apps"))]) { + const text = shippedRust(file); + add(text, /"(notification\.[A-Za-z0-9.]+)"/g); + add(text, /\b[a-z]+_key:\s*"([a-z][A-Za-z0-9.]*)"/g); + for (const def of text.matchAll(/\bDef\s*\{([\s\S]*?)\n\s*\},?\n/g)) { + const body = def[1] ?? ""; + const key = /\bkey:\s*"([^"]+)"/.exec(body)?.[1]; + const section = /\bsection:\s*"([^"]+)"/.exec(body)?.[1]; + if (section !== undefined) { + keys.add(`settings.section.${section}`); + } + const values = /Kind::Enum\(&\[([^\]]*)\]\)/.exec(body)?.[1] ?? ""; + for (const value of values.matchAll(/"([^"]+)"/g)) { + keys.add(`settings.${key ?? ""}.value.${camel(value[1] ?? "")}`); + } + } + } + keys.delete(""); + return keys; +})(); afterEach(() => { vi.restoreAllMocks(); @@ -206,6 +183,19 @@ describe("en.json", () => { expect(missing).toEqual([]); }); + it("finds the runtime keys of every source", () => { + for (const key of [ + "notification.vcs.committed", + "notification.project.unsavedChanges", + "settings.editor.fontSize.label", + "settings.section.git", + "settings.appearance.theme.value.lutraDark", + "theme.lutraLight", + ]) { + expect(RUNTIME_KEYS.has(key), key).toBe(true); + } + }); + it("has every runtime key", () => { expect([...RUNTIME_KEYS].filter((key) => !hasMessage(key))).toEqual([]); }); diff --git a/ui/tests/menu/AppMenu.test.ts b/ui/tests/menu/AppMenu.test.ts index 2943641..9fc76fa 100644 --- a/ui/tests/menu/AppMenu.test.ts +++ b/ui/tests/menu/AppMenu.test.ts @@ -255,49 +255,32 @@ describe("AppMenu", () => { expect(menu.find("[data-test=menu-button]").attributes("aria-expanded")).toBe("true"); const headings = [...document.querySelectorAll("[data-test=menu-group]")].map((g) => g.querySelector(".app-menu__heading")?.textContent.trim()); expect(headings).toEqual(["File", "Edit", "View", "Go", "Git", "Help"]); - expect(itemIds()).toEqual([ + const listed = listing() as { id: string; menuPath: string | null }[]; + const withPath = listed.filter((c) => c.menuPath !== null); + expect([...itemIds()].sort()).toEqual(withPath.map((c) => c.id).sort()); + const groups = [...document.querySelectorAll("[data-test=menu-group]")].map((g) => ({ + heading: g.querySelector(".app-menu__heading")?.textContent.trim() ?? "", + ids: [...g.querySelectorAll("[data-test=menu-item]")].map((el) => el.dataset.command ?? ""), + labels: [...g.querySelectorAll("[data-test=menu-item]")].map((el) => el.querySelector(".app-menu__label")?.textContent.trim() ?? ""), + })); + for (const group of groups) { + for (const id of group.ids) { + expect(withPath.find((c) => c.id === id)?.menuPath?.split("/")[0], id).toBe(group.heading); + } + } + expect(groups.find((g) => g.heading === "File")?.ids).toEqual([ "project.openDialog", "file.save", "file.saveAll", "buffer.close", "project.close", "app.quit", - "editor.complete", - "editor.parameterInfo", - "editor.quickDocumentation", - "palette.open", - "view.toggleProjectTree", - "view.toggleStructure", - "find.open", - "terminal.open", - "problems.open", - "settings.open", - "goto.fileOpen", - "goto.classOpen", - "goto.symbolOpen", - "vcs.abortMerge", - "vcs.toggleBlame", - "vcs.branches", - "vcs.openChanges", - "vcs.clone", - "vcs.commit", - "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", - "vcs.stash", - "vcs.showStashes", - "app.about", ]); + expect(groups.find((g) => g.heading === "Go")?.ids).toEqual(["goto.fileOpen", "goto.classOpen", "goto.symbolOpen"]); + const git = groups.find((g) => g.heading === "Git")?.labels ?? []; + expect(git.length).toBeGreaterThan(1); + expect(git).toEqual([...git].sort((x, y) => x.localeCompare(y))); + expect(itemIds().at(-1)).toBe("app.about"); const close = document.querySelector("[data-command='buffer.close']"); expect(close?.textContent).toContain("Close Tab"); expect(close?.querySelector("[data-test=menu-shortcut]")?.textContent).toBe("Ctrl+W"); diff --git a/ui/tests/palette/CommandPalette.test.ts b/ui/tests/palette/CommandPalette.test.ts index e771e54..c5486f8 100644 --- a/ui/tests/palette/CommandPalette.test.ts +++ b/ui/tests/palette/CommandPalette.test.ts @@ -257,49 +257,14 @@ describe("CommandPalette", () => { await press(PALETTE_KEY); 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.toggleBlame", - "vcs.branches", - "vcs.openChanges", - "vcs.checkout", - "vcs.clone", - "project.close", - "palette.open", - "vcs.commit", - "editor.complete", - "vcs.fetch", - "find.open", - "goto.classOpen", - "goto.fileOpen", - "goto.symbolOpen", - "vcs.showLog", - "vcs.manageRemotes", - "vcs.merge", - "vcs.newBranch", - "vcs.nextChange", - "project.openDialog", - "menu.open", - "editor.parameterInfo", - "vcs.previousChange", - "problems.open", - "vcs.pull", - "vcs.push", - "editor.quickDocumentation", - "app.quit", - "vcs.refresh", - "vcs.resolveConflicts", - "editor.reveal", - "settings.open", - "vcs.showCommit", - "vcs.showDiff", - "vcs.showHistory", - "view.toggleProjectTree", - "view.toggleStructure", - "vcs.stash", - "vcs.showStashes", - "terminal.open", - ]); + const offered = (listing() as { id: string; menuPath: string | null; defaultShortcut: string | null; ui: boolean }[]) + .filter((c) => c.ui || c.menuPath !== null || c.defaultShortcut !== null) + .map((c) => c.id); + expect(offered).toContain("palette.open"); + expect(offered).not.toContain("buffer.edit"); + expect([...rows(wrapper)].sort()).toEqual([...offered].sort()); + const labels = wrapper.findAll("[data-test=palette-row] .palette__label").map((label) => label.text()); + expect(labels).toEqual([...labels].sort((x, y) => x.localeCompare(y))); const quit = wrapper.find("[data-command='app.quit']"); expect(quit.find("[data-test=palette-shortcut]").text()).toBe("Ctrl+Q"); expect(quit.text()).toContain("Quit"); diff --git a/ui/tests/problems/ProblemsToolWindow.test.ts b/ui/tests/problems/ProblemsToolWindow.test.ts index 1c91086..968aef3 100644 --- a/ui/tests/problems/ProblemsToolWindow.test.ts +++ b/ui/tests/problems/ProblemsToolWindow.test.ts @@ -211,7 +211,7 @@ describe("ProblemsToolWindow", () => { items: [diag(4, "warning", "Unused variable"), { ...diag(1, "error", "Undefined method"), code: "E12" }], }); await emit({ kind: "diagnosticsChanged", path: "a.php", items: [diag(0, "hint", "Could be final")] }); - expect(wrapper.get("[data-test=problems-status]").text()).toBe("1 errors, 1 warnings, 1 other"); + expect(wrapper.get("[data-test=problems-status]").text()).toBe("Errors: 1, warnings: 1, other: 1"); const files = wrapper.findAll("[data-test=problems-file]").map((f) => f.text()); expect(files[0]).toContain("a.php"); expect(files[1]).toContain("Service.php"); diff --git a/ui/tests/vcs/ChangesToolWindow.test.ts b/ui/tests/vcs/ChangesToolWindow.test.ts index 0936a02..f7ef920 100644 --- a/ui/tests/vcs/ChangesToolWindow.test.ts +++ b/ui/tests/vcs/ChangesToolWindow.test.ts @@ -49,6 +49,8 @@ let listeners: ((event: { payload: unknown }) => void)[]; let gitStatus: unknown; /** Errors to throw, by command id. */ let failures: Record; +/** What `git.mergeMessage` answers. */ +let mergeMessage: string | null; /** What `file.saveAll` answers. */ let saveAll: unknown; /** Pinia of the current test. */ @@ -118,6 +120,7 @@ beforeEach(() => { mounted = []; failures = {}; gitStatus = sampleStatus(); + mergeMessage = null; saveAll = { saved: [], failed: [], skipped: [] }; Element.prototype.scrollIntoView = () => undefined; invoke.mockReset(); @@ -145,6 +148,8 @@ beforeEach(() => { return Promise.resolve(gitStatus); case "git.lastMessage": return Promise.resolve({ message: "Last subject\n\nLast body" }); + case "git.mergeMessage": + return Promise.resolve({ message: mergeMessage }); case "git.commit": return Promise.resolve({ commit: "fedcba9876543210", summary: String(args.params.message).split("\n")[0] }); case "file.saveAll": @@ -338,6 +343,32 @@ describe("the Changes store", () => { expect(callsOf("git.lastMessage")).toHaveLength(1); }); + it("offers git's prepared merge message once while a merge has conflicts", async () => { + const changes = useChangesStore(pinia); + await changes.refresh(); + expect(callsOf("git.mergeMessage")).toHaveLength(0); + mergeMessage = "Merge branch 'feature'"; + gitStatus = { + ...sampleStatus(), + files: [{ path: "a.php", index: "conflicted", worktree: "conflicted" }], + }; + await changes.refresh(); + await flushPromises(); + expect(callsOf("git.mergeMessage")).toHaveLength(1); + expect(changes.message).toBe("Merge branch 'feature'"); + changes.message = ""; + await emit({ kind: "gitChanged", available: true, repo: null, filesChanged: true }); + expect(callsOf("git.mergeMessage")).toHaveLength(1); + expect(changes.message).toBe(""); + changes.focusMessage(); + await flushPromises(); + expect(changes.message).toBe("Merge branch 'feature'"); + changes.message = "mine"; + changes.focusMessage(); + await flushPromises(); + expect(changes.message).toBe("mine"); + }); + it("keeps the message when git refuses the commit", async () => { const changes = useChangesStore(pinia); await changes.refresh(); @@ -399,6 +430,35 @@ describe("the Changes window", () => { expect(callsOf("file.open").map((c) => c.params)).toEqual([{ path: "src/a.php" }]); }); + it("adds an untracked file to .gitignore from its context menu", async () => { + const wrapper = await mountChanges(); + const rows = wrapper.findAll("[data-test=changes-row]"); + await rows[0]?.trigger("contextmenu", { clientX: 10, clientY: 10 }); + const items = (): HTMLElement[] => [...document.querySelectorAll("[data-test=changes-menu-item]")]; + expect(items().map((item) => item.dataset.item)).toEqual(["open", "ignore"]); + expect(items()[1]?.getAttribute("aria-disabled")).toBe("true"); + items()[1]?.click(); + await flushPromises(); + expect(callsOf("git.ignore")).toHaveLength(0); + document.querySelector("[data-test=changes-menu]")?.dispatchEvent( + new KeyboardEvent("keydown", { key: "Escape", bubbles: true }), + ); + await flushPromises(); + expect(document.querySelector("[data-test=changes-menu]")).toBeNull(); + + const list = wrapper.get("[data-test=changes-list]"); + await list.trigger("keydown", { key: "End" }); + await list.trigger("keydown", { key: "F10", shiftKey: true }); + expect(items()[1]?.getAttribute("aria-disabled")).toBe("false"); + const refreshes = callsOf("git.status").length; + items()[1]?.click(); + await flushPromises(); + expect(callsOf("git.ignore").map((c) => c.params)).toEqual([{ paths: ["tmp.txt"] }]); + expect(callsOf("git.status").length).toBe(refreshes + 1); + expect(useNotificationsStore(pinia).toasts.map((toast) => toast.text)).toContain("Added to .gitignore: tmp.txt"); + expect(document.querySelector("[data-test=changes-menu]")).toBeNull(); + }); + it("opens through vcs.showDiff when it is provided, and never opens a deleted file", async () => { const wrapper = await mountChanges(); const rows = wrapper.findAll("[data-test=changes-row]");