Lutra/crates/engine/tests/git_stash.rs
danny e09ef8b8c0 M4.9: Git stash (stash, list, apply, pop, drop) with clear refusals
- crates/vcs: stash.rs (append) with Repo::stash, stash_list, stash_apply
  and stash_drop; refusals decided structurally (no commit, nothing to
  stash, unmerged files, conflicts after apply, missing or changed entry)
  plus hints for overwritten and untracked files. Works around git leaving
  untracked files behind under --literal-pathspecs. Repo::lock is
  pub(crate), as for M4.8.
- engine: git.stash, git.stashList, git.stashApply {index, pop, hash?},
  git.stashDrop through the M4.6 hook; gitChanged after changes.
- ui: stash dialog (vcs.stash, vcs.showStashes; Git menu, no shortcuts),
  two buttons in the Changes window, dirty buffers saved first, drop asks.
- Tests: vcs integration and property tests, engine test, 13 Vitest tests.
- Docs: architecture section, G8, tooling checklist, roadmap, Git row
  evidence (score left to the PM).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 17:37:53 +01:00

189 lines
5.7 KiB
Rust

//! 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<Engine>,
/// Events published so far.
events: Mutex<Vec<Event>>,
}
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<Value, EngineError> {
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"), "<?php // 1\n").unwrap();
git(d, &["add", "-A"]);
git(d, &["commit", "-q", "-m", "First"]);
let host = Host::open(d);
assert_eq!(
host.run("git.stashList", Value::Null).unwrap(),
json!({"stashes": []})
);
let err = host.run("git.stash", json!({})).unwrap_err();
assert_eq!(err.code(), "failed");
assert!(err.to_string().contains("no local changes"), "{err}");
host.git_changed();
std::fs::write(d.join("a.php"), "<?php // 2\n").unwrap();
std::fs::write(d.join("new.php"), "<?php\n").unwrap();
let stashed = host
.run(
"git.stash",
json!({"message": "work", "includeUntracked": true}),
)
.unwrap();
let entry = &stashed["entry"];
assert_eq!(entry["index"], 0);
assert_eq!(entry["message"], "work");
assert_eq!(entry["branch"], "main");
assert_eq!(entry["wip"], false);
assert!(!d.join("new.php").exists());
assert_eq!(host.git_changed(), 1);
let list = host.run("git.stashList", json!({})).unwrap();
assert_eq!(list["stashes"][0]["hash"], entry["hash"]);
assert_eq!(host.git_changed(), 0);
let err = host
.run("git.stashApply", json!({"index": 0, "hash": "0000000"}))
.unwrap_err();
assert_eq!(err.code(), "failed");
assert!(err.to_string().contains("Refresh the list"), "{err}");
host.run(
"git.stashApply",
json!({"index": 0, "pop": true, "hash": entry["hash"]}),
)
.unwrap();
assert_eq!(
std::fs::read_to_string(d.join("a.php")).unwrap(),
"<?php // 2\n"
);
assert!(d.join("new.php").exists());
assert_eq!(host.git_changed(), 1);
assert_eq!(
host.run("git.stashList", Value::Null).unwrap()["stashes"],
json!([])
);
host.run("git.stash", Value::Null).unwrap();
host.run("git.stashApply", json!({"index": 0})).unwrap();
assert_eq!(
host.run("git.stashList", Value::Null).unwrap()["stashes"]
.as_array()
.unwrap()
.len(),
1
);
host.run("git.stashDrop", json!({"index": 0})).unwrap();
let err = host.run("git.stashDrop", json!({"index": 0})).unwrap_err();
assert_eq!(err.code(), "failed");
assert!(err.to_string().contains("The stash is empty."), "{err}");
for (command, params) in [
("git.stash", json!({"bogus": 1})),
("git.stash", json!({"includeUntracked": "yes"})),
("git.stashList", json!([1])),
("git.stashApply", json!({})),
("git.stashApply", json!({"index": -1})),
("git.stashApply", json!({"index": 100_001})),
("git.stashApply", json!({"index": 0, "hash": "stash@{0}"})),
("git.stashDrop", json!({"index": "0"})),
] {
let err = host.run(command, params.clone()).unwrap_err();
assert_eq!(err.code(), "invalid_params", "{command} {params}");
}
}