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>
This commit is contained in:
parent
65907d925a
commit
e09ef8b8c0
23 changed files with 2681 additions and 13 deletions
221
crates/engine/src/cmd/git_stash.rs
Normal file
221
crates/engine/src/cmd/git_stash.rs
Normal file
|
|
@ -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<String>,
|
||||
/// 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 <branch>\" 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<Outcome, EngineError> {
|
||||
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<Outcome, EngineError> {
|
||||
let command = self.spec().id;
|
||||
let _: serde_json::Map<String, Value> = parse(command, params)?;
|
||||
start_with(
|
||||
state,
|
||||
command,
|
||||
false,
|
||||
Box::new(move |repo| {
|
||||
let stashes: Vec<Value> = 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<String>,
|
||||
}
|
||||
|
||||
/// `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<Outcome, EngineError> {
|
||||
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<String>,
|
||||
}
|
||||
|
||||
/// `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<Outcome, EngineError> {
|
||||
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!({}))
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -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(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
189
crates/engine/tests/git_stash.rs
Normal file
189
crates/engine/tests/git_stash.rs
Normal file
|
|
@ -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<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}");
|
||||
}
|
||||
}
|
||||
|
|
@ -27,6 +27,7 @@ pub mod porcelain;
|
|||
mod remote;
|
||||
mod repo;
|
||||
pub mod runner;
|
||||
pub mod stash;
|
||||
mod watch;
|
||||
|
||||
pub use error::VcsError;
|
||||
|
|
@ -41,6 +42,7 @@ pub use repo::{
|
|||
decode,
|
||||
};
|
||||
pub use runner::{Cancel, ProgressSink, redact_urls};
|
||||
pub use stash::StashEntry;
|
||||
pub use watch::{RepoWatch, fingerprint};
|
||||
mod merge;
|
||||
pub use merge::{
|
||||
|
|
|
|||
588
crates/vcs/src/stash.rs
Normal file
588
crates/vcs/src/stash.rs
Normal file
|
|
@ -0,0 +1,588 @@
|
|||
//! Stash (M4.9): set local changes aside, list the stash, apply or pop an
|
||||
//! entry, drop one.
|
||||
//!
|
||||
//! The stash belongs to the whole repository, not to the project folder:
|
||||
//! `git stash push` takes every change of the work tree, as git does.
|
||||
//!
|
||||
//! Refusals carry a sentence that says what to do, followed by git's own
|
||||
//! message where git gave one. The checks that decide which sentence fit
|
||||
//! are structural (does HEAD exist, did `refs/stash` move, are there
|
||||
//! unmerged index entries), so they work whatever language git speaks;
|
||||
//! only the hints for overwritten files and existing untracked files
|
||||
//! read git's English text, and without a match git's message stands
|
||||
//! alone.
|
||||
|
||||
use crate::Repo;
|
||||
use crate::VcsError;
|
||||
use crate::repo::SMALL_CAP;
|
||||
use crate::runner::{Call, HOOK_TIMEOUT};
|
||||
|
||||
/// Most entries [`Repo::stash_list`] returns.
|
||||
pub const STASH_LIST_CAP: usize = 1000;
|
||||
|
||||
/// Most characters of a stash message; longer ones are cut.
|
||||
pub const STASH_MESSAGE_CAP: usize = 1000;
|
||||
|
||||
/// Most bytes of paths one `git clean` call gets as arguments.
|
||||
const CLEAN_CHUNK: usize = 16 * 1024;
|
||||
|
||||
/// Separator before each record of the list format.
|
||||
const RECORD: u8 = 0x1e;
|
||||
|
||||
/// The list format: hash, reflog subject, date (strict ISO 8601); fields
|
||||
/// NUL-separated, each record starting with [`RECORD`].
|
||||
const LIST_FORMAT: &str = "--format=%x1e%H%x00%gs%x00%cI";
|
||||
|
||||
/// One stash entry.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct StashEntry {
|
||||
/// Its position: 0 is the newest (`stash@{0}`).
|
||||
pub index: usize,
|
||||
/// The stash commit's full hash; it identifies the entry when indexes
|
||||
/// shift.
|
||||
pub hash: String,
|
||||
/// The branch it was made on; `None` when the subject has another
|
||||
/// form, `(no branch)` for a detached HEAD.
|
||||
pub branch: Option<String>,
|
||||
/// The message given, or git's `<short hash> <subject>` 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<Vec<StashEntry>, 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<StashEntry, VcsError> {
|
||||
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<String, VcsError> {
|
||||
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<String> = 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<Option<String>, 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<bool, VcsError> {
|
||||
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<usize, VcsError> {
|
||||
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::<String>()
|
||||
.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: `<mode> <oid> <stage>\t<path>`).
|
||||
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>, 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<StashEntry> {
|
||||
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<String> = ["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::<u8>(), 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::<String>()) {
|
||||
let cleaned = clean_message(&text);
|
||||
prop_assert!(!cleaned.chars().any(char::is_control));
|
||||
prop_assert!(cleaned.chars().count() <= STASH_MESSAGE_CAP);
|
||||
}
|
||||
}
|
||||
}
|
||||
246
crates/vcs/tests/stash.rs
Normal file
246
crates/vcs/tests/stash.rs
Normal file
|
|
@ -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<Git> {
|
||||
match Git::detect("") {
|
||||
Ok(git) => Some(git),
|
||||
Err(e) => {
|
||||
eprintln!("skipped: no usable git installed ({e})");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs git in `dir` for test setup and asserts it succeeded.
|
||||
fn git(dir: &Path, args: &[&str]) -> String {
|
||||
let out = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.env_remove("GIT_DIR")
|
||||
.env_remove("GIT_WORK_TREE")
|
||||
.env_remove("GIT_INDEX_FILE")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"git {args:?}: {}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
String::from_utf8_lossy(&out.stdout).trim().to_string()
|
||||
}
|
||||
|
||||
/// 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<impl std::fmt::Debug, VcsError>) -> 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}"
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue