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:
danny 2026-10-29 18:49:54 +01:00
parent 65907d925a
commit e09ef8b8c0
23 changed files with 2681 additions and 13 deletions

View file

@ -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
View 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);
}
}
}