Skip to content

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

perf(config): batch git config reads, collapse ~30% off alias dispatch (#2344)

Maximilian Roos1cd5bcf5c3f8
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index 0859d535d..df0da110a 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -630,9 +630,9 @@ pub fn handle_state_get(
// Read raw config to get both marker and set_at
let config_key = format!("worktrunk.state.{branch_name}.marker");
let raw = repo
- .run_command(&["config", "--get", &config_key])
+ .config_value(&config_key)
.ok()
- .map(|s| s.trim().to_string())
+ .flatten()
.filter(|s| !s.is_empty());
let output = match raw {
Some(json_str) => {
@@ -753,7 +753,7 @@ pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> any
});
let config_key = format!("worktrunk.state.{branch_name}.marker");
- repo.run_command(&["config", &config_key, &json.to_string()])?;
+ repo.set_config(&config_key, &json.to_string())?;
eprintln!(
"{}",
@@ -783,10 +783,7 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho
}
}
"previous-branch" => {
- if repo
- .run_command(&["config", "--unset", "worktrunk.history"])
- .is_ok()
- {
+ if repo.unset_config("worktrunk.history").unwrap_or(false) {
eprintln!("{}", success_message("Cleared previous branch"));
} else {
eprintln!("{}", info_message("No previous branch to clear"));
@@ -813,10 +810,7 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho
None => repo.require_current_branch("clear ci-status for current branch")?,
};
let config_key = format!("worktrunk.state.{branch_name}.ci-status");
- if repo
- .run_command(&["config", "--unset", &config_key])
- .is_ok()
- {
+ if repo.unset_config(&config_key).unwrap_or(false) {
eprintln!(
"{}",
success_message(cformat!("Cleared CI cache for <bold>{branch_name}</>"))
@@ -838,7 +832,7 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho
let mut cleared_count = 0;
for line in output.lines() {
if let Some(config_key) = line.split_whitespace().next() {
- repo.run_command(&["config", "--unset", config_key])?;
+ repo.unset_config(config_key)?;
cleared_count += 1;
}
}
@@ -861,10 +855,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
- .run_command(&["config", "--unset", &config_key])
- .is_ok()
- {
+ if repo.unset_config(&config_key).unwrap_or(false) {
eprintln!(
"{}",
success_message(cformat!("Cleared marker for <bold>{branch_name}</>"))
@@ -913,10 +904,7 @@ pub fn handle_state_clear_all() -> anyhow::Result<()> {
}
// Clear previous branch
- if repo
- .run_command(&["config", "--unset", "worktrunk.history"])
- .is_ok()
- {
+ if repo.unset_config("worktrunk.history").unwrap_or(false) {
eprintln!("{}", success_message("Cleared previous branch"));
cleared_any = true;
}
@@ -928,7 +916,7 @@ pub fn handle_state_clear_all() -> anyhow::Result<()> {
let mut markers_cleared = 0;
for line in markers_output.lines() {
if let Some(config_key) = line.split_whitespace().next() {
- let _ = repo.run_command(&["config", "--unset", config_key]);
+ let _ = repo.unset_config(config_key);
markers_cleared += 1;
}
}
@@ -1344,7 +1332,7 @@ pub fn handle_vars_set(key: &str, value: &str, branch: Option<String>) -> anyhow
};
let config_key = format!("worktrunk.state.{branch_name}.vars.{key}");
- repo.run_command(&["config", &config_key, value])?;
+ repo.set_config(&config_key, value)?;
eprintln!(
"{}",
@@ -1409,7 +1397,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.run_command(&["config", "--unset", &config_key]);
+ let _ = repo.unset_config(&config_key);
}
eprintln!(
"{}",
@@ -1423,10 +1411,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
- .run_command(&["config", "--unset", &config_key])
- .is_ok()
- {
+ if repo.unset_config(&config_key).unwrap_or(false) {
eprintln!(
"{}",
success_message(cformat!(
@@ -1452,7 +1437,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.run_command(&["config", "--unset", &config_key]);
+ let _ = repo.unset_config(&config_key);
cleared += 1;
}
}
diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rs
index 9ea1e40e3..6b1cdcce2 100644
--- a/src/commands/list/collect/execution.rs
+++ b/src/commands/list/collect/execution.rs
@@ -358,6 +358,8 @@ pub fn work_items_for_worktree(
item_idx,
item_url,
llm_command: options.llm_command.clone(),
+ default_branch: options.default_branch.clone(),
+ integration_target: options.integration_target.clone(),
};
let has_commits = wt.has_commits();
@@ -469,6 +471,8 @@ pub fn work_items_for_branch(
item_idx,
item_url: None, // Branches without worktrees don't have URLs
llm_command: options.llm_command.clone(),
+ default_branch: options.default_branch.clone(),
+ integration_target: options.integration_target.clone(),
};
let mut items = Vec::with_capacity(11);
@@ -545,6 +549,8 @@ mod tests {
skip_tasks,
url_template: Some("http://localhost/{{ branch }}".to_string()),
llm_command: None,
+ default_branch: None,
+ integration_target: None,
};
let expected_results = Arc::new(ExpectedResults::default());
@@ -587,6 +593,8 @@ mod tests {
skip_tasks: HashSet::new(),
llm_command: None,
url_template: None,
+ default_branch: None,
+ integration_target: None,
};
let expected_results = Arc::new(ExpectedResults::default());
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 7e1fd63b4..1902f348d 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -287,6 +287,16 @@ pub struct CollectOptions {
/// LLM command for summary generation (from commit.generation config).
/// None if not configured — SummaryGenerate task will be skipped.
pub llm_command: Option<String>,
+
+ /// Default branch resolved for this list invocation. `None` when unset
+ /// or when the persisted value was stale (branch deleted externally).
+ /// Tasks read this through `TaskContext::default_branch` so a stale
+ /// persisted value degrades silently (empty cells) here rather than
+ /// emitting a cascade of "ambiguous argument" errors from every task.
+ pub default_branch: Option<String>,
+ /// Integration target (`default_branch`, or its upstream when ahead).
+ /// `None` when the default branch is unset or stale.
+ pub integration_target: Option<String>,
}
fn worktree_branch_set(worktrees: &[WorktreeInfo]) -> HashSet<&str> {
@@ -613,15 +623,38 @@ pub fn collect(
}
};
+ // Opportunistic stale-default-branch check: `default_branch` above is
+ // the persisted value, now trusted without validation on the hot path.
+ // Cross-check against the enumerated branch set and surface a warning
+ // if it's been deleted externally. When `show_branches` is off but a
+ // persisted default is set and isn't a worktree branch, fetch the
+ // local branch list anyway (one `for-each-ref` fork) so the warning
+ // fires on plain `wt list` too — otherwise downstream tasks resolve
+ // against the stale ref and emit a cascade of "ambiguous argument"
+ // noise instead of one clean warning.
+ let worktree_branches = worktree_branch_set(&worktrees);
+ let needs_stale_check = default_branch
+ .as_deref()
+ .is_some_and(|b| !worktree_branches.contains(b));
+ let fetched_local: Option<Vec<(String, String)>> = if show_branches {
+ Some(match local_branches_cell.into_inner() {
+ Some(result) => result?,
+ None => repo.list_local_branches()?,
+ })
+ } else if needs_stale_check {
+ Some(repo.list_local_branches()?)
+ } else {
+ None
+ };
+ let warn_stale_default = needs_stale_check
+ && fetched_local.as_ref().is_some_and(|all| {
+ !all.iter()
+ .any(|(n, _)| Some(n.as_str()) == default_branch.as_deref())
+ });
+
// Filter local branches to those without worktrees (CPU-only, no git commands)
- let branches_without_worktrees = if show_branches {
- let all_local = if let Some(result) = local_branches_cell.into_inner() {
- result?
- } else {
- // Config-triggered (not fetched speculatively) — fetch now
- repo.list_local_branches()?
- };
- let worktree_branches = worktree_branch_set(&worktrees);
+ let branches_without_worktrees: Vec<(String, String)> = if show_branches {
+ let all_local = fetched_local.unwrap_or_default();
all_local
.into_iter()
.filter(|(name, _)| !worktree_branches.contains(name.as_str()))
@@ -629,6 +662,32 @@ pub fn collect(
} else {
Vec::new()
};
+
+ if warn_stale_default && let Some(branch) = default_branch.as_deref() {
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "Configured default branch <bold>{branch}</> does not exist locally"
+ ))
+ );
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "To reset, run <underline>wt config state default-branch clear</>"
+ ))
+ );
+ }
+
+ // When the persisted default is stale, drop it for downstream tasks.
+ // Tasks that resolve against it (ahead-behind, merge-tree-conflicts,
+ // etc.) would otherwise emit a cascade of "ambiguous argument" errors;
+ // passing `None` here preserves the old None-returns silent-skip
+ // behavior that callers already handle for repos with no default branch.
+ let default_branch = if warn_stale_default {
+ None
+ } else {
+ default_branch
+ };
let remote_branches = if show_remotes {
if let Some(result) = remote_branches_cell.into_inner() {
result?
@@ -650,15 +709,6 @@ pub fn collect(
.find(|wt| canonicalize(&wt.path).map(|p| p == root).unwrap_or(false))
.map(|wt| wt.path.clone())
});
- // Show warning if user configured a default branch that doesn't exist locally
- if let Some(configured) = repo.invalid_default_branch_config() {
- let msg =
- cformat!("Configured default branch <bold>{configured}</> does not exist locally");
- eprintln!("{}", warning_message(msg));
- let hint = cformat!("To reset, run <underline>wt config state default-branch clear</>");
- eprintln!("{}", hint_message(hint));
- }
-
// Main worktree is the primary worktree (for sorting and is_main display).
// - Normal repos: the main worktree (repo root)
// - Bare repos: the default branch's worktree
@@ -813,11 +863,16 @@ pub fn collect(
// Single-line invariant: use safe width to prevent line wrapping
let max_width = crate::display::terminal_width();
- // Create collection options from skip set
- let options = CollectOptions {
+ // Create collection options from skip set. `integration_target` is
+ // patched in after the parallel phase below extracts it — at this
+ // point we haven't yet resolved it, but task spawning doesn't happen
+ // until line 1090+ so late population is safe.
+ let mut options = CollectOptions {
skip_tasks: effective_skip_tasks,
url_template: url_template.clone(),
llm_command,
+ default_branch: default_branch.clone(),
+ integration_target: None,
};
// Track expected results per item - populated as spawns are queued
@@ -970,6 +1025,15 @@ pub fn collect(
let previous_branch = previous_branch_cell.into_inner().flatten();
let integration_target = integration_target_cell.into_inner().flatten();
+ // Patch integration_target into options now that it's resolved. When
+ // default_branch is None (unset or stale), also null it out — tasks
+ // otherwise see a target derived from the stale value and emit
+ // "ambiguous argument" noise.
+ options.integration_target = options
+ .default_branch
+ .as_ref()
+ .and(integration_target.clone());
+
// Update is_previous on items
if let Some(prev) = previous_branch.as_deref() {
for item in &mut all_items {
@@ -1486,7 +1550,7 @@ pub fn build_worktree_item(
pub fn populate_item(
repo: &Repository,
item: &mut ListItem,
- options: CollectOptions,
+ mut options: CollectOptions,
) -> anyhow::Result<()> {
// Extract worktree data (skip if not a worktree item)
let Some(data) = item.worktree_data() else {
@@ -1497,6 +1561,18 @@ pub fn populate_item(
// None if default branch cannot be determined - status symbols will be skipped
let target = repo.integration_target();
+ // Populate default_branch / integration_target if the caller didn't.
+ // Tasks read these through `TaskContext`; `None` here tells them to
+ // skip (see collect()'s stale-default-branch path). Single-item callers
+ // like statusline pass `CollectOptions::default()` and expect the
+ // repo-derived values.
+ if options.default_branch.is_none() {
+ options.default_branch = repo.default_branch();
+ }
+ if options.integration_target.is_none() {
+ options.integration_target = target.clone();
+ }
+
// Create channel for task results
let (tx, rx) = chan::unbounded::<Result<TaskResult, TaskError>>();
diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rs
index 9615c2254..d24d09ec7 100644
--- a/src/commands/list/collect/tasks.rs
+++ b/src/commands/list/collect/tasks.rs
@@ -42,6 +42,18 @@ pub struct TaskContext {
pub item_url: Option<String>,
/// LLM command for summary generation (from commit.generation config).
pub llm_command: Option<String>,
+ /// Default branch resolved for this list invocation. Populated from
+ /// the collect-phase check that verifies the persisted value still
+ /// resolves locally; `None` when unset or stale. Tasks read this
+ /// instead of `repo.default_branch()` so a stale persisted value
+ /// degrades silently (empty cells) here rather than emitting a cascade
+ /// of "ambiguous argument" errors.
+ pub default_branch: Option<String>,
+ /// Integration target (`default_branch`, or its upstream when ahead).
+ /// `None` when the default branch is unset or stale — keeps the same
+ /// silent-skip contract as `default_branch` for tasks that compare
+ /// against the integration target.
+ pub integration_target: Option<String>,
}
impl TaskContext {
@@ -65,20 +77,21 @@ impl TaskContext {
TaskError::new(self.item_idx, kind, err.to_string(), cause)
}
- /// Get the default branch (cached in Repository).
+ /// Get the default branch resolved for this list invocation.
///
- /// Used for informational stats (ahead/behind, branch diff).
- /// Returns None if default branch cannot be determined.
+ /// Used for informational stats (ahead/behind, branch diff). Returns
+ /// `None` if default branch cannot be determined, or if the persisted
+ /// value is stale (see `TaskContext::default_branch` docs).
pub(super) fn default_branch(&self) -> Option<String> {
- self.repo.default_branch()
+ self.default_branch.clone()
}
- /// Get the integration target (cached in Repository).
+ /// Get the integration target resolved for this list invocation.
///
/// Used for integration checks (status symbols, safe deletion).
- /// Returns None if default branch cannot be determined.
+ /// Returns `None` if default branch cannot be determined or is stale.
pub(super) fn integration_target(&self) -> Option<String> {
- self.repo.integration_target()
+ self.integration_target.clone()
}
}
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index ecdece318..9dd5cc13c 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -435,24 +435,11 @@ fn resolve_switch_target(
}
}
- // Compute base branch for creation
+ // Compute base branch for creation. When the cached default branch
+ // no longer resolves locally, return None and let the downstream
+ // StaleDefaultBranch error emerge at the actual use site.
let base_branch = if create {
resolved_base.or_else(|| {
- // Check for invalid configured default branch
- if let Some(configured) = repo.invalid_default_branch_config() {
- eprintln!(
- "{}",
- warning_message(cformat!(
- "Configured default branch <bold>{configured}</> does not exist locally"
- ))
- );
- eprintln!(
- "{}",
- hint_message(cformat!(
- "To reset, run <underline>wt config state default-branch clear</>"
- ))
- );
- }
repo.resolve_target_branch(None)
.ok()
.filter(|b| repo.branch(b).exists_locally().unwrap_or(false))
@@ -565,15 +552,15 @@ fn setup_fork_branch(
let branch_merge_key = format!("branch.{}.merge", branch);
let merge_ref = format!("refs/{}", remote_ref);
- repo.run_command(&["config", &branch_remote_key, remote])
+ repo.set_config(&branch_remote_key, remote)
.with_context(|| format!("Failed to configure branch.{}.remote", branch))?;
- repo.run_command(&["config", &branch_merge_key, &merge_ref])
+ repo.set_config(&branch_merge_key, &merge_ref)
.with_context(|| format!("Failed to configure branch.{}.merge", branch))?;
// Only configure pushRemote if we have a fork URL (not using prefixed branch)
if let Some(url) = fork_push_url {
let branch_push_remote_key = format!("branch.{}.pushRemote", branch);
- repo.run_command(&["config", &branch_push_remote_key, url])
+ repo.set_config(&branch_push_remote_key, url)
.with_context(|| format!("Failed to configure branch.{}.pushRemote", branch))?;
}
diff --git a/src/git/error.rs b/src/git/error.rs
index 1e00a9286..57e3915ba 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -188,6 +188,13 @@ pub enum GitError {
ReferenceNotFound {
reference: String,
},
+ /// Persisted `worktrunk.default-branch` points at a branch that no longer
+ /// resolves locally. Surfaced when a command would use the default branch
+ /// (no explicit `--target`) and the cached value is stale, so the user
+ /// gets a cache-reset hint instead of a generic "branch not found".
+ StaleDefaultBranch {
+ branch: String,
+ },
// Worktree errors
NotInWorktree {
@@ -441,6 +448,19 @@ impl GitError {
)
}
+ GitError::StaleDefaultBranch { branch } => {
+ write!(
+ f,
+ "{}\n{}",
+ error_message(cformat!(
+ "Default branch <bold>{branch}</> does not exist locally"
+ )),
+ hint_message(cformat!(
+ "Reset the cached value with <underline>wt config state default-branch clear</>, or set it explicitly with <underline>wt config state default-branch set BRANCH</>"
+ ))
+ )
+ }
+
GitError::NotInWorktree { action } => {
let message = match action {
Some(action) => cformat!("Cannot {action}: not in a worktree"),
diff --git a/src/git/repository/config.rs b/src/git/repository/config.rs
index d13bd2e79..4707c6717 100644
--- a/src/git/repository/config.rs
+++ b/src/git/repository/config.rs
@@ -12,27 +12,81 @@ use super::{DefaultBranchName, GitError, Repository};
impl Repository {
/// Get a git config value. Returns None if the key doesn't exist.
///
- /// Distinguishes "key not found" (exit code 1) from actual errors
- /// (corrupt config, permission denied, etc.) which are propagated.
+ /// Reads from the bulk config map populated by the private
+ /// `all_config()` accessor. Returns an error only if the bulk read
+ /// itself fails (corrupt config, git subprocess failure).
pub fn config_value(&self, key: &str) -> anyhow::Result<Option<String>> {
- let output = self.run_command_output(&["config", key])?;
- if output.status.success() {
- let stdout = String::from_utf8_lossy(&output.stdout);
- Ok(Some(stdout.trim().to_string()))
- } else if output.status.code() == Some(1) {
- Ok(None) // Config key doesn't exist
- } else {
- let stderr = String::from_utf8_lossy(&output.stderr);
- anyhow::bail!("git config {}: {}", key, stderr.trim());
- }
+ self.config_last(key)
}
/// Set a git config value.
+ ///
+ /// Writes to the on-disk config AND updates the bulk config map if
+ /// populated, so subsequent in-process reads see the new value.
pub fn set_config(&self, key: &str, value: &str) -> anyhow::Result<()> {
+ self.set_config_value(key, value)
+ }
+
+ /// Unset a git config value.
+ ///
+ /// Returns `true` if the key was cleared, `false` if it didn't exist.
+ /// Removes the key from the bulk config map if populated.
+ pub fn unset_config(&self, key: &str) -> anyhow::Result<bool> {
+ self.unset_config_value(key)
+ }
+
+ /// Write a config value and keep the bulk config map coherent.
+ ///
+ /// Every writer in the codebase routes through this helper so that a
+ /// `set` followed by a `get` in the same process sees the new value —
+ /// the bulk map is updated in-memory when populated, in addition to the
+ /// on-disk `git config` write.
+ ///
+ /// Map keys are canonicalized to match git's emitted form (section +
+ /// variable lowercased, subsection preserved) so writes with mixed-case
+ /// variable names (e.g. `branch.<name>.pushRemote`) land under the same
+ /// key `config_last` looks up. Without this, a later `--list -z`
+ /// populate would emit the canonical form while this insert would leave
+ /// behind a stale duplicate under the literal form.
+ pub(super) fn set_config_value(&self, key: &str, value: &str) -> anyhow::Result<()> {
self.run_command(&["config", key, value])?;
+ if let Some(lock) = self.cache.all_config.get() {
+ let canonical = super::canonical_config_key(key);
+ lock.write()
+ .unwrap()
+ .insert(canonical, vec![value.to_string()]);
+ }
Ok(())
}
+ /// Unset a config key and keep the bulk config map coherent.
+ ///
+ /// Returns `true` if the key was cleared, `false` if it didn't exist.
+ /// Propagates actual git config errors (corrupt config, permission denied).
+ ///
+ /// Removes the canonical form (matching what git emits) to stay in
+ /// sync with `set_config_value` and `config_last`.
+ pub(super) fn unset_config_value(&self, key: &str) -> anyhow::Result<bool> {
+ let output = self.run_command_output(&["config", "--unset", key])?;
+ let existed = if output.status.success() {
+ true
+ } else if output.status.code() == Some(5) {
+ // --unset exit code 5 = key didn't exist
+ false
+ } else {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ anyhow::bail!("git config --unset {}: {}", key, stderr.trim());
+ };
+ if let Some(lock) = self.cache.all_config.get() {
+ // `shift_remove` preserves remaining order (swap_remove would
+ // reorder); order matters for `primary_remote` which picks the
+ // first remote with a configured URL.
+ let canonical = super::canonical_config_key(key);
+ lock.write().unwrap().shift_remove(&canonical);
+ }
+ Ok(existed)
+ }
+
/// Read a user-defined marker from `worktrunk.state.<branch>.marker` in git config.
///
/// Markers are stored as JSON: `{"marker": "text", "set_at": unix_timestamp}`.
@@ -42,13 +96,11 @@ impl Repository {
marker: Option<String>,
}
- let config_key = format!("worktrunk.state.{branch}.marker");
let raw = self
- .run_command(&["config", "--get", &config_key])
+ .config_last(&format!("worktrunk.state.{branch}.marker"))
.ok()
- .map(|output| output.trim().to_string())
+ .flatten()
.filter(|s| !s.is_empty())?;
-
let parsed: MarkerValue = serde_json::from_str(&raw).ok()?;
parsed.marker
}
@@ -62,6 +114,12 @@ impl Repository {
///
/// Returns a `BTreeMap` so it serializes to a minijinja object for template access
/// via `{{ vars.key }}`.
+ ///
+ /// Reads git config directly — **not** via the bulk `all_config` cache —
+ /// because lazy template expansion in hook/alias pipelines depends on
+ /// seeing writes that earlier steps made via their own `git config`
+ /// subprocesses. Those external writes don't round-trip through our
+ /// coherent `set_config_value` helper.
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\.");
@@ -82,8 +140,9 @@ impl Repository {
/// Get all vars entries across all branches in a single git call.
///
- /// Returns a map of branch → (key → value). Uses one `git config --get-regexp`
- /// instead of N per-branch calls, avoiding N+1 subprocess spawns in `wt list --format=json`.
+ /// Returns a map of branch → (key → value). Reads git config directly
+ /// (see [`Self::vars_entries`] for rationale) but still uses one
+ /// `git config --get-regexp` rather than N per-branch calls.
pub fn all_vars_entries(
&self,
) -> std::collections::HashMap<String, std::collections::BTreeMap<String, String>> {
@@ -121,7 +180,7 @@ impl Repository {
/// Stores the branch we're switching FROM, so `wt switch -` can return to it.
pub fn set_switch_previous(&self, previous: Option<&str>) -> anyhow::Result<()> {
if let Some(prev) = previous {
- self.run_command(&["config", "worktrunk.history", prev])?;
+ self.set_config_value("worktrunk.history", prev)?;
}
// If previous is None (detached HEAD), don't update history
Ok(())
@@ -131,9 +190,9 @@ impl Repository {
///
/// Returns the branch we came from, enabling ping-pong switching.
pub fn switch_previous(&self) -> Option<String> {
- self.run_command(&["config", "--get", "worktrunk.history"])
+ self.config_last("worktrunk.history")
.ok()
- .map(|s| s.trim().to_string())
+ .flatten()
.filter(|s| !s.is_empty())
}
@@ -142,14 +201,15 @@ impl Repository {
/// Hints are stored as `worktrunk.hints.<name> = true`.
/// TODO: Could move to global git config if we accumulate more global hints.
pub fn has_shown_hint(&self, name: &str) -> bool {
- self.run_command(&["config", "--get", &format!("worktrunk.hints.{name}")])
- .is_ok()
+ self.config_last(&format!("worktrunk.hints.{name}"))
+ .ok()
+ .flatten()
+ .is_some()
}
/// Mark a hint as shown in this repo.
pub fn mark_hint_shown(&self, name: &str) -> anyhow::Result<()> {
- self.run_command(&["config", &format!("worktrunk.hints.{name}"), "true"])?;
- Ok(())
+ self.set_config_value(&format!("worktrunk.hints.{name}"), "true")
}
/// Clear a hint so it will show again.
@@ -157,31 +217,24 @@ impl Repository {
/// Returns `true` if the hint was cleared, `false` if it didn't exist.
/// Propagates actual git config errors (corrupt config, permission denied).
pub fn clear_hint(&self, name: &str) -> anyhow::Result<bool> {
- let key = format!("worktrunk.hints.{name}");
- let output = self.run_command_output(&["config", "--unset", &key])?;
- if output.status.success() {
- Ok(true)
- } else if output.status.code() == Some(5) {
- Ok(false) // Key didn't exist (--unset uses exit code 5)
- } else {
- let stderr = String::from_utf8_lossy(&output.stderr);
- anyhow::bail!("git config --unset {}: {}", key, stderr.trim());
- }
+ self.unset_config_value(&format!("worktrunk.hints.{name}"))
}
/// List all hints that have been shown in this repo.
+ ///
+ /// Output is sorted alphabetically for deterministic rendering — the
+ /// `HashMap` backing `all_config` doesn't preserve insertion order.
pub fn list_shown_hints(&self) -> Vec<String> {
- self.run_command(&["config", "--get-regexp", r"^worktrunk\.hints\."])
- .unwrap_or_default()
- .lines()
- .filter_map(|line| {
- // Format: "worktrunk.hints.worktree-path true"
- line.split_whitespace()
- .next()
- .and_then(|key| key.strip_prefix("worktrunk.hints."))
- .map(String::from)
- })
- .collect()
+ let Ok(lock) = self.all_config() else {
+ return Vec::new();
+ };
+ let guard = lock.read().unwrap();
+ let mut hints: Vec<String> = guard
+ .keys()
+ .filter_map(|k| k.strip_prefix("worktrunk.hints.").map(String::from))
+ .collect();
+ hints.sort();
+ hints
}
/// Clear all hints so they will show again.
@@ -221,36 +274,21 @@ impl Repository {
self.cache
.default_branch
.get_or_init(|| {
- // Fast path: check worktrunk's persistent cache (git config)
+ // Fast path: trust the persisted value without re-validating
+ // that the branch still resolves locally. This avoids an
+ // extra fork on every command, at the cost of surfacing a
+ // clearer error downstream (see GitError::StaleDefaultBranch)
+ // when the configured branch was deleted externally.
let configured = self
- .run_command(&["config", "--get", "worktrunk.default-branch"])
+ .config_last("worktrunk.default-branch")
.ok()
+ .flatten()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
-
- // If configured, validate it exists locally
- if let Some(ref branch) = configured {
- if self.branch(branch).exists_locally().unwrap_or(false) {
- let _ = self.cache.invalid_default_branch.set(None);
- return Some(branch.clone());
- }
- // Check if this is the unborn default branch (HEAD points to it but no commits yet)
- if self.is_unborn_head_branch(branch) {
- let _ = self.cache.invalid_default_branch.set(None);
- return Some(branch.clone());
- }
- // Configured branch doesn't exist - cache for warning, return None
- let _ = self.cache.invalid_default_branch.set(Some(branch.clone()));
- log::debug!(
- "Configured default branch '{}' doesn't exist locally",
- branch
- );
- return None;
+ if let Some(branch) = configured {
+ return Some(branch);
}
- // Not configured - no invalid branch to report
- let _ = self.cache.invalid_default_branch.set(None);
-
// Detect: try remote, then local inference
let detected = self.detect_from_remote().or_else(|| {
self.infer_default_branch_locally()
@@ -259,8 +297,10 @@ impl Repository {
});
// Cache detected result to git config for future runs
- if let Some(ref branch) = detected {
- let _ = self.run_command(&["config", "worktrunk.default-branch", branch]);
+ if let Some(ref branch) = detected
+ && let Err(e) = self.set_config_value("worktrunk.default-branch", branch)
+ {
+ log::debug!("Failed to persist default-branch cache: {e}");
}
detected
@@ -268,25 +308,6 @@ impl Repository {
.clone()
}
- /// Check if user configured an invalid default branch.
- ///
- /// Returns `Some(branch_name)` if user set `worktrunk.default-branch` to a branch
- /// that doesn't exist locally. Returns `None` if:
- /// - No branch is configured (detection will be used)
- /// - Configured branch exists locally
- ///
- /// Used to show warnings when the configured branch is invalid.
- ///
- /// This is a cache read - `default_branch()` populates both caches when it runs.
- pub fn invalid_default_branch_config(&self) -> Option<String> {
- // Ensure default_branch() has run (populates both caches, no-op if already called)
- let _ = self.default_branch();
- self.cache
- .invalid_default_branch
- .get()
- .and_then(|opt| opt.clone())
- }
-
/// Try to detect default branch from remote.
fn detect_from_remote(&self) -> Option<String> {
let remote = self.primary_remote().ok()?;
@@ -326,9 +347,18 @@ impl Repository {
///
/// Use this for commands that update a branch ref (merge, push).
/// Validates before approval prompts to avoid wasting user time.
+ ///
+ /// When `target` is `None` (resolving via the cached default branch)
+ /// and the resolved branch doesn't exist, surfaces
+ /// [`GitError::StaleDefaultBranch`] with cache-reset hints rather than
+ /// the generic "branch not found" — the user didn't type that name,
+ /// the persisted cache did.
pub fn require_target_branch(&self, target: Option<&str>) -> anyhow::Result<String> {
let branch = self.resolve_target_branch(target)?;
if !self.branch(&branch).exists()? {
+ if target.is_none() {
+ return Err(GitError::StaleDefaultBranch { branch }.into());
+ }
return Err(GitError::BranchNotFound {
branch,
show_create_hint: true,
@@ -343,9 +373,17 @@ impl Repository {
///
/// Use this for commands that reference a commit (rebase, squash).
/// Validates before approval prompts to avoid wasting user time.
+ ///
+ /// When `target` is `None` (resolving via the cached default branch)
+ /// and the resolved reference doesn't exist, surfaces
+ /// [`GitError::StaleDefaultBranch`] with cache-reset hints rather than
+ /// the generic "reference not found".
pub fn require_target_ref(&self, target: Option<&str>) -> anyhow::Result<String> {
let reference = self.resolve_target_branch(target)?;
if !self.ref_exists(&reference)? {
+ if target.is_none() {
+ return Err(GitError::StaleDefaultBranch { branch: reference }.into());
+ }
return Err(GitError::ReferenceNotFound { reference }.into());
}
Ok(reference)
@@ -381,7 +419,7 @@ impl Repository {
}
// 3. Check git config init.defaultBranch (if branch exists)
- if let Ok(default) = self.run_command(&["config", "--get", "init.defaultBranch"]) {
+ if let Ok(Some(default)) = self.config_last("init.defaultBranch") {
let branch = default.trim().to_string();
if !branch.is_empty() && branches.contains(&branch) {
return Ok(branch);
@@ -406,18 +444,6 @@ impl Repository {
// Private helpers for default_branch detection
- /// Check if a branch is the unborn default branch (HEAD points to it but no commits exist).
- ///
- /// This is the case in a freshly `git init`-ed repo: HEAD is `refs/heads/main` but the
- /// branch doesn't exist yet (no commits). We accept this as a valid default branch.
- fn is_unborn_head_branch(&self, branch: &str) -> bool {
- self.run_command(&["symbolic-ref", "HEAD"])
- .ok()
- .and_then(|s| s.trim().strip_prefix("refs/heads/").map(String::from))
- .is_some_and(|head_branch| head_branch == branch)
- && self.all_branches().is_ok_and(|b| b.is_empty())
- }
-
fn local_default_branch(&self, remote: &str) -> anyhow::Result<String> {
let stdout =
self.run_command(&["rev-parse", "--abbrev-ref", &format!("{}/HEAD", remote)])?;
@@ -434,8 +460,7 @@ impl Repository {
/// This sets worktrunk's cache (`worktrunk.default-branch`). Use `clear` then
/// `get` to re-detect from remote.
pub fn set_default_branch(&self, branch: &str) -> anyhow::Result<()> {
- self.run_command(&["config", "worktrunk.default-branch", branch])?;
- Ok(())
+ self.set_config_value("worktrunk.default-branch", branch)
}
/// Clear the default branch cache.
@@ -446,18 +471,7 @@ impl Repository {
/// Returns `true` if cache was cleared, `false` if no cache existed.
/// Propagates actual git config errors (corrupt config, permission denied).
pub fn clear_default_branch_cache(&self) -> anyhow::Result<bool> {
- let output = self.run_command_output(&["config", "--unset", "worktrunk.default-branch"])?;
- if output.status.success() {
- Ok(true)
- } else if output.status.code() == Some(5) {
- Ok(false) // Key didn't exist (--unset uses exit code 5)
- } else {
- let stderr = String::from_utf8_lossy(&output.stderr);
- anyhow::bail!(
- "git config --unset worktrunk.default-branch: {}",
- stderr.trim()
- );
- }
+ self.unset_config_value("worktrunk.default-branch")
}
// =========================================================================
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index fa2154d4a..0c12f6f8f 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -196,21 +196,27 @@ fn stream_exit_result(
#[derive(Debug, Default)]
pub(super) struct RepoCache {
// ========== Repo-wide values (same for all worktrees) ==========
- /// Whether this is a bare repository
- pub(super) is_bare: OnceCell<bool>,
+ /// Every git config key in the merged config (system + global + repo),
+ /// populated by one `git config --list -z` read on first access.
+ ///
+ /// All the single-key config accessors (`is_bare`, `primary_remote`,
+ /// `remote_url`, `default_branch` fast path, hint/marker readers)
+ /// consult this map instead of spawning their own subprocess. Multivars
+ /// (e.g., multiple `remote.origin.url` entries) accumulate in the Vec.
+ /// `RwLock` rather than `OnceCell` so in-process writes via
+ /// [`Repository::set_config_value`] stay coherent after population.
+ ///
+ /// `IndexMap` preserves insertion order, matching git's own `--list -z`
+ /// output order — so accessors that iterate the map (e.g.,
+ /// `primary_remote` picking "first remote with a URL") follow config
+ /// file order the same way the old `--get-regexp` calls did.
+ pub(super) all_config: OnceCell<std::sync::RwLock<indexmap::IndexMap<String, Vec<String>>>>,
/// Repository root path (main worktree for normal repos, bare directory for bare repos)
pub(super) repo_path: OnceCell<PathBuf>,
/// Default branch (main, master, etc.)
pub(super) default_branch: OnceCell<Option<String>>,
- /// Invalid default branch config (user configured a branch that doesn't exist).
- /// Populated by `default_branch()` during config validation.
- pub(super) invalid_default_branch: OnceCell<Option<String>>,
/// Effective integration target (local default branch or upstream if ahead)
pub(super) integration_target: OnceCell<Option<String>>,
- /// Primary remote name (None if no remotes configured)
- pub(super) primary_remote: OnceCell<Option<String>>,
- /// Primary remote URL (None if no remotes configured or no URL)
- pub(super) primary_remote_url: OnceCell<Option<String>>,
/// Project identifier derived from remote URL
pub(super) project_identifier: OnceCell<String>,
/// Project config (loaded from .config/wt.toml in main worktree)
@@ -228,12 +234,9 @@ pub(super) struct RepoCache {
/// Batch ahead/behind cache: (base_ref, branch_name) -> (ahead, behind)
/// Populated by batch_ahead_behind(), used by cached_ahead_behind()
pub(super) ahead_behind: DashMap<(String, String), (usize, usize)>,
- /// Raw remote URLs: remote_name -> URL from `.git/config` (no `url.insteadOf`).
- /// Cached because `primary_remote` validates the URL, then `primary_remote_url`
- /// reads it again — two calls for the same key without this cache.
- pub(super) remote_urls: DashMap<String, Option<String>>,
/// Effective remote URLs: remote_name -> effective URL (with `url.insteadOf` applied).
- /// Cached because forge detection may query the same remote multiple times.
+ /// Separate from `all_config` because `git remote get-url` applies
+ /// `url.insteadOf` rewrites that aren't visible in raw config.
pub(super) effective_remote_urls: DashMap<String, Option<String>>,
/// Resolved refs: unresolved ref (e.g., "main") -> resolved form (e.g., "refs/heads/main")
/// or original if not a local branch. Populated by `resolve_preferring_branch()`.
@@ -719,51 +722,74 @@ impl Repository {
.map(|p| p.as_path())
}
+ /// Access the bulk git config map, populating on first call.
+ ///
+ /// Reads every key from the merged git config (system + global + repo)
+ /// via a single `git config --list -z` subprocess. The NUL-delimited
+ /// `-z` format handles values containing newlines or `=`. Populated
+ /// lazily on first access; every config-reading accessor consults this
+ /// map rather than spawning its own subprocess.
+ ///
+ /// Run from `git_common_dir` so linked worktrees of bare repos correctly
+ /// read the bare repo's config.
+ pub(super) fn all_config(
+ &self,
+ ) -> anyhow::Result<&std::sync::RwLock<indexmap::IndexMap<String, Vec<String>>>> {
+ self.cache.all_config.get_or_try_init(|| {
+ let output = Cmd::new("git")
+ .args(["config", "--list", "-z"])
+ .current_dir(&self.git_common_dir)
+ .context(path_to_logging_context(&self.git_common_dir))
+ .run()
+ .context("failed to read git config")?;
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ bail!("git config --list failed: {}", stderr.trim());
+ }
+ Ok(std::sync::RwLock::new(parse_config_list_z(&output.stdout)))
+ })
+ }
+
+ /// Read the last value for a config key from the bulk map.
+ ///
+ /// Convenience wrapper for the common "single-value" accessor pattern.
+ /// Git treats the last value as authoritative when a key is set multiple
+ /// times; callers that need multivars read through `all_config()` directly.
+ ///
+ /// Keys are normalized to git's canonical form (section and variable
+ /// names lowercased, subsection preserved) so callers may pass the
+ /// mixed-case form from git docs (e.g., `init.defaultBranch`) without
+ /// missing the lookup.
+ pub(super) fn config_last(&self, key: &str) -> anyhow::Result<Option<String>> {
+ let canonical = canonical_config_key(key);
+ let guard = self.all_config()?.read().unwrap();
+ Ok(guard.get(&canonical).and_then(|v| v.last().cloned()))
+ }
+
/// Check if this is a bare repository (no working tree).
///
/// Bare repositories have no main worktree — all worktrees are linked
/// worktrees at templated paths, including the default branch.
///
- /// Result is cached in the repository's shared cache (same for all clones).
- ///
- /// Reads `core.bare` from git config rather than using `git rev-parse
- /// --is-bare-repository`. The rev-parse approach is unreliable when run from
- /// inside a `.git` directory — when `core.bare` is unset, git infers based
- /// on directory context, and from inside `.git/` there's no working tree so
- /// it returns `true` even for normal repos. This affects repos where
- /// `core.bare` was never written (e.g., repos cloned by Eclipse/EGit).
- /// Reading the config value directly avoids this false positive.
+ /// Reads `core.bare` from the bulk config map rather than using `git
+ /// rev-parse --is-bare-repository`. The rev-parse approach is unreliable
+ /// when run from inside a `.git` directory — when `core.bare` is unset,
+ /// git infers based on directory context, and from inside `.git/` there's
+ /// no working tree so it returns `true` even for normal repos. This
+ /// affects repos where `core.bare` was never written (e.g., repos cloned
+ /// by Eclipse/EGit). Reading the config value directly avoids this false
+ /// positive.
///
- /// Uses `--type=bool` to normalize all git boolean representations (`yes`,
- /// `1`, `on`, `TRUE`) to `true`/`false`. When `core.bare` is unset (exit 1),
- /// defaults to non-bare — matching libgit2's behavior.
+ /// When `core.bare` is unset, defaults to non-bare — matching libgit2's
+ /// behavior.
///
/// See <https://github.com/max-sixty/worktrunk/issues/1939>.
pub fn is_bare(&self) -> anyhow::Result<bool> {
- self.cache
- .is_bare
- .get_or_try_init(|| {
- // Read core.bare from git config. We run from git_common_dir so
- // linked worktrees of bare repos correctly read the bare repo's
- // config (not the worktree's).
- let output = Cmd::new("git")
- .args(["config", "--type=bool", "core.bare"])
- .current_dir(&self.git_common_dir)
- .context(path_to_logging_context(&self.git_common_dir))
- .run()
- .context("failed to check if repository is bare")?;
- // Exit 0 = key found (value printed), 1 = key missing (not bare),
- // 2+ = config error (corrupt file, invalid type).
- match output.status.code() {
- Some(0) => Ok(String::from_utf8_lossy(&output.stdout).trim() == "true"),
- Some(1) => Ok(false),
- _ => {
- let stderr = String::from_utf8_lossy(&output.stderr);
- bail!("git config core.bare failed: {}", stderr.trim());
- }
- }
- })
- .copied()
+ Ok(self
+ .config_last("core.bare")?
+ .as_deref()
+ .map(parse_git_bool)
+ .unwrap_or(false))
}
/// Get the sparse checkout paths for this repository.
@@ -1104,5 +1130,75 @@ impl Repository {
}
}
+/// Normalize a git config key to its canonical form.
+///
+/// Git section and variable names are case-insensitive; subsection names
+/// (the middle parts of 3+-part keys) preserve case. `git config --list`
+/// emits the canonical form — so lookups against the parsed map must
+/// normalize the same way.
+///
+/// - 1 or 2 parts (`section` or `section.variable`): lowercase the whole thing.
+/// - 3+ parts (`section.subsection….variable`): lowercase first and last parts,
+/// preserve the middle.
+pub(super) fn canonical_config_key(key: &str) -> String {
+ let parts: Vec<&str> = key.split('.').collect();
+ match parts.len() {
+ 0 | 1 => key.to_ascii_lowercase(),
+ 2 => key.to_ascii_lowercase(),
+ _ => {
+ let (first, rest) = parts.split_first().unwrap();
+ let (last, middle) = rest.split_last().unwrap();
+ let mut out = String::with_capacity(key.len());
+ out.push_str(&first.to_ascii_lowercase());
+ for part in middle {
+ out.push('.');
+ out.push_str(part);
+ }
+ out.push('.');
+ out.push_str(&last.to_ascii_lowercase());
+ out
+ }
+ }
+}
+
+/// Parse the output of `git config --list -z`.
+///
+/// Format: each entry is `key\nvalue\0`. Values may be empty (no `\n`) for
+/// keys set via `git config key ""` — handled as `key -> ""`.
+///
+/// Returns a map from canonical key (as git emits it) to the list of
+/// values, preserving order (matches git's own multivar semantics where
+/// the last value wins).
+fn parse_config_list_z(stdout: &[u8]) -> indexmap::IndexMap<String, Vec<String>> {
+ let mut map: indexmap::IndexMap<String, Vec<String>> = indexmap::IndexMap::new();
+ for entry in stdout.split(|&b| b == 0) {
+ if entry.is_empty() {
+ continue;
+ }
+ let text = String::from_utf8_lossy(entry);
+ let (key, value) = match text.split_once('\n') {
+ Some((k, v)) => (k, v),
+ // `key` without any newline → no value set (shouldn't happen
+ // with `--list -z`, but tolerate gracefully).
+ None => (text.as_ref(), ""),
+ };
+ map.entry(key.to_string())
+ .or_default()
+ .push(value.to_string());
+ }
+ map
+}
+
+/// Parse a git boolean config value.
+///
+/// Accepts the forms `git config --type=bool` normalizes: `true/1/yes/on`
+/// (case-insensitive) → `true`; anything else → `false`.
+fn parse_git_bool(value: &str) -> bool {
+ matches!(
+ value.trim().to_ascii_lowercase().as_str(),
+ "true" | "1" | "yes" | "on"
+ )
+}
+
#[cfg(test)]
mod tests;
diff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rs
index bffc621b3..47e3b2844 100644
--- a/src/git/repository/remotes.rs
+++ b/src/git/repository/remotes.rs
@@ -103,44 +103,31 @@ impl Repository {
/// 2. Otherwise, get the first remote with a configured URL
/// 3. Return error if no remotes exist
///
- /// Result is cached in the shared repo cache (shared across all worktrees).
+ /// Resolved from the bulk config map — O(1) once populated.
///
/// [1]: https://git-scm.com/docs/git-config#Documentation/git-config.txt-checkoutdefaultRemote
pub fn primary_remote(&self) -> anyhow::Result<String> {
- self.cache
- .primary_remote
- .get_or_init(|| {
- // Check git's checkout.defaultRemote config
- if let Ok(default_remote) = self.run_command(&["config", "checkout.defaultRemote"])
- {
- let default_remote = default_remote.trim();
- if !default_remote.is_empty() && self.remote_url(default_remote).is_some() {
- return Some(default_remote.to_string());
- }
- }
-
- // Fall back to first remote with a configured URL
- // Use git config to find remotes with URLs, filtering out phantom remotes
- // from global config (e.g., `remote.origin.prunetags=true` without a URL)
- let output = self
- .run_command(&["config", "--get-regexp", r"remote\..+\.url"])
- .unwrap_or_default();
- let first_remote = output.lines().find_map(|line| {
- // Parse "remote.<name>.url <value>" format
- // Use ".url " as delimiter to handle remote names with dots (e.g., "my.remote")
- // Use find_map (not next + parse) because the unanchored regex matches
- // any config key containing "remote.<something>.url" — not just actual
- // remote entries. For example, includeIf.hasconfig:remote.*.url:... keys
- // match and can appear before the first real remote URL.
- line.strip_prefix("remote.")
- .and_then(|s| s.split_once(".url "))
- .map(|(name, _)| name)
- });
+ // Check git's checkout.defaultRemote config
+ if let Some(default_remote) = self.config_last("checkout.defaultRemote")? {
+ let default_remote = default_remote.trim();
+ if !default_remote.is_empty() && self.remote_url(default_remote).is_some() {
+ return Ok(default_remote.to_string());
+ }
+ }
- first_remote.map(|s| s.to_string())
- })
- .clone()
- .ok_or_else(|| anyhow::anyhow!("No remotes configured"))
+ // Fall back to first remote with a configured URL. Filters out
+ // phantom remotes from global config (e.g., `remote.origin.prunetags
+ // = true` without a URL) by requiring a `remote.<NAME>.url` entry.
+ let guard = self.all_config()?.read().unwrap();
+ let first_remote = guard.keys().find_map(|k| {
+ let rest = k.strip_prefix("remote.")?;
+ // `.url` suffix identifies url entries. Remote names can contain
+ // dots (e.g., "my.remote"), so rsplit from the right: the last
+ // `.url` is always the suffix.
+ let name = rest.strip_suffix(".url")?;
+ Some(name.to_string())
+ });
+ first_remote.ok_or_else(|| anyhow::anyhow!("No remotes configured"))
}
/// Get the URL for a remote, if configured.
@@ -149,18 +136,12 @@ impl Repository {
/// rewrites. Use [`effective_remote_url`](Self::effective_remote_url) when you
/// need forge detection to work with `insteadOf` aliases.
///
- /// Results are cached per-remote in the shared repo cache.
+ /// Resolved from the bulk config map — O(1) once populated.
pub fn remote_url(&self, remote: &str) -> Option<String> {
- self.cache
- .remote_urls
- .entry(remote.to_string())
- .or_insert_with(|| {
- self.run_command(&["config", &format!("remote.{}.url", remote)])
- .ok()
- .map(|url| url.trim().to_string())
- .filter(|url| !url.is_empty())
- })
- .clone()
+ self.config_last(&format!("remote.{remote}.url"))
+ .ok()
+ .flatten()
+ .filter(|url| !url.is_empty())
}
/// Get the effective URL for a remote, with `url.insteadOf` rewrites applied.
@@ -247,17 +228,19 @@ impl Repository {
/// Returns a list of (remote_name, url) pairs for all remotes with URLs.
/// Useful for searching across remotes when the specific remote is unknown.
pub fn all_remote_urls(&self) -> Vec<(String, String)> {
- let output = match self.run_command(&["config", "--get-regexp", r"remote\..+\.url"]) {
- Ok(output) => output,
- Err(_) => return Vec::new(),
+ let Ok(lock) = self.all_config() else {
+ return Vec::new();
};
-
- output
- .lines()
- .filter_map(|line| {
- // Parse "remote.<name>.url <value>" format
- let rest = line.strip_prefix("remote.")?;
- let (name, url) = rest.split_once(".url ")?;
+ let guard = lock.read().unwrap();
+ guard
+ .iter()
+ .filter_map(|(k, values)| {
+ let rest = k.strip_prefix("remote.")?;
+ let name = rest.strip_suffix(".url")?;
+ let url = values.last()?.trim();
+ if url.is_empty() {
+ return None;
+ }
Some((name.to_string(), url.to_string()))
})
.collect()
@@ -265,16 +248,11 @@ impl Repository {
/// Get the URL for the primary remote, if configured.
///
- /// Returns the raw config value. Result is cached in the shared repo cache.
+ /// Returns the raw config value. Resolves via the bulk config map.
pub fn primary_remote_url(&self) -> Option<String> {
- self.cache
- .primary_remote_url
- .get_or_init(|| {
- self.primary_remote()
- .ok()
- .and_then(|remote| self.remote_url(&remote))
- })
- .clone()
+ self.primary_remote()
+ .ok()
+ .and_then(|remote| self.remote_url(&remote))
}
/// Parse the primary remote URL into structured host/owner/repo components.
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index ed8f1f175..83ba6c320 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -385,7 +385,8 @@ fn repo_path_error_when_is_bare_fails() {
// Create a Repository with a non-existent git_common_dir.
// This makes --show-toplevel fail (reaching the is_bare branch),
- // and then is_bare() also fails because git can't run in a missing dir.
+ // and then is_bare() also fails because the bulk config read
+ // can't run in a missing dir.
let repo = super::Repository {
discovery_path: PathBuf::from("/nonexistent/repo"),
git_common_dir: PathBuf::from("/nonexistent/.git"),
@@ -397,11 +398,109 @@ fn repo_path_error_when_is_bare_fails() {
// The OS error text is platform-specific (e.g., "No such file or directory" on Unix,
// "The directory name is invalid." on Windows), so only assert the stable prefix.
assert!(
- msg.starts_with("failed to check if repository is bare: "),
+ msg.starts_with("failed to read git config: "),
"unexpected error message: {msg}"
);
}
+#[test]
+fn parse_config_list_z_basic() {
+ let input = b"core.bare\nfalse\0remote.origin.url\nhttps://example.com/a.git\0";
+ let map = super::parse_config_list_z(input);
+ assert_eq!(map["core.bare"], vec!["false"]);
+ assert_eq!(map["remote.origin.url"], vec!["https://example.com/a.git"]);
+}
+
+#[test]
+fn parse_config_list_z_multivar() {
+ let input =
+ b"remote.origin.fetch\n+refs/heads/*:refs/remotes/origin/*\0remote.origin.fetch\n+refs/tags/*:refs/tags/*\0";
+ let map = super::parse_config_list_z(input);
+ assert_eq!(
+ map["remote.origin.fetch"],
+ vec![
+ "+refs/heads/*:refs/remotes/origin/*",
+ "+refs/tags/*:refs/tags/*"
+ ]
+ );
+}
+
+#[test]
+fn parse_config_list_z_newline_in_value() {
+ // A value with embedded newlines is preserved verbatim because -z uses
+ // NUL as the record separator. The split_once('\n') only splits on the
+ // first newline (which separates key from value).
+ let input = b"commit.template\nline1\nline2\0core.bare\nfalse\0";
+ let map = super::parse_config_list_z(input);
+ assert_eq!(map["commit.template"], vec!["line1\nline2"]);
+ assert_eq!(map["core.bare"], vec!["false"]);
+}
+
+#[test]
+fn parse_config_list_z_equals_in_value() {
+ // Values containing `=` are preserved — no splitting on `=` because
+ // the key/value separator under `-z` is `\n`.
+ let input = b"user.email\[email protected]\0";
+ let map = super::parse_config_list_z(input);
+ assert_eq!(map["user.email"], vec!["[email protected]"]);
+}
+
+#[test]
+fn parse_config_list_z_empty() {
+ let map = super::parse_config_list_z(b"");
+ assert!(map.is_empty());
+}
+
+#[test]
+fn parse_config_list_z_entry_without_newline_tolerates_key_only() {
+ // `git config --list -z` always emits `key\nvalue\0`, but the parser
+ // tolerates bare `key\0` by mapping it to `key -> ""` rather than
+ // dropping the entry. Lets a future git oddity be diagnosed at the
+ // use-site instead of silently missing.
+ let input = b"core.bare\0other.key\nfalse\0";
+ let map = super::parse_config_list_z(input);
+ assert_eq!(map["core.bare"], vec![""]);
+ assert_eq!(map["other.key"], vec!["false"]);
+}
+
+#[test]
+fn canonical_config_key_cases() {
+ // section + variable: both lowercased
+ assert_eq!(
+ super::canonical_config_key("init.defaultBranch"),
+ "init.defaultbranch"
+ );
+ assert_eq!(
+ super::canonical_config_key("checkout.defaultRemote"),
+ "checkout.defaultremote"
+ );
+ assert_eq!(super::canonical_config_key("core.Bare"), "core.bare");
+ // 3+ parts: section + variable lowercased, subsection preserved
+ assert_eq!(
+ super::canonical_config_key("remote.MyFork.url"),
+ "remote.MyFork.url"
+ );
+ assert_eq!(
+ super::canonical_config_key("branch.MyBranch.pushRemote"),
+ "branch.MyBranch.pushremote"
+ );
+ // 4+ parts: subsection is the middle (spanning dots); only first and last lowercase
+ assert_eq!(
+ super::canonical_config_key("worktrunk.state.MyBranch.marker"),
+ "worktrunk.state.MyBranch.marker"
+ );
+}
+
+#[test]
+fn parse_git_bool_variants() {
+ for truthy in ["true", "TRUE", "True", "1", "yes", "YES", "on", "ON"] {
+ assert!(super::parse_git_bool(truthy), "{truthy} should be true");
+ }
+ for falsy in ["false", "0", "no", "off", "", "anything-else"] {
+ assert!(!super::parse_git_bool(falsy), "{falsy} should be false");
+ }
+}
+
#[test]
fn extract_failed_command_from_stream_error() {
use super::StreamCommandError;
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index f8d619956..3a9429ea1 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -1406,8 +1406,8 @@ fn test_state_hints_get_with_hints(repo: TestRepo) {
let output = wt_state_cmd(&repo, "hints", "get", &[]).output().unwrap();
assert!(output.status.success());
assert_snapshot!(String::from_utf8_lossy(&output.stdout), @"
- worktree-path
another-hint
+ worktree-path
");
}
diff --git a/tests/integration_tests/default_branch.rs b/tests/integration_tests/default_branch.rs
index f169940f3..558424c3c 100644
--- a/tests/integration_tests/default_branch.rs
+++ b/tests/integration_tests/default_branch.rs
@@ -228,53 +228,35 @@ fn test_default_branch_no_remote_uses_init_config(repo: TestRepo) {
}
#[rstest]
-fn test_configured_default_branch_does_not_exist_returns_none(repo: TestRepo) {
- // Configure a non-existent branch
+fn test_configured_default_branch_is_trusted_without_validation(repo: TestRepo) {
+ // Configure a non-existent branch — `default_branch()` no longer
+ // validates that the branch resolves locally on the fast path. The
+ // persisted value is returned as-is; a stale cache surfaces as a
+ // `StaleDefaultBranch` error downstream (e.g., from `wt merge`) with
+ // cache-reset hints.
repo.git_command()
.args(["config", "worktrunk.default-branch", "nonexistent-branch"])
.run()
.unwrap();
- // Should return None when configured branch doesn't exist locally
let result = Repository::at(repo.root_path()).unwrap().default_branch();
- assert!(
- result.is_none(),
- "Expected None when configured branch doesn't exist, got: {:?}",
- result
- );
-}
-
-#[rstest]
-fn test_invalid_default_branch_config_returns_configured_value(repo: TestRepo) {
- // Configure a non-existent branch
- repo.git_command()
- .args(["config", "worktrunk.default-branch", "nonexistent-branch"])
- .run()
- .unwrap();
-
- // Should report the invalid configuration
- let invalid = Repository::at(repo.root_path())
- .unwrap()
- .invalid_default_branch_config();
- assert_eq!(invalid, Some("nonexistent-branch".to_string()));
+ assert_eq!(result, Some("nonexistent-branch".to_string()));
}
+/// In-process `set` followed by `get` sees the new value even when the
+/// config key has a mixed-case variable name. Regression: previously
+/// `set_config_value` inserted the literal key (`…pushRemote`) while
+/// `config_last` looked up the canonical key (`…pushremote`) — the map
+/// ended up with two entries, and reads missed the write.
#[rstest]
-fn test_invalid_default_branch_config_returns_none_when_valid(repo: TestRepo) {
- // Configure the existing "main" branch
- repo.git_command()
- .args(["config", "worktrunk.default-branch", "main"])
- .run()
- .unwrap();
-
- // Should return None since the configured branch exists
- let invalid = Repository::at(repo.root_path())
- .unwrap()
- .invalid_default_branch_config();
- assert!(
- invalid.is_none(),
- "Expected None when configured branch exists, got: {:?}",
- invalid
+fn test_set_config_then_get_mixed_case_variable(repo: TestRepo) {
+ let r = Repository::at(repo.root_path()).unwrap();
+ // Trigger bulk config population before the write.
+ let _ = r.is_bare();
+ r.set_config("branch.main.pushRemote", "origin").unwrap();
+ assert_eq!(
+ r.config_value("branch.main.pushRemote").unwrap(),
+ Some("origin".to_string())
);
}
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index 7d05ac2d6..e04d060a9 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -2999,15 +2999,21 @@ fn test_list_skips_operations_for_prunable_worktrees(mut repo: TestRepo) {
/// Tests that wt list works correctly when the configured default branch doesn't exist.
///
/// When a user sets `wt config state default-branch set develop` but the `develop`
-/// branch doesn't exist locally, `wt list` should show a warning and degrade gracefully
-/// (empty cells for columns needing default branch) rather than failing with git errors.
+/// branch doesn't exist locally, `wt list` degrades gracefully — columns needing
+/// default branch show empty cells rather than failing with git errors.
+///
+/// With `--branches`, the opportunistic stale-default check surfaces a
+/// warning using the already-enumerated branch set (no extra fork). Plain
+/// `wt list` (worktrees only) does not have the full branch set and so does
+/// not emit the warning — the user sees a clearer `StaleDefaultBranch`
+/// error the moment they run a default-branch-consuming command.
#[rstest]
fn test_list_with_nonexistent_default_branch(repo: TestRepo) {
// Set default branch to a non-existent branch
repo.run_git(&["config", "worktrunk.default-branch", "nonexistent"]);
- // wt list should show a warning and degrade gracefully (empty columns for
- // main-related data) when configured default branch doesn't exist locally
+ // wt list should degrade gracefully (empty columns for main-related data)
+ // when configured default branch doesn't exist locally
assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
}
@@ -3028,6 +3034,19 @@ fn test_list_full_with_nonexistent_default_branch(repo: TestRepo) {
});
}
+/// With `--branches`, `wt list` emits the stale-default-branch warning via
+/// the already-enumerated branch set — no extra fork.
+#[rstest]
+fn test_list_branches_with_nonexistent_default_branch(repo: TestRepo) {
+ repo.run_git(&["config", "worktrunk.default-branch", "nonexistent"]);
+
+ assert_cmd_snapshot!({
+ let mut cmd = list_snapshots::command(&repo, repo.root_path());
+ cmd.arg("--branches");
+ cmd
+ });
+}
+
/// Tests that the current worktree indicator (@) is correct for nested worktrees.
///
/// When worktrees are placed inside other worktrees (e.g., `.worktrees/` layout),
@@ -3091,7 +3110,7 @@ fn test_list_empty_repo() {
let guard =
setup_snapshot_settings_for_paths(repo.root_path(), &repo.worktrees).bind_to_scope();
std::mem::forget(guard);
- // Pre-set default branch cache so the `is_unborn_head_branch` validation path is exercised
+ // Pre-set default branch so the unborn-HEAD case has something to resolve to
repo.run_git(&["config", "worktrunk.default-branch", "main"]);
// Should show the branch with empty commit columns and no errors
assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 901be96bc..4278a8f90 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -117,6 +117,18 @@ fn test_merge_already_on_target(repo: TestRepo) {
assert_cmd_snapshot!(make_snapshot_cmd(&repo, "merge", &[], None));
}
+/// When `worktrunk.default-branch` points at a branch that no longer
+/// resolves locally (user deleted it externally), `wt merge` without
+/// `--target` surfaces `StaleDefaultBranch` with cache-reset hints rather
+/// than the generic `BranchNotFound` "create it?" path.
+#[rstest]
+fn test_merge_with_stale_default_branch_cache(mut repo: TestRepo) {
+ // Configure a cached default branch that doesn't exist locally
+ repo.run_git(&["config", "worktrunk.default-branch", "nonexistent"]);
+ let feature_wt = repo.add_feature();
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "merge", &[], Some(&feature_wt)));
+}
+
#[rstest]
fn test_merge_from_primary_worktree_to_other_branch(mut repo: TestRepo) {
// Create a feature branch with a commit, then merge from main worktree into it.
diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rs
index 6f42bbe95..8ef0f092b 100644
--- a/tests/integration_tests/repository.rs
+++ b/tests/integration_tests/repository.rs
@@ -412,6 +412,252 @@ fn test_clear_hint_propagates_error_on_corrupt_config() {
);
}
+// =============================================================================
+// Bulk config cache coverage
+// =============================================================================
+
+/// `mark_hint_shown` → `has_shown_hint` → `list_shown_hints` → `clear_hint`
+/// exercises the full write-then-read round trip through the bulk config
+/// cache, including coherent in-memory updates.
+#[test]
+fn test_hint_roundtrip_through_bulk_cache() {
+ let repo = TestRepo::new();
+ let r = Repository::at(repo.root_path().to_path_buf()).unwrap();
+
+ // Populate bulk cache before the write so set/unset hit the in-memory
+ // update paths.
+ assert!(!r.is_bare().unwrap());
+
+ r.mark_hint_shown("zebra").unwrap();
+ r.mark_hint_shown("alpha").unwrap();
+ assert!(r.has_shown_hint("zebra"));
+ assert!(r.has_shown_hint("alpha"));
+ assert!(!r.has_shown_hint("unknown"));
+
+ // Deterministic alphabetical ordering (bulk cache is a HashMap — order
+ // must be explicitly sorted for display).
+ let hints = r.list_shown_hints();
+ assert_eq!(hints, vec!["alpha".to_string(), "zebra".to_string()]);
+
+ // Clear one → coherent in-memory removal.
+ assert!(r.clear_hint("alpha").unwrap());
+ assert!(!r.has_shown_hint("alpha"));
+ assert!(r.has_shown_hint("zebra"));
+ assert_eq!(r.list_shown_hints(), vec!["zebra".to_string()]);
+
+ // Clear missing → Ok(false).
+ assert!(!r.clear_hint("never-set").unwrap());
+}
+
+/// `primary_remote()` honours `checkout.defaultRemote` when it points at
+/// a configured remote — covers the early-return branch in the new bulk
+/// lookup.
+#[test]
+fn test_primary_remote_honours_checkout_default_remote() {
+ let repo = TestRepo::new();
+ repo.run_git(&[
+ "remote",
+ "add",
+ "origin",
+ "https://github.com/max-sixty/worktrunk.git",
+ ]);
+ repo.run_git(&[
+ "remote",
+ "add",
+ "upstream",
+ "https://github.com/max-sixty/worktrunk.git",
+ ]);
+ repo.run_git(&["config", "checkout.defaultRemote", "upstream"]);
+
+ let r = Repository::at(repo.root_path().to_path_buf()).unwrap();
+ assert_eq!(r.primary_remote().unwrap(), "upstream");
+ // With no `checkout.defaultRemote`, falls back to the first remote
+ // with a URL (the filter-out-phantom-entries path).
+ repo.run_git(&["config", "--unset", "checkout.defaultRemote"]);
+ let r2 = Repository::at(repo.root_path().to_path_buf()).unwrap();
+ assert_eq!(r2.primary_remote().unwrap(), "origin");
+}
+
+/// `all_remote_urls()` enumerates every configured remote via the bulk
+/// map, filtering out phantom entries (keys with `remote.X.*` that have
+/// no `.url`).
+#[test]
+fn test_all_remote_urls_filters_phantom_remotes() {
+ let repo = TestRepo::new();
+ repo.run_git(&[
+ "remote",
+ "add",
+ "origin",
+ "https://github.com/max-sixty/worktrunk.git",
+ ]);
+ // A phantom entry: remote.X.prunetags set but no URL → should not appear.
+ repo.run_git(&["config", "remote.phantom.prunetags", "true"]);
+
+ let r = Repository::at(repo.root_path().to_path_buf()).unwrap();
+ let urls = r.all_remote_urls();
+ assert_eq!(urls.len(), 1, "expected only origin, got {urls:?}");
+ assert_eq!(urls[0].0, "origin");
+}
+
+/// `unset_config_value` cleanly removes in-memory state after the bulk
+/// cache is populated. Guards against a regression where the in-memory
+/// remove used the literal key instead of the canonical form.
+#[test]
+fn test_unset_config_removes_from_bulk_cache() {
+ let repo = TestRepo::new();
+ let r = Repository::at(repo.root_path().to_path_buf()).unwrap();
+
+ // Populate cache, then write a mixed-case variable key (canonical
+ // variable name is lowercased by git).
+ let _ = r.is_bare();
+ r.set_config("branch.main.pushRemote", "origin").unwrap();
+ assert_eq!(
+ r.config_value("branch.main.pushRemote").unwrap(),
+ Some("origin".to_string())
+ );
+
+ // Unset removes it — subsequent reads return None.
+ assert!(r.unset_config("branch.main.pushRemote").unwrap());
+ assert_eq!(r.config_value("branch.main.pushRemote").unwrap(), None);
+
+ // Unsetting again → Ok(false).
+ assert!(!r.unset_config("branch.main.pushRemote").unwrap());
+}
+
+/// `set_default_branch` → `clear_default_branch_cache` round trip,
+/// covering the specialized default-branch writers that route through
+/// `set_config_value` / `unset_config_value`.
+#[test]
+fn test_set_and_clear_default_branch() {
+ let repo = TestRepo::new();
+ let r = Repository::at(repo.root_path().to_path_buf()).unwrap();
+ r.set_default_branch("main").unwrap();
+ assert_eq!(r.default_branch(), Some("main".to_string()));
+
+ // Clearing an existing cache returns true; a second clear returns false.
+ let r2 = Repository::at(repo.root_path().to_path_buf()).unwrap();
+ assert!(r2.clear_default_branch_cache().unwrap());
+ assert!(!r2.clear_default_branch_cache().unwrap());
+}
+
+/// `switch_previous` / `set_switch_previous` round trip. Exercises
+/// `worktrunk.history` read + write through the bulk-config helpers.
+#[test]
+fn test_switch_previous_roundtrip() {
+ let repo = TestRepo::new();
+ let r = Repository::at(repo.root_path().to_path_buf()).unwrap();
+ // Populate the cache first to hit the in-memory update branch.
+ let _ = r.is_bare();
+ assert_eq!(r.switch_previous(), None);
+ r.set_switch_previous(Some("feature-a")).unwrap();
+ assert_eq!(r.switch_previous(), Some("feature-a".to_string()));
+ // `None` is a no-op — doesn't clear.
+ r.set_switch_previous(None).unwrap();
+ assert_eq!(r.switch_previous(), Some("feature-a".to_string()));
+}
+
+/// `primary_remote_url` composes `primary_remote` + `remote_url`,
+/// returning the raw URL for the primary remote. `primary_remote_parsed_url`
+/// threads that through `GitRemoteUrl::parse`.
+#[test]
+fn test_primary_remote_url_composition() {
+ let repo = TestRepo::new();
+ repo.run_git(&[
+ "remote",
+ "add",
+ "origin",
+ "https://github.com/max-sixty/worktrunk.git",
+ ]);
+ let r = Repository::at(repo.root_path().to_path_buf()).unwrap();
+ assert_eq!(
+ r.primary_remote_url(),
+ Some("https://github.com/max-sixty/worktrunk.git".to_string())
+ );
+ let parsed = r.primary_remote_parsed_url().expect("parses");
+ assert_eq!(parsed.owner(), "max-sixty");
+ assert_eq!(parsed.repo(), "worktrunk");
+
+ // Without a remote, both return None.
+ let bare = TestRepo::new();
+ let r2 = Repository::at(bare.root_path().to_path_buf()).unwrap();
+ assert_eq!(r2.primary_remote_url(), None);
+ assert!(r2.primary_remote_parsed_url().is_none());
+}
+
+/// `remote_url` for a configured remote round-trips; unknown remotes
+/// return `None`. Covers the `.filter(|url| !url.is_empty())` branch
+/// via the happy-path URL read.
+#[test]
+fn test_remote_url_known_and_unknown() {
+ let repo = TestRepo::new();
+ repo.run_git(&[
+ "remote",
+ "add",
+ "origin",
+ "[email protected]:max-sixty/worktrunk.git",
+ ]);
+ let r = Repository::at(repo.root_path().to_path_buf()).unwrap();
+ assert_eq!(
+ r.remote_url("origin"),
+ Some("[email protected]:max-sixty/worktrunk.git".to_string())
+ );
+ assert_eq!(r.remote_url("nonexistent"), None);
+}
+
+/// `primary_remote()` errors when no remotes are configured — covers
+/// the `ok_or_else(|| anyhow!("No remotes configured"))` final arm.
+#[test]
+fn test_primary_remote_errors_with_no_remotes() {
+ let repo = TestRepo::new(); // TestRepo::new() ships without a remote.
+ let r = Repository::at(repo.root_path().to_path_buf()).unwrap();
+ let err = r.primary_remote().unwrap_err();
+ assert!(
+ err.to_string().contains("No remotes configured"),
+ "unexpected error: {err}"
+ );
+}
+
+/// `require_target_ref(None)` surfaces `StaleDefaultBranch` when the
+/// persisted default branch no longer resolves locally. Covers the
+/// `target.is_none()` arm added alongside `require_target_branch` for
+/// commands like `wt step commit` that accept any commit-ish target.
+#[test]
+fn test_require_target_ref_surfaces_stale_default_branch() {
+ use worktrunk::git::GitError;
+ let repo = TestRepo::new();
+ let r = Repository::at(repo.root_path().to_path_buf()).unwrap();
+ r.set_config("worktrunk.default-branch", "nonexistent-branch")
+ .unwrap();
+
+ // Fresh Repository so the OnceCell re-reads the stale value.
+ let r2 = Repository::at(repo.root_path().to_path_buf()).unwrap();
+ let err = r2.require_target_ref(None).unwrap_err();
+ let gerr = err.downcast_ref::<GitError>().expect("GitError");
+ assert!(
+ matches!(gerr, GitError::StaleDefaultBranch { branch } if branch == "nonexistent-branch"),
+ "expected StaleDefaultBranch, got {gerr:?}"
+ );
+}
+
+/// `unset_config_value` propagates errors from corrupt git config
+/// rather than returning `Ok(false)` (the exit-code-5 "key absent" case).
+#[test]
+fn test_unset_config_propagates_error_on_corrupt_config() {
+ let repo = TestRepo::new();
+ let root = repo.root_path().to_path_buf();
+ let r = Repository::at(root.clone()).unwrap();
+ r.set_default_branch("main").unwrap();
+
+ // Corrupt the git config so subsequent writes fail with a real error
+ // (not the benign exit-code-5 that maps to Ok(false)).
+ fs::write(root.join(".git/config"), "[invalid section\n").unwrap();
+ let err = r.unset_config("worktrunk.default-branch");
+ assert!(
+ err.is_err(),
+ "unset_config should propagate corrupt-config errors: {err:?}"
+ );
+}
+
// =============================================================================
// Bug #1: Tag/branch name collision tests
// =============================================================================
diff --git a/tests/integration_tests/step_relocate.rs b/tests/integration_tests/step_relocate.rs
index 121ab1500..adffcc1df 100644
--- a/tests/integration_tests/step_relocate.rs
+++ b/tests/integration_tests/step_relocate.rs
@@ -598,12 +598,19 @@ worktree-path = "{{ nonexistent_variable }}"
);
}
-/// Test that empty default branch is detected early with actionable error
+/// Test that empty default branch is detected early with actionable error.
+///
+/// Engineers a state where detection genuinely fails (no remote, no
+/// standard branch names, no init.defaultBranch) so `default_branch()`
+/// returns None — relocate's preflight bails with a clear setup hint.
#[rstest]
fn test_relocate_empty_default_branch(repo: TestRepo) {
let parent = worktree_parent(&repo);
- // Create a worktree at a non-standard location
+ // Create a worktree at a non-standard location on a branch with a
+ // non-standard name, then rename `main` to another non-standard name
+ // and remove the remote. With no remote, no main/master/develop/trunk,
+ // and no init.defaultBranch, detection has nothing to go on.
let wrong_path = parent.join("wrong-location");
repo.run_git(&[
"worktree",
@@ -612,15 +619,8 @@ fn test_relocate_empty_default_branch(repo: TestRepo) {
"feature",
wrong_path.to_str().unwrap(),
]);
-
- // Set worktrunk.default-branch to a non-existent branch.
- // The detection logic validates that configured branches exist locally,
- // and returns None if they don't. This triggers the empty default branch error.
- repo.run_git(&[
- "config",
- "worktrunk.default-branch",
- "nonexistent-branch-xyz",
- ]);
+ repo.run_git(&["branch", "-m", "main", "trunk-a"]);
+ repo.run_git(&["remote", "remove", "origin"]);
// Relocate should fail early with helpful error
assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));
diff --git a/tests/snapshots/integration__integration_tests__list__list_branches_with_nonexistent_default_branch.snap b/tests/snapshots/integration__integration_tests__list__list_branches_with_nonexistent_default_branch.snap
new file mode 100644
index 000000000..70cbdead1
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__list_branches_with_nonexistent_default_branch.snap
@@ -0,0 +1,55 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--branches"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+ Branch Status HEAD± main↕ Remote⇅ Path Commit Age Message
+@ main ⚑^| | . 05a4a45d 16h Initial commit
++ feature-a _ ../repo.feature-a 1b87d473 16h Add feature-a file
++ feature-b _ ../repo.feature-b f62940fc 16h Add feature-b file
++ feature-c _ ../repo.feature-c 345c7c93 16h Add feature-c file
+
+○ Showing 4 worktrees
+
+----- stderr -----
+▲ Configured default branch nonexistent does not exist locally
+↳ To reset, run wt config state default-branch clear
diff --git a/tests/snapshots/integration__integration_tests__list__list_full_with_nonexistent_default_branch.snap b/tests/snapshots/integration__integration_tests__list__list_full_with_nonexistent_default_branch.snap
index 99d08054e..134128232 100644
--- a/tests/snapshots/integration__integration_tests__list__list_full_with_nonexistent_default_branch.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_full_with_nonexistent_default_branch.snap
@@ -44,9 +44,9 @@ exit_code: 0
----- stdout -----
Branch Status HEAD± main↕ main…± Remote⇅ CI Path Commit Age Message
@ main ⚑^| | . 05a4a45d 16h Initial commit
-+ feature-a ../repo.feature-a 1b87d473 16h Add feature-a file
-+ feature-b ../repo.feature-b f62940fc 16h Add feature-b file
-+ feature-c ../repo.feature-c 345c7c93 16h Add feature-c file
++ feature-a _ ../repo.feature-a 1b87d473 16h Add feature-a file
++ feature-b _ ../repo.feature-b f62940fc 16h Add feature-b file
++ feature-c _ ../repo.feature-c 345c7c93 16h Add feature-c file
○ Showing 4 worktrees
diff --git a/tests/snapshots/integration__integration_tests__list__list_with_nonexistent_default_branch.snap b/tests/snapshots/integration__integration_tests__list__list_with_nonexistent_default_branch.snap
index 161e4a4e2..b8f5d8c96 100644
--- a/tests/snapshots/integration__integration_tests__list__list_with_nonexistent_default_branch.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_with_nonexistent_default_branch.snap
@@ -43,9 +43,9 @@ exit_code: 0
----- stdout -----
Branch Status HEAD± main↕ Remote⇅ Path Commit Age Message
@ main ⚑^| | . 05a4a45d 16h Initial commit
-+ feature-a ../repo.feature-a 1b87d473 16h Add feature-a file
-+ feature-b ../repo.feature-b f62940fc 16h Add feature-b file
-+ feature-c ../repo.feature-c 345c7c93 16h Add feature-c file
++ feature-a _ ../repo.feature-a 1b87d473 16h Add feature-a file
++ feature-b _ ../repo.feature-b f62940fc 16h Add feature-b file
++ feature-c _ ../repo.feature-c 345c7c93 16h Add feature-c file
○ Showing 4 worktrees
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_with_stale_default_branch_cache.snap b/tests/snapshots/integration__integration_tests__merge__merge_with_stale_default_branch_cache.snap
new file mode 100644
index 000000000..f1bb7c9de
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_with_stale_default_branch_cache.snap
@@ -0,0 +1,47 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Default branch nonexistent does not exist locally
+↳ Reset the cached value with wt config state default-branch clear, or set it explicitly with wt config state default-branch set BRANCH