Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(state): propagate errors from every user-initiated clear path (#2400)
Maximilian Roos72d68552ce87
diff --git a/src/cache_dir.rs b/src/cache_dir.rsnew file mode 100644index 000000000..f56136476--- /dev/null+++ b/src/cache_dir.rs@@ -0,0 +1,119 @@+//! Shared helpers for the `.git/wt/cache/` subdirectories.+//!+//! Worktrunk keeps several disk-backed caches under `.git/wt/cache/`:+//! `ci-status/<branch>.json` and `{kind}/<sha-pair>.json` for `sha_cache`+//! kinds. Their user-initiated clear semantics coincide: enumerate+//! `.json` files, delete them, tolerate missing dirs and concurrent+//! removal as success, surface other I/O errors so `wt config state+//! clear` cannot report a count it didn't actually achieve.++use std::fs;+use std::path::Path;++use anyhow::{Context, Result};++/// Delete all `.json` files directly inside `dir`, returning the count.+///+/// - Missing `dir` is `Ok(0)` (cache never populated).+/// - A per-file `NotFound` is skipped (another process cleared it+/// between listing and removal).+/// - Any other I/O error — `read_dir`, per-entry iteration, or+/// `remove_file` — is returned with the relevant path in context.+///+/// Only entries with exactly the `.json` extension are removed;+/// siblings like `.json.tmp` or `README` survive.+pub fn clear_json_files_in(dir: &Path) -> Result<usize> {+ let entries = match fs::read_dir(dir) {+ Ok(entries) => entries,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),+ Err(e) => {+ return Err(anyhow::Error::new(e).context(format!("failed to read {}", dir.display())));+ }+ };+ let mut cleared = 0;+ for entry in entries {+ let entry = entry.with_context(|| format!("failed to read entry in {}", dir.display()))?;+ let path = entry.path();+ if path.extension().is_none_or(|ext| ext != "json") {+ continue;+ }+ match fs::remove_file(&path) {+ Ok(()) => cleared += 1,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,+ Err(e) => {+ return Err(+ anyhow::Error::new(e).context(format!("failed to remove {}", path.display()))+ );+ }+ }+ }+ Ok(cleared)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::testing::TestRepo;++ #[test]+ fn test_missing_dir_returns_zero() {+ let test = TestRepo::with_initial_commit();+ let missing = test.root_path().join("never-existed");++ assert_eq!(clear_json_files_in(&missing).unwrap(), 0);+ }++ #[test]+ fn test_propagates_non_not_found_read_dir_error() {+ let test = TestRepo::with_initial_commit();+ // Regular file where a directory is expected → ENOTDIR.+ let path = test.root_path().join("not-a-dir");+ fs::write(&path, "stray").unwrap();++ let err = clear_json_files_in(&path).unwrap_err();+ assert!(+ err.to_string().contains("failed to read"),+ "expected read-failure context, got: {err}"+ );+ }++ #[test]+ fn test_propagates_per_file_remove_error() {+ let test = TestRepo::with_initial_commit();+ let dir = test.root_path().join("cache");+ fs::create_dir(&dir).unwrap();+ // A directory named `*.json` makes remove_file return EISDIR.+ fs::create_dir(dir.join("bad.json")).unwrap();++ let err = clear_json_files_in(&dir).unwrap_err();+ assert!(+ err.to_string().contains("failed to remove"),+ "expected remove-failure context, got: {err}"+ );+ }++ #[test]+ fn test_skips_non_json_extensions() {+ let test = TestRepo::with_initial_commit();+ let dir = test.root_path().join("cache");+ fs::create_dir(&dir).unwrap();+ fs::write(dir.join("a.json"), "{}").unwrap();+ fs::write(dir.join("a.json.tmp"), "leftover").unwrap();+ fs::write(dir.join("README"), "stray").unwrap();++ let count = clear_json_files_in(&dir).unwrap();+ assert_eq!(count, 1);+ assert!(!dir.join("a.json").exists());+ assert!(dir.join("a.json.tmp").exists());+ assert!(dir.join("README").exists());+ }++ #[test]+ fn test_empty_dir_returns_zero() {+ let test = TestRepo::with_initial_commit();+ let dir = test.root_path().join("cache");+ fs::create_dir(&dir).unwrap();++ assert_eq!(clear_json_files_in(&dir).unwrap(), 0);+ }+}diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex e9f27bc55..069f2cd88 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -937,7 +937,7 @@ pub fn handle_state_clear_all() -> anyhow::Result<()> {}// Clear git commands cache (merge-tree, ancestry, diff results)- let sha_cleared = repo.clear_git_commands_cache();+ let sha_cleared = repo.clear_git_commands_cache()?;if sha_cleared > 0 {eprintln!("{}",@@ -1425,14 +1425,12 @@ pub fn handle_vars_clear(/// Clear all branch markers. Used by `state clear marker --all` and/// `state clear --all`.///-/// `git config --get-regexp` exits 1 when no keys match, which `run_command`-/// surfaces as an error; `.unwrap_or_default()` absorbs that as the "nothing-/// to clear" path. Errors from individual `unset_config` calls during the-/// iteration (corrupt config, permission denied) propagate.+/// `get_config_regexp` returns an empty string when no keys match (git exit 1)+/// and `Err` for real config errors — both the listing step and each+/// `unset_config` call propagate errors so user-initiated clears never lie+/// about success.fn clear_all_markers(repo: &Repository) -> anyhow::Result<usize> {- let output = repo- .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])- .unwrap_or_default();+ let output = repo.get_config_regexp(r"^worktrunk\.state\..+\.marker$")?;let mut cleared = 0;for line in output.lines() {if let Some(config_key) = line.split_whitespace().next() {@@ -1444,13 +1442,16 @@ fn clear_all_markers(repo: &Repository) -> anyhow::Result<usize> {}/// Clear all vars entries across all branches (used by handle_state_clear_all).+///+/// Enumerates keys via `get_config_regexp` (not `all_vars_entries`) so a+/// config read failure surfaces as an error — the display-path helper+/// absorbs errors as empty, which would silently report "cleared 0" here.fn clear_all_vars(repo: &Repository) -> anyhow::Result<usize> {- let all_vars = repo.all_vars_entries();+ let output = repo.get_config_regexp(r"^worktrunk\.state\..+\.vars\.")?;let mut cleared = 0;- for (branch, entries) in &all_vars {- for key in entries.keys() {- let config_key = format!("worktrunk.state.{branch}.vars.{key}");- repo.unset_config(&config_key)?;+ for line in output.lines() {+ if let Some(config_key) = line.split_whitespace().next() {+ repo.unset_config(config_key)?;cleared += 1;}}@@ -1469,7 +1470,7 @@ pub(super) struct MarkerEntry {/// Get all branch markers from git config with timestampspub(super) fn all_markers(repo: &Repository) -> Vec<MarkerEntry> {let output = repo- .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])+ .get_config_regexp(r"^worktrunk\.state\..+\.marker$").unwrap_or_default();let mut markers = Vec::new();diff --git a/src/commands/list/ci_status/cache.rs b/src/commands/list/ci_status/cache.rsindex eec7b5280..e0be43e48 100644--- a/src/commands/list/ci_status/cache.rs+++ b/src/commands/list/ci_status/cache.rs@@ -9,6 +9,7 @@ use std::hash::{Hash, Hasher};use std::path::{Path, PathBuf};use serde::{Deserialize, Serialize};+use worktrunk::cache_dir::clear_json_files_in;use worktrunk::git::Repository;use worktrunk::path::sanitize_for_filename;@@ -150,6 +151,22 @@ impl CachedCiStatus {.collect()}+ /// Remove a cache file at `path`.+ ///+ /// Returns `Ok(true)` if the file existed and was removed, `Ok(false)`+ /// if it was already gone (either never existed, or another process+ /// deleted it concurrently). Propagates other I/O errors with the+ /// path in context. Shared by `clear_one` and `clear_all`.+ fn remove_cache_file(path: &Path) -> anyhow::Result<bool> {+ match fs::remove_file(path) {+ Ok(()) => Ok(true),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),+ Err(e) => {+ Err(anyhow::Error::new(e).context(format!("failed to remove {}", path.display())))+ }+ }+ }+/// Clear the cached CI status for a single branch.////// Returns `Ok(true)` if a cache file was removed, `Ok(false)` if none@@ -159,50 +176,15 @@ impl CachedCiStatus {/// caller reports "Cleared"/"No cache" directly to the user, a silent/// swallow would lie when the file exists but we can't delete it.pub(crate) fn clear_one(repo: &Repository, branch: &str) -> anyhow::Result<bool> {- let path = Self::cache_file(repo, branch);- match fs::remove_file(&path) {- Ok(()) => Ok(true),- Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),- Err(e) => {- Err(anyhow::Error::new(e).context(format!("failed to remove {}", path.display())))- }- }+ Self::remove_cache_file(&Self::cache_file(repo, branch))}/// Clear all cached CI statuses, returns count cleared.///- /// Missing cache dir is `Ok(0)` (nothing to clear). A file that vanishes- /// between listing and removal — another process cleared concurrently —- /// is counted as not-removed and skipped. Other I/O errors propagate.+ /// Delegates to [`clear_json_files_in`], which documents the+ /// missing-dir / concurrent-removal / error-propagation semantics.pub(crate) fn clear_all(repo: &Repository) -> anyhow::Result<usize> {- let cache_dir = Self::cache_dir(repo);-- let entries = match fs::read_dir(&cache_dir) {- Ok(entries) => entries,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),- Err(e) => {- return Err(anyhow::Error::new(e)- .context(format!("failed to read {}", cache_dir.display())));- }- };-- let mut cleared = 0;- for entry in entries.flatten() {- let path = entry.path();- // Only remove .json files- if path.extension().is_none_or(|ext| ext != "json") {- continue;- }- match fs::remove_file(&path) {- Ok(()) => cleared += 1,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,- Err(e) => {- return Err(anyhow::Error::new(e)- .context(format!("failed to remove {}", path.display())));- }- }- }- Ok(cleared)+ clear_json_files_in(&Self::cache_dir(repo))}}@@ -211,6 +193,18 @@ mod tests {use super::*;use worktrunk::testing::TestRepo;+ #[test]+ fn test_remove_cache_file_returns_false_when_missing() {+ // The concurrent-removal path for clear_all (another process deletes+ // a cache file between listing and remove_file) routes through this+ // helper, which reports the missing file as Ok(false) rather than+ // erroring.+ let test = TestRepo::with_initial_commit();+ let missing = test.root_path().join("never-existed.json");++ assert!(!CachedCiStatus::remove_cache_file(&missing).unwrap());+ }+#[test]fn test_clear_one_propagates_non_not_found_error() {let test = TestRepo::with_initial_commit();@@ -228,61 +222,6 @@ mod tests {);}- #[test]- fn test_clear_all_propagates_non_not_found_read_dir_error() {- let test = TestRepo::with_initial_commit();- let repo = Repository::at(test.root_path()).unwrap();-- // Put a regular file where the cache *directory* should be so- // read_dir returns NotADirectory (non-NotFound).- let cache_dir = CachedCiStatus::cache_dir(&repo);- fs::create_dir_all(cache_dir.parent().unwrap()).unwrap();- fs::write(&cache_dir, "not a dir").unwrap();-- let err = CachedCiStatus::clear_all(&repo).unwrap_err();- assert!(- err.to_string().contains("failed to read"),- "expected read-failure context, got: {err}"- );- }-- #[test]- fn test_clear_all_skips_non_json_extensions() {- let test = TestRepo::with_initial_commit();- let repo = Repository::at(test.root_path()).unwrap();-- let cache_dir = CachedCiStatus::cache_dir(&repo);- fs::create_dir_all(&cache_dir).unwrap();- fs::write(cache_dir.join("a.json"), "{}").unwrap();- // Non-.json siblings must be skipped without being counted.- fs::write(cache_dir.join("a.json.tmp"), "leftover").unwrap();- fs::write(cache_dir.join("README"), "stray").unwrap();-- let count = CachedCiStatus::clear_all(&repo).unwrap();- assert_eq!(count, 1, "only the .json file should be counted");- assert!(!cache_dir.join("a.json").exists());- assert!(cache_dir.join("a.json.tmp").exists());- assert!(cache_dir.join("README").exists());- }-- #[test]- fn test_clear_all_propagates_per_file_remove_error() {- let test = TestRepo::with_initial_commit();- let repo = Repository::at(test.root_path()).unwrap();-- let cache_dir = CachedCiStatus::cache_dir(&repo);- fs::create_dir_all(&cache_dir).unwrap();- // A directory named `*.json` makes remove_file return a non-NotFound- // error (EISDIR / similar).- fs::create_dir(cache_dir.join("bad.json")).unwrap();-- let err = CachedCiStatus::clear_all(&repo).unwrap_err();- assert!(- err.to_string().contains("failed to remove"),- "expected remove-failure context, got: {err}"- );- }-#[test]fn test_ttl_jitter_range_and_determinism() {// Check range: TTL should be in [30, 60)diff --git a/src/git/repository/config.rs b/src/git/repository/config.rsindex 1d2674caa..fe910f0a4 100644--- a/src/git/repository/config.rs+++ b/src/git/repository/config.rs@@ -87,6 +87,25 @@ impl Repository {Ok(existed)}+ /// Run `git config --get-regexp <pattern>` and return stdout.+ ///+ /// Distinguishes exit 1 (no matching keys — expected, returns empty+ /// string) from real config errors (corrupt config, permission denied —+ /// surfaced as `Err`). Use this instead of `run_command` + `.unwrap_or_default()`,+ /// which conflates the two.+ pub fn get_config_regexp(&self, pattern: &str) -> anyhow::Result<String> {+ let output = self.run_command_output(&["config", "--get-regexp", pattern])?;+ if output.status.success() {+ Ok(String::from_utf8_lossy(&output.stdout).into_owned())+ } else if output.status.code() == Some(1) {+ // Exit 1 = no keys matched the pattern+ Ok(String::new())+ } else {+ let stderr = String::from_utf8_lossy(&output.stderr);+ anyhow::bail!("git config --get-regexp {}: {}", pattern, stderr.trim());+ }+ }+/// Read a user-defined marker from `worktrunk.state.<branch>.marker` in git config.////// Markers are stored as JSON: `{"marker": "text", "set_at": unix_timestamp}`.@@ -123,9 +142,7 @@ impl Repository {pub fn vars_entries(&self, branch: &str) -> std::collections::BTreeMap<String, String> {let escaped = regex::escape(branch);let pattern = format!(r"^worktrunk\.state\.{escaped}\.vars\.");- let output = self- .run_command(&["config", "--get-regexp", &pattern])- .unwrap_or_default();+ let output = self.get_config_regexp(&pattern).unwrap_or_default();let prefix = format!("worktrunk.state.{branch}.vars.");output@@ -147,7 +164,7 @@ impl Repository {&self,) -> std::collections::HashMap<String, std::collections::BTreeMap<String, String>> {let output = self- .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.vars\."])+ .get_config_regexp(r"^worktrunk\.state\..+\.vars\.").unwrap_or_default();let mut result: std::collections::HashMap<@@ -534,3 +551,40 @@ impl Repository {.cloned()}}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::testing::TestRepo;++ #[test]+ fn test_get_config_regexp_no_match_returns_empty() {+ // Exit 1 from git config --get-regexp means "no keys matched" — must+ // surface as Ok("") rather than an error so callers don't conflate+ // no-matches with real config failures.+ let test = TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();++ let output = repo+ .get_config_regexp(r"^worktrunk\.state\..+\.marker$")+ .unwrap();+ assert_eq!(output, "");+ }++ #[test]+ fn test_get_config_regexp_returns_matches() {+ let test = TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();++ repo.set_config("worktrunk.state.feature.marker", r#"{"marker":"wip"}"#)+ .unwrap();+ repo.set_config("worktrunk.state.bugfix.marker", r#"{"marker":"fix"}"#)+ .unwrap();++ let output = repo+ .get_config_regexp(r"^worktrunk\.state\..+\.marker$")+ .unwrap();+ assert!(output.contains("worktrunk.state.feature.marker"));+ assert!(output.contains("worktrunk.state.bugfix.marker"));+ }+}diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 7fe273a4e..1cfb1e8cd 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -653,7 +653,10 @@ impl Repository {}/// Clear all cached git command results, returning the count removed.- pub fn clear_git_commands_cache(&self) -> usize {+ ///+ /// Propagates I/O errors so the user-initiated clear path cannot lie+ /// about success; see `sha_cache`'s module docs.+ pub fn clear_git_commands_cache(&self) -> anyhow::Result<usize> {sha_cache::clear_all(self)}diff --git a/src/git/repository/sha_cache.rs b/src/git/repository/sha_cache.rsindex a19db8295..1a111f2dc 100644--- a/src/git/repository/sha_cache.rs+++ b/src/git/repository/sha_cache.rs@@ -33,9 +33,15 @@//!//! # Failure handling//!-//! All cache failures (corrupt JSON, I/O errors, permission denied) are-//! logged at `debug` level and degrade silently: reads return `None`,-//! writes are no-ops. Callers must never observe cache failures.+//! Read and write paths degrade silently — corrupt JSON, I/O errors, and+//! permission denied are logged at `debug` level; reads return `None`,+//! writes are no-ops. Callers must never observe cache failures there+//! because the cache is always an optimization over re-running git.+//!+//! The user-initiated clear path ([`clear_all`], reached via+//! `wt config state clear`) propagates I/O errors instead. A failed clear+//! that reports "cleared N entries" would be a lie to the user, mirroring+//! the same bug the ci-status file cache has already fixed.use std::fs;use std::path::{Path, PathBuf};@@ -45,6 +51,7 @@ use serde::{Serialize, de::DeserializeOwned};use super::Repository;use super::integration::MergeProbeResult;+use crate::cache_dir::clear_json_files_in;use crate::git::LineDiff;/// Maximum cached entries per task kind before the LRU sweep removes the@@ -299,22 +306,16 @@ pub(super) fn put_diff_stats(repo: &Repository, base_sha: &str, head_sha: &str,/// Clear all cached SHA-keyed entries, returning the count removed.///-/// Called by `wt config state clear` to give users a clean slate.-pub(crate) fn clear_all(repo: &Repository) -> usize {+/// Called by `wt config state clear`. Delegates the per-kind-directory+/// work to [`clear_json_files_in`], which documents the+/// missing-dir / concurrent-removal / error-propagation semantics that+/// the module-level "Failure handling" section enshrines.+pub(crate) fn clear_all(repo: &Repository) -> anyhow::Result<usize> {let mut cleared = 0;for kind in ALL_KINDS {- let dir = cache_dir(repo, kind);- let Ok(entries) = fs::read_dir(&dir) else {- continue;- };- for entry in entries.flatten() {- let path = entry.path();- if path.extension().is_some_and(|ext| ext == "json") && fs::remove_file(&path).is_ok() {- cleared += 1;- }- }+ cleared += clear_json_files_in(&cache_dir(repo, kind))?;}- cleared+ Ok(cleared)}/// Count all cached SHA-keyed entries across every kind.@@ -827,7 +828,7 @@ mod tests {},);- let cleared = clear_all(&repo);+ let cleared = clear_all(&repo).unwrap();assert_eq!(cleared, 5, "should clear one entry per kind");// All kinds should be emptydiff --git a/src/lib.rs b/src/lib.rsindex fc7a04fae..4455a1364 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -7,6 +7,7 @@//! with worktrunk, please [open an issue](https://github.com/max-sixty/worktrunk/issues)//! to discuss your use case.+pub mod cache_dir;pub mod command_log;pub mod config;pub mod copy;