diff --git a/crates/engine/src/cmd/git_stash.rs b/crates/engine/src/cmd/git_stash.rs new file mode 100644 index 0000000..cdefd97 --- /dev/null +++ b/crates/engine/src/cmd/git_stash.rs @@ -0,0 +1,221 @@ +//! Stash commands (M4.9): `git.stash`, `git.stashList`, `git.stashApply` +//! and `git.stashDrop`, run like every `git.*` command (a pending outcome +//! off the lock, git and the repository cached by [`super::git`]). The +//! three that change the repository emit `gitChanged`. + +use lutra_vcs::StashEntry; +use serde::Deserialize; +use serde_json::{Value, json}; + +use super::git::start_with; +use super::params::parse; +use crate::{Command, CommandSpec, EngineError, Outcome, Registry, State}; + +/// Largest index the commands take; the list holds at most 1,000 entries. +const MAX_INDEX: usize = 100_000; + +/// Registers the stash commands. +/// +/// # Errors +/// [`EngineError::Internal`] if an id is taken. +pub fn register(registry: &mut Registry) -> Result<(), EngineError> { + registry.register(Box::new(Stash))?; + registry.register(Box::new(StashList))?; + registry.register(Box::new(StashApply))?; + registry.register(Box::new(StashDrop))?; + Ok(()) +} + +/// One entry as the commands return it. +fn entry_json(entry: &StashEntry) -> Value { + json!({ + "index": entry.index, + "hash": entry.hash, + "branch": entry.branch, + "message": entry.message, + "wip": entry.wip, + "date": entry.date, + }) +} + +/// Refuses an index past [`MAX_INDEX`]. +fn check_index(command: &str, index: usize) -> Result<(), EngineError> { + if index > MAX_INDEX { + return Err(EngineError::invalid_params( + command, + format!("index must be 0 to {MAX_INDEX}"), + )); + } + Ok(()) +} + +/// Params of `git.stash`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +struct StashParams { + /// The entry's message; blank means git's "WIP on" message. + #[serde(default)] + message: Option, + /// Stash untracked files too. + #[serde(default)] + include_untracked: bool, +} + +/// `git.stash`. +struct Stash; + +impl Command for Stash { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "git.stash", + label: "Git: Stash Changes", + menu_path: None, + default_shortcut: None, + params: "{ message?: string (blank: git's \"WIP on \" message; line breaks become spaces), includeUntracked?: boolean (false) }; stashes every local change of the repository's work tree and resets it to HEAD; returns { entry: { index: 0, hash, branch, message, wip, date } }; refused with a clear message without a commit, with unmerged files, or with nothing to stash. Dirty buffers are not saved first", + } + } + + fn enabled(&self, state: &State) -> bool { + state.has_project() + } + + fn run(&self, state: &mut State, params: Value) -> Result { + let command = self.spec().id; + let p: StashParams = parse(command, params)?; + start_with( + state, + command, + true, + Box::new(move |repo| { + let entry = repo.stash(p.message.as_deref(), p.include_untracked)?; + Ok(json!({"entry": entry_json(&entry)})) + }), + ) + } +} + +/// `git.stashList`. +struct StashList; + +impl Command for StashList { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "git.stashList", + label: "Git: List Stashes", + menu_path: None, + default_shortcut: None, + params: "none; returns { stashes: [{ index, hash, branch: string | null, message, wip, date (ISO 8601) }] } newest first (index 0 is stash@{0}), at most 1,000", + } + } + + 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(move |repo| { + let stashes: Vec = repo.stash_list()?.iter().map(entry_json).collect(); + Ok(json!({"stashes": stashes})) + }), + ) + } +} + +/// Params of `git.stashApply`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct ApplyParams { + /// The entry. + index: usize, + /// Drop the entry after applying it cleanly. + #[serde(default)] + pop: bool, + /// The entry's hash as listed; refuses when the stash changed since. + #[serde(default)] + hash: Option, +} + +/// `git.stashApply`. +struct StashApply; + +impl Command for StashApply { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "git.stashApply", + label: "Git: Apply Stash", + menu_path: None, + default_shortcut: None, + params: "{ index: number (stash@{index}), pop?: boolean (false: keep the entry), hash?: the entry's hash from git.stashList, refused when the entry at index differs }; returns {}; refused with a clear message for a missing entry, unmerged files, local changes that would be overwritten, untracked files in the way, or conflicts (the files then hold conflict markers and the entry is kept)", + } + } + + 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: ApplyParams = parse(command, params)?; + check_index(command, p.index)?; + start_with( + state, + command, + true, + Box::new(move |repo| { + repo.stash_apply(p.index, p.pop, p.hash.as_deref())?; + Ok(json!({})) + }), + ) + } +} + +/// Params of `git.stashDrop`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct DropParams { + /// The entry. + index: usize, + /// The entry's hash as listed. + #[serde(default)] + hash: Option, +} + +/// `git.stashDrop`. +struct StashDrop; + +impl Command for StashDrop { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "git.stashDrop", + label: "Git: Drop Stash", + menu_path: None, + default_shortcut: None, + params: "{ index: number (stash@{index}), hash?: the entry's hash from git.stashList, refused when the entry at index differs }; deletes the entry; returns {}", + } + } + + 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: DropParams = parse(command, params)?; + check_index(command, p.index)?; + start_with( + state, + command, + true, + Box::new(move |repo| { + repo.stash_drop(p.index, p.hash.as_deref())?; + Ok(json!({})) + }), + ) + } +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index c17b70a..e3a2e3d 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -8,6 +8,7 @@ pub mod git_lines; pub mod git_log; pub mod git_merge; pub mod git_remote; +pub mod git_stash; pub mod goto; mod lsp_assist; mod lsp_diagnostics; @@ -74,5 +75,6 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> { git_log::register(registry)?; git_remote::register(registry)?; git_merge::register(registry)?; + git_stash::register(registry)?; Ok(()) } diff --git a/crates/engine/src/engine.rs b/crates/engine/src/engine.rs index 09fb30c..9f1c713 100644 --- a/crates/engine/src/engine.rs +++ b/crates/engine/src/engine.rs @@ -505,6 +505,10 @@ mod tests { "git.showAt", "git.showCommit", "git.stage", + "git.stash", + "git.stashApply", + "git.stashDrop", + "git.stashList", "git.status", "git.unstage", "goto.class", diff --git a/crates/engine/tests/git_stash.rs b/crates/engine/tests/git_stash.rs new file mode 100644 index 0000000..d3ab2cd --- /dev/null +++ b/crates/engine/tests/git_stash.rs @@ -0,0 +1,189 @@ +//! The stash commands (M4.9) through the engine: `git.stash`, +//! `git.stashList`, `git.stashApply` with and without pop, `git.stashDrop`, +//! refusals as `failed` with a clear message, bad params, and `gitChanged` +//! after the changes only. Skips with a message when git is not installed. + +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::indexing_slicing +)] + +use std::path::Path; +use std::process::Command; +use std::sync::Mutex; + +use lutra_engine::{Engine, EngineError, Event, run_waiting}; +use serde_json::{Value, json}; + +/// Whether git is installed; prints why a test is skipped. +fn have_git() -> bool { + let ok = Command::new("git") + .arg("--version") + .output() + .is_ok_and(|o| o.status.success()); + if !ok { + eprintln!("skipped: git is not installed"); + } + ok +} + +/// Runs git for test setup. +fn git(dir: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .args(args) + .current_dir(dir) + .output() + .unwrap(); + assert!( + out.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +/// An engine with `root` open, recording events. +struct Host { + /// The engine. + engine: Mutex, + /// Events published so far. + events: Mutex>, +} + +impl Host { + /// Opens `root` as the project. + fn open(root: &Path) -> Self { + let host = Self { + engine: Mutex::new(Engine::new().unwrap()), + events: Mutex::new(Vec::new()), + }; + host.run("project.open", json!({"path": root})).unwrap(); + host + } + + /// Runs a command the way hosts do. + fn run(&self, command: &str, params: Value) -> Result { + run_waiting( + || self.engine.lock().unwrap(), + command, + params, + |events| self.events.lock().unwrap().extend_from_slice(events), + ) + .map(|o| o.value) + } + + /// Takes the number of `gitChanged` events so far and forgets them. + fn git_changed(&self) -> usize { + let mut events = self.events.lock().unwrap(); + let count = events + .iter() + .filter(|e| matches!(e, Event::GitChanged(_))) + .count(); + events.clear(); + count + } +} + +#[test] +fn stash_list_apply_and_drop() { + if !have_git() { + return; + } + let dir = tempfile::tempdir().unwrap(); + let d = dir.path(); + git(d, &["init", "-q", "-b", "main"]); + for (key, value) in [ + ("user.name", "Lutra Test"), + ("user.email", "test@lutra.invalid"), + ("commit.gpgsign", "false"), + ("core.autocrlf", "false"), + ("core.hooksPath", ".git/hooks"), + ] { + git(d, &["config", key, value]); + } + std::fs::write(d.join("a.php"), ", + /// The message given, or git's ` ` of the commit + /// it was made on when none was given. + pub message: String, + /// Whether no message was given (git's "WIP on" entry). + pub wip: bool, + /// When it was made, strict ISO 8601. + pub date: String, +} + +impl Repo { + /// The stash, newest first, at most [`STASH_LIST_CAP`] entries. + /// + /// # Errors + /// The runner's errors or git's refusal. No stash is an empty list. + pub fn stash_list(&self) -> Result, VcsError> { + if self.stash_top()?.is_none() { + return Ok(Vec::new()); + } + let count = format!("--max-count={STASH_LIST_CAP}"); + let output = self + .run(Call::read( + self.root(), + &["stash", "list", LIST_FORMAT, &count], + SMALL_CAP, + ))? + .checked()?; + Ok(parse_stash_list(&output.stdout)) + } + + /// Stashes the local changes of the whole work tree (staged and not) + /// and resets it to HEAD. + /// + /// # Parameters + /// - `message`: the entry's message; blank means git's "WIP on" + /// message. Line breaks become spaces, other control characters are + /// dropped, and it is cut at [`STASH_MESSAGE_CAP`] characters. + /// - `include_untracked`: stash untracked files too (ignored files + /// never). + /// + /// # Returns + /// The new entry (`stash@{0}`). + /// + /// # Errors + /// [`VcsError::Git`] with a clear sentence when the repository has no + /// commit yet, when files are unmerged, or when there is nothing to + /// stash; git's refusal otherwise. + pub fn stash( + &self, + message: Option<&str>, + include_untracked: bool, + ) -> Result { + let message = message.map(clean_message).filter(|m| !m.is_empty()); + let _guard = self.lock(); + if !self.has_commit()? { + return Err(VcsError::Git( + "Nothing can be stashed before the first commit. Commit once, then stash." + .to_string(), + )); + } + self.refuse_unmerged("Stashing")?; + let before = self.stash_top()?; + let mut args = vec!["stash", "push", "--quiet"]; + if include_untracked { + args.push("--include-untracked"); + } + let message_arg = message.map(|m| format!("--message={m}")); + args.extend(message_arg.as_deref()); + self.run(Call::write(self.root(), &args).timeout(HOOK_TIMEOUT))? + .checked()?; + let after = self.stash_top()?; + if after.is_none() || after == before { + let hint = if include_untracked { + "There are no local changes to stash." + } else { + "There are no local changes to stash. Untracked files are stashed only when untracked files are included." + }; + return Err(VcsError::Git(hint.to_string())); + } + if include_untracked { + self.remove_stashed_untracked()?; + } + self.stash_list()? + .into_iter() + .next() + .ok_or_else(|| VcsError::BadOutput("stash list is empty after stashing".to_string())) + } + + /// Applies a stash entry to the work tree; with `pop` the entry is + /// dropped when it applied cleanly. + /// + /// # Parameters + /// - `index`: the entry (`stash@{index}`). + /// - `pop`: drop the entry after applying it. + /// - `hash`: the entry's hash as the caller listed it; when given and + /// the entry at `index` has another hash (the stash changed since), + /// nothing is applied. + /// + /// # Errors + /// [`VcsError::InvalidName`] for a hash that is not 4 to 64 hex + /// digits; [`VcsError::Git`] with a clear sentence for a missing or + /// changed entry, unmerged files, conflicts while applying (the files + /// then hold conflict markers and the entry is kept), local changes + /// that would be overwritten and untracked files in the way; git's + /// refusal otherwise. + pub fn stash_apply(&self, index: usize, pop: bool, hash: Option<&str>) -> Result<(), VcsError> { + let _guard = self.lock(); + let reference = self.stash_entry(index, hash)?; + self.refuse_unmerged("Applying a stash")?; + let action = if pop { "pop" } else { "apply" }; + let output = self.run( + Call::write(self.root(), &["stash", action, "--quiet", &reference]) + .timeout(HOOK_TIMEOUT), + )?; + if output.success() { + return Ok(()); + } + let message = output.message(); + let conflicts = self.unmerged_count()?; + if conflicts > 0 { + let kept = if pop { + " The stash entry was kept; drop it once the conflicts are resolved." + } else { + "" + }; + return Err(VcsError::Git(format!( + "The stash was applied with conflicts in {conflicts} {}. Resolve them in the Changes window.{kept}", + if conflicts == 1 { "file" } else { "files" }, + ))); + } + Err(VcsError::Git(explain(&message))) + } + + /// Drops a stash entry. It cannot be restored from Lutra afterwards. + /// + /// # Parameters + /// - `index`: the entry (`stash@{index}`). + /// - `hash`: as for [`Repo::stash_apply`]. + /// + /// # Errors + /// As [`Repo::stash_apply`] for a missing or changed entry, or git's + /// refusal. + pub fn stash_drop(&self, index: usize, hash: Option<&str>) -> Result<(), VcsError> { + let _guard = self.lock(); + let reference = self.stash_entry(index, hash)?; + self.run(Call::write( + self.root(), + &["stash", "drop", "--quiet", &reference], + ))? + .checked()?; + Ok(()) + } + + /// The reference `stash@{index}` after checking the entry exists and, + /// when `hash` is given, is the one the caller saw. + fn stash_entry(&self, index: usize, hash: Option<&str>) -> Result { + if let Some(hash) = hash { + check_hash(hash)?; + } + let list = self.stash_list()?; + let Some(entry) = list.get(index) else { + return Err(VcsError::Git(if list.is_empty() { + "The stash is empty.".to_string() + } else { + format!( + "There is no stash entry {index}; the stash holds {} {}. Refresh the list.", + list.len(), + if list.len() == 1 { "entry" } else { "entries" }, + ) + })); + }; + if let Some(hash) = hash + && !entry.hash.starts_with(&hash.to_ascii_lowercase()) + { + return Err(VcsError::Git( + "The stash changed since it was listed. Refresh the list and try again." + .to_string(), + )); + } + Ok(format!("stash@{{{index}}}")) + } + + /// Removes the untracked files the newest entry holds from the work + /// tree, as `git stash push --include-untracked` should have done. + /// + /// Every call runs with `--literal-pathspecs`, and under it git's stash + /// stores untracked files without removing them (git's internal clean + /// uses a pathspec with magic). So the files listed in the entry's + /// untracked tree (`stash@{0}^3`) go through `git clean -f`, which only + /// ever removes untracked files, in chunks of at most + /// [`CLEAN_CHUNK`] bytes of arguments; folders left empty are removed. + /// A folder that cannot be removed is left (`.ok()`): it is empty and + /// git does not see it. + /// + /// # Errors + /// The runner's errors or git's refusal. + fn remove_stashed_untracked(&self) -> Result<(), VcsError> { + let output = self.run(Call::read( + self.root(), + &[ + "ls-tree", + "-r", + "-z", + "--name-only", + "--full-tree", + "stash@{0}^3", + ], + SMALL_CAP, + ))?; + if !output.success() { + return Ok(()); + } + let paths: Vec = output + .stdout + .split(|b| *b == 0) + .filter(|p| !p.is_empty()) + .map(|p| String::from_utf8_lossy(p).into_owned()) + .collect(); + for chunk in chunks(&paths, CLEAN_CHUNK) { + let mut args = vec!["clean", "-f", "-q", "--"]; + args.extend(chunk.iter().map(String::as_str)); + self.run(Call::write(self.root(), &args))?.checked()?; + } + let mut dirs: Vec<&str> = paths + .iter() + .flat_map(|p| p.match_indices('/').filter_map(move |(i, _)| p.get(..i))) + .collect(); + dirs.sort_unstable_by_key(|d| std::cmp::Reverse(d.len())); + dirs.dedup(); + for dir in dirs { + std::fs::remove_dir(self.root().join(dir)).ok(); + } + Ok(()) + } + + /// The hash `refs/stash` points to, `None` without a stash. + fn stash_top(&self) -> Result, VcsError> { + let output = self.run(Call::read( + self.root(), + &["rev-parse", "--verify", "--quiet", "refs/stash"], + 4096, + ))?; + if !output.success() { + return Ok(None); + } + let text = String::from_utf8_lossy(&output.stdout).trim().to_string(); + Ok(Some(text).filter(|t| !t.is_empty())) + } + + /// Whether HEAD points to a commit. + fn has_commit(&self) -> Result { + Ok(self + .run(Call::read( + self.root(), + &["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], + 4096, + ))? + .success()) + } + + /// How many paths have unmerged index entries (merge conflicts). + fn unmerged_count(&self) -> Result { + let output = self + .run(Call::read( + self.root(), + &["ls-files", "--unmerged", "-z"], + SMALL_CAP, + ))? + .checked()?; + Ok(count_unmerged(&output.stdout)) + } + + /// Refuses while files are unmerged, naming `what` was refused. + fn refuse_unmerged(&self, what: &str) -> Result<(), VcsError> { + let count = self.unmerged_count()?; + if count == 0 { + return Ok(()); + } + Err(VcsError::Git(format!( + "{what} is not possible while {count} {} merge conflicts. Resolve them first.", + if count == 1 { "file has" } else { "files have" }, + ))) + } +} + +/// Splits paths into groups whose total length stays within `limit` bytes +/// (a path longer than the limit forms its own group), so a command line +/// stays below Windows' 32,767 characters. +fn chunks(paths: &[String], limit: usize) -> Vec<&[String]> { + let mut out = Vec::new(); + let mut start = 0; + let mut size = 0; + for (i, path) in paths.iter().enumerate() { + let len = path.len() + 1; + if i > start && size + len > limit { + out.extend(paths.get(start..i)); + start = i; + size = 0; + } + size += len; + } + if start < paths.len() { + out.extend(paths.get(start..)); + } + out +} + +/// A message git can take: line breaks become spaces, other control +/// characters are dropped, the ends trimmed, the length capped. +fn clean_message(message: &str) -> String { + message + .chars() + .filter_map(|c| match c { + '\n' | '\r' | '\t' => Some(' '), + c if c.is_control() => None, + c => Some(c), + }) + .take(STASH_MESSAGE_CAP) + .collect::() + .trim() + .to_string() +} + +/// Rejects anything but 4 to 64 hex digits. +fn check_hash(hash: &str) -> Result<(), VcsError> { + if (4..=64).contains(&hash.len()) && hash.bytes().all(|b| b.is_ascii_hexdigit()) { + Ok(()) + } else { + Err(VcsError::InvalidName(hash.to_string())) + } +} + +/// Puts a sentence that says what to do before git's message, for the +/// refusals that have one. +fn explain(message: &str) -> String { + let hint = if message.contains("would be overwritten") { + Some( + "Local changes to files the stash also changes would be overwritten. Commit, stash or roll them back first.", + ) + } else if message.contains("already exists, no checkout") + || message.contains("could not restore untracked files") + { + Some( + "Untracked files from the stash already exist in the working tree. Move or delete them first.", + ) + } else { + None + }; + match hint { + Some(hint) if message.trim().is_empty() => hint.to_string(), + Some(hint) => format!("{hint}\n\n{}", message.trim()), + None => message.trim().to_string(), + } +} + +/// Counts the distinct paths of `ls-files --unmerged -z` (one line per +/// stage: ` \t`). +pub fn count_unmerged(bytes: &[u8]) -> usize { + let mut paths: Vec<&[u8]> = bytes + .split(|b| *b == 0) + .filter_map(|line| { + let tab = line.iter().position(|b| *b == b'\t')?; + line.get(tab + 1..).filter(|p| !p.is_empty()) + }) + .collect(); + paths.sort_unstable(); + paths.dedup(); + paths.len() +} + +/// Splits a reflog subject (`On main: message`, `WIP on main: abc1234 +/// subject`) into branch, message and whether it is a "WIP" entry. Other +/// forms keep the whole subject as the message. +pub fn parse_subject(subject: &str) -> (Option, String, bool) { + let (rest, wip) = if let Some(rest) = subject.strip_prefix("WIP on ") { + (rest, true) + } else if let Some(rest) = subject.strip_prefix("On ") { + (rest, false) + } else { + return (None, subject.to_string(), false); + }; + match rest.split_once(": ") { + Some((branch, message)) if !branch.is_empty() => { + (Some(branch.to_string()), message.to_string(), wip) + } + _ => (None, subject.to_string(), false), + } +} + +/// Parses the [`LIST_FORMAT`] output; the position of a record is its +/// index. Records without a hash are skipped (and do not count). +pub fn parse_stash_list(bytes: &[u8]) -> Vec { + let mut entries = Vec::new(); + for record in bytes.split(|b| *b == RECORD) { + let text = String::from_utf8_lossy(record); + let text = text.trim_end_matches(['\n', '\r']); + let mut fields = text.split('\0'); + let (Some(hash), Some(subject), Some(date)) = (fields.next(), fields.next(), fields.next()) + else { + continue; + }; + let hash = hash.trim(); + if hash.is_empty() { + continue; + } + let (branch, message, wip) = parse_subject(subject); + entries.push(StashEntry { + index: entries.len(), + hash: hash.to_string(), + branch, + message, + wip, + date: date.trim().to_string(), + }); + } + entries +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::indexing_slicing)] + + use super::*; + use proptest::prelude::*; + + #[test] + fn list_records_parse() { + let bytes = b"\x1eaaa\0WIP on main: 41aa1cf init\x002026-10-28T18:08:36+01:00\n\x1ebbb\0On feature/x: my work\x002026-10-28T18:00:00Z\n\x1eccc\0odd subject\0d\n"; + let entries = parse_stash_list(bytes); + assert_eq!(entries.len(), 3); + assert_eq!(entries[0].index, 0); + assert_eq!(entries[0].branch.as_deref(), Some("main")); + assert_eq!(entries[0].message, "41aa1cf init"); + assert!(entries[0].wip); + assert_eq!(entries[1].branch.as_deref(), Some("feature/x")); + assert_eq!(entries[1].message, "my work"); + assert!(!entries[1].wip); + assert_eq!(entries[1].date, "2026-10-28T18:00:00Z"); + assert_eq!(entries[2].branch, None); + assert_eq!(entries[2].message, "odd subject"); + assert_eq!(entries[2].index, 2); + } + + #[test] + fn short_records_are_skipped() { + assert!(parse_stash_list(b"\x1eaaa\0only two").is_empty()); + assert!(parse_stash_list(b"").is_empty()); + let entries = parse_stash_list(b"\x1e\0x\0d\x1eh\0On m: x\0d"); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].index, 0); + } + + #[test] + fn subjects_split() { + assert_eq!( + parse_subject("On main: a: b"), + (Some("main".into()), "a: b".into(), false) + ); + assert_eq!( + parse_subject("WIP on (no branch): abc x"), + (Some("(no branch)".into()), "abc x".into(), true) + ); + assert_eq!(parse_subject("On : x"), (None, "On : x".into(), false)); + assert_eq!( + parse_subject("autostash"), + (None, "autostash".into(), false) + ); + } + + #[test] + fn messages_are_cleaned() { + assert_eq!(clean_message(" a\nb\r\tc\u{1b}d "), "a b cd"); + assert_eq!(clean_message("\n"), ""); + assert_eq!( + clean_message(&"x".repeat(2000)).chars().count(), + STASH_MESSAGE_CAP + ); + assert_eq!(clean_message("--all"), "--all"); + } + + #[test] + fn unmerged_paths_are_counted_once() { + let bytes = b"100644 aaa 1\ta.php\x00100644 bbb 2\ta.php\x00100644 ccc 3\ta.php\x00100644 ddd 2\tb c.php\0"; + assert_eq!(count_unmerged(bytes), 2); + assert_eq!(count_unmerged(b""), 0); + assert_eq!(count_unmerged(b"no tab\0"), 0); + } + + #[test] + fn refusals_get_a_hint() { + let overwritten = explain( + "error: Your local changes to the following files would be overwritten by merge:\n\ta\nAborting\n", + ); + assert!(overwritten.starts_with("Local changes to files")); + assert!(overwritten.ends_with("Aborting")); + let untracked = explain( + "u already exists, no checkout\nerror: could not restore untracked files from stash", + ); + assert!(untracked.starts_with("Untracked files from the stash")); + assert_eq!(explain(" something else \n"), "something else"); + } + + #[test] + fn paths_are_chunked() { + let paths: Vec = ["aaaa", "bbbb", "cccc", &"d".repeat(30)] + .iter() + .map(|s| s.to_string()) + .collect(); + let groups = chunks(&paths, 10); + assert_eq!(groups.len(), 3); + assert_eq!(groups[0], &paths[..2]); + assert_eq!(groups[2], &paths[3..]); + assert!(chunks(&[], 10).is_empty()); + } + + #[test] + fn hashes_are_checked() { + assert!(check_hash("abcd").is_ok()); + assert!(check_hash("abc").is_err()); + assert!(check_hash("stash@{0}").is_err()); + assert!(check_hash("-abcd").is_err()); + } + + proptest! { + #[test] + fn parsers_never_panic(bytes in proptest::collection::vec(any::(), 0..512)) { + let entries = parse_stash_list(&bytes); + for (i, entry) in entries.iter().enumerate() { + prop_assert_eq!(entry.index, i); + } + let _ = count_unmerged(&bytes); + let _ = parse_subject(&String::from_utf8_lossy(&bytes)); + let _ = explain(&String::from_utf8_lossy(&bytes)); + } + + #[test] + fn cleaned_messages_have_no_controls(text in any::()) { + let cleaned = clean_message(&text); + prop_assert!(!cleaned.chars().any(char::is_control)); + prop_assert!(cleaned.chars().count() <= STASH_MESSAGE_CAP); + } + } +} diff --git a/crates/vcs/tests/stash.rs b/crates/vcs/tests/stash.rs new file mode 100644 index 0000000..d65571b --- /dev/null +++ b/crates/vcs/tests/stash.rs @@ -0,0 +1,246 @@ +//! Stash (M4.9) against real repositories in temp folders: stash with and +//! without a message and untracked files, the list, apply, pop and drop, +//! and every refusal (no commit, nothing to stash, unmerged files, +//! conflicts, overwritten changes, untracked files in the way, a missing or +//! changed entry). Every test skips with a message when git is not +//! installed. + +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::indexing_slicing +)] + +use std::path::Path; +use std::process::Command; + +use lutra_vcs::{Git, Repo, VcsError}; + +/// The installed git, or `None` (with a message) when there is none. +fn installed() -> Option { + match Git::detect("") { + Ok(git) => Some(git), + Err(e) => { + eprintln!("skipped: no usable git installed ({e})"); + None + } + } +} + +/// Runs git in `dir` for test setup and asserts it succeeded. +fn git(dir: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .args(args) + .current_dir(dir) + .env_remove("GIT_DIR") + .env_remove("GIT_WORK_TREE") + .env_remove("GIT_INDEX_FILE") + .output() + .unwrap(); + assert!( + out.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +/// A new repository on `main` with a local identity. +fn init(dir: &Path) { + git(dir, &["init", "-q", "-b", "main"]); + for (key, value) in [ + ("user.name", "Lutra Test"), + ("user.email", "test@lutra.invalid"), + ("commit.gpgsign", "false"), + ("core.autocrlf", "false"), + ("core.hooksPath", ".git/hooks"), + ] { + git(dir, &["config", key, value]); + } +} + +/// Writes a file. +fn write(dir: &Path, path: &str, text: &str) { + std::fs::write(dir.join(path), text).unwrap(); +} + +/// Reads a file. +fn read(dir: &Path, path: &str) -> String { + std::fs::read_to_string(dir.join(path)).unwrap() +} + +/// A repository with `a.txt` committed, opened. +fn repo_with_commit(git_: &Git, dir: &Path) -> Repo { + init(dir); + write(dir, "a.txt", "one\n"); + git(dir, &["add", "-A"]); + git(dir, &["commit", "-q", "-m", "init"]); + git_.open(dir).unwrap().expect("a repository") +} + +/// The message of a `VcsError::Git`. +fn refusal(result: Result) -> String { + match result { + Err(VcsError::Git(message)) => message, + other => panic!("expected a refusal, got {other:?}"), + } +} + +#[test] +fn stash_list_apply_pop_drop() { + let Some(g) = installed() else { return }; + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + let repo = repo_with_commit(&g, dir); + assert!(repo.stash_list().unwrap().is_empty()); + + write(dir, "a.txt", "two\n"); + let first = repo.stash(Some(" first\nline "), false).unwrap(); + assert_eq!(first.index, 0); + assert_eq!(first.message, "first line"); + assert_eq!(first.branch.as_deref(), Some("main")); + assert!(!first.wip); + assert_eq!(read(dir, "a.txt"), "one\n"); + + write(dir, "a.txt", "three\n"); + let second = repo.stash(None, false).unwrap(); + assert!(second.wip); + assert!(second.message.ends_with("init"), "{}", second.message); + + let list = repo.stash_list().unwrap(); + assert_eq!(list.len(), 2); + assert_eq!(list[0].hash, second.hash); + assert_eq!(list[1].hash, first.hash); + assert_eq!(list[1].index, 1); + assert!(!list[0].date.is_empty()); + + repo.stash_apply(1, false, Some(&first.hash)).unwrap(); + assert_eq!(read(dir, "a.txt"), "two\n"); + assert_eq!(repo.stash_list().unwrap().len(), 2); + + git(dir, &["checkout", "--", "a.txt"]); + repo.stash_apply(0, true, second.hash.get(..8)).unwrap(); + assert_eq!(read(dir, "a.txt"), "three\n"); + let list = repo.stash_list().unwrap(); + assert_eq!(list.len(), 1); + assert_eq!(list[0].hash, first.hash); + + repo.stash_drop(0, Some(&first.hash)).unwrap(); + assert!(repo.stash_list().unwrap().is_empty()); +} + +#[test] +fn untracked_files_only_with_the_flag() { + let Some(g) = installed() else { return }; + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + let repo = repo_with_commit(&g, dir); + write(dir, "new.txt", "new\n"); + let message = refusal(repo.stash(None, false)); + assert!(message.contains("no local changes"), "{message}"); + assert!(message.contains("untracked"), "{message}"); + assert!(dir.join("new.txt").exists()); + + std::fs::create_dir_all(dir.join("d/e")).unwrap(); + write(dir, "d/e/-f.txt", "deep\n"); + repo.stash(Some("with untracked"), true).unwrap(); + assert!(!dir.join("new.txt").exists()); + assert!(!dir.join("d").exists()); + assert_eq!(read(dir, "a.txt"), "one\n"); + repo.stash_apply(0, true, None).unwrap(); + assert_eq!(read(dir, "new.txt"), "new\n"); + assert_eq!(read(dir, "d/e/-f.txt"), "deep\n"); + assert!(repo.stash_list().unwrap().is_empty()); +} + +#[test] +fn nothing_to_stash_and_no_commit() { + let Some(g) = installed() else { return }; + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + init(dir); + write(dir, "a.txt", "x\n"); + let repo = g.open(dir).unwrap().unwrap(); + let message = refusal(repo.stash(None, true)); + assert!(message.contains("first commit"), "{message}"); + + git(dir, &["add", "-A"]); + git(dir, &["commit", "-q", "-m", "init"]); + let message = refusal(repo.stash(Some("x"), true)); + assert_eq!(message, "There are no local changes to stash."); + assert!(repo.stash_list().unwrap().is_empty()); +} + +#[test] +fn missing_and_changed_entries_are_refused() { + let Some(g) = installed() else { return }; + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + let repo = repo_with_commit(&g, dir); + assert_eq!(refusal(repo.stash_drop(0, None)), "The stash is empty."); + + write(dir, "a.txt", "two\n"); + let entry = repo.stash(None, false).unwrap(); + let message = refusal(repo.stash_apply(3, false, None)); + assert!(message.contains("no stash entry 3"), "{message}"); + assert!(message.contains("1 entry"), "{message}"); + + let message = refusal(repo.stash_drop(0, Some("deadbeef"))); + assert!(message.contains("changed since it was listed"), "{message}"); + assert!(matches!( + repo.stash_drop(0, Some("stash@{0}")), + Err(VcsError::InvalidName(_)) + )); + assert_eq!(repo.stash_list().unwrap()[0].hash, entry.hash); +} + +#[test] +fn overwritten_changes_and_untracked_in_the_way() { + let Some(g) = installed() else { return }; + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + let repo = repo_with_commit(&g, dir); + write(dir, "a.txt", "stashed\n"); + repo.stash(None, false).unwrap(); + write(dir, "a.txt", "local\n"); + let message = refusal(repo.stash_apply(0, true, None)); + assert!(message.contains("would be overwritten"), "{message}"); + assert_eq!(read(dir, "a.txt"), "local\n"); + assert_eq!(repo.stash_list().unwrap().len(), 1); + + git(dir, &["checkout", "--", "a.txt"]); + repo.stash_drop(0, None).unwrap(); + write(dir, "u.txt", "stashed\n"); + repo.stash(None, true).unwrap(); + write(dir, "u.txt", "in the way\n"); + let message = refusal(repo.stash_apply(0, false, None)); + assert!(message.contains("already exist"), "{message}"); + assert_eq!(read(dir, "u.txt"), "in the way\n"); +} + +#[test] +fn conflicts_keep_the_entry_and_block_the_next_stash() { + let Some(g) = installed() else { return }; + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + let repo = repo_with_commit(&g, dir); + write(dir, "a.txt", "stashed\n"); + repo.stash(None, false).unwrap(); + write(dir, "a.txt", "committed\n"); + git(dir, &["commit", "-q", "-am", "change"]); + + let message = refusal(repo.stash_apply(0, true, None)); + assert!(message.contains("conflicts in 1 file"), "{message}"); + assert!(message.contains("was kept"), "{message}"); + assert_eq!(repo.stash_list().unwrap().len(), 1); + assert!(read(dir, "a.txt").contains("<<<<<<<")); + + let message = refusal(repo.stash(None, false)); + assert!(message.starts_with("Stashing is not possible"), "{message}"); + let message = refusal(repo.stash_apply(0, false, None)); + assert!( + message.starts_with("Applying a stash is not possible"), + "{message}" + ); +} diff --git a/docs/architecture.md b/docs/architecture.md index f481d6f..cb25dd3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2); line changes, gutter markers and status colours (M4.4), diff viewer (M4.3), branches (M4.5); remotes: fetch, pull, push, clone and remote management (M4.10) · **Last updated:** 2026-10-28 +> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2); line changes, gutter markers and status colours (M4.4), diff viewer (M4.3), branches (M4.5); remotes: fetch, pull, push, clone and remote management (M4.10); stash (M4.9) · **Last updated:** 2026-10-28 ## Overview @@ -707,10 +707,32 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat - **Not yet:** an "ignore" action, a compare menu, reverting a resolution, prefilling the commit message from `MERGE_MSG`, rebase and cherry-pick conflicts, synchronised scrolling. - **Tests:** `crates/vcs/tests/merge.rs` (5 against real temp repositories: clean merge, fast-forward, up to date, a content conflict with its versions, resolve and commit, add/add and modify/delete, abort, refusals); unit and property tests in `merge.rs`; `crates/engine/tests/git_merge.rs` (2: the command shapes, `gitChanged`, bad params, no project); Vitest `ui/tests/vcs/Merge.test.ts` (22: the merge on fixed and 300 random texts, layout, parsing, merging after `flushDirty`, the dialog's branches, list, resolve view, apply through the buffer, deleted and binary files, abort, the Changes entry point, registration). +### Stash (M4.9) + +- **Backend** (`crates/vcs/src/stash.rs`, an append; `Repo::lock` became `pub(crate)`, as for M4.8): `stash`, `stash_list`, `stash_apply` and `stash_drop` on `Repo`, run through the M4.1 runner. The stash belongs to the repository, so `git stash push` takes every change of the work tree, also outside the project folder. Changes hold the repository's mutex; the entry is checked under it. + - **List:** `stash list --format=%x1e%H%x00%gs%x00%cI`, at most 1,000 entries; the position is the index. The reflog subject is split into the branch and the message (`On : `, `WIP on : ` for an entry without a message, flagged `wip`); another form keeps the whole subject. + - **Stash:** `stash push [--include-untracked] [--message=…]` with the 120 s timeout. The message loses control characters (line breaks become spaces) and is cut at 1,000 characters. Whether an entry was made is read from `refs/stash` before and after, not from git's text (git exits 0 with "No local changes to save"). + - **`--literal-pathspecs` workaround:** every call runs with it, and under it git's `stash push --include-untracked` stores the untracked files but leaves them in the work tree (its internal clean uses a magic pathspec; found by the integration test, reproduced with git 2.47.1 by hand). So after such a stash the files listed in `stash@{0}^3` go through `git clean -f -- ` (it removes untracked files only; arguments in chunks of 16 KiB, as `clean` has no `--pathspec-from-file`), and folders left empty are removed. + - **Apply, pop, drop:** `stash apply|pop|drop --quiet stash@{n}` with the 120 s timeout for apply and pop. An optional `hash` (as listed) must match the entry at `index`, so a stash changed in between (another tool, another window) is refused instead of applying the wrong entry. + - **Refusals** (`VcsError::Git`, so `failed` with the text): a sentence that says what to do, then git's own message where there is one. Decided structurally, so they hold whatever language git speaks: no commit yet (`HEAD^{commit}`), nothing to stash (`refs/stash` did not move; without `includeUntracked` the text adds that untracked files need it), unmerged files before stash or apply (`ls-files --unmerged`), a missing entry (the list's length), a changed entry (the hash), conflicts after a failed apply or pop (unmerged entries now exist: "applied with conflicts in N files … the stash entry was kept"). Two hints read git's English text and fall back to git's message alone: local changes that would be overwritten, untracked files already in the work tree. +- **Commands** (`crates/engine/src/cmd/git_stash.rs`, through M4.6's `start_with` hook; pending outcomes; `gitChanged` after stash, apply and drop): + - `git.stash {message?, includeUntracked?}` → `{entry: {index, hash, branch, message, wip, date}}`. + - `git.stashList` → `{stashes: [{index, hash, branch|null, message, wip, date}]}` newest first. + - `git.stashApply {index, pop?, hash?}` → `{}`; `git.stashDrop {index, hash?}` → `{}`. + - The result shapes and the optional `hash` are additions to the C6 contract, which named the params only. A bad hash or an index over 100,000 is `invalid_params`. + - A conflicted apply is `failed` but changed the work tree; the `.git` watch reports it as `gitChanged` within about 300 ms. `refs/stash` is not watched, so a stash made outside Lutra shows the next time the list is read. +- **UI** (`ui/src/components/vcs/stash/`): `stash.ts` is the Pinia store, `StashDialog.vue` the dialog, mounted once in `MainLayout.vue`. It supplies the UI commands `vcs.stash` (Git › Stash Changes…) and `vcs.showStashes` (Git › Stashes…), enabled with `git.stash` (an open project), without default shortcuts. The Changes window's bar has a button for each, next to refresh. + - **Form:** message (optional), "Include untracked files" (kept between uses), a note that every change of the repository is set aside. Enter or Stash runs `flushDirty()` first, so git stashes what the editor shows and the reset files reload instead of keeping unsaved edits on top; a failed save does nothing and says so. A refusal shows under the form (`role="alert"`) and the dialog stays; success closes it with an info toast. + - **List:** read with `git.stashList` each time it shows and after every change; rows show `stash@{n}`, the message ("WIP: …" for an entry without one), the branch and the local date. Up/Down/Home/End move, Enter or Apply applies, Pop applies and drops, Delete or Drop asks inline ("Drop stash@{n}? It cannot be restored.") before `git.stashDrop`. Apply and pop save dirty buffers first. Every call passes the listed hash. Refusals (conflicts, overwritten files) show under the list, which is read again. + - **Modal:** an exclusive modal (`ModalId` `stash`); Escape cancels a drop question first, then closes; the focus goes back where it was. The answer is untrusted: entries without an index or hash are dropped, at most 1,000. +- **Checked in the app** (debug build with the bundled UI, Windows 11, git 2.47.1, control port 7949, a demo repository with two stashes on two branches and a modified file; commands and screenshots only, no input): `git.stashList` 143–157 ms, `git.stash` 640 ms, a pop 366 ms, each including the control round trip. The refusals came back as written above: applying onto a modified file ("would be overwritten" with git's text), nothing to stash (with the untracked hint), a missing entry. Screenshots of the list (`stash@{n}`, WIP text, branch, date; Drop, Pop, Apply) and of the form, plus the two new buttons in the Changes bar, read in the dark theme. +- **Tests:** `crates/vcs/tests/stash.rs` (6 tests against real temp repositories: stash with and without a message, list order and hashes, apply, pop by an abbreviated hash, drop; untracked files only with the flag, including a nested folder and a name starting with `-`; no commit and nothing to stash; a missing and a changed entry, a bad hash; overwritten local changes and untracked files in the way, both leaving the work tree and the entry alone; a conflicted pop keeping the entry and blocking the next stash and apply); unit and property tests in `stash.rs` (list and subject parsing, message cleaning, unmerged counting, hints, chunking); `crates/engine/tests/git_stash.rs` (the command shapes, `gitChanged` only after changes, a changed hash, an empty stash, bad params); Vitest `ui/tests/vcs/Stash.test.ts` (13 tests: parsing, the form with `flushDirty` first, a blank message, a refusal, a failed save, Escape and focus, the list with keyboard and apply, a conflicted pop, the drop question, an empty stash, a failed read, the commands' registration, the Changes window's buttons). + ## Decisions (M0) | Question | Decision | Why | |---|---|---| +| 2026-10-30 | minor | M4.9: stash backend (`git.stash`, `git.stashList`, `git.stashApply`, `git.stashDrop`), the `--literal-pathspecs` workaround for untracked files, the stash dialog | | Highlighting | A Lezer grammar (`@lezer/php`, MIT) in CodeMirror highlights instantly on the UI thread. tree-sitter in `crates/syntax` stays the structural source (outline, folding, index) and later adds semantic tokens on top. | The keystroke-to-highlight budget (< 16 ms) leaves no room for an IPC round trip per keystroke; Lezer is incremental inside CodeMirror. tree-sitter gives the core one parser for every structural feature. | | Git library | `gix` (MIT OR Apache-2.0) for reading: status, log, diff, blame, refs. Writes the library doesn't cover well (push, pull, rebase, merge, hooks, signing) run the user's `git` executable. `git2`/libgit2 is not used. | gix is pure Rust and permissively licensed; libgit2 is GPL-2.0 with a linking exception, outside the permitted licences. Shelling out for writes keeps the user's hooks, credential helpers and config working. | | Terminal | `portable-pty` (MIT) in the new L3 crate `crates/terminal`; xterm.js (MIT) renders in the frontend. Output is streamed as events, input goes through commands. | ConPTY on Windows and Unix PTYs behind one API; xterm.js is the standard web terminal. A separate crate keeps PTY code out of the engine. | diff --git a/docs/gaps.md b/docs/gaps.md index 4fe0bec..844380a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,11 +1,12 @@ # Gaps -> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3; branch widget and popup, M4.5; merge conflicts, M4.8; remotes, M4.10); G14 English UI catalog in place · **Last updated:** 2026-10-26 +> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3; branch widget and popup, M4.5; merge conflicts, M4.8; remotes, M4.10; stash, M4.9); G14 English UI catalog in place · **Last updated:** 2026-10-26 Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated. | # | Gap | Milestone | Estimate (one agent) | |---|---|---|---| +| 2026-10-30 | patch | G8: stash (M4.9) | | G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) | | G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), tab management (preview, pin, split, close others, reopen), conflict UI for files changed on disk, ~~autosave~~ (M3.10), local history | M1 | ~14 h | | G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, ~~showing truncated listings~~ (M1.13), ~~error notifications for the folder picker~~ (M1.12), ~~tabs~~ (M1.6), ~~command palette~~ (M1.8: commands only, global keymap, UI commands over the control channel); ~~settings~~ (backend: M1.9a; dialog with search: M1.9b; string and path controls: H4), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker in the dialog, M1.9b), ~~main menu~~ (M3.9: hamburger dropdown from `menuPath`s; native macOS menu bar and display modes open) | M1 | ~24 h | @@ -13,7 +14,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t | G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h | | G6 | Language server: completion, definition, hover, rename via Phpactor (~~PHP detection and Phpactor download~~, M3.1; ~~engine wiring and diagnostics~~, M3.3; ~~completion, hover, signature help~~, M3.4; ~~definition, references, rename~~, M3.5) | M3 | ~15 h | | G7 | ~~Terminal~~ (M3.6: PTY sessions, xterm.js sub-tabs in the bottom panel; settings, persistence, links and search still open), ~~`lutra` CLI and single instance~~ (M3.7: open folders and files at a line, `--wait`, forwarding a second start, token-protected rendezvous), ~~MCP server~~ (M3.8: `lutra mcp` with list/execute every command, screenshot, read buffer, recent events, open buffers as resources; still missing: resource and tool change notifications, progress for long commands), files outside the open project (the CLI refuses them; needs out-of-project buffers or a second window), `lutra diff` | M3 | ~16 h | -| G8 | Git integration: ~~backend through the installed git~~ (M4.1: status, stage/unstage, commit and amend, file contents at HEAD/index, branches, checkout, branch creation, `gitChanged`), ~~Changes window~~ (M4.2: staged/changes/untracked groups, stage and unstage per file and group, commit and amend after saving, amend prefilled with the last message (C6 F1), no chunk staging), ~~gutter markers and status colours~~ (M4.4: added/modified/deleted against the index, tree and tab colours; no chunk actions), ~~diff viewer~~ (M4.3: side by side against the index or HEAD, editable working copy, next/previous change; no unified view, chunk actions or other revisions), ~~branch popup~~ (M4.5: status-bar branch, popup with local and remote branches and a filter, checkout after saving, new branch from HEAD; no merge, rebase, rename or delete), ~~log~~ (M4.6: Log tab with graph lanes, filters, paging, commit details, diffs at a commit, file history; no date or branch filters, no actions on commits), ~~remotes~~ (M4.10: fetch, pull by merge or rebase, push with the upstream set on the first push, clone, manage remotes, progress and cancel, explained refusals, any HTTPS or SSH server through git's credential helper and the ssh agent; no force push, tags, per-branch push targets or hosting features such as pull requests), blame, ~~conflicts~~ (M4.8: `git.merge`, conflicts list, three-pane resolve view with accept left/right per chunk, mark resolved, abort; no ignore action, compare menu or rebase conflicts), stash | M4 | ~122 h | +| G8 | Git integration: ~~backend through the installed git~~ (M4.1: status, stage/unstage, commit and amend, file contents at HEAD/index, branches, checkout, branch creation, `gitChanged`), ~~Changes window~~ (M4.2: staged/changes/untracked groups, stage and unstage per file and group, commit and amend after saving, amend prefilled with the last message (C6 F1), no chunk staging), ~~gutter markers and status colours~~ (M4.4: added/modified/deleted against the index, tree and tab colours; no chunk actions), ~~diff viewer~~ (M4.3: side by side against the index or HEAD, editable working copy, next/previous change; no unified view, chunk actions or other revisions), ~~branch popup~~ (M4.5: status-bar branch, popup with local and remote branches and a filter, checkout after saving, new branch from HEAD; no merge, rebase, rename or delete), ~~log~~ (M4.6: Log tab with graph lanes, filters, paging, commit details, diffs at a commit, file history; no date or branch filters, no actions on commits), ~~remotes~~ (M4.10: fetch, pull by merge or rebase, push with the upstream set on the first push, clone, manage remotes, progress and cancel, explained refusals, any HTTPS or SSH server through git's credential helper and the ssh agent; no force push, tags, per-branch push targets or hosting features such as pull requests), blame, ~~conflicts~~ (M4.8: `git.merge`, conflicts list, three-pane resolve view with accept left/right per chunk, mark resolved, abort; no ignore action, compare menu or rebase conflicts), ~~stash~~ (M4.9: stash with a message and optionally untracked files, list, apply, pop and drop after a question, refusals that say what to do; no partial stash, no stash diff, no "unstash as branch") | M4 | ~122 h | | G9 | Debugger, test runner, Composer, run configurations | M5 | ~300 h | | G10 | Own indexer, type inference, inspections, refactorings | M6 | ~800 h | | G11 | Stability: crash-free operation on real projects and machines (~~recovery journal~~, M1.7) | ongoing | ~95 h | diff --git a/docs/roadmap.md b/docs/roadmap.md index 4e3fa07..e499a5b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Milestones -> **Status:** M0–M3 done, M4 in progress (C5: Git backend, Changes window, gutter markers and status colours, diff viewer, branches; C6: log, remotes) · **Last updated:** 2026-10-28 +> **Status:** M0–M3 done, M4 in progress (C5: Git backend, Changes window, gutter markers and status colours, diff viewer, branches; C6: log, remotes, stash) · **Last updated:** 2026-10-28 Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, the rest estimated. Since cycle C1 (factor 0.07) M1–M3 were scaled ×0.1 to ×0.15 (measured factors: C1 0.07, C2 0.10, C3 0.14, C4 0.17; next cycle ×0.18); M4–M6 keep their first raw estimates (multiply by ~0.1 for the calibrated value). @@ -10,7 +10,7 @@ Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, t | M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | done 2026-10-16 (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups, M1.8 command palette and keymap, M1.14 app icon, M1.9b settings dialog; C2 live checks pending, gaming mode) | ~5.6 (measured: C1 2.5, C2 3.1) | | M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | done 2026-10-17 (C3: M2.1 tree-sitter syntax, M2.2 highlighting + `editor.reveal`, M2.3 search backend, M2.4 Find tool window, M2.5 symbol index + go-to commands, M2.6 go-to popup, M2.7 Structure tool window) | ~6.1 (measured) | | M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | done 2026-10-22 (C4: M3.1 PHP detection and Phpactor download, M3.2 LSP client, M3.3 engine wiring and diagnostics, M3.4 completion, hover and signature help, M3.5 definition, references and rename, M3.6 integrated terminal, M3.7 CLI and single instance, M3.8 MCP server, M3.9 app menu, M3.10 autosave; live check with real key presses pending) | ~14 (measured) | -| M4 | Git: status, diff, commit, branches, log, blame, conflicts | in progress (C5: M4.1 backend, M4.2 Changes window, M4.4 gutter markers and status colours, M4.3 diff viewer, M4.5 branches done; C6: M4.6 log, M4.8 merge conflicts, M4.10 remotes done) | ~122 | +| M4 | Git: status, diff, commit, branches, log, blame, conflicts | in progress (C5: M4.1 backend, M4.2 Changes window, M4.4 gutter markers and status colours, M4.3 diff viewer, M4.5 branches done; C6: M4.6 log, M4.8 merge conflicts, M4.10 remotes, M4.9 stash done) | ~122 | | M5 | Debugger (Xdebug via DAP), PHPUnit/Pest runner, Composer, run configurations | not started | ~300 | | M6 | Own indexer and inspections; Symfony, Laravel, Shopware, WordPress support | not started | ~1,100 | | M7 | Workbench and tools: Deployment (FTP/SFTP/local mappings, upload/download, compare with server, save before deploy, optional upload on save per server), Local History, diff tool (files/folders), scratch files, macros, keymap editor, user themes, plug-in system, Database tools and SQL, HTTP Client, SSH/Docker/Vagrant/WSL, File Watchers, external tools, TODO view, tasks and contexts | not started | ~900 | @@ -34,6 +34,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | M4.9 stash | | 2026-10-28 | minor | M4.6 log and file history | | 2026-10-28 | minor | M4.10 remotes (fetch, pull, push, clone, manage remotes) | | 2026-10-28 | minor | M4.8 merge conflicts | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1f16cc7..4757e67 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity -> **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and the go-to popup, the Structure tool window; M3 started: the integrated terminal, go to definition, find references and rename through Phpactor; M4 started: Git backend (M4.1), Changes tool window (M4.2), diff viewer (M4.3), branches (M4.5), merge conflicts (M4.8), remotes (M4.10) · **Last updated:** 2026-10-28 · **Target:** PhpStorm 2026.x +> **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and the go-to popup, the Structure tool window; M3 started: the integrated terminal, go to definition, find references and rename through Phpactor; M4 started: Git backend (M4.1), Changes tool window (M4.2), diff viewer (M4.3), branches (M4.5), merge conflicts (M4.8), remotes (M4.10), stash (M4.9) · **Last updated:** 2026-10-28 · **Target:** PhpStorm 2026.x ## How this is measured @@ -22,7 +22,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour | Inspections and quick-fixes | 8 | 5% (est.) | Lutra's own inspections and their settings, severities per inspection, quick-fixes (LSP code actions), suppression, inspection profiles, running inspections on a scope, the editor's problem counter and scrollbar marks, next/previous problem, a current-file Problems view and severity filters, external tools (PHPStan, Psalm, PHP_CodeSniffer) | ~287 (est.) | H3: PHP syntax errors on Windows from Lutra's own `php -l` (on open and save, off the engine lock, killed with Lutra), merged into the editor underlines and the Problems tab with source `php -l`; the language server's messages as notifications and its log as `lsp.log`. Tests: `crates/engine/tests/lsp_ux.rs`, unit tests incl. a parser proptest. M3.3: diagnostics from Phpactor (worse reflection: missing members, unknown classes, …) as wavy underlines, gutter markers and hover messages in the editor (`ui/src/components/editor/lint.ts`, tokens only), and a Problems tab in the bottom panel grouped by file with click to reveal (`ui/src/components/problems/`, `problems.open` `Mod+Alt+P`); engine `diagnosticsChanged`, `diagnostics.list`, `lspStatus` (`crates/engine/src/lsp/`). Tests: 10 engine tests against a fake server incl. a sync proptest, a TCP test, 16 Vitest tests, an ignored test against the real PHAR. Checked in the app on Windows 11 with the real Phpactor (port 7933): five errors underlined and listed; first diagnostics 2.7 s after `file.open`, 2.7–2.9 s after an edit (debug build, measured, incl. Phpactor's 1 s debounce). Graded against `plan/phpstorm/11-problems.md`: the depth comes from Phpactor, Lutra has no inspections of its own | | Refactoring | 7 | 3% (est.) | rename: preview of all changes, comments/strings and text occurrences, scope, renaming files with classes, one undo across files (closed files written on disk are not undone by the editor); extract variable/method/constant, inline, move, change signature, safe delete, pull up/push down, introduce parameter | ~244 (est.) | M3.5: Rename (`lsp.prepareRename` then `lsp.rename`, F2) through Phpactor with an inline field over the symbol that shows how many uses in how many files change. The workspace edit is checked completely first (inside the project, ranges fit, open buffers unchanged since the request, no file operations); then closed files are written atomically through the VFS (written ones restored if a later write fails), open buffers change through `buffer.edit` (dirty, one undo step each in the editor), Phpactor reindexes the written files (sent as `didOpen`/`didSave`/`didClose`; its index followed in 140 ms, measured) and a summary notification follows. Live: renaming a method used in 3 files took 28 ms (open buffer + 2 closed files, CRLF kept). Tests: `crates/engine/tests/lsp_nav.rs` (multi-file rename incl. a closed CRLF file, an edit outside the project refused, a bad range refused, a buffer edited meanwhile refused; ignored real-Phpactor rename and rename back), Vitest `ui/tests/nav/`. | | Code style and formatting | 4 | 0% | everything | ~120 (est.) | — | -| Git | 8 | 11% (est.) | Changes window: chunk and line staging, changelists, recent messages and a message template, pre-commit checks, skipping hooks, commit-and-push, a tree view and grouping, a context menu (rollback, delete, ignore); gutter markers: actions (show the old text, revert or stage a chunk, next/previous change), markers against HEAD; directory status colours; diff viewer: a unified view, three-way merge, revert or stage a chunk from the diff, comparing with any revision or branch, ignore-whitespace options, folders; branches: merge, rebase, rename, delete, compare, favourites, incoming/outgoing markers, a branch from another start point; log: date and branch filters, several selected commits, cherry-pick, revert, reset, checkout or new branch from a commit, compare two commits, history of a selection; blame, stash (C6); remotes: force push, tags, a push dialog with the outgoing commits and a target branch, hosting features (pull requests, issues), a check against a real hosted server; ignored files in the status | ~122 (est.) | M4.8: `vcs.merge` (Git › Merge…) merges a branch after saving and toasts merged, up to date or git's refusal; on conflicts the merge dialog lists the conflicted files (also from Changes and Git › Resolve Conflicts…); each opens a three-pane resolve view (current branch, the editable result starting from the base with non-conflicting changes applied, merged branch) with » / « per chunk, accept left/right, accept all and previous/next conflict; Apply writes the result through the file's buffer and runs `git.markResolved`; modify/delete keeps one side; Abort Merge after a confirmation. Backend `git.merge`, `git.mergeAbort`, `git.conflictVersions`, `git.markResolved`. Tests: `crates/vcs/tests/merge.rs`, `crates/engine/tests/git_merge.rs`, 22 Vitest tests (`ui/tests/vcs/Merge.test.ts`). M4.10: fetch, pull (merge or rebase per `git.pull.mode`, open files saved first) and push (upstream set on the first push) as `git.fetch/pull/push` and Git › Fetch / Pull / Push, with `gitProgress` in the status bar, Cancel (`git.cancel`, git and its children killed) and explained refusals (rejected push, sign-in, unknown host key, not found, unreachable, no upstream, conflicts); Git › Clone Repository… (`git.clone`, then `project.open`) and Git › Manage Remotes… (`git.remotes/remoteAdd/remoteSetUrl/remoteRemove`). Any HTTPS or SSH server through git's credential helper (its window allowed) and the ssh agent; no terminal prompts, `ext::` refused, URL userinfo redacted everywhere (D23). Tests against local bare repositories only (`crates/vcs/tests/remote.rs` 8, `crates/engine/tests/git_remote.rs` 3, Vitest `ui/tests/vcs/Remote.test.ts` 11); not checked against a hosted server. C6 M4.6: a Log tab in the bottom panel (`vcs.showLog`, menu Git › Log) lists all branches' commits in topological order with graph lanes, ref badges, author and date, 100 per page loaded as the list scrolls; message and author filters; the selected commit's message and changed files, each opening a read-only "Diff: ()" at that commit against its parent (renames followed); history of a file or folder (`vcs.showHistory`: menu, the tree's context menu, or the active editor tab) follows renames. Backend `git.log`, `git.showCommit`, `git.showAt`. Tests: `crates/vcs/tests/log.rs`, `crates/engine/tests/git_log.rs`, Vitest `ui/tests/vcs/Log.test.ts` (21). C6 F1: Amend fills an empty message box with the last commit message (`git.lastMessage`); checking out a remote branch whose remote is not configured gives an untracked local branch and a clean tree instead of a half-done checkout; one shared status store, so a `gitChanged` costs one `git.status` for the Changes window, the colours and the branch item. M4.5: a status-bar item shows the current branch, or the short hash when detached (`ui/src/components/vcs/branches/`); clicking it or `vcs.branches` (menu Git › Branches…) opens a popup with a filter field, "New branch…", the local branches (current marked, upstream shown) and the remote branches, keyboard-driven; choosing one runs `vcs.checkout {branch}`, which saves dirty buffers through `flushDirty()` first, cancels when a save fails and toasts git's refusal with the branch name; a remote branch checks out its tracking branch. "New branch…" / `vcs.newBranch {name?, checkout?}` creates one from HEAD (checked out by default) and keeps git's refusal next to the name. Tests: 16 Vitest tests (`ui/tests/vcs/Branches.test.ts`). M4.3: `vcs.showDiff {path, staged?}` (`Mod+Alt+Shift+D`, menu Git › Show Diff, double-click in Changes, the project tree's context menu, the palette) opens a "Diff: " tab in the editor area: `@codemirror/merge` side by side, the staged version (or the last commit for a staged row) read-only on the left, the working copy editable on the right through its normal engine buffer (saves, autosave, the journal), changed lines and words tinted with `--lt-vcs-*`, unchanged stretches collapsed, the left side re-read on `gitChanged`; next/previous change (`Alt+Shift+]` / `Alt+Shift+[`); notices for binary, too large, failed and deleted files (`ui/src/components/vcs/diff/`, 21 Vitest tests). M4.2: Changes tab in the bottom panel (`ui/src/components/vcs/changes/`): Staged / Changes / Untracked groups from `git.status` (re-read on `gitChanged`), stage and unstage per file and per group with checkboxes (a staged rename passes both paths), keyboard navigation with Space to stage, double-click or Enter opens through `vcs.showDiff` when the diff viewer provides it, else the file; a commit message box with Amend and Commit (also `Mod+Enter`), which runs `flushDirty()` first, cancels when a save fails and toasts the short hash; hints for a missing git and a folder without a repository; `vcs.openChanges` `Mod+Alt+Shift+G`, `vcs.commit` `Mod+Alt+Shift+M`, `vcs.refresh`. Tests: 19 Vitest tests (`ui/tests/vcs/ChangesToolWindow.test.ts`). M4.4: change markers in the editor gutter (added, modified, deleted against the index, 150 ms after typing and on every `gitChanged`, CRLF-safe) through `git.lineChanges` (line diff in Rust off the lock, index text cached and dropped on `gitChanged`); file names in the project tree and the editor tabs coloured by Git status (`--lt-vcs-*`), ignored entries in the ignored colour inside a repository. Tests: `crates/engine/tests/git_lines.rs` (real temp repositories), unit and property tests, Vitest (`ui/tests/editor/gitGutter.test.ts`, `ui/tests/vcs/vcsStatus.test.ts`). M4.1 (backend, reachable through the palette, control channel and MCP): `git.status`, `git.stage`, `git.unstage` (also before the first commit), `git.commit {message, amend}` with hooks, `git.show` at HEAD or the index, `git.branches`, `git.checkout` (remote → tracking branch), `git.createBranch`; `gitChanged` after changes and from a `.git` poll plus the project watcher. Runs the installed git ≥ 2.30 (`git.executable`), porcelain v2 / `-z` only, no prompts, timeouts and caps, off the engine lock. Tests against real temp repositories (`crates/vcs/tests/repo.rs`, `crates/engine/tests/git.rs`). Graded against `plan/phpstorm/16-vcs-basics.md`: committing, staging and switching or creating branches work from the UI, and changed lines and files are marked (read-only markers, no chunk actions); diff, log, blame and remotes do not yet. | +| Git | 8 | 11% (est.) | Changes window: chunk and line staging, changelists, recent messages and a message template, pre-commit checks, skipping hooks, commit-and-push, a tree view and grouping, a context menu (rollback, delete, ignore); gutter markers: actions (show the old text, revert or stage a chunk, next/previous change), markers against HEAD; directory status colours; diff viewer: a unified view, three-way merge, revert or stage a chunk from the diff, comparing with any revision or branch, ignore-whitespace options, folders; branches: merge, rebase, rename, delete, compare, favourites, incoming/outgoing markers, a branch from another start point; log: date and branch filters, several selected commits, cherry-pick, revert, reset, checkout or new branch from a commit, compare two commits, history of a selection; blame (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. | | 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-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 | | 2026-10-28 | minor | Git row: remotes (M4.10), 9% → 11% (est.) | | 2026-10-28 | patch | M4.8 evidence in the Git row (merge conflicts); score left to the PM | diff --git a/docs/tooling-parity.md b/docs/tooling-parity.md index 511e23a..857d809 100644 --- a/docs/tooling-parity.md +++ b/docs/tooling-parity.md @@ -1,6 +1,6 @@ # Tooling checklist -> **Status:** integrated terminal partial (M3.6), Git backend, Changes window, diff viewer, branches, log and remotes partial (M4.1, M4.2, M4.3, M4.5, M4.6, M4.10) · **Last updated:** 2026-10-28 +> **Status:** integrated terminal partial (M3.6), Git backend, Changes window, diff viewer, branches, log, remotes and stash partial (M4.1, M4.2, M4.3, M4.5, M4.6, M4.10, M4.9) · **Last updated:** 2026-10-28 - [ ] Integrated terminal with tabs - M3.6 (2026-10-18): PTY sessions (pwsh → powershell → cmd on Windows, `$SHELL` or `/bin/sh` on Unix; cwd = project root) in the bottom panel's Terminal tab, several terminals as sub-tabs, xterm.js rendering with Lutra's colours, copy/paste, resize, exit codes; closed with the project. Missing: settings, persistence across restarts, split tabs, search, links, the PHP interpreter in `PATH`. @@ -11,6 +11,7 @@ - M4.6 (2026-10-28): Log tab with graph lanes, message and author filters and lazy paging; commit details with each file's diff at that commit; history of a file from the tree, the editor or the menu. Missing: date and branch filters, actions on commits (cherry-pick, revert, reset, checkout), comparing two commits, blame, conflicts, stash, push/pull. - M4.10 (2026-10-28): fetch, pull (merge or rebase, setting `git.pull.mode`; open files saved first) and push (upstream set on the first push), each with progress and Cancel in the status bar and explained refusals; Clone Repository… from any HTTPS or SSH URL or a path, then the project opens; Manage Remotes… (list with redacted URLs, add, change URL, remove). Sign-in stays with git's credential helper (its own window is allowed) and the ssh agent; terminal prompts are off, so a missing credential fails with a message. Tested against local bare repositories only. Missing: force push, tags, pushing to another branch name, fetch/pull of one branch, prune options, hosting features (pull requests, issues), checked against a real GitHub/GitLab/Forgejo server. - M4.8 (2026-10-28): merge a branch into the current one (Git › Merge…), list the conflicted files, resolve each in a three-pane view (current branch / result / merged branch) with accept left or right per chunk and accept all, apply and mark resolved, abort the merge after a confirmation. Missing: an ignore action, comparing base/local/remote, reverting a resolution, rebase and cherry-pick conflicts, merge-message prefill. + - M4.9 (2026-10-30): stash the local changes with an optional message and optionally untracked files, then list, apply, pop or drop entries (Git menu and the Changes window), saving open files first; refusals say what to do (nothing to stash, no commit yet, unresolved conflicts, files that would be overwritten, a stash changed meanwhile). Missing: stashing selected files, a stash's diff, "unstash as branch", restoring the index, blame. - [ ] Composer: install, update, require, scripts - [ ] PHP interpreters: local, Docker - [ ] Xdebug via DAP: breakpoints, stepping, variables, watches @@ -24,6 +25,7 @@ | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | Git: stash (M4.9) | | 2026-10-28 | minor | Git: log and file history (M4.6) | | 2026-10-28 | minor | Git: fetch, pull, push, clone and remote management (M4.10) | | 2026-10-26 | minor | Git: branch widget, checkout and new branch (M4.5) | diff --git a/ui/src/commands/modals.ts b/ui/src/commands/modals.ts index 5a41bce..15e0031 100644 --- a/ui/src/commands/modals.ts +++ b/ui/src/commands/modals.ts @@ -19,8 +19,8 @@ * command but `menu.open` closes it. * - **Navigation (M3.5):** the definition picker and the inline rename field * are exclusive modals too. So is the branches popup (M4.5), and so are - * "Clone Repository…" and "Manage Remotes…" (M4.10) and the merge - * dialog (M4.8). + * "Clone Repository…" and "Manage Remotes…" (M4.10), the merge + * dialog (M4.8) and the stash dialog (M4.9). */ import { defineStore } from "pinia"; import { ref, watch } from "vue"; @@ -38,7 +38,8 @@ export type ModalId = | "branches" | "clone" | "remotes" - | "merge"; + | "merge" + | "stash"; /** Store of the open exclusive modal. */ export const useModalsStore = defineStore("modals", () => { diff --git a/ui/src/commands/uiCommands.ts b/ui/src/commands/uiCommands.ts index 23c7485..bc811cb 100644 --- a/ui/src/commands/uiCommands.ts +++ b/ui/src/commands/uiCommands.ts @@ -51,6 +51,8 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [ { id: "vcs.refresh", labelKey: "command.vcs.refresh", menuPath: "Git/Refresh Changes" }, { id: "vcs.showLog", labelKey: "command.vcs.showLog", menuPath: "Git/Log" }, { id: "vcs.showHistory", labelKey: "command.vcs.showHistory", menuPath: "Git/Show History" }, + { id: "vcs.stash", labelKey: "command.vcs.stash", menuPath: "Git/Stash Changes…" }, + { id: "vcs.showStashes", labelKey: "command.vcs.showStashes", menuPath: "Git/Stashes…" }, { id: "vcs.showDiff", labelKey: "command.vcs.showDiff", menuPath: "Git/Show Diff", defaultShortcut: "Mod+Alt+Shift+D" }, { id: "vcs.nextChange", labelKey: "command.vcs.nextChange", menuPath: "Git/Next Change", defaultShortcut: "Alt+Shift+]" }, { id: "vcs.previousChange", labelKey: "command.vcs.previousChange", menuPath: "Git/Previous Change", defaultShortcut: "Alt+Shift+[" }, diff --git a/ui/src/components/layout/MainLayout.vue b/ui/src/components/layout/MainLayout.vue index ad53fb7..abf5762 100644 --- a/ui/src/components/layout/MainLayout.vue +++ b/ui/src/components/layout/MainLayout.vue @@ -53,6 +53,7 @@ import ChangesToolWindow from "../vcs/changes/ChangesToolWindow.vue"; import { useChangesStore } from "../vcs/changes/changes"; import LogToolWindow from "../vcs/log/LogToolWindow.vue"; import { SHOW_HISTORY_COMMAND, SHOW_LOG_COMMAND, useLogStore } from "../vcs/log/log"; +import StashDialog from "../vcs/stash/StashDialog.vue"; import { useEditorStore } from "../../stores/editor"; import { useProjectStore } from "../../stores/project"; import ProjectToolWindow from "../project/ProjectToolWindow.vue"; @@ -326,6 +327,7 @@ onBeforeUnmount(() => { /> + diff --git a/ui/src/components/vcs/changes/ChangesToolWindow.vue b/ui/src/components/vcs/changes/ChangesToolWindow.vue index 06012f5..8bc49ba 100644 --- a/ui/src/components/vcs/changes/ChangesToolWindow.vue +++ b/ui/src/components/vcs/changes/ChangesToolWindow.vue @@ -7,7 +7,8 @@ * - **Status line:** the branch (or the short hash when detached) and the * counts, or why there is nothing to show: git missing or too old (with * a hint to the setting `git.executable`), no repository, no changes. - * A refresh button runs `vcs.refresh`. + * A refresh button runs `vcs.refresh`; two more open the stash dialog + * (M4.9) on its form (`vcs.stash`) and on its list (`vcs.showStashes`). * - **Groups:** a header with a checkbox that stages (Changes, Untracked) * or unstages (Staged) the whole group, then the files. Each file has a * checkbox doing the same for itself, its name coloured by its state @@ -26,7 +27,7 @@ * message survive hiding the window. Icons are Lucide's; colours are * tokens. */ -import { RefreshCw } from "@lucide/vue"; +import { Archive, ArchiveRestore, RefreshCw } from "@lucide/vue"; import { computed, nextTick, onMounted, ref, watch } from "vue"; import { useCommandsStore } from "../../../commands/store"; import { isMac } from "../../../commands/keymap"; @@ -325,6 +326,28 @@ watch( > + +
+/** + * The stash dialog (M4.9), centred over the window. + * + * - **Stash form:** a message (optional), "Include untracked files" and + * Stash. Enter in the message or Stash saves dirty buffers and stashes + * (see the Stash store); a refusal shows under the form and the dialog + * stays. + * - **Stashes:** the entries, newest first: `stash@{n}`, the message (or + * git's "WIP" text), the branch and the date. Up/Down, Home and End + * move; Enter or Apply applies the selected entry, Pop applies and drops + * it, Delete or Drop asks, then drops it. A refusal (conflicts, files in + * the way, a changed stash) shows under the list. + * - **Commands:** the dialog supplies the UI commands `vcs.stash` (the + * form) and `vcs.showStashes` (the list), both enabled while `git.stash` + * is (an open project). The Changes window has buttons for both. + * - **Closing:** Escape (first it cancels a drop question), Cancel or a + * click outside; the focus goes back where it was. The dialog is an + * exclusive modal (`commands/modals.ts`). + */ +import { Archive } from "@lucide/vue"; +import { nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"; +import { useModalsStore } from "../../../commands/modals"; +import { useCommandsStore } from "../../../commands/store"; +import { t } from "../../../i18n"; +import { useStashStore, type StashEntry } from "./stash"; + +const stash = useStashStore(); +const modals = useModalsStore(); +const commands = useCommandsStore(); + +/** The message field. */ +const messageInput = ref(null); +/** The list. */ +const list = ref(null); +/** The dialog box; it takes the focus while the list is empty. */ +const dialogBox = ref(null); +/** The element that had the focus before the dialog opened. */ +let returnFocus: HTMLElement | null = null; + +/** + * The DOM id of an entry's row. + * + * @param index - its index in the list. + */ +function rowId(index: number): string { + return `lt-stash-${String(index)}`; +} + +/** + * The name git gives an entry. + * + * @param entry - the entry. + */ +function refName(entry: StashEntry): string { + return `stash@{${String(entry.index)}}`; +} + +/** + * A date for the list: the local date and time, short. + * + * @param iso - ISO 8601 date. + */ +function shortDate(iso: string): string { + const date = new Date(iso); + if (Number.isNaN(date.getTime())) { + return iso; + } + return date.toLocaleString(undefined, { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }); +} + +/** + * What a row shows as its text. + * + * @param entry - the entry. + */ +function entryText(entry: StashEntry): string { + return entry.wip ? t("vcs.stash.wip", { message: entry.message }) : entry.message; +} + +/** Closes the dialog. */ +function close(): void { + if (stash.open) { + stash.hide(); + } +} + +watch( + () => stash.open, + (isOpen) => { + if (isOpen) { + const active = document.activeElement; + returnFocus = active instanceof HTMLElement ? active : null; + modals.opened("stash", close); + } else { + modals.closed("stash"); + returnFocus?.focus(); + returnFocus = null; + } + }, +); + +watch( + () => stash.focusRequest, + async () => { + await nextTick(); + if (stash.mode === "stash") { + messageInput.value?.focus(); + } else { + dialogBox.value?.focus(); + focusList(); + } + }, +); + +/** + * Moves the focus into the list once it has entries, unless something in + * the dialog other than the dialog itself has it. + */ +function focusList(): void { + const active = document.activeElement; + const inside = dialogBox.value?.contains(active) === true && active !== dialogBox.value; + if (stash.open && stash.mode === "list" && (stash.list?.length ?? 0) > 0 && !inside) { + list.value?.focus(); + } +} + +watch( + () => stash.list, + async () => { + await nextTick(); + focusList(); + }, +); + +/** Keeps the selected row in view. */ +function scrollSelected(): void { + void nextTick(() => { + const row = list.value?.querySelector(`#${rowId(stash.selected)}`); + if (row && typeof row.scrollIntoView === "function") { + row.scrollIntoView({ block: "nearest" }); + } + }); +} + +/** + * Keyboard handling of the dialog: Escape cancels a drop question, else + * closes. + * + * @param event - the key press. + */ +function onDialogKey(event: KeyboardEvent): void { + if (event.key !== "Escape") { + return; + } + event.preventDefault(); + event.stopPropagation(); + if (stash.confirmDrop !== null) { + stash.cancelDrop(); + list.value?.focus(); + } else { + close(); + } +} + +/** + * Keyboard handling of the list. + * + * @param event - the key press. + */ +function onListKey(event: KeyboardEvent): void { + const count = stash.list?.length ?? 0; + const moves: Record = { ArrowDown: 1, ArrowUp: -1, Home: -count, End: count }; + const delta = moves[event.key]; + const entry = stash.current; + if (delta !== undefined) { + stash.move(delta); + scrollSelected(); + } else if (event.key === "Enter" && entry) { + void stash.apply(entry, false); + } else if (event.key === "Delete" && entry) { + stash.askDrop(entry); + } else { + return; + } + event.preventDefault(); + event.stopPropagation(); +} + +/** Withdraws the command handlers; filled while mounted. */ +let withdraw: (() => void)[] = []; + +onMounted(() => { + const enabled = (): boolean => commands.isEnabled("git.stash"); + withdraw = [ + commands.provide("vcs.stash", { run: () => stash.show("stash"), enabled }), + commands.provide("vcs.showStashes", { run: () => stash.show("list"), enabled }), + ]; +}); + +onBeforeUnmount(() => { + for (const fn of withdraw) { + fn(); + } + withdraw = []; +}); + + + + + diff --git a/ui/src/components/vcs/stash/stash.ts b/ui/src/components/vcs/stash/stash.ts new file mode 100644 index 0000000..ab3a493 --- /dev/null +++ b/ui/src/components/vcs/stash/stash.ts @@ -0,0 +1,380 @@ +/** + * The stash dialog's state (M4.9): stash the local changes, list the + * stash, apply, pop or drop an entry. + * + * - **Stash:** a message (optional) and "Include untracked files". Dirty + * buffers are saved first (`flushDirty`), so git stashes what the editor + * shows and the editor reloads the reset files instead of keeping + * unsaved edits on top of them; a save that failed cancels the stash. + * Then `git.stash {message, includeUntracked}`. + * - **List:** `git.stashList` each time the list shows and after every + * change. Apply and pop save dirty buffers first for the same reason, + * then run `git.stashApply {index, pop, hash}`; drop asks first, then + * `git.stashDrop {index, hash}`. The hash makes the engine refuse when + * the stash changed since the list was read. + * - **Refusals** (nothing to stash, conflicts, overwritten files, a changed + * stash) stay in the dialog as git's and the engine's sentence, so they + * can be read next to the list; success closes the stash form or keeps + * the list, with an info toast. + * - **Untrusted input:** the list comes from git through the engine; + * malformed entries are dropped ({@link toStashes}). + */ +import { defineStore } from "pinia"; +import { computed, ref, shallowRef } from "vue"; +import { t } from "../../../i18n"; +import { runWaiting, type JsonValue } from "../../../ipc"; +import { useAutosaveStore } from "../../../stores/autosave"; +import { useNotificationsStore } from "../../../stores/notifications"; + +/** Most entries kept from `git.stashList` (the engine sends at most 1,000). */ +export const MAX_STASHES = 1000; + +/** One stash entry. */ +export interface StashEntry { + /** Its position: 0 is `stash@{0}`, the newest. */ + index: number; + /** The stash commit's hash. */ + hash: string; + /** The branch it was made on, if known. */ + branch: string | null; + /** The message, or git's ` ` for a "WIP" entry. */ + message: string; + /** Whether it was made without a message. */ + wip: boolean; + /** When it was made, ISO 8601. */ + date: string; +} + +/** Which part of the dialog shows. */ +export type StashMode = "stash" | "list"; + +/** + * Reads one entry of `git.stashList`. + * + * @param raw - untrusted value. + * @returns the entry, or null when the index or hash is missing. + */ +export function toStash(raw: unknown): StashEntry | null { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { + return null; + } + const r = raw as Record; + if (typeof r.index !== "number" || !Number.isInteger(r.index) || r.index < 0) { + return null; + } + if (typeof r.hash !== "string" || r.hash === "") { + return null; + } + return { + index: r.index, + hash: r.hash, + branch: typeof r.branch === "string" && r.branch !== "" ? r.branch : null, + message: typeof r.message === "string" ? r.message : "", + wip: r.wip === true, + date: typeof r.date === "string" ? r.date : "", + }; +} + +/** + * Reads `git.stashList`'s value. + * + * @param raw - untrusted value. + * @returns the entries in index order, at most {@link MAX_STASHES}, or null + * when the value has no `stashes` array. + */ +export function toStashes(raw: unknown): StashEntry[] | null { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { + return null; + } + const list = (raw as Record).stashes; + if (!Array.isArray(list)) { + return null; + } + const out: StashEntry[] = []; + for (const item of list.slice(0, MAX_STASHES)) { + const entry = toStash(item); + if (entry !== null) { + out.push(entry); + } + } + return out.sort((a, b) => a.index - b.index); +} + +/** + * An engine error's text for people. + * + * @param message - the error message. + */ +function reasonOf(message: string): string { + return message.trim() === "" ? "?" : message.trim(); +} + +/** The Stash store. */ +export const useStashStore = defineStore("stash", () => { + const notifications = useNotificationsStore(); + + /** Whether the dialog is open. */ + const open = ref(false); + /** Which part of the dialog shows. */ + const mode = ref("stash"); + /** The message typed for a new entry. */ + const message = ref(""); + /** Whether untracked files are stashed too. */ + const includeUntracked = ref(false); + /** The last list read; null before it arrived. */ + const list = shallowRef(null); + /** Whether `git.stashList` runs. */ + const loading = ref(false); + /** Index in {@link list} of the selected entry. */ + const selected = ref(0); + /** Whether a stash, apply, pop or drop runs. */ + const busy = ref(false); + /** The last refusal or read failure, shown in the dialog. */ + const error = ref(null); + /** The entry waiting for the drop to be confirmed. */ + const confirmDrop = ref(null); + /** Bumped when the dialog's first field should take the focus. */ + const focusRequest = ref(0); + + /** The selected entry. */ + const current = computed(() => list.value?.[selected.value] ?? null); + + /** Counts loads, so an older answer never replaces a newer one. */ + let loads = 0; + + /** Reads `git.stashList`. */ + async function load(): Promise { + loads += 1; + const mine = loads; + loading.value = true; + const result = await runWaiting("git.stashList"); + if (mine !== loads) { + return; + } + loading.value = false; + if (!result.ok) { + error.value = reasonOf(result.error.message); + return; + } + const next = toStashes(result.value); + if (next === null) { + error.value = "unexpected result of git.stashList"; + return; + } + list.value = next; + selected.value = Math.min(Math.max(0, selected.value), Math.max(0, next.length - 1)); + } + + /** + * Opens the dialog. + * + * @param as - `stash` for the form, `list` for the entries. + * @returns when the list arrived (`list`), at once otherwise. + */ + function show(as: StashMode): Promise { + open.value = true; + mode.value = as; + error.value = null; + confirmDrop.value = null; + focusRequest.value += 1; + if (as === "stash") { + message.value = ""; + return Promise.resolve(); + } + selected.value = 0; + return load(); + } + + /** Closes the dialog. */ + function hide(): void { + open.value = false; + confirmDrop.value = null; + } + + /** + * Moves the selection by `delta` entries, clamped. + * + * @param delta - entries to move; positive is down. + */ + function move(delta: number): void { + const count = list.value?.length ?? 0; + confirmDrop.value = null; + selected.value = Math.min(Math.max(0, selected.value + delta), Math.max(0, count - 1)); + } + + /** + * Saves every dirty buffer. + * + * @returns whether every buffer was saved; otherwise the reason is in + * {@link error}. + */ + async function saveFirst(): Promise { + const flushed = await useAutosaveStore().flushDirty(); + if (flushed.error !== null || flushed.failed.length > 0) { + error.value = t("vcs.stash.notSaved"); + return false; + } + return true; + } + + /** + * Runs a stash command, keeping its refusal in {@link error}. + * + * @param command - the command id. + * @param params - its params. + * @returns its value, or null when it failed. + */ + async function mutate(command: string, params: JsonValue): Promise { + const result = await runWaiting(command, params); + if (!result.ok) { + error.value = reasonOf(result.error.message); + return null; + } + error.value = null; + return result.value; + } + + /** + * Saves dirty buffers, then stashes the local changes with the form's + * message and flag. Closes the dialog when it worked. + * + * @returns whether an entry was made. + */ + async function stash(): Promise { + if (busy.value) { + return false; + } + busy.value = true; + try { + error.value = null; + if (!(await saveFirst())) { + return false; + } + const params: Record = { includeUntracked: includeUntracked.value }; + if (message.value.trim() !== "") { + params.message = message.value; + } + const value = await mutate("git.stash", params); + if (value === null) { + return false; + } + const entry = + typeof value === "object" && !Array.isArray(value) ? toStash((value as Record).entry) : null; + notifications.notify({ + level: "info", + messageKey: "notification.vcs.stashed", + params: { message: entry?.message ?? "" }, + }); + message.value = ""; + hide(); + return true; + } finally { + busy.value = false; + } + } + + /** + * Saves dirty buffers, then applies an entry; with `pop` it is dropped + * when it applied cleanly. The list is read again either way (a + * conflicted pop keeps the entry). + * + * @param entry - the entry. + * @param pop - drop it afterwards. + * @returns whether it applied. + */ + async function apply(entry: StashEntry, pop: boolean): Promise { + if (busy.value) { + return false; + } + busy.value = true; + confirmDrop.value = null; + try { + error.value = null; + if (!(await saveFirst())) { + return false; + } + const value = await mutate("git.stashApply", { index: entry.index, pop, hash: entry.hash }); + await load(); + if (value === null) { + return false; + } + notifications.notify({ + level: "info", + messageKey: pop ? "notification.vcs.stashPopped" : "notification.vcs.stashApplied", + params: { name: `stash@{${String(entry.index)}}` }, + }); + return true; + } finally { + busy.value = false; + } + } + + /** + * Asks to drop an entry: {@link confirmDrop} holds it until + * {@link drop} or {@link cancelDrop}. + * + * @param entry - the entry. + */ + function askDrop(entry: StashEntry): void { + error.value = null; + confirmDrop.value = entry; + } + + /** Forgets the drop question. */ + function cancelDrop(): void { + confirmDrop.value = null; + } + + /** + * Drops the entry waiting in {@link confirmDrop}. + * + * @returns whether it was dropped. + */ + async function drop(): Promise { + const entry = confirmDrop.value; + if (entry === null || busy.value) { + return false; + } + busy.value = true; + confirmDrop.value = null; + try { + const value = await mutate("git.stashDrop", { index: entry.index, hash: entry.hash }); + await load(); + if (value === null) { + return false; + } + notifications.notify({ + level: "info", + messageKey: "notification.vcs.stashDropped", + params: { name: `stash@{${String(entry.index)}}` }, + }); + return true; + } finally { + busy.value = false; + } + } + + return { + open, + mode, + message, + includeUntracked, + list, + loading, + selected, + busy, + error, + confirmDrop, + focusRequest, + current, + load, + show, + hide, + move, + stash, + apply, + askDrop, + cancelDrop, + drop, + }; +}); diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index 78f8f68..c5374cd 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -38,6 +38,8 @@ "command.vcs.showDiff": "Show Diff", "command.vcs.showHistory": "Show History", "command.vcs.showLog": "Log", + "command.vcs.showStashes": "Stashes…", + "command.vcs.stash": "Stash Changes…", "command.view.toggleProjectTree": "Show or Hide Project", "command.view.toggleStructure": "Show or Hide Structure", "common.cancel": "Cancel", @@ -190,6 +192,10 @@ "notification.vcs.pushedUpstream": "Pushed {branch} to {remote} and set it as the upstream", "notification.vcs.remoteCancelled": "Git operation cancelled", "notification.vcs.resolved": "Marked {path} as resolved", + "notification.vcs.stashApplied": "Applied {name}", + "notification.vcs.stashDropped": "Dropped {name}", + "notification.vcs.stashPopped": "Applied and dropped {name}", + "notification.vcs.stashed": "Stashed the local changes: {message}", "notification.vfs.pumpFailed": "Applying changes on disk failed: {reason}", "notification.watch.failed": "Lutra stopped watching the project for changes on disk: {reason}", "palette.label": "Command palette", @@ -467,6 +473,26 @@ "vcs.remotes.url": "URL of the new remote", "vcs.remotes.urlEmpty": "Enter the new URL.", "vcs.remotes.urlOf": "URL of {name}", + "vcs.stash.apply": "Apply", + "vcs.stash.applyHint": "Apply the selected entry and keep it (Enter)", + "vcs.stash.drop": "Drop", + "vcs.stash.dropHint": "Delete the selected entry (Delete)", + "vcs.stash.dropQuestion": "Drop {name}? It cannot be restored.", + "vcs.stash.empty": "The stash is empty.", + "vcs.stash.includeUntracked": "Include untracked files", + "vcs.stash.listTitle": "Stashes", + "vcs.stash.loading": "Reading the stash…", + "vcs.stash.message": "Message", + "vcs.stash.messagePlaceholder": "Optional; Git names the entry after the last commit without one", + "vcs.stash.newStash": "Stash changes…", + "vcs.stash.notSaved": "Nothing was done: not every file could be saved first.", + "vcs.stash.note": "Every local change of the repository is set aside and the files go back to the last commit. Unsaved files are saved first.", + "vcs.stash.pop": "Pop", + "vcs.stash.popHint": "Apply the selected entry and drop it if it applies cleanly", + "vcs.stash.showList": "Show stashes…", + "vcs.stash.stash": "Stash", + "vcs.stash.title": "Stash Changes", + "vcs.stash.wip": "WIP: {message}", "vcs.state.added": "added", "vcs.state.conflicted": "conflicted", "vcs.state.copied": "copied", diff --git a/ui/tests/i18n/catalog.test.ts b/ui/tests/i18n/catalog.test.ts index 21417c4..72f6166 100644 --- a/ui/tests/i18n/catalog.test.ts +++ b/ui/tests/i18n/catalog.test.ts @@ -86,6 +86,10 @@ const RUNTIME_KEYS = new Set([ "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", diff --git a/ui/tests/menu/AppMenu.test.ts b/ui/tests/menu/AppMenu.test.ts index dd2753c..62906fe 100644 --- a/ui/tests/menu/AppMenu.test.ts +++ b/ui/tests/menu/AppMenu.test.ts @@ -293,6 +293,8 @@ describe("AppMenu", () => { "vcs.resolveConflicts", "vcs.showDiff", "vcs.showHistory", + "vcs.stash", + "vcs.showStashes", "app.about", ]); const close = document.querySelector("[data-command='buffer.close']"); diff --git a/ui/tests/palette/CommandPalette.test.ts b/ui/tests/palette/CommandPalette.test.ts index 484e17d..66f3cd0 100644 --- a/ui/tests/palette/CommandPalette.test.ts +++ b/ui/tests/palette/CommandPalette.test.ts @@ -294,6 +294,8 @@ describe("CommandPalette", () => { "vcs.showHistory", "view.toggleProjectTree", "view.toggleStructure", + "vcs.stash", + "vcs.showStashes", "terminal.open", ]); const quit = wrapper.find("[data-command='app.quit']"); diff --git a/ui/tests/vcs/Stash.test.ts b/ui/tests/vcs/Stash.test.ts new file mode 100644 index 0000000..6933191 --- /dev/null +++ b/ui/tests/vcs/Stash.test.ts @@ -0,0 +1,328 @@ +/** + * Tests of the stash feature (M4.9): reading an untrusted `git.stashList`, + * the dialog's form (message, untracked flag, `flushDirty` first, a failed + * save, git's refusal kept in the dialog), the list (entries, keyboard, + * apply, pop with a conflict, drop after the question, Escape), the UI + * commands `vcs.stash` and `vcs.showStashes` and the Changes window's + * buttons. The engine is a fake behind the mocked Tauri `invoke` and + * `listen`. + */ +import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; +import { createPinia, setActivePinia, type Pinia } from "pinia"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const invoke = vi.hoisted(() => vi.fn()); +const listen = vi.hoisted(() => vi.fn()); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); +vi.mock("@tauri-apps/api/event", () => ({ listen })); + +import { useModalsStore } from "../../src/commands/modals"; +import { useCommandsStore } from "../../src/commands/store"; +import { UI_COMMANDS } from "../../src/commands/uiCommands"; +import ChangesToolWindow from "../../src/components/vcs/changes/ChangesToolWindow.vue"; +import { useChangesStore } from "../../src/components/vcs/changes/changes"; +import StashDialog from "../../src/components/vcs/stash/StashDialog.vue"; +import { MAX_STASHES, toStash, toStashes, useStashStore } from "../../src/components/vcs/stash/stash"; +import { useNotificationsStore } from "../../src/stores/notifications"; + +/** A recorded engine call. */ +interface Call { + /** Command id. */ + command: string; + /** Its params. */ + params: Record; +} + +/** Every engine call, in order. */ +let calls: Call[]; +/** What `git.stashList` answers. */ +let stashes: unknown[]; +/** Errors to throw, by command id. */ +let failures: Record; +/** What `file.saveAll` answers. */ +let saveAll: unknown; +/** Pinia of the current test. */ +let pinia: Pinia; +/** Mounted components, unmounted after each test. */ +let mounted: VueWrapper[]; + +/** Two entries as the engine sends them. */ +const ENTRIES = [ + { index: 0, hash: "aaaa1111", branch: "main", message: "41aa1cf init", wip: true, date: "2026-10-28T18:08:36+01:00" }, + { index: 1, hash: "bbbb2222", branch: "feature/x", message: "half done", wip: false, date: "2026-10-27T10:00:00Z" }, +]; + +/** + * The calls of a command. + * + * @param command - the command id. + */ +function callsOf(command: string): Call[] { + return calls.filter((c) => c.command === command); +} + +/** Mounts the dialog with the command store started. */ +async function mountDialog(): Promise { + const wrapper = mount(StashDialog, { attachTo: document.body, global: { plugins: [pinia] } }); + mounted.push(wrapper); + await useCommandsStore(pinia).start(); + await flushPromises(); + return wrapper; +} + +/** + * The texts of the list's rows. + * + * @param wrapper - the dialog. + */ +function rows(wrapper: VueWrapper): string[] { + return wrapper.findAll("[data-test=stash-row]").map((row) => row.text()); +} + +beforeEach(() => { + pinia = createPinia(); + setActivePinia(pinia); + calls = []; + mounted = []; + failures = {}; + stashes = ENTRIES.map((e) => ({ ...e })); + saveAll = { saved: [], failed: [], skipped: [] }; + Element.prototype.scrollIntoView = () => undefined; + invoke.mockReset(); + listen.mockReset(); + listen.mockImplementation(() => Promise.resolve(() => undefined)); + invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { + if (cmd === "engine_list_commands") { + return Promise.resolve([ + { id: "git.status", label: "Git Status", enabled: true }, + { id: "git.stash", label: "Git Stash", enabled: true }, + ]); + } + if ((cmd !== "engine_execute" && cmd !== "engine_execute_waiting") || !args) { + return Promise.resolve(null); + } + calls.push({ command: args.command, params: args.params }); + const failure = failures[args.command]; + if (failure) { + return Promise.reject(Object.assign(new Error(failure.message), failure)); + } + switch (args.command) { + case "git.status": + return Promise.resolve({ available: true, repo: { root: "C:/p", branch: "main", detached: false }, files: [] }); + case "git.stashList": + return Promise.resolve({ stashes }); + case "git.stash": + return Promise.resolve({ entry: { ...ENTRIES[1], index: 0, message: typeof args.params.message === "string" ? args.params.message : "" } }); + case "file.saveAll": + return Promise.resolve(saveAll); + default: + return Promise.resolve({}); + } + }); +}); + +afterEach(() => { + for (const wrapper of mounted) { + wrapper.unmount(); + } + useChangesStore(pinia).stop(); + document.body.innerHTML = ""; +}); + +describe("reading git.stashList", () => { + it("drops malformed entries, sorts by index and caps the count", () => { + expect( + toStashes({ + stashes: [ + { index: 1, hash: "b", branch: "", message: 5, wip: "yes" }, + { index: 0, hash: "a", branch: "main", message: "m", wip: true, date: "d" }, + { index: -1, hash: "x" }, + { index: 2.5, hash: "y" }, + { index: 3, hash: "" }, + null, + "z", + ], + }), + ).toEqual([ + { index: 0, hash: "a", branch: "main", message: "m", wip: true, date: "d" }, + { index: 1, hash: "b", branch: null, message: "", wip: false, date: "" }, + ]); + expect(toStashes(null)).toBeNull(); + expect(toStashes({ stashes: "no" })).toBeNull(); + expect(toStash([1])).toBeNull(); + const many = Array.from({ length: MAX_STASHES + 5 }, (_, i) => ({ index: i, hash: `h${String(i)}` })); + expect(toStashes({ stashes: many })).toHaveLength(MAX_STASHES); + }); +}); + +describe("the stash form", () => { + it("saves first, then stashes with the message and the untracked flag", async () => { + const wrapper = await mountDialog(); + await useCommandsStore(pinia).execute("vcs.stash"); + await flushPromises(); + expect(useModalsStore(pinia).current).toBe("stash"); + expect(document.activeElement).toBe(wrapper.get("[data-test=stash-message]").element); + await wrapper.get("[data-test=stash-message]").setValue("half done"); + await wrapper.get("[data-test=stash-untracked]").setValue(true); + await wrapper.get("[data-test=stash-form]").trigger("submit"); + await flushPromises(); + const order = calls.map((c) => c.command).filter((c) => c === "file.saveAll" || c === "git.stash"); + expect(order).toEqual(["file.saveAll", "git.stash"]); + expect(callsOf("git.stash")[0]?.params).toEqual({ message: "half done", includeUntracked: true }); + expect(wrapper.find("[data-test=stash]").exists()).toBe(false); + const toast = useNotificationsStore(pinia).toasts.at(-1); + expect(toast?.text).toContain("half done"); + expect(useModalsStore(pinia).current).toBeNull(); + }); + + it("leaves out a blank message", async () => { + const wrapper = await mountDialog(); + await useStashStore(pinia).show("stash"); + await flushPromises(); + await wrapper.get("[data-test=stash-message]").setValue(" "); + await wrapper.get("[data-test=stash-submit]").trigger("click"); + await flushPromises(); + expect(callsOf("git.stash")[0]?.params).toEqual({ includeUntracked: false }); + }); + + it("keeps git's refusal in the dialog", async () => { + failures["git.stash"] = { code: "failed", message: "There are no local changes to stash." }; + const wrapper = await mountDialog(); + await useStashStore(pinia).show("stash"); + await flushPromises(); + await wrapper.get("[data-test=stash-form]").trigger("submit"); + await flushPromises(); + expect(wrapper.get("[data-test=stash-error]").text()).toBe("There are no local changes to stash."); + expect(wrapper.find("[data-test=stash]").exists()).toBe(true); + }); + + it("cancels when a save fails", async () => { + saveAll = { saved: [], failed: [{ id: 1, path: "a.php", message: "denied" }], skipped: [] }; + const wrapper = await mountDialog(); + await useStashStore(pinia).show("stash"); + await flushPromises(); + await wrapper.get("[data-test=stash-form]").trigger("submit"); + await flushPromises(); + expect(callsOf("git.stash")).toHaveLength(0); + expect(wrapper.get("[data-test=stash-error]").text()).toContain("could be saved"); + }); + + it("closes on Escape and gives the focus back", async () => { + const before = document.createElement("button"); + document.body.append(before); + before.focus(); + const wrapper = await mountDialog(); + await useStashStore(pinia).show("stash"); + await flushPromises(); + await wrapper.get("[data-test=stash-message]").trigger("keydown", { key: "Escape" }); + await flushPromises(); + expect(wrapper.find("[data-test=stash]").exists()).toBe(false); + expect(document.activeElement).toBe(before); + }); +}); + +describe("the list", () => { + it("shows the entries and applies with Enter after saving", async () => { + const wrapper = await mountDialog(); + await useCommandsStore(pinia).execute("vcs.showStashes"); + await flushPromises(); + const texts = rows(wrapper); + expect(texts).toHaveLength(2); + expect(texts[0]).toContain("stash@{0}"); + expect(texts[0]).toContain("WIP: 41aa1cf init"); + expect(texts[1]).toContain("half done"); + expect(texts[1]).toContain("feature/x"); + const list = wrapper.get("[data-test=stash-list]"); + expect(document.activeElement).toBe(list.element); + await list.trigger("keydown", { key: "ArrowDown" }); + await list.trigger("keydown", { key: "Enter" }); + await flushPromises(); + expect(callsOf("file.saveAll")).toHaveLength(1); + expect(callsOf("git.stashApply")[0]?.params).toEqual({ index: 1, pop: false, hash: "bbbb2222" }); + expect(callsOf("git.stashList")).toHaveLength(2); + expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toBe("Applied stash@{1}"); + }); + + it("shows a conflicted pop's message and reads the list again", async () => { + failures["git.stashApply"] = { + code: "failed", + message: "The stash was applied with conflicts in 1 file. Resolve them in the Changes window.", + }; + const wrapper = await mountDialog(); + await useStashStore(pinia).show("list"); + await flushPromises(); + await wrapper.get("[data-test=stash-pop]").trigger("click"); + await flushPromises(); + expect(callsOf("git.stashApply")[0]?.params).toEqual({ index: 0, pop: true, hash: "aaaa1111" }); + expect(wrapper.get("[data-test=stash-error]").text()).toContain("conflicts in 1 file"); + expect(callsOf("git.stashList")).toHaveLength(2); + expect(rows(wrapper)).toHaveLength(2); + }); + + it("drops only after the question, and Escape cancels the question first", async () => { + const wrapper = await mountDialog(); + await useStashStore(pinia).show("list"); + await flushPromises(); + const list = wrapper.get("[data-test=stash-list]"); + await list.trigger("keydown", { key: "Delete" }); + expect(wrapper.get("[data-test=stash-confirm]").text()).toContain("Drop stash@{0}?"); + expect(callsOf("git.stashDrop")).toHaveLength(0); + await list.trigger("keydown", { key: "Escape" }); + expect(wrapper.find("[data-test=stash-confirm]").exists()).toBe(false); + expect(wrapper.find("[data-test=stash]").exists()).toBe(true); + + await wrapper.get("[data-test=stash-drop]").trigger("click"); + stashes = [ENTRIES[1]].map((e) => ({ ...e, index: 0 })); + await wrapper.get("[data-test=stash-drop-confirm]").trigger("click"); + await flushPromises(); + expect(callsOf("git.stashDrop")[0]?.params).toEqual({ index: 0, hash: "aaaa1111" }); + expect(rows(wrapper)).toHaveLength(1); + expect(callsOf("file.saveAll")).toHaveLength(0); + }); + + it("says when the stash is empty and switches to the form", async () => { + stashes = []; + const wrapper = await mountDialog(); + await useStashStore(pinia).show("list"); + await flushPromises(); + expect(wrapper.get("[data-test=stash-hint]").text()).toBe("The stash is empty."); + expect(wrapper.get("[data-test=stash-apply]").attributes("disabled")).toBeDefined(); + await wrapper.get("[data-test=stash-switch]").trigger("click"); + await flushPromises(); + expect(wrapper.find("[data-test=stash-form]").exists()).toBe(true); + }); + + it("shows a failed read", async () => { + failures["git.stashList"] = { code: "failed", message: "fatal: bad object" }; + const wrapper = await mountDialog(); + await useStashStore(pinia).show("list"); + await flushPromises(); + expect(wrapper.get("[data-test=stash-error]").text()).toBe("fatal: bad object"); + }); +}); + +describe("commands and entry points", () => { + it("registers vcs.stash and vcs.showStashes in the Git menu without shortcuts", () => { + for (const id of ["vcs.stash", "vcs.showStashes"]) { + const spec = UI_COMMANDS.find((c) => c.id === id); + expect(spec?.menuPath?.startsWith("Git/")).toBe(true); + expect(spec?.defaultShortcut).toBeUndefined(); + } + }); + + it("opens the dialog from the Changes window's buttons", async () => { + useChangesStore(pinia).start(); + const dialog = await mountDialog(); + const changes = mount(ChangesToolWindow, { attachTo: document.body, global: { plugins: [pinia] } }); + mounted.push(changes); + await flushPromises(); + await changes.get("[data-test=changes-stash]").trigger("click"); + await flushPromises(); + expect(dialog.find("[data-test=stash-form]").exists()).toBe(true); + useStashStore(pinia).hide(); + await flushPromises(); + await changes.get("[data-test=changes-stashes]").trigger("click"); + await flushPromises(); + expect(rows(dialog)).toHaveLength(2); + }); +});