Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(state): surface unset_config failures instead of lying about them (#2394)

Maximilian Roos4c731d035af7
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index 6ef79248e..e9f27bc55 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -796,7 +796,7 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho
}
}
"previous-branch" => {
- if repo.unset_config("worktrunk.history").unwrap_or(false) {
+ if repo.unset_config("worktrunk.history")? {
eprintln!("{}", success_message("Cleared previous branch"));
} else {
eprintln!("{}", info_message("No previous branch to clear"));
@@ -804,7 +804,7 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho
}
"ci-status" => {
if all {
- let cleared = CachedCiStatus::clear_all(&repo);
+ let cleared = CachedCiStatus::clear_all(&repo)?;
if cleared == 0 {
eprintln!("{}", info_message("No CI cache entries to clear"));
} else {
@@ -822,7 +822,7 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho
Some(b) => b,
None => repo.require_current_branch("clear ci-status for current branch")?,
};
- if CachedCiStatus::clear_one(&repo, &branch_name) {
+ if CachedCiStatus::clear_one(&repo, &branch_name)? {
eprintln!(
"{}",
success_message(cformat!("Cleared CI cache for <bold>{branch_name}</>"))
@@ -837,18 +837,7 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho
}
"marker" => {
if all {
- let output = repo
- .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])
- .unwrap_or_default();
-
- let mut cleared_count = 0;
- for line in output.lines() {
- if let Some(config_key) = line.split_whitespace().next() {
- repo.unset_config(config_key)?;
- cleared_count += 1;
- }
- }
-
+ let cleared_count = clear_all_markers(&repo)?;
if cleared_count == 0 {
eprintln!("{}", info_message("No markers to clear"));
} else {
@@ -867,7 +856,7 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho
};
let config_key = format!("worktrunk.state.{branch_name}.marker");
- if repo.unset_config(&config_key).unwrap_or(false) {
+ if repo.unset_config(&config_key)? {
eprintln!(
"{}",
success_message(cformat!("Cleared marker for <bold>{branch_name}</>"))
@@ -910,28 +899,19 @@ pub fn handle_state_clear_all() -> anyhow::Result<()> {
let mut cleared_any = false;
// Clear default branch cache
- if matches!(repo.clear_default_branch_cache(), Ok(true)) {
+ if repo.clear_default_branch_cache()? {
eprintln!("{}", success_message("Cleared default branch cache"));
cleared_any = true;
}
// Clear previous branch
- if repo.unset_config("worktrunk.history").unwrap_or(false) {
+ if repo.unset_config("worktrunk.history")? {
eprintln!("{}", success_message("Cleared previous branch"));
cleared_any = true;
}
// Clear all markers
- let markers_output = repo
- .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])
- .unwrap_or_default();
- let mut markers_cleared = 0;
- for line in markers_output.lines() {
- if let Some(config_key) = line.split_whitespace().next() {
- let _ = repo.unset_config(config_key);
- markers_cleared += 1;
- }
- }
+ let markers_cleared = clear_all_markers(&repo)?;
if markers_cleared > 0 {
eprintln!(
"{}",
@@ -944,7 +924,7 @@ pub fn handle_state_clear_all() -> anyhow::Result<()> {
}
// Clear all CI status cache
- let ci_cleared = CachedCiStatus::clear_all(&repo);
+ let ci_cleared = CachedCiStatus::clear_all(&repo)?;
if ci_cleared > 0 {
eprintln!(
"{}",
@@ -1409,7 +1389,7 @@ pub fn handle_vars_clear(
let count = entries.len();
for (key, _) in entries {
let config_key = format!("worktrunk.state.{branch_name}.vars.{key}");
- let _ = repo.unset_config(&config_key);
+ repo.unset_config(&config_key)?;
}
eprintln!(
"{}",
@@ -1423,7 +1403,7 @@ pub fn handle_vars_clear(
let key = key.expect("key required when --all not set");
validate_vars_key(key)?;
let config_key = format!("worktrunk.state.{branch_name}.vars.{key}");
- if repo.unset_config(&config_key).unwrap_or(false) {
+ if repo.unset_config(&config_key)? {
eprintln!(
"{}",
success_message(cformat!(
@@ -1442,6 +1422,27 @@ pub fn handle_vars_clear(
Ok(())
}
+/// 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.
+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 mut cleared = 0;
+ for line in output.lines() {
+ if let Some(config_key) = line.split_whitespace().next() {
+ repo.unset_config(config_key)?;
+ cleared += 1;
+ }
+ }
+ Ok(cleared)
+}
+
/// Clear all vars entries across all branches (used by handle_state_clear_all).
fn clear_all_vars(repo: &Repository) -> anyhow::Result<usize> {
let all_vars = repo.all_vars_entries();
@@ -1449,7 +1450,7 @@ fn clear_all_vars(repo: &Repository) -> anyhow::Result<usize> {
for (branch, entries) in &all_vars {
for key in entries.keys() {
let config_key = format!("worktrunk.state.{branch}.vars.{key}");
- let _ = repo.unset_config(&config_key);
+ repo.unset_config(&config_key)?;
cleared += 1;
}
}
diff --git a/src/commands/list/ci_status/cache.rs b/src/commands/list/ci_status/cache.rs
index c530d11b3..eec7b5280 100644
--- a/src/commands/list/ci_status/cache.rs
+++ b/src/commands/list/ci_status/cache.rs
@@ -152,39 +152,136 @@ impl CachedCiStatus {
/// Clear the cached CI status for a single branch.
///
- /// Returns `true` if a cache file was removed, `false` otherwise (no file
- /// existed, or the removal failed). Mirrors `clear_all`'s best-effort
- /// swallowing so the caller's success vs info message stays a simple
- /// boolean.
- pub(crate) fn clear_one(repo: &Repository, branch: &str) -> bool {
+ /// Returns `Ok(true)` if a cache file was removed, `Ok(false)` if none
+ /// existed (including the concurrent-removal case — another process
+ /// deleted the file between the caller deciding to clear and this call).
+ /// Propagates other I/O errors (permission denied, etc.) — since the
+ /// 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);
- fs::remove_file(&path).is_ok()
+ 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 all cached CI statuses, returns count cleared.
- pub(crate) fn clear_all(repo: &Repository) -> usize {
+ ///
+ /// 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.
+ 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(_) => return 0,
+ 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_some_and(|ext| ext == "json") && fs::remove_file(&path).is_ok() {
- cleared += 1;
+ 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())));
+ }
}
}
- cleared
+ Ok(cleared)
}
}
#[cfg(test)]
mod tests {
use super::*;
+ use worktrunk::testing::TestRepo;
+
+ #[test]
+ fn test_clear_one_propagates_non_not_found_error() {
+ let test = TestRepo::with_initial_commit();
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ // Place a directory where the .json cache file should live so
+ // remove_file returns a non-NotFound error (EISDIR / similar).
+ let path = CachedCiStatus::cache_file(&repo, "feature");
+ fs::create_dir_all(&path).unwrap();
+
+ let err = CachedCiStatus::clear_one(&repo, "feature").unwrap_err();
+ assert!(
+ err.to_string().contains("failed to remove"),
+ "expected remove-failure context, got: {err}"
+ );
+ }
+
+ #[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() {
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index 2bae6e1e1..b0b439e41 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -1045,7 +1045,7 @@ fn test_state_get_with_ci_entries(repo: TestRepo) {
&repo,
"feature",
&format!(
- r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890","branch":"feature"}}"#
+ r#"{{"status":{{"ci_status":"passed","source":"pr","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890","branch":"feature"}}"#
),
);
@@ -1113,7 +1113,7 @@ fn test_state_get_comprehensive(repo: TestRepo) {
&repo,
"feature",
&format!(
- r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890","branch":"feature"}}"#
+ r#"{{"status":{{"ci_status":"passed","source":"pr","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890","branch":"feature"}}"#
),
);
@@ -1200,7 +1200,7 @@ fn test_state_get_json_comprehensive(repo: TestRepo) {
&repo,
"feature",
&format!(
- r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890","branch":"feature"}}"#
+ r#"{{"status":{{"ci_status":"passed","source":"pr","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890","branch":"feature"}}"#
),
);
@@ -1355,7 +1355,7 @@ fn test_state_clear_ci_status_all_with_entries(repo: TestRepo) {
&repo,
"feature",
&format!(
- r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345","branch":"feature"}}"#
+ r#"{{"status":{{"ci_status":"passed","source":"pr","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345","branch":"feature"}}"#
),
);
write_ci_cache(
@@ -1380,7 +1380,7 @@ fn test_state_clear_ci_status_all_single_entry(repo: TestRepo) {
&repo,
"feature",
&format!(
- r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345","branch":"feature"}}"#
+ r#"{{"status":{{"ci_status":"passed","source":"pr","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345","branch":"feature"}}"#
),
);
@@ -2133,7 +2133,7 @@ fn test_ci_status_get_json_with_cached_data(repo: TestRepo) {
&repo,
"main",
&format!(
- r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"{head}","branch":"main"}}"#
+ r#"{{"status":{{"ci_status":"passed","source":"pr","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"{head}","branch":"main"}}"#
),
);
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index 81e7edab8..419c6a55a 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -1832,15 +1832,15 @@ TODO: Add request/response examples for each endpoint
// The worktree is still around and can be removed. Shows dimmed in list output.
let fix_typos = repo.add_worktree("fix-typos");
repo.run_git_in(&fix_typos, &["push", "-u", "origin", "fix-typos"]);
- mock_ci_status(repo, "fix-typos", "passed", "pull-request", false);
+ mock_ci_status(repo, "fix-typos", "passed", "pr", false);
// === Mock CI status ===
// CI requires --full flag, but we mock it so examples show realistic output
// Note: main's CI is mocked AFTER the merge commit so the hash matches
- mock_ci_status(repo, "main", "passed", "pull-request", false);
- mock_ci_status(repo, "fix-auth", "passed", "pull-request", false);
+ mock_ci_status(repo, "main", "passed", "pr", false);
+ mock_ci_status(repo, "fix-auth", "passed", "pr", false);
// feature-api has unpushed commits, so CI is stale (shows dimmed)
- mock_ci_status(repo, "feature-api", "running", "pull-request", true);
+ mock_ci_status(repo, "feature-api", "running", "pr", true);
// === Mock LLM summaries ===
// Summary requires --full + [list] summary = true + [commit.generation] command