Skip to content

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

Simplify code by extracting helpers and normalizing config (#1813)

Maximilian Roosc5c446539e66
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 08489bae3..c2ba63cce 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -116,6 +116,7 @@ use worktrunk::styling::{
use crate::commands::is_worktree_at_expected_path;
use super::model::{DisplayFields, ItemKind, ListItem, WorktreeData};
+use super::progressive_table::ProgressiveTable;
// Re-exports for sibling modules (columns.rs, render.rs, layout.rs)
pub(crate) use tasks::parse_port_from_url;
@@ -128,6 +129,37 @@ use results::drain_results;
use types::{DrainOutcome, StatusContext};
use types::{TaskError, TaskResult};
+struct TableRenderPlan {
+ progressive_table: Option<ProgressiveTable>,
+ header: String,
+ rows: Vec<String>,
+ summary: String,
+}
+
+impl TableRenderPlan {
+ fn render(mut self) -> anyhow::Result<()> {
+ if let Some(mut table) = self.progressive_table.take() {
+ if table.is_tty() {
+ table.finalize(self.rows, self.summary)?;
+ } else {
+ print_buffered_table(&self.header, &self.rows, &self.summary);
+ }
+ } else {
+ print_buffered_table(&self.header, &self.rows, &self.summary);
+ }
+ Ok(())
+ }
+}
+
+fn print_buffered_table(header: &str, rows: &[String], summary: &str) {
+ println!("{header}");
+ for row in rows {
+ println!("{row}");
+ }
+ println!();
+ println!("{summary}");
+}
+
/// Options for controlling what data to collect.
///
/// This is operation parameters for a single `wt list` invocation, not a cache.
@@ -240,7 +272,6 @@ pub fn collect(
render_table: bool,
skip_expensive_for_stale: bool,
) -> anyhow::Result<Option<super::model::ListData>> {
- use super::progressive_table::ProgressiveTable;
worktrunk::shell_exec::trace_instant("List collect started");
// Determine what to fetch speculatively in the parallel phase.
@@ -942,50 +973,24 @@ pub fn collect(
let error_count = errors.len();
let timed_out_count = errors.iter().filter(|e| e.is_timeout()).count();
- // Finalize progressive table or render buffered output
- if let Some(mut table) = progressive_table {
- // Build final summary string
- let final_msg = super::format_summary_message(
- &all_items,
- show_branches || show_remotes,
- layout.hidden_column_count,
- error_count,
- timed_out_count,
- );
-
- if table.is_tty() {
- // Interactive: do final render pass and update footer to summary
- let rows: Vec<String> = all_items
- .iter()
- .map(|item| layout.format_list_item_line(item))
- .collect();
- table.finalize(rows, final_msg)?;
- } else {
- // Non-TTY: output to stdout (same as buffered mode)
- // Progressive skeleton was suppressed; now output the final table
- println!("{}", layout.format_header_line());
- for item in &all_items {
- println!("{}", layout.format_list_item_line(item));
- }
- println!();
- println!("{}", final_msg);
- }
- } else if render_table {
- // Buffered mode: render final table
- let final_msg = super::format_summary_message(
+ let table_render = render_table.then(|| TableRenderPlan {
+ progressive_table,
+ header: layout.format_header_line(),
+ rows: all_items
+ .iter()
+ .map(|item| layout.format_list_item_line(item))
+ .collect(),
+ summary: super::format_summary_message(
&all_items,
show_branches || show_remotes,
layout.hidden_column_count,
error_count,
timed_out_count,
- );
+ ),
+ });
- println!("{}", layout.format_header_line());
- for item in &all_items {
- println!("{}", layout.format_list_item_line(item));
- }
- println!();
- println!("{}", final_msg);
+ if let Some(table_render) = table_render {
+ table_render.render()?;
}
// Status symbols are now computed during data collection (both modes), no fallback needed
diff --git a/src/config/user/accessors.rs b/src/config/user/accessors.rs
index 75f46731b..127f34b91 100644
--- a/src/config/user/accessors.rs
+++ b/src/config/user/accessors.rs
@@ -22,6 +22,25 @@ fn default_worktree_path() -> String {
}
impl UserConfig {
+ fn project_overrides(
+ &self,
+ project: Option<&str>,
+ ) -> Option<&super::sections::UserProjectOverrides> {
+ project.and_then(|p| self.projects.get(p))
+ }
+
+ fn merged_project_config<T: Merge + Clone>(
+ &self,
+ project: Option<&str>,
+ global: Option<&T>,
+ project_config: impl FnOnce(&super::sections::UserProjectOverrides) -> Option<&T>,
+ ) -> Option<T> {
+ merge_optional(
+ global,
+ self.project_overrides(project).and_then(project_config),
+ )
+ }
+
/// Returns the worktree path template, falling back to the default if not set.
pub fn worktree_path(&self) -> String {
self.configs
@@ -49,36 +68,25 @@ impl UserConfig {
/// Returns the commit generation config for a specific project.
///
/// Merges project-specific settings with global settings, where project
- /// settings take precedence for fields that are set.
- ///
- /// Checks locations in order of precedence:
- /// 1. `[commit.generation]` (new format)
- /// 2. `[commit-generation]` (deprecated format)
- /// 3. Per-project overrides
+ /// settings take precedence for fields that are set. Deprecated
+ /// `[commit-generation]` sections are normalized into `[commit.generation]`
+ /// during config loading.
pub fn commit_generation(&self, project: Option<&str>) -> CommitGenerationConfig {
- // Get global config: prefer new location, fall back to deprecated
- let global = self
- .configs
- .commit
- .as_ref()
- .and_then(|c| c.generation.as_ref())
- .or(self.commit_generation.as_ref())
- .cloned()
- .unwrap_or_default();
-
- // Get project override (also checks both locations)
- let project_config = project.and_then(|p| self.projects.get(p)).and_then(|c| {
- c.overrides
+ self.merged_project_config(
+ project,
+ self.configs
.commit
.as_ref()
- .and_then(|cc| cc.generation.as_ref())
- .or(c.commit_generation.as_ref())
- });
-
- match project_config {
- Some(pc) => global.merge_with(pc),
- None => global,
- }
+ .and_then(|commit| commit.generation.as_ref()),
+ |config| {
+ config
+ .overrides
+ .commit
+ .as_ref()
+ .and_then(|commit| commit.generation.as_ref())
+ },
+ )
+ .unwrap_or_default()
}
/// Returns the list config for a specific project.
@@ -86,10 +94,9 @@ impl UserConfig {
/// Merges project-specific settings with global settings, where project
/// settings take precedence for fields that are set.
pub fn list(&self, project: Option<&str>) -> Option<ListConfig> {
- let project_config = project
- .and_then(|p| self.projects.get(p))
- .and_then(|c| c.overrides.list.as_ref());
- merge_optional(self.configs.list.as_ref(), project_config)
+ self.merged_project_config(project, self.configs.list.as_ref(), |config| {
+ config.overrides.list.as_ref()
+ })
}
/// Returns the commit config for a specific project.
@@ -97,10 +104,9 @@ impl UserConfig {
/// Merges project-specific settings with global settings, where project
/// settings take precedence for fields that are set.
pub fn commit(&self, project: Option<&str>) -> Option<CommitConfig> {
- let project_config = project
- .and_then(|p| self.projects.get(p))
- .and_then(|c| c.overrides.commit.as_ref());
- merge_optional(self.configs.commit.as_ref(), project_config)
+ self.merged_project_config(project, self.configs.commit.as_ref(), |config| {
+ config.overrides.commit.as_ref()
+ })
}
/// Returns the merge config for a specific project.
@@ -108,10 +114,9 @@ impl UserConfig {
/// Merges project-specific settings with global settings, where project
/// settings take precedence for fields that are set.
pub fn merge(&self, project: Option<&str>) -> Option<MergeConfig> {
- let project_config = project
- .and_then(|p| self.projects.get(p))
- .and_then(|c| c.overrides.merge.as_ref());
- merge_optional(self.configs.merge.as_ref(), project_config)
+ self.merged_project_config(project, self.configs.merge.as_ref(), |config| {
+ config.overrides.merge.as_ref()
+ })
}
/// Returns the switch config for a specific project.
@@ -119,18 +124,16 @@ impl UserConfig {
/// Merges project-specific settings with global settings, where project
/// settings take precedence for fields that are set.
pub fn switch(&self, project: Option<&str>) -> Option<SwitchConfig> {
- let project_config = project
- .and_then(|p| self.projects.get(p))
- .and_then(|c| c.overrides.switch.as_ref());
- merge_optional(self.configs.switch.as_ref(), project_config)
+ self.merged_project_config(project, self.configs.switch.as_ref(), |config| {
+ config.overrides.switch.as_ref()
+ })
}
/// Returns the `wt step` config for a specific project.
pub fn step(&self, project: Option<&str>) -> Option<StepConfig> {
- let project_config = project
- .and_then(|p| self.projects.get(p))
- .and_then(|c| c.overrides.step.as_ref());
- merge_optional(self.configs.step.as_ref(), project_config)
+ self.merged_project_config(project, self.configs.step.as_ref(), |config| {
+ config.overrides.step.as_ref()
+ })
}
/// Returns the `wt step copy-ignored` config for a specific project.
@@ -145,55 +148,36 @@ impl UserConfig {
/// Merges project-specific settings with global settings, where project
/// settings take precedence for fields that are set.
pub fn select(&self, project: Option<&str>) -> Option<SelectConfig> {
- let project_config = project
- .and_then(|p| self.projects.get(p))
- .and_then(|c| c.overrides.select.as_ref());
- merge_optional(self.configs.select.as_ref(), project_config)
+ self.merged_project_config(project, self.configs.select.as_ref(), |config| {
+ config.overrides.select.as_ref()
+ })
}
/// Returns the switch picker config for a specific project.
///
- /// Prefers `[switch.picker]` (new format), falls back to `[select]` (deprecated).
/// Merges project-specific settings with global settings, where project
- /// settings take precedence for fields that are set.
+ /// settings take precedence for fields that are set. Deprecated `[select]`
+ /// sections are normalized into `[switch.picker]` during config loading.
pub fn switch_picker(&self, project: Option<&str>) -> SwitchPickerConfig {
- // Get global config: prefer switch.picker, fall back to select
let global = self
.configs
.switch
.as_ref()
- .and_then(|s| s.picker.as_ref())
+ .and_then(|switch| switch.picker.as_ref())
.cloned()
- .unwrap_or_else(|| {
- self.configs
- .select
- .as_ref()
- .map(|sel| SwitchPickerConfig {
- pager: sel.pager.clone(),
- timeout_ms: None,
- })
- .unwrap_or_default()
- });
-
- // Get project override (also checks both locations)
- let project_config = project.and_then(|p| self.projects.get(p)).and_then(|c| {
- c.overrides
- .switch
- .as_ref()
- .and_then(|s| s.picker.as_ref())
- .cloned()
- .or_else(|| {
- c.overrides.select.as_ref().map(|sel| SwitchPickerConfig {
- pager: sel.pager.clone(),
- timeout_ms: None,
- })
- })
- });
+ .unwrap_or_default();
- match project_config {
- Some(pc) => global.merge_with(&pc),
- None => global,
- }
+ self.project_overrides(project)
+ .and_then(|config| {
+ config
+ .overrides
+ .switch
+ .as_ref()
+ .and_then(|switch| switch.picker.as_ref())
+ .cloned()
+ })
+ .map(|project_config| global.merge_with(&project_config))
+ .unwrap_or(global)
}
/// Returns effective hooks for a specific project.
@@ -202,9 +186,9 @@ impl UserConfig {
/// Both global and per-project hooks run (global first, then per-project).
pub fn hooks(&self, project: Option<&str>) -> HooksConfig {
let global = &self.configs.hooks;
- let project_hooks = project
- .and_then(|p| self.projects.get(p))
- .map(|c| &c.overrides.hooks);
+ let project_hooks = self
+ .project_overrides(project)
+ .map(|config| &config.overrides.hooks);
match project_hooks {
Some(ph) => global.merge_with(ph),
diff --git a/src/config/user/mod.rs b/src/config/user/mod.rs
index fe3105f01..84819a614 100644
--- a/src/config/user/mod.rs
+++ b/src/config/user/mod.rs
@@ -110,6 +110,64 @@ pub struct UserConfig {
}
impl UserConfig {
+ fn normalize_deprecated_sections(&mut self) {
+ Self::normalize_commit_generation_section(
+ &mut self.commit_generation,
+ &mut self.configs.commit,
+ );
+ Self::normalize_select_section(&mut self.configs.select, &mut self.configs.switch);
+
+ for project in self.projects.values_mut() {
+ Self::normalize_commit_generation_section(
+ &mut project.commit_generation,
+ &mut project.overrides.commit,
+ );
+ Self::normalize_select_section(
+ &mut project.overrides.select,
+ &mut project.overrides.switch,
+ );
+ }
+ }
+
+ fn normalize_commit_generation_section(
+ deprecated: &mut Option<CommitGenerationConfig>,
+ commit: &mut Option<CommitConfig>,
+ ) {
+ let Some(deprecated_config) = deprecated.take() else {
+ return;
+ };
+
+ if deprecated_config == CommitGenerationConfig::default() {
+ return;
+ }
+
+ let commit_config = commit.get_or_insert_with(CommitConfig::default);
+ if commit_config.generation.is_none() {
+ commit_config.generation = Some(deprecated_config);
+ }
+ }
+
+ fn normalize_select_section(
+ deprecated: &mut Option<SelectConfig>,
+ switch: &mut Option<SwitchConfig>,
+ ) {
+ let Some(select_config) = deprecated.take() else {
+ return;
+ };
+
+ if select_config == SelectConfig::default() {
+ return;
+ }
+
+ let switch_config = switch.get_or_insert_with(SwitchConfig::default);
+ if switch_config.picker.is_none() {
+ switch_config.picker = Some(SwitchPickerConfig {
+ pager: select_config.pager,
+ timeout_ms: None,
+ });
+ }
+ }
+
/// Load configuration from system config, user config, and environment variables.
///
/// Configuration is loaded in the following order (later sources override earlier ones):
@@ -206,7 +264,8 @@ impl UserConfig {
// The config crate's `preserve_order` feature ensures TOML insertion order
// is preserved (uses IndexMap instead of HashMap internally).
// See: https://github.com/max-sixty/worktrunk/issues/737
- let config: Self = builder.build()?.try_deserialize()?;
+ let mut config: Self = builder.build()?.try_deserialize()?;
+ config.normalize_deprecated_sections();
config.validate()?;
Ok(config)
@@ -215,8 +274,9 @@ impl UserConfig {
/// Load configuration from a TOML string for testing.
#[cfg(test)]
pub(crate) fn load_from_str(content: &str) -> Result<Self, ConfigError> {
- let config: Self =
+ let mut config: Self =
toml::from_str(content).map_err(|e| ConfigError::Message(e.to_string()))?;
+ config.normalize_deprecated_sections();
config.validate()?;
Ok(config)
}
diff --git a/src/config/user/mutation.rs b/src/config/user/mutation.rs
index c70798a4c..5b8a5029e 100644
--- a/src/config/user/mutation.rs
+++ b/src/config/user/mutation.rs
@@ -100,13 +100,14 @@ impl UserConfig {
))
})?;
- let disk_config: UserConfig = toml::from_str(&content).map_err(|e| {
+ let mut disk_config: UserConfig = toml::from_str(&content).map_err(|e| {
ConfigError::Message(format!(
"Failed to parse config file {}: {}",
format_path_for_display(&path),
e
))
})?;
+ disk_config.normalize_deprecated_sections();
// Replace in-memory projects with disk state (disk is authoritative)
self.projects = disk_config.projects;
diff --git a/src/config/user/persistence.rs b/src/config/user/persistence.rs
index db212544e..99c2703e7 100644
--- a/src/config/user/persistence.rs
+++ b/src/config/user/persistence.rs
@@ -11,6 +11,54 @@ use super::path;
use super::sections::CommitGenerationConfig;
impl UserConfig {
+ fn update_bool_flag(doc: &mut toml_edit::DocumentMut, key: &str, enabled: bool) {
+ if enabled {
+ doc[key] = toml_edit::value(true);
+ } else {
+ doc.remove(key);
+ }
+ }
+
+ fn sync_string_field(table: &mut toml_edit::Table, key: &str, new_value: Option<&String>) {
+ match new_value {
+ Some(v) => {
+ let current = table.get(key).and_then(|i| i.as_str());
+ if current != Some(v.as_str()) {
+ table[key] = toml_edit::value(v.as_str());
+ }
+ }
+ None => {
+ table.remove(key);
+ }
+ }
+ }
+
+ fn sync_serialized_section(
+ table: &mut toml_edit::Table,
+ section_name: &str,
+ config: Option<&impl Serialize>,
+ ) {
+ match Self::serialize_section_item(config) {
+ Some(item) => {
+ table[section_name] = item;
+ }
+ None => {
+ table.remove(section_name);
+ }
+ }
+ }
+
+ fn serialize_section_item(config: Option<&impl Serialize>) -> Option<toml_edit::Item> {
+ let cfg = config?;
+ let toml_value = toml::to_string(cfg).ok()?;
+ let parsed = toml_value.parse::<toml_edit::DocumentMut>().ok()?;
+ let mut table = toml_edit::Table::new();
+ for (k, v) in parsed.iter() {
+ table[k] = v.clone();
+ }
+ Some(toml_edit::Item::Table(table))
+ }
+
/// Save the current configuration to the default config file location
pub fn save(&self) -> Result<(), ConfigError> {
self.save_impl(None)
@@ -36,26 +84,6 @@ impl UserConfig {
/// Update the [commit.generation] section in the document.
fn update_commit_generation_section(&self, doc: &mut toml_edit::DocumentMut) {
- // Helper to update a string field only if changed, preserving comments
- fn update_string_field(
- table: &mut toml_edit::Table,
- key: &str,
- new_value: Option<&String>,
- ) {
- match new_value {
- Some(v) => {
- // Only update if value changed (preserves comments if unchanged)
- let current = table.get(key).and_then(|i| i.as_str());
- if current != Some(v.as_str()) {
- table[key] = toml_edit::value(v.as_str());
- }
- }
- None => {
- table.remove(key);
- }
- }
- }
-
if let Some(ref commit_cfg) = self.configs.commit
&& let Some(ref gen_cfg) = commit_cfg.generation
{
@@ -69,19 +97,18 @@ impl UserConfig {
commit_table["generation"] = toml_edit::Item::Table(toml_edit::Table::new());
}
if let Some(gen_table) = commit_table["generation"].as_table_mut() {
- update_string_field(gen_table, "command", gen_cfg.command.as_ref());
- update_string_field(gen_table, "template", gen_cfg.template.as_ref());
- update_string_field(gen_table, "template-file", gen_cfg.template_file.as_ref());
- update_string_field(
- gen_table,
- "squash-template",
- gen_cfg.squash_template.as_ref(),
- );
- update_string_field(
- gen_table,
- "squash-template-file",
- gen_cfg.squash_template_file.as_ref(),
- );
+ for (key, value) in [
+ ("command", gen_cfg.command.as_ref()),
+ ("template", gen_cfg.template.as_ref()),
+ ("template-file", gen_cfg.template_file.as_ref()),
+ ("squash-template", gen_cfg.squash_template.as_ref()),
+ (
+ "squash-template-file",
+ gen_cfg.squash_template_file.as_ref(),
+ ),
+ ] {
+ Self::sync_string_field(gen_table, key, value);
+ }
}
}
}
@@ -111,47 +138,43 @@ impl UserConfig {
projects[project_id] = toml_edit::Item::Table(toml_edit::Table::new());
}
- // worktree-path (only if set)
- if let Some(ref path) = project_config.overrides.worktree_path {
- projects[project_id]["worktree-path"] = toml_edit::value(path);
- } else if let Some(table) = projects[project_id].as_table_mut() {
- table.remove("worktree-path");
- }
+ let Some(project_table) = projects[project_id].as_table_mut() else {
+ continue;
+ };
+
+ Self::sync_string_field(
+ project_table,
+ "worktree-path",
+ project_config.overrides.worktree_path.as_ref(),
+ );
- // Per-project nested config sections
- Self::serialize_project_config_section(
- projects,
- project_id,
+ Self::sync_serialized_section(
+ project_table,
"commit-generation",
project_config.commit_generation.as_ref(),
);
- Self::serialize_project_config_section(
- projects,
- project_id,
+ Self::sync_serialized_section(
+ project_table,
"list",
project_config.overrides.list.as_ref(),
);
- Self::serialize_project_config_section(
- projects,
- project_id,
+ Self::sync_serialized_section(
+ project_table,
"commit",
project_config.overrides.commit.as_ref(),
);
- Self::serialize_project_config_section(
- projects,
- project_id,
+ Self::sync_serialized_section(
+ project_table,
"merge",
project_config.overrides.merge.as_ref(),
);
- Self::serialize_project_config_section(
- projects,
- project_id,
+ Self::sync_serialized_section(
+ project_table,
"switch",
project_config.overrides.switch.as_ref(),
);
- Self::serialize_project_config_section(
- projects,
- project_id,
+ Self::sync_serialized_section(
+ project_table,
"select",
project_config.overrides.select.as_ref(),
);
@@ -159,32 +182,6 @@ impl UserConfig {
}
}
- /// Serialize a per-project config section (commit-generation, list, commit, merge).
- ///
- /// If the config is Some, serializes it as a nested table. If None, removes the section.
- /// Used when updating an existing file.
- fn serialize_project_config_section<T: Serialize>(
- projects: &mut toml_edit::Table,
- project_id: &str,
- section_name: &str,
- config: Option<&T>,
- ) {
- if let Some(cfg) = config {
- // Serialize to TOML value, then convert to toml_edit Item
- if let Ok(toml_value) = toml::to_string(cfg)
- && let Ok(parsed) = toml_value.parse::<toml_edit::DocumentMut>()
- {
- let mut table = toml_edit::Table::new();
- for (k, v) in parsed.iter() {
- table[k] = v.clone();
- }
- projects[project_id][section_name] = toml_edit::Item::Table(table);
- }
- } else if let Some(project_table) = projects[project_id].as_table_mut() {
- project_table.remove(section_name);
- }
- }
-
/// Recursively convert inline tables to standard tables for readability.
///
/// When using `toml_edit::ser::to_document()`, nested structs are serialized as inline tables
@@ -243,17 +240,16 @@ impl UserConfig {
// Update all programmatically-modifiable sections
// NOTE: If you add a new setter that modifies config, add the update here too!
- if self.skip_shell_integration_prompt {
- doc["skip-shell-integration-prompt"] = toml_edit::value(true);
- } else {
- doc.remove("skip-shell-integration-prompt");
- }
-
- if self.skip_commit_generation_prompt {
- doc["skip-commit-generation-prompt"] = toml_edit::value(true);
- } else {
- doc.remove("skip-commit-generation-prompt");
- }
+ Self::update_bool_flag(
+ &mut doc,
+ "skip-shell-integration-prompt",
+ self.skip_shell_integration_prompt,
+ );
+ Self::update_bool_flag(
+ &mut doc,
+ "skip-commit-generation-prompt",
+ self.skip_commit_generation_prompt,
+ );
self.update_commit_generation_section(&mut doc);
self.update_projects_section(&mut doc);
@@ -309,12 +305,6 @@ impl UserConfig {
)));
}
- // Validate commit generation config (check both old and new locations)
- // Old: [projects."...".commit-generation] (deprecated)
- if let Some(ref cg) = project_config.commit_generation {
- Self::validate_commit_generation(cg, &format!("projects.{project}"))?;
- }
- // New: [projects."...".commit.generation]
if let Some(ref commit) = project_config.overrides.commit
&& let Some(ref cg) = commit.generation
{
@@ -322,18 +312,20 @@ impl UserConfig {
}
}
- // Validate commit generation config (check both old and new locations)
- let commit_gen = self.commit_generation(None);
- if commit_gen.template.is_some() && commit_gen.template_file.is_some() {
- return Err(ConfigError::Message(
- "commit.generation.template and commit.generation.template-file are mutually exclusive".into(),
- ));
- }
+ if let Some(ref commit) = self.configs.commit
+ && let Some(ref cg) = commit.generation
+ {
+ if cg.template.is_some() && cg.template_file.is_some() {
+ return Err(ConfigError::Message(
+ "commit.generation.template and commit.generation.template-file are mutually exclusive".into(),
+ ));
+ }
- if commit_gen.squash_template.is_some() && commit_gen.squash_template_file.is_some() {
- return Err(ConfigError::Message(
- "commit.generation.squash-template and commit.generation.squash-template-file are mutually exclusive".into(),
- ));
+ if cg.squash_template.is_some() && cg.squash_template_file.is_some() {
+ return Err(ConfigError::Message(
+ "commit.generation.squash-template and commit.generation.squash-template-file are mutually exclusive".into(),
+ ));
+ }
}
Ok(())
diff --git a/src/config/user/resolved.rs b/src/config/user/resolved.rs
index 81cc7026a..388838a62 100644
--- a/src/config/user/resolved.rs
+++ b/src/config/user/resolved.rs
@@ -30,9 +30,9 @@ pub struct ResolvedConfig {
pub list: ListConfig,
pub merge: MergeConfig,
pub commit: CommitConfig,
- /// Resolved commit generation config (handles deprecated `[commit-generation]` fallback)
+ /// Resolved commit generation config
pub commit_generation: CommitGenerationConfig,
- /// Resolved switch picker config (handles deprecated `[select]` fallback)
+ /// Resolved switch picker config
pub switch_picker: SwitchPickerConfig,
/// Resolved switch config
pub switch: SwitchConfig,
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index 1c9d076f0..b57e01299 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -1280,19 +1280,26 @@ no-cd = true
#[test]
fn test_switch_picker_fallback_from_select() {
- // When only [select] is configured, switch_picker() should use its pager
- let config = UserConfig {
- configs: OverridableConfig {
- select: Some(SelectConfig {
- pager: Some("bat".to_string()),
- }),
- ..Default::default()
- },
- ..Default::default()
- };
+ let config = UserConfig::load_from_str(
+ r#"
+[select]
+pager = "bat"
+"#,
+ )
+ .unwrap();
let picker = config.switch_picker(None);
assert_eq!(picker.pager.as_deref(), Some("bat"));
+ assert!(config.configs.select.is_none());
+ assert_eq!(
+ config
+ .configs
+ .switch
+ .as_ref()
+ .and_then(|switch| switch.picker.as_ref())
+ .and_then(|picker| picker.pager.as_deref()),
+ Some("bat")
+ );
// timeout_ms not available from select, so default applies
assert_eq!(picker.timeout_ms, None);
assert_eq!(
@@ -1303,29 +1310,22 @@ fn test_switch_picker_fallback_from_select() {
#[test]
fn test_switch_picker_prefers_new_over_select() {
- use crate::config::user::{SwitchConfig, SwitchPickerConfig};
+ let config = UserConfig::load_from_str(
+ r#"
+[switch.picker]
+pager = "delta"
+timeout-ms = 100
- // When both [switch.picker] and [select] are configured, switch.picker wins
- let config = UserConfig {
- configs: OverridableConfig {
- switch: Some(SwitchConfig {
- picker: Some(SwitchPickerConfig {
- pager: Some("delta".to_string()),
- timeout_ms: Some(100),
- }),
- ..Default::default()
- }),
- select: Some(SelectConfig {
- pager: Some("bat".to_string()),
- }),
- ..Default::default()
- },
- ..Default::default()
- };
+[select]
+pager = "bat"
+"#,
+ )
+ .unwrap();
let picker = config.switch_picker(None);
assert_eq!(picker.pager.as_deref(), Some("delta"));
assert_eq!(picker.timeout_ms, Some(100));
+ assert!(config.configs.select.is_none());
}
#[test]
@@ -1370,40 +1370,30 @@ fn test_switch_picker_project_override() {
#[test]
fn test_switch_picker_project_fallback_from_select() {
- // Project has [select], global has [switch.picker]
- // Project's select pager should be used
- use crate::config::user::{SwitchConfig, SwitchPickerConfig};
-
- let mut config = UserConfig {
- configs: OverridableConfig {
- switch: Some(SwitchConfig {
- picker: Some(SwitchPickerConfig {
- pager: Some("delta".to_string()),
- timeout_ms: Some(300),
- }),
- ..Default::default()
- }),
- ..Default::default()
- },
- ..Default::default()
- };
+ let config = UserConfig::load_from_str(
+ r#"
+[switch.picker]
+pager = "delta"
+timeout-ms = 300
- config.projects.insert(
- "github.com/user/repo".to_string(),
- UserProjectOverrides {
- overrides: OverridableConfig {
- select: Some(SelectConfig {
- pager: Some("bat".to_string()),
- }),
- ..Default::default()
- },
- ..Default::default()
- },
- );
+[projects."github.com/user/repo".select]
+pager = "bat"
+"#,
+ )
+ .unwrap();
let picker = config.switch_picker(Some("github.com/user/repo"));
- assert_eq!(picker.pager.as_deref(), Some("bat")); // Project select fallback
- assert_eq!(picker.timeout_ms, Some(300)); // From global (select has no timeout)
+ assert_eq!(picker.pager.as_deref(), Some("bat"));
+ assert_eq!(picker.timeout_ms, Some(300));
+ assert!(
+ config
+ .projects
+ .get("github.com/user/repo")
+ .unwrap()
+ .overrides
+ .select
+ .is_none()
+ );
}
#[test]
@@ -1623,7 +1613,7 @@ exclude = [".repo-local/", ".entire/"]
#[test]
fn test_deprecated_commit_generation_format_serde() {
- // Test old format: [commit-generation] is still parsed for backward compatibility
+ // Raw serde still accepts the old shape for backward compatibility.
let content = r#"
[commit-generation]
command = "llm -m claude-haiku-4.5"
@@ -1646,8 +1636,43 @@ command = "claude -p --model opus"
project.commit_generation.as_ref().unwrap().command,
Some("claude -p --model opus".to_string())
);
+}
+
+#[test]
+fn test_load_normalizes_deprecated_commit_generation_sections() {
+ let content = r#"
+[commit-generation]
+command = "llm -m claude-haiku-4.5"
+
+[projects."github.com/user/repo".commit-generation]
+command = "claude -p --model opus"
+"#;
+
+ let config = UserConfig::load_from_str(content).unwrap();
+
+ assert!(config.commit_generation.is_none());
+ assert_eq!(
+ config
+ .configs
+ .commit
+ .as_ref()
+ .and_then(|commit| commit.generation.as_ref())
+ .and_then(|generation| generation.command.as_deref()),
+ Some("llm -m claude-haiku-4.5")
+ );
+
+ let project = config.projects.get("github.com/user/repo").unwrap();
+ assert!(project.commit_generation.is_none());
+ assert_eq!(
+ project
+ .overrides
+ .commit
+ .as_ref()
+ .and_then(|commit| commit.generation.as_ref())
+ .and_then(|generation| generation.command.as_deref()),
+ Some("claude -p --model opus")
+ );
- // Effective config uses the deprecated values
let effective_cg = config.commit_generation(Some("github.com/user/repo"));
assert_eq!(
effective_cg.command,
diff --git a/src/git/remote_ref/github.rs b/src/git/remote_ref/github.rs
index 83e108313..17aa8f987 100644
--- a/src/git/remote_ref/github.rs
+++ b/src/git/remote_ref/github.rs
@@ -2,15 +2,14 @@
//!
//! Implements `RemoteRefProvider` for GitHub Pull Requests using the `gh` CLI.
-use std::io::ErrorKind;
-
use anyhow::{Context, bail};
use serde::Deserialize;
-use super::{PlatformData, RemoteRefInfo, RemoteRefProvider};
-use crate::git::error::GitError;
+use super::{
+ CliApiRequest, PlatformData, RemoteRefInfo, RemoteRefProvider, cli_api_error, cli_config_value,
+ run_cli_api,
+};
use crate::git::{self, RefType, Repository};
-use crate::shell_exec::Cmd;
/// GitHub Pull Request provider.
#[derive(Debug, Clone, Copy)]
@@ -92,21 +91,15 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefI
.unwrap_or_else(|| "github.com".to_string());
let api_path = format!("repos/{{owner}}/{{repo}}/pulls/{}", pr_number);
-
- let output = match Cmd::new("gh")
- .args(["api", &api_path, "--hostname", &hostname])
- .current_dir(repo_root)
- .env("GH_PROMPT_DISABLED", "1")
- .run()
- {
- Ok(output) => output,
- Err(e) => {
- if e.kind() == ErrorKind::NotFound {
- bail!("GitHub CLI (gh) not installed; install from https://cli.github.com/");
- }
- return Err(anyhow::Error::from(e).context("Failed to run gh api"));
- }
- };
+ let args = ["api", api_path.as_str(), "--hostname", hostname.as_str()];
+ let output = run_cli_api(CliApiRequest {
+ tool: "gh",
+ args: &args,
+ repo_root,
+ prompt_env: ("GH_PROMPT_DISABLED", "1"),
+ install_hint: "GitHub CLI (gh) not installed; install from https://cli.github.com/",
+ run_context: "Failed to run gh api",
+ })?;
if !output.status.success() {
if let Ok(error_response) = serde_json::from_slice::<GhApiErrorResponse>(&output.stdout) {
@@ -124,18 +117,11 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefI
}
}
- let stderr = String::from_utf8_lossy(&output.stderr);
- let details = if stderr.trim().is_empty() {
- String::from_utf8_lossy(&output.stdout).trim().to_string()
- } else {
- stderr.trim().to_string()
- };
- return Err(GitError::CliApiError {
- ref_type: RefType::Pr,
- message: format!("gh api failed for PR #{}", pr_number),
- stderr: details,
- }
- .into());
+ return Err(cli_api_error(
+ RefType::Pr,
+ format!("gh api failed for PR #{}", pr_number),
+ &output,
+ ));
}
let response: GhApiPrResponse = serde_json::from_slice(&output.stdout).with_context(|| {
@@ -215,13 +201,7 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefI
/// Get the git protocol preference from `gh` (GitHub CLI).
fn use_ssh_protocol() -> bool {
- Cmd::new("gh")
- .args(["config", "get", "git_protocol"])
- .run()
- .ok()
- .filter(|output| output.status.success())
- .map(|output| String::from_utf8_lossy(&output.stdout).trim() == "ssh")
- .unwrap_or(false)
+ cli_config_value("gh", "git_protocol").as_deref() == Some("ssh")
}
/// Construct the remote URL for a fork repository.
diff --git a/src/git/remote_ref/gitlab.rs b/src/git/remote_ref/gitlab.rs
index 022a4f7bc..ff12cbcb0 100644
--- a/src/git/remote_ref/gitlab.rs
+++ b/src/git/remote_ref/gitlab.rs
@@ -21,16 +21,16 @@
//!
//! This saves ~1 second for the common case (switching to an existing MR branch).
-use std::io::ErrorKind;
use std::path::Path;
use anyhow::{Context, bail};
use serde::Deserialize;
-use super::{PlatformData, RemoteRefInfo, RemoteRefProvider};
-use crate::git::error::GitError;
+use super::{
+ CliApiRequest, PlatformData, RemoteRefInfo, RemoteRefProvider, cli_api_error, cli_config_value,
+ run_cli_api,
+};
use crate::git::{RefType, Repository};
-use crate::shell_exec::Cmd;
/// GitLab Merge Request provider.
#[derive(Debug, Clone, Copy)]
@@ -88,23 +88,15 @@ struct GlabApiErrorResponse {
/// Fetch MR information from GitLab using the `glab` CLI.
fn fetch_mr_info(mr_number: u32, repo_root: &Path) -> anyhow::Result<RemoteRefInfo> {
let api_path = format!("projects/:id/merge_requests/{}", mr_number);
-
- let output = match Cmd::new("glab")
- .args(["api", &api_path])
- .current_dir(repo_root)
- .env("GLAB_NO_PROMPT", "1")
- .run()
- {
- Ok(output) => output,
- Err(e) => {
- if e.kind() == ErrorKind::NotFound {
- bail!(
- "GitLab CLI (glab) not installed; install from https://gitlab.com/gitlab-org/cli#installation"
- );
- }
- return Err(anyhow::Error::from(e).context("Failed to run glab api"));
- }
- };
+ let args = ["api", api_path.as_str()];
+ let output = run_cli_api(CliApiRequest {
+ tool: "glab",
+ args: &args,
+ repo_root,
+ prompt_env: ("GLAB_NO_PROMPT", "1"),
+ install_hint: "GitLab CLI (glab) not installed; install from https://gitlab.com/gitlab-org/cli#installation",
+ run_context: "Failed to run glab api",
+ })?;
if !output.status.success() {
if let Ok(error_response) = serde_json::from_slice::<GlabApiErrorResponse>(&output.stdout) {
@@ -125,18 +117,11 @@ fn fetch_mr_info(mr_number: u32, repo_root: &Path) -> anyhow::Result<RemoteRefIn
}
}
- let stderr = String::from_utf8_lossy(&output.stderr);
- let details = if stderr.trim().is_empty() {
- String::from_utf8_lossy(&output.stdout).trim().to_string()
- } else {
- stderr.trim().to_string()
- };
- return Err(GitError::CliApiError {
- ref_type: RefType::Mr,
- message: format!("glab api failed for MR !{}", mr_number),
- stderr: details,
- }
- .into());
+ return Err(cli_api_error(
+ RefType::Mr,
+ format!("glab api failed for MR !{}", mr_number),
+ &output,
+ ));
}
let response: GlabMrResponse = serde_json::from_slice(&output.stdout).with_context(|| {
@@ -263,12 +248,15 @@ fn fetch_project_urls(
repo_root: &Path,
) -> anyhow::Result<(Option<String>, Option<String>)> {
let api_path = format!("projects/{}", project_id);
-
- let output = Cmd::new("glab")
- .args(["api", &api_path])
- .current_dir(repo_root)
- .env("GLAB_NO_PROMPT", "1")
- .run()?;
+ let args = ["api", api_path.as_str()];
+ let output = run_cli_api(CliApiRequest {
+ tool: "glab",
+ args: &args,
+ repo_root,
+ prompt_env: ("GLAB_NO_PROMPT", "1"),
+ install_hint: "GitLab CLI (glab) not installed; install from https://gitlab.com/gitlab-org/cli#installation",
+ run_context: "Failed to run glab api",
+ })?;
if !output.status.success() {
bail!("Failed to fetch project {}", project_id);
@@ -280,12 +268,7 @@ fn fetch_project_urls(
/// Get the git protocol configured in `glab` (GitLab CLI).
pub fn git_protocol() -> String {
- Cmd::new("glab")
- .args(["config", "get", "git_protocol"])
- .run()
- .ok()
- .filter(|output| output.status.success())
- .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
+ cli_config_value("glab", "git_protocol")
.filter(|p| p == "ssh" || p == "https")
.unwrap_or_else(|| "https".to_string())
}
diff --git a/src/git/remote_ref/mod.rs b/src/git/remote_ref/mod.rs
index 43989eaf3..b5d2f5a3f 100644
--- a/src/git/remote_ref/mod.rs
+++ b/src/git/remote_ref/mod.rs
@@ -38,9 +38,15 @@ pub use github::GitHubProvider;
pub use gitlab::GitLabProvider;
pub use info::{PlatformData, RemoteRefInfo};
+use std::io::ErrorKind;
use std::path::Path;
+use std::process::Output;
+use anyhow::bail;
+
+use crate::git::error::GitError;
use crate::git::{RefType, Repository};
+use crate::shell_exec::Cmd;
/// Provider trait for platform-specific PR/MR operations.
///
@@ -69,6 +75,59 @@ pub trait RemoteRefProvider {
}
}
+pub(super) struct CliApiRequest<'a> {
+ pub tool: &'a str,
+ pub args: &'a [&'a str],
+ pub repo_root: &'a Path,
+ pub prompt_env: (&'a str, &'a str),
+ pub install_hint: &'a str,
+ pub run_context: &'a str,
+}
+
+pub(super) fn run_cli_api(request: CliApiRequest<'_>) -> anyhow::Result<Output> {
+ match Cmd::new(request.tool)
+ .args(request.args.iter().copied())
+ .current_dir(request.repo_root)
+ .env(request.prompt_env.0, request.prompt_env.1)
+ .run()
+ {
+ Ok(output) => Ok(output),
+ Err(error) => {
+ if error.kind() == ErrorKind::NotFound {
+ bail!("{}", request.install_hint);
+ }
+ Err(anyhow::Error::from(error).context(request.run_context.to_string()))
+ }
+ }
+}
+
+pub(super) fn cli_api_error_details(output: &Output) -> String {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ if stderr.trim().is_empty() {
+ String::from_utf8_lossy(&output.stdout).trim().to_string()
+ } else {
+ stderr.trim().to_string()
+ }
+}
+
+pub(super) fn cli_api_error(ref_type: RefType, message: String, output: &Output) -> anyhow::Error {
+ GitError::CliApiError {
+ ref_type,
+ message,
+ stderr: cli_api_error_details(output),
+ }
+ .into()
+}
+
+pub(super) fn cli_config_value(tool: &str, key: &str) -> Option<String> {
+ Cmd::new(tool)
+ .args(["config", "get", key])
+ .run()
+ .ok()
+ .filter(|output| output.status.success())
+ .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
+}
+
/// Check if a local branch is tracking a specific remote ref.
///
/// Returns `Some(true)` if the branch is configured to track the given ref.
diff --git a/src/main.rs b/src/main.rs
index 7efd3eb89..3d4eff87b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -793,7 +793,7 @@ fn handle_remove_command(spec: RemoveCommandArgs) -> anyhow::Result<()> {
})
}
-fn main() {
+fn init_rayon_thread_pool() {
// Configure Rayon's global thread pool for mixed I/O workloads.
// The `wt list` command runs git operations (CPU + disk I/O) and network
// requests (CI status, URL health checks) in parallel. Using 2x CPU cores
@@ -810,17 +810,16 @@ fn main() {
let _ = rayon::ThreadPoolBuilder::new()
.num_threads(num_threads)
.build_global();
+}
- // Tell crossterm to always emit ANSI sequences
- crossterm::style::force_color_output(true);
-
+fn parse_cli() -> Option<Cli> {
if completion::maybe_handle_env_completion() {
- return;
+ return None;
}
// Handle --help with pager before clap processes it
if help::maybe_handle_help_with_pager() {
- return;
+ return None;
}
// TODO: Enhance error messages to show possible values for missing enum arguments
@@ -832,40 +831,60 @@ fn main() {
let matches = cmd.try_get_matches().unwrap_or_else(|e| {
enhance_and_exit_error(e);
});
- let cli = Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit());
+ Some(Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit()))
+}
+fn apply_global_options(directory: Option<std::path::PathBuf>, config: Option<std::path::PathBuf>) {
// Initialize base path from -C flag if provided
- if let Some(path) = cli.directory {
+ if let Some(path) = directory {
set_base_path(path);
}
// Initialize config path from --config flag if provided
- if let Some(path) = cli.config {
+ if let Some(path) = config {
set_config_path(path);
}
+}
- // Configure logging based on --verbose flag or RUST_LOG env var
- // When -vv is set, also write logs to .git/wt/logs/verbose.log
- if cli.verbose >= 2 {
- verbose_log::init();
- }
-
- // Capture verbose level and command line before cli is partially consumed
- let verbose_level = cli.verbose;
- let command_line = std::env::args().collect::<Vec<_>>().join(" ");
-
+fn init_command_log(command_line: &str) {
// Initialize command log for always-on logging of hooks and LLM commands.
// Directory and file are created lazily on first log_command() call.
if let Ok(repo) = worktrunk::git::Repository::current() {
- worktrunk::command_log::init(&repo.wt_logs_dir(), &command_line);
+ worktrunk::command_log::init(&repo.wt_logs_dir(), command_line);
+ }
+}
+
+fn thread_label() -> char {
+ let thread_id = format!("{:?}", std::thread::current().id());
+ thread_id
+ .strip_prefix("ThreadId(")
+ .and_then(|s| s.strip_suffix(")"))
+ .and_then(|s| s.parse::<usize>().ok())
+ .map(|n| {
+ if n == 0 {
+ '0'
+ } else if n <= 26 {
+ char::from(b'a' + (n - 1) as u8)
+ } else if n <= 52 {
+ char::from(b'A' + (n - 27) as u8)
+ } else {
+ '?'
+ }
+ })
+ .unwrap_or('?')
+}
+
+fn init_logging(verbose_level: u8) {
+ // Configure logging based on --verbose flag or RUST_LOG env var
+ // When -vv is set, also write logs to .git/wt/logs/verbose.log
+ if verbose_level >= 2 {
+ verbose_log::init();
}
// Set global verbosity level for styled verbose output
output::set_verbosity(verbose_level);
- // -vv enables debug logging via env_logger; -v uses styled output (not logging)
- // Otherwise, respect RUST_LOG (defaulting to off)
- let mut builder = if cli.verbose >= 2 {
+ let mut builder = if verbose_level >= 2 {
let mut b = env_logger::Builder::new();
b.filter_level(log::LevelFilter::Debug);
b
@@ -876,25 +895,7 @@ fn main() {
builder
.format(|buf, record| {
let msg = record.args().to_string();
-
- // Map thread ID to a single character (a-z, then A-Z)
- let thread_id = format!("{:?}", std::thread::current().id());
- let thread_num = thread_id
- .strip_prefix("ThreadId(")
- .and_then(|s| s.strip_suffix(")"))
- .and_then(|s| s.parse::<usize>().ok())
- .map(|n| {
- if n == 0 {
- '0'
- } else if n <= 26 {
- char::from(b'a' + (n - 1) as u8)
- } else if n <= 52 {
- char::from(b'A' + (n - 27) as u8)
- } else {
- '?'
- }
- })
- .unwrap_or('?');
+ let thread_num = thread_label();
// Write plain text to log file (no ANSI codes)
verbose_log::write_line(&format!("[{thread_num}] {msg}"));
@@ -926,16 +927,10 @@ fn main() {
}
})
.init();
+}
- let Some(command) = cli.command else {
- // No subcommand provided - print help to stderr (stdout is eval'd by shell wrapper)
- let mut cmd = cli::build_command();
- let help = cmd.render_help().ansi().to_string();
- eprintln!("{help}");
- return;
- };
-
- let result = match command {
+fn dispatch_command(command: Commands) -> anyhow::Result<()> {
+ match command {
Commands::Config { action } => handle_config_command(action),
Commands::Step { action } => handle_step_command(action),
Commands::Hook { action } => handle_hook_command(action),
@@ -1028,80 +1023,116 @@ fn main() {
yes,
stage,
}),
- };
+ }
+}
- if let Err(e) = result {
- // GitError, WorktrunkError, and HookErrorWithHint produce styled output via Display.
- // Some variants (AlreadyDisplayed, CommandNotApproved) have empty Display impls —
- // skip eprintln! for those to avoid phantom blank lines.
- if let Some(err) = e.downcast_ref::<worktrunk::git::GitError>() {
- eprintln!("{}", err);
- } else if let Some(err) = e.downcast_ref::<worktrunk::git::WorktrunkError>() {
- let display = err.to_string();
- if !display.is_empty() {
- eprintln!("{display}");
- }
- } else if let Some(err) = e.downcast_ref::<worktrunk::git::HookErrorWithHint>() {
- eprintln!("{}", err);
- } else if let Some(err) = e.downcast_ref::<worktrunk::config::TemplateExpandError>() {
- eprintln!("{}", err);
- } else {
- // Anyhow error formatting:
- // - With context: show context as header, root cause in gutter
- // - Simple error: inline with emoji
- // - Empty error: skip (errors already printed elsewhere)
- let msg = e.to_string();
- if !msg.is_empty() {
- // Collect the error chain (skipping the first which is in msg)
- let chain: Vec<String> = e.chain().skip(1).map(|e| e.to_string()).collect();
- if !chain.is_empty() {
- // Has context: msg is context, chain contains intermediate + root cause
- eprintln!("{}", error_message(&msg));
- let chain_text = chain.join("\n");
- eprintln!("{}", format_with_gutter(&chain_text, None));
- } else if msg.contains('\n') || msg.contains('\r') {
- // Multiline error without context - this shouldn't happen if all
- // errors have proper context. Catch in debug builds, log in release.
- debug_assert!(false, "Multiline error without context: {msg}");
- log::warn!("Multiline error without context: {msg}");
- // Normalize line endings for display
- let normalized = msg.replace("\r\n", "\n").replace('\r', "\n");
- eprintln!("{}", error_message("Command failed"));
- eprintln!("{}", format_with_gutter(&normalized, None));
- } else {
- // Single-line error without context: inline with emoji
- eprintln!("{}", error_message(&msg));
- }
- }
+fn print_command_error(error: &anyhow::Error) {
+ // GitError, WorktrunkError, and HookErrorWithHint produce styled output via Display.
+ // Some variants (AlreadyDisplayed, CommandNotApproved) have empty Display impls —
+ // skip eprintln! for those to avoid phantom blank lines.
+ if let Some(err) = error.downcast_ref::<worktrunk::git::GitError>() {
+ eprintln!("{}", err);
+ } else if let Some(err) = error.downcast_ref::<worktrunk::git::WorktrunkError>() {
+ let display = err.to_string();
+ if !display.is_empty() {
+ eprintln!("{display}");
}
-
- // If the CWD has been deleted, hint the user about recovery options.
- // Check both: (1) explicit flag set by merge/remove when it knows the CWD
- // worktree was removed (reliable on all platforms), and (2) OS-level detection
- // for cases not covered by the flag (e.g., external worktree removal).
- let cwd_gone = output::was_cwd_removed() || std::env::current_dir().is_err();
- if cwd_gone {
- if let Some(hint) = cwd_removed_hint() {
- eprintln!("{}", hint_message(hint));
+ } else if let Some(err) = error.downcast_ref::<worktrunk::git::HookErrorWithHint>() {
+ eprintln!("{}", err);
+ } else if let Some(err) = error.downcast_ref::<worktrunk::config::TemplateExpandError>() {
+ eprintln!("{}", err);
+ } else {
+ // Anyhow error formatting:
+ // - With context: show context as header, root cause in gutter
+ // - Simple error: inline with emoji
+ // - Empty error: skip (errors already printed elsewhere)
+ let msg = error.to_string();
+ if !msg.is_empty() {
+ let chain: Vec<String> = error.chain().skip(1).map(|e| e.to_string()).collect();
+ if !chain.is_empty() {
+ eprintln!("{}", error_message(&msg));
+ let chain_text = chain.join("\n");
+ eprintln!("{}", format_with_gutter(&chain_text, None));
+ } else if msg.contains('\n') || msg.contains('\r') {
+ debug_assert!(false, "Multiline error without context: {msg}");
+ log::warn!("Multiline error without context: {msg}");
+ let normalized = msg.replace("\r\n", "\n").replace('\r', "\n");
+ eprintln!("{}", error_message("Command failed"));
+ eprintln!("{}", format_with_gutter(&normalized, None));
} else {
- eprintln!("{}", info_message("Current directory was removed"));
+ eprintln!("{}", error_message(&msg));
}
}
+ }
+}
+
+fn print_cwd_removed_hint_if_needed() {
+ // If the CWD has been deleted, hint the user about recovery options.
+ // Check both: (1) explicit flag set by merge/remove when it knows the CWD
+ // worktree was removed (reliable on all platforms), and (2) OS-level detection
+ // for cases not covered by the flag (e.g., external worktree removal).
+ let cwd_gone = output::was_cwd_removed() || std::env::current_dir().is_err();
+ if cwd_gone {
+ if let Some(hint) = cwd_removed_hint() {
+ eprintln!("{}", hint_message(hint));
+ } else {
+ eprintln!("{}", info_message("Current directory was removed"));
+ }
+ }
+}
- // Preserve exit code from child processes (especially for signals like SIGINT)
- let code = exit_code(&e).unwrap_or(1);
+fn finish_command(verbose_level: u8, command_line: &str, error: Option<&anyhow::Error>) {
+ let error_text = error.map(|err| err.to_string());
+ diagnostic::write_if_verbose(verbose_level, command_line, error_text.as_deref());
+ let _ = output::terminate_output();
+}
- // Write diagnostic if -vv was used (error case)
- diagnostic::write_if_verbose(verbose_level, &command_line, Some(&e.to_string()));
+fn handle_command_failure(error: anyhow::Error, verbose_level: u8, command_line: &str) -> ! {
+ print_command_error(&error);
+ print_cwd_removed_hint_if_needed();
- // Reset ANSI state before exiting
- let _ = output::terminate_output();
- process::exit(code);
- }
+ // Preserve exit code from child processes (especially for signals like SIGINT)
+ let code = exit_code(&error).unwrap_or(1);
+ finish_command(verbose_level, command_line, Some(&error));
+ process::exit(code);
+}
- // Write diagnostic if -vv was used (success case)
- diagnostic::write_if_verbose(verbose_level, &command_line, None);
+fn print_help_to_stderr() {
+ // No subcommand provided - print help to stderr (stdout is eval'd by shell wrapper)
+ let mut cmd = cli::build_command();
+ let help = cmd.render_help().ansi().to_string();
+ eprintln!("{help}");
+}
- // Reset ANSI state before returning to shell (success case)
- let _ = output::terminate_output();
+fn main() {
+ init_rayon_thread_pool();
+
+ // Tell crossterm to always emit ANSI sequences
+ crossterm::style::force_color_output(true);
+
+ let Some(cli) = parse_cli() else {
+ return;
+ };
+
+ let Cli {
+ directory,
+ config,
+ verbose,
+ command,
+ } = cli;
+ apply_global_options(directory, config);
+
+ let command_line = std::env::args().collect::<Vec<_>>().join(" ");
+ init_command_log(&command_line);
+ init_logging(verbose);
+
+ let Some(command) = command else {
+ print_help_to_stderr();
+ return;
+ };
+
+ match dispatch_command(command) {
+ Ok(()) => finish_command(verbose, &command_line, None),
+ Err(error) => handle_command_failure(error, verbose, &command_line),
+ }
}
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 660de8bcd..df274ca51 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -4,6 +4,7 @@ use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Stdio;
+use anstyle::AnsiColor;
use color_print::cformat;
use worktrunk::shell_exec::Cmd;
use worktrunk::styling::{eprint, format_bash_with_gutter, stderr};
@@ -212,42 +213,196 @@ fn format_path_mismatch_warning(
))
}
+struct SwitchOutputContext {
+ path: PathBuf,
+ path_display: String,
+ branch: String,
+ shell_warning_reason: Option<String>,
+ user_wont_be_in_worktree: bool,
+ branch_worktree_mismatch_warning: Option<FormattedMessage>,
+ is_git_subcommand: bool,
+}
+
+fn build_switch_output_context(
+ result: &SwitchResult,
+ branch_info: &SwitchBranchInfo,
+ change_dir: bool,
+) -> SwitchOutputContext {
+ let path = super::to_logical_path(result.path());
+ let path_display = format_path_for_display(&path);
+ let branch = branch_info
+ .branch
+ .clone()
+ .unwrap_or_else(|| "detached worktree".to_string());
+
+ let is_git_subcommand = crate::is_git_subcommand();
+ let is_shell_integration_active = super::is_shell_integration_active();
+ let shell_warning_reason = if !change_dir || is_shell_integration_active {
+ None
+ } else if is_git_subcommand {
+ Some("ran git wt; running through git prevents cd".to_string())
+ } else {
+ Some(compute_shell_warning_reason())
+ };
+ let user_wont_be_in_worktree = !change_dir || shell_warning_reason.is_some();
+ let branch_worktree_mismatch_warning = branch_info
+ .expected_path
+ .as_ref()
+ .map(|expected| format_path_mismatch_warning(&branch, &path, expected));
+
+ SwitchOutputContext {
+ path,
+ path_display,
+ branch,
+ shell_warning_reason,
+ user_wont_be_in_worktree,
+ branch_worktree_mismatch_warning,
+ is_git_subcommand,
+ }
+}
+
+fn print_switch_path_mismatch_warning(ctx: &SwitchOutputContext) {
+ if let Some(warning) = &ctx.branch_worktree_mismatch_warning {
+ eprintln!("{}", warning);
+ }
+}
+
+fn print_switch_directory_hint(branch: &str, is_git_subcommand: bool) {
+ if is_git_subcommand {
+ eprintln!("{}", hint_message(git_subcommand_warning()));
+ } else if should_show_explicit_path_hint() {
+ eprintln!("{}", hint_message(explicit_path_hint(branch)));
+ }
+}
+
+fn handle_switch_already_at_output(ctx: &SwitchOutputContext) -> Option<PathBuf> {
+ print_switch_path_mismatch_warning(ctx);
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "Already on worktree for <bold>{}</> @ <bold>{}</>",
+ ctx.branch,
+ ctx.path_display
+ ))
+ );
+ None
+}
+
+fn handle_switch_existing_output(ctx: &SwitchOutputContext) -> Option<PathBuf> {
+ print_switch_path_mismatch_warning(ctx);
+
+ if let Some(reason) = &ctx.shell_warning_reason {
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "Worktree for <bold>{}</> @ <bold>{}</>, but cannot change directory — {reason}",
+ ctx.branch,
+ ctx.path_display
+ ))
+ );
+ print_switch_directory_hint(&ctx.branch, ctx.is_git_subcommand);
+ } else {
+ eprintln!(
+ "{}",
+ info_message(format_switch_message(
+ &ctx.branch,
+ &ctx.path,
+ false, // worktree_created
+ false, // created_branch
+ None,
+ None,
+ ))
+ );
+ }
+
+ ctx.user_wont_be_in_worktree.then(|| ctx.path.clone())
+}
+
+fn maybe_print_worktree_path_hint(created_branch: bool) {
+ if !created_branch {
+ return;
+ }
+
+ if let Ok(repo) = worktrunk::git::Repository::current() {
+ let has_custom_config = UserConfig::load()
+ .map(|c| c.has_custom_worktree_path())
+ .unwrap_or(false);
+ if !has_custom_config && !repo.has_shown_hint("worktree-path") {
+ let hint = hint_message(cformat!(
+ "To customize worktree locations, run <underline>wt config create</>"
+ ));
+ eprintln!("{}", hint);
+ let _ = repo.mark_hint_shown("worktree-path");
+ }
+ }
+}
+
+fn handle_switch_created_output(
+ ctx: &SwitchOutputContext,
+ created_branch: bool,
+ base_branch: Option<&str>,
+ from_remote: Option<&str>,
+) -> Option<PathBuf> {
+ eprintln!(
+ "{}",
+ success_message(format_switch_message(
+ &ctx.branch,
+ &ctx.path,
+ true, // worktree_created
+ created_branch,
+ base_branch,
+ from_remote,
+ ))
+ );
+
+ maybe_print_worktree_path_hint(created_branch);
+
+ if let Some(reason) = &ctx.shell_warning_reason {
+ eprintln!(
+ "{}",
+ warning_message(cformat!("Cannot change directory — {reason}"))
+ );
+ print_switch_directory_hint(&ctx.branch, ctx.is_git_subcommand);
+ }
+
+ ctx.user_wont_be_in_worktree.then(|| ctx.path.clone())
+}
+
+struct BranchDeletionDisplay {
+ deletion: BranchDeletionResult,
+ show_unmerged_hint: bool,
+}
+
+fn print_retained_unmerged_branch(branch_name: &str) {
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "Branch <bold>{branch_name}</> retained; has unmerged changes"
+ ))
+ );
+ let cmd = suggest_command("remove", &[branch_name], &["-D"]);
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "To delete the unmerged branch, run <underline>{cmd}</>"
+ ))
+ );
+}
+
/// Handle the result of a branch deletion attempt.
///
-/// Shows appropriate messages for non-deleted branches:
-/// - `NotDeleted`: We checked and chose not to delete (not integrated) - show info
+/// Converts a deletion attempt into structured display data:
+/// - `NotDeleted`: We checked and chose not to delete (not integrated)
/// - `Err(e)`: Git command failed - show warning with actual error
-///
-/// Returns (result, needs_hint) where needs_hint indicates the caller should print
-/// the unmerged branch hint after any success message.
-///
-/// When `defer_output` is true, info and hint are suppressed (caller will handle).
fn handle_branch_deletion_result(
result: anyhow::Result<BranchDeletionResult>,
branch_name: &str,
- defer_output: bool,
-) -> anyhow::Result<(BranchDeletionResult, bool)> {
+) -> anyhow::Result<BranchDeletionDisplay> {
match result {
- Ok(r) if !matches!(r.outcome, BranchDeletionOutcome::NotDeleted) => Ok((r, false)),
- Ok(r) => {
- // Branch not integrated - we chose not to delete (not a failure)
- if !defer_output {
- eprintln!(
- "{}",
- info_message(cformat!(
- "Branch <bold>{branch_name}</> retained; has unmerged changes"
- ))
- );
- let cmd = suggest_command("remove", &[branch_name], &["-D"]);
- eprintln!(
- "{}",
- hint_message(cformat!(
- "To delete the unmerged branch, run <underline>{cmd}</>"
- ))
- );
- }
- Ok((r, defer_output))
- }
+ Ok(deletion) => Ok(BranchDeletionDisplay {
+ show_unmerged_hint: matches!(deletion.outcome, BranchDeletionOutcome::NotDeleted),
+ deletion,
+ }),
Err(e) => {
// Git command failed - this is an error (we decided to delete but couldn't)
eprintln!(
@@ -260,17 +415,6 @@ fn handle_branch_deletion_result(
}
}
-// ============================================================================
-// FlagNote: Workaround for cformat! being compile-time only
-// ============================================================================
-//
-// We want to parameterize the color (cyan/green) but can't because cformat!
-// parses color tags at compile time before generic substitution. So we have
-// duplicate methods (after_cyan, after_green) instead of after(color).
-//
-// This is ugly but unavoidable. Keep it encapsulated here.
-// ============================================================================
-
struct FlagNote {
text: String,
symbol: Option<String>,
@@ -306,23 +450,18 @@ impl FlagNote {
}
}
- fn after_cyan(&self) -> String {
- match &self.symbol {
- Some(s) => cformat!("{}<cyan>{}</>", s, self.suffix),
- None => String::new(),
- }
- }
-
- fn after_green(&self) -> String {
+ fn after(&self, color: AnsiColor) -> String {
match &self.symbol {
- Some(s) => cformat!("{}<green>{}</>", s, self.suffix),
+ Some(s) => match color {
+ AnsiColor::Cyan => cformat!("{}<cyan>{}</>", s, self.suffix),
+ AnsiColor::Green => cformat!("{}<green>{}</>", s, self.suffix),
+ _ => format!("{s}{}", self.suffix),
+ },
None => String::new(),
}
}
}
-// ============================================================================
-
/// Get flag acknowledgment note for remove messages
///
/// `target_branch`: The branch we checked integration against (shown in reason)
@@ -489,157 +628,22 @@ pub fn handle_switch_output(
// Translate to the user's logical (symlink-preserved) path for display messages.
// The cd directive (above) handles its own translation internally.
- let path = super::to_logical_path(result.path());
- let path_display = format_path_for_display(&path);
- // For detached HEAD worktrees, use a static label since the path already appears after @.
- let branch: &str = match &branch_info.branch {
- Some(b) => b,
- None => "detached worktree",
- };
-
- // Check if shell integration is active (directive file set)
- let is_shell_integration_active = super::is_shell_integration_active();
-
- // Compute shell warning reason once (only if we'll need it)
- // Git subcommand case is special — needs a hint after the warning
- // With --no-cd: no warning (user explicitly requested no cd), but hooks still get path
- let is_git_subcommand = crate::is_git_subcommand();
- let shell_warning_reason: Option<String> = if !change_dir || is_shell_integration_active {
- None
- } else if is_git_subcommand {
- Some("ran git wt; running through git prevents cd".to_string())
- } else {
- Some(compute_shell_warning_reason())
- };
-
- // When not changing directory, user won't be in the worktree (unless already there)
- // Used to determine if hooks should show "@ path" annotation
- let user_wont_be_in_worktree = !change_dir || shell_warning_reason.is_some();
-
- // Compute branch-worktree mismatch warning (shown before action messages)
- let branch_worktree_mismatch_warning = branch_info
- .expected_path
- .as_ref()
- .map(|expected| format_path_mismatch_warning(branch, &path, expected));
+ let ctx = build_switch_output_context(result, branch_info, change_dir);
let display_path_for_hooks = match result {
- SwitchResult::AlreadyAt(_) => {
- // Already in target directory — no shell warning needed
- // Show path mismatch warning first - discovered while checking current state
- if let Some(warning) = branch_worktree_mismatch_warning {
- eprintln!("{}", warning);
- }
- eprintln!(
- "{}",
- info_message(cformat!(
- "Already on worktree for <bold>{branch}</> @ <bold>{path_display}</>"
- ))
- );
- // User is already there - no path annotation needed
- None
- }
- SwitchResult::Existing { .. } => {
- if let Some(reason) = &shell_warning_reason {
- // Shell integration not active — single warning with context
- if let Some(warning) = branch_worktree_mismatch_warning {
- eprintln!("{}", warning);
- }
- // Show what exists + why cd won't happen
- // (--execute command display is handled by execute_user_command)
- eprintln!(
- "{}",
- warning_message(cformat!(
- "Worktree for <bold>{branch}</> @ <bold>{path_display}</>, but cannot change directory — {reason}"
- ))
- );
- // Show appropriate hint based on invocation mode
- // (regular shell integration hint is shown by prompt_shell_integration in main.rs)
- if is_git_subcommand {
- eprintln!("{}", hint_message(git_subcommand_warning()));
- } else if should_show_explicit_path_hint() {
- eprintln!("{}", hint_message(explicit_path_hint(branch)));
- }
- } else {
- // Shell integration active or --no-cd — user switched (or chose not to cd)
- // Show path mismatch warning first - discovered while evaluating the switch
- if let Some(warning) = branch_worktree_mismatch_warning {
- eprintln!("{}", warning);
- }
- eprintln!(
- "{}",
- info_message(format_switch_message(
- branch, &path, false, // worktree_created
- false, // created_branch
- None, None,
- ))
- );
- }
- // Return path for hook annotations if user won't be in the worktree
- if user_wont_be_in_worktree {
- Some(path.clone())
- } else {
- None
- }
- }
+ SwitchResult::AlreadyAt(_) => handle_switch_already_at_output(&ctx),
+ SwitchResult::Existing { .. } => handle_switch_existing_output(&ctx),
SwitchResult::Created {
created_branch,
base_branch,
from_remote,
..
- } => {
- // Always show success for creation
- eprintln!(
- "{}",
- success_message(format_switch_message(
- branch,
- &path,
- true, // worktree_created
- *created_branch,
- base_branch.as_deref(),
- from_remote.as_deref(),
- ))
- );
-
- // Show worktree-path config hint on first --create in this repo,
- // unless user already has a custom worktree-path config
- if *created_branch && let Ok(repo) = worktrunk::git::Repository::current() {
- let has_custom_config = UserConfig::load()
- .map(|c| c.has_custom_worktree_path())
- .unwrap_or(false);
- if !has_custom_config && !repo.has_shown_hint("worktree-path") {
- let hint = hint_message(cformat!(
- "To customize worktree locations, run <underline>wt config create</>"
- ));
- eprintln!("{}", hint);
- let _ = repo.mark_hint_shown("worktree-path");
- }
- }
-
- // Warn if shell won't cd to the new worktree (but not for --no-cd)
- // (--execute command display is handled by execute_user_command)
- if let Some(reason) = shell_warning_reason {
- // Don't repeat "Created worktree" — success message above already said that
- eprintln!(
- "{}",
- warning_message(cformat!("Cannot change directory — {reason}"))
- );
- // Show appropriate hint based on invocation mode
- // (regular shell integration hint is shown by prompt_shell_integration in main.rs)
- if is_git_subcommand {
- eprintln!("{}", hint_message(git_subcommand_warning()));
- } else if should_show_explicit_path_hint() {
- eprintln!("{}", hint_message(explicit_path_hint(branch)));
- }
- }
- // Return path for hook annotations if user won't be in the worktree
- if user_wont_be_in_worktree {
- Some(path.clone())
- } else {
- None
- }
- // Note: No branch_worktree_mismatch_warning — created worktrees are always at
- // the expected path (SwitchBranchInfo::expected_path is None)
- }
+ } => handle_switch_created_output(
+ &ctx,
+ *created_branch,
+ base_branch.as_deref(),
+ from_remote.as_deref(),
+ ),
};
stderr().flush()?;
@@ -744,35 +748,21 @@ fn handle_branch_only_output(
let check_target = default_branch.as_deref().unwrap_or("HEAD");
let result = delete_branch_if_safe(&repo, branch_name, check_target, deletion_mode.is_force());
- // Defer "retained" output so we control message ordering (info before retained)
- let (deletion, deferred) = handle_branch_deletion_result(result, branch_name, true)?;
+ let deletion = handle_branch_deletion_result(result, branch_name)?;
- if matches!(deletion.outcome, BranchDeletionOutcome::NotDeleted) {
- // Print info first, then deferred "retained" + hint
+ if matches!(deletion.deletion.outcome, BranchDeletionOutcome::NotDeleted) {
eprintln!("{}", info_message(&branch_info));
- if deferred {
- eprintln!(
- "{}",
- info_message(cformat!(
- "Branch <bold>{branch_name}</> retained; has unmerged changes"
- ))
- );
- let cmd = suggest_command("remove", &[branch_name], &["-D"]);
- eprintln!(
- "{}",
- hint_message(cformat!(
- "To delete the unmerged branch, run <underline>{cmd}</>"
- ))
- );
+ if deletion.show_unmerged_hint {
+ print_retained_unmerged_branch(branch_name);
}
} else {
let flag_note = flag_note(
deletion_mode,
- &deletion.outcome,
- Some(&deletion.integration_target),
+ &deletion.deletion.outcome,
+ Some(&deletion.deletion.integration_target),
);
let flag_text = &flag_note.text;
- let flag_after = flag_note.after_green();
+ let flag_after = flag_note.after(AnsiColor::Green);
if pruned {
// Combined: pruned stale metadata & deleted branch in one line
@@ -942,11 +932,15 @@ impl RemovalDisplayInfo {
let (outcome, integration_target, show_unmerged_hint) = match branch_deletion {
Some(result) => {
- let (deletion, needs_hint) =
- handle_branch_deletion_result(result, branch_name, true)?;
+ let deletion = handle_branch_deletion_result(result, branch_name)?;
// Only use integration_target for display if we had a real target (not "HEAD" fallback)
- let display_target = target_branch.map(|_| deletion.integration_target);
- (deletion.outcome, display_target, needs_hint)
+ let display_target =
+ target_branch.map(|_| deletion.deletion.integration_target.clone());
+ (
+ deletion.deletion.outcome,
+ display_target,
+ deletion.show_unmerged_hint,
+ )
}
None => (
BranchDeletionOutcome::NotDeleted,
@@ -995,7 +989,7 @@ impl RemovalDisplayInfo {
success_message(cformat!(
"Removed <bold>{branch_name}</> worktree{force_text} & branch{flag_text}"
))
- .append(&flag_note.after_green())
+ .append(&flag_note.after(AnsiColor::Green))
} else {
success_message(cformat!(
"Removed <bold>{branch_name}</> worktree{force_text}"
@@ -1006,7 +1000,7 @@ impl RemovalDisplayInfo {
progress_message(cformat!(
"Removing <bold>{branch_name}</> worktree{force_text} & branch in background{flag_text}"
))
- .append(&flag_note.after_cyan())
+ .append(&flag_note.after(AnsiColor::Cyan))
} else {
progress_message(cformat!(
"Removing <bold>{branch_name}</> worktree{force_text} in background"
@@ -1076,68 +1070,56 @@ struct RemovedWorktreeOutputContext<'a> {
verify: bool,
}
-/// Handle output for RemovedWorktree removal
-fn handle_removed_worktree_output(ctx: RemovedWorktreeOutputContext<'_>) -> anyhow::Result<()> {
- let RemovedWorktreeOutputContext {
- main_path,
- worktree_path,
- changed_directory,
- branch_name,
- deletion_mode,
- target_branch,
- pre_computed_integration,
- force_worktree,
- expected_path,
- removed_commit,
- foreground,
- verify,
- } = ctx;
-
- // Use main_path for discovery - the worktree being removed might be cwd,
- // and git operations after removal need a valid working directory.
- let repo = worktrunk::git::Repository::at(main_path)?;
-
- // Execute pre-remove hooks in the worktree being removed BEFORE writing cd directive.
- // Non-zero exit aborts removal (FailFast strategy).
- // If hooks fail, we don't want the shell to cd to main_path.
- // For detached HEAD, {{ branch }} expands to "HEAD" in templates
- if verify && let Ok(config) = UserConfig::load() {
- let ctx = CommandContext::new(
- &repo,
- &config,
- branch_name,
- worktree_path,
- false, // yes=false for CommandContext (not approval-related)
- );
- // Show path when removing a different worktree (user is elsewhere)
- let display_path = if changed_directory {
- None // User was already here
- } else {
- Some(worktree_path) // Show path when user is elsewhere
- };
- // Target vars: where the user will end up after removal
- let target_branch = repo
- .worktree_at(main_path)
- .branch()
- .ok()
- .flatten()
- .unwrap_or_default();
- let target_path_str = worktrunk::path::to_posix_path(&main_path.to_string_lossy());
- let extra_vars: Vec<(&str, &str)> = vec![
- ("target", &target_branch),
- ("target_worktree_path", &target_path_str),
- ];
- execute_hook(
- &ctx,
- worktrunk::HookType::PreRemove,
- &extra_vars,
- HookFailureStrategy::FailFast,
- None,
- display_path,
- )?;
+fn execute_pre_remove_hooks_if_needed(
+ repo: &Repository,
+ ctx: &RemovedWorktreeOutputContext<'_>,
+) -> anyhow::Result<()> {
+ if !ctx.verify {
+ return Ok(());
}
- // Emit cd directive only after pre-remove hooks succeed
+ let Ok(config) = UserConfig::load() else {
+ return Ok(());
+ };
+
+ let command_ctx = CommandContext::new(
+ repo,
+ &config,
+ ctx.branch_name,
+ ctx.worktree_path,
+ false, // yes=false for CommandContext (not approval-related)
+ );
+ let display_path = if ctx.changed_directory {
+ None
+ } else {
+ Some(ctx.worktree_path)
+ };
+ let target_branch = repo
+ .worktree_at(ctx.main_path)
+ .branch()
+ .ok()
+ .flatten()
+ .unwrap_or_default();
+ let target_path_str = worktrunk::path::to_posix_path(&ctx.main_path.to_string_lossy());
+ let extra_vars: Vec<(&str, &str)> = vec![
+ ("target", &target_branch),
+ ("target_worktree_path", &target_path_str),
+ ];
+
+ execute_hook(
+ &command_ctx,
+ worktrunk::HookType::PreRemove,
+ &extra_vars,
+ HookFailureStrategy::FailFast,
+ None,
+ display_path,
+ )
+}
+
+fn prepare_remove_directory_change(
+ main_path: &Path,
+ changed_directory: bool,
+) -> anyhow::Result<()> {
if changed_directory {
super::change_directory(main_path)?;
stderr().flush()?; // Force flush to ensure shell processes the cd
@@ -1146,173 +1128,201 @@ fn handle_removed_worktree_output(ctx: RemovedWorktreeOutputContext<'_>) -> anyh
super::mark_cwd_removed();
}
- // Handle detached HEAD case (no branch known)
- let Some(branch_name) = branch_name else {
- // No branch associated - just remove the worktree
- if foreground {
- // Progress message after pre-remove hooks, before actual removal
- eprintln!(
- "{}",
- progress_message(cformat!(
- "Removing worktree @ <bold>{}</>... (detached HEAD, no branch to delete)",
- format_path_for_display(worktree_path)
- ))
- );
- let output = execute_removal(
- &repo,
- worktree_path,
- None,
- deletion_mode,
- target_branch,
- force_worktree,
- )
- .map_err(|err| GitError::WorktreeRemovalFailed {
- branch: path_dir_name(worktree_path).to_string(),
- path: worktree_path.to_path_buf(),
- remaining_entries: list_remaining_entries(worktree_path),
- error: err.to_string(),
- })?;
- if let Some(staged) = output.staged_path {
- let _ = std::fs::remove_dir_all(&staged);
- }
- eprintln!(
- "{}",
- success_message(cformat!(
- "Removed worktree @ <bold>{}</> (detached HEAD, no branch to delete)",
- format_path_for_display(worktree_path)
- ))
- );
- } else {
- let path_display = format_path_for_display(worktree_path);
- eprintln!(
- "{}",
- progress_message(cformat!(
- "Removing worktree @ <bold>{path_display}</> in background (detached HEAD, no branch to delete)"
- ))
- );
-
- spawn_background_removal(
- &repo,
- main_path,
- worktree_path,
- None,
- force_worktree,
- "detached",
- )?;
- }
- // Post-remove hooks for detached HEAD use "HEAD" as the branch identifier
- spawn_hooks_after_remove(
- &repo,
- main_path,
- worktree_path,
- "HEAD",
- removed_commit,
- verify,
- changed_directory,
- )?;
- stderr().flush()?;
- return Ok(());
- };
-
- if foreground {
- // Foreground mode: remove immediately and report actual results
+ Ok(())
+}
- // Progress message after pre-remove hooks, before actual removal
+fn handle_detached_removed_worktree_output(
+ repo: &Repository,
+ ctx: &RemovedWorktreeOutputContext<'_>,
+) -> anyhow::Result<()> {
+ if ctx.foreground {
eprintln!(
"{}",
- progress_message(cformat!("Removing <bold>{branch_name}</> worktree..."))
+ progress_message(cformat!(
+ "Removing worktree @ <bold>{}</>... (detached HEAD, no branch to delete)",
+ format_path_for_display(ctx.worktree_path)
+ ))
);
-
- // Foreground mode: show warning after progress (contextual info during operation)
- if let Some(expected) = expected_path {
- eprintln!(
- "{}",
- format_path_mismatch_warning(branch_name, worktree_path, expected)
- );
- }
-
let output = execute_removal(
- &repo,
- worktree_path,
- Some(branch_name),
- deletion_mode,
- target_branch,
- force_worktree,
+ repo,
+ ctx.worktree_path,
+ None,
+ ctx.deletion_mode,
+ ctx.target_branch,
+ ctx.force_worktree,
)
.map_err(|err| GitError::WorktreeRemovalFailed {
- branch: branch_name.into(),
- path: worktree_path.to_path_buf(),
- remaining_entries: list_remaining_entries(worktree_path),
+ branch: path_dir_name(ctx.worktree_path).to_string(),
+ path: ctx.worktree_path.to_path_buf(),
+ remaining_entries: list_remaining_entries(ctx.worktree_path),
error: err.to_string(),
})?;
if let Some(staged) = output.staged_path {
let _ = std::fs::remove_dir_all(&staged);
}
+ eprintln!(
+ "{}",
+ success_message(cformat!(
+ "Removed worktree @ <bold>{}</> (detached HEAD, no branch to delete)",
+ format_path_for_display(ctx.worktree_path)
+ ))
+ );
+ } else {
+ let path_display = format_path_for_display(ctx.worktree_path);
+ eprintln!(
+ "{}",
+ progress_message(cformat!(
+ "Removing worktree @ <bold>{path_display}</> in background (detached HEAD, no branch to delete)"
+ ))
+ );
- let display_info = RemovalDisplayInfo::from_branch_result(
- output.branch_result,
- branch_name,
- pre_computed_integration,
- target_branch,
- force_worktree,
+ spawn_background_removal(
+ repo,
+ ctx.main_path,
+ ctx.worktree_path,
+ None,
+ ctx.force_worktree,
+ "detached",
)?;
+ }
- display_info.print_message(branch_name, true)?;
- display_info.print_hints(branch_name, deletion_mode, pre_computed_integration)?;
- print_switch_message_if_changed(changed_directory, main_path)?;
+ // Post-remove hooks for detached HEAD use "HEAD" as the branch identifier
+ spawn_hooks_after_remove(
+ repo,
+ ctx.main_path,
+ ctx.worktree_path,
+ "HEAD",
+ ctx.removed_commit,
+ ctx.verify,
+ ctx.changed_directory,
+ )?;
+ stderr().flush()?;
+ Ok(())
+}
- spawn_hooks_after_remove(
- &repo,
- main_path,
- worktree_path,
- branch_name,
- removed_commit,
- verify,
- changed_directory,
- )?;
- stderr().flush()?;
- Ok(())
- } else {
- // Background mode: show warning before decision announcement
- if let Some(expected) = expected_path {
- eprintln!(
- "{}",
- format_path_mismatch_warning(branch_name, worktree_path, expected)
- );
- }
+fn handle_named_removed_worktree_foreground(
+ repo: &Repository,
+ ctx: &RemovedWorktreeOutputContext<'_>,
+ branch_name: &str,
+) -> anyhow::Result<()> {
+ eprintln!(
+ "{}",
+ progress_message(cformat!("Removing <bold>{branch_name}</> worktree..."))
+ );
- // Background mode: spawn detached process
- let display_info = RemovalDisplayInfo::from_precomputed(
- deletion_mode,
- pre_computed_integration,
- target_branch,
- force_worktree,
+ if let Some(expected) = ctx.expected_path {
+ eprintln!(
+ "{}",
+ format_path_mismatch_warning(branch_name, ctx.worktree_path, expected)
);
+ }
- display_info.print_message(branch_name, false)?;
- display_info.print_hints(branch_name, deletion_mode, pre_computed_integration)?;
- print_switch_message_if_changed(changed_directory, main_path)?;
+ let output = execute_removal(
+ repo,
+ ctx.worktree_path,
+ Some(branch_name),
+ ctx.deletion_mode,
+ ctx.target_branch,
+ ctx.force_worktree,
+ )
+ .map_err(|err| GitError::WorktreeRemovalFailed {
+ branch: branch_name.into(),
+ path: ctx.worktree_path.to_path_buf(),
+ remaining_entries: list_remaining_entries(ctx.worktree_path),
+ error: err.to_string(),
+ })?;
+ if let Some(staged) = output.staged_path {
+ let _ = std::fs::remove_dir_all(&staged);
+ }
- spawn_background_removal(
- &repo,
- main_path,
- worktree_path,
- display_info.branch_deleted().then_some(branch_name),
- force_worktree,
- branch_name,
- )?;
+ let display_info = RemovalDisplayInfo::from_branch_result(
+ output.branch_result,
+ branch_name,
+ ctx.pre_computed_integration,
+ ctx.target_branch,
+ ctx.force_worktree,
+ )?;
- spawn_hooks_after_remove(
- &repo,
- main_path,
- worktree_path,
- branch_name,
- removed_commit,
- verify,
- changed_directory,
- )?;
- stderr().flush()?;
- Ok(())
+ display_info.print_message(branch_name, true)?;
+ display_info.print_hints(branch_name, ctx.deletion_mode, ctx.pre_computed_integration)?;
+ print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;
+
+ spawn_hooks_after_remove(
+ repo,
+ ctx.main_path,
+ ctx.worktree_path,
+ branch_name,
+ ctx.removed_commit,
+ ctx.verify,
+ ctx.changed_directory,
+ )?;
+ stderr().flush()?;
+ Ok(())
+}
+
+fn handle_named_removed_worktree_background(
+ repo: &Repository,
+ ctx: &RemovedWorktreeOutputContext<'_>,
+ branch_name: &str,
+) -> anyhow::Result<()> {
+ if let Some(expected) = ctx.expected_path {
+ eprintln!(
+ "{}",
+ format_path_mismatch_warning(branch_name, ctx.worktree_path, expected)
+ );
+ }
+
+ let display_info = RemovalDisplayInfo::from_precomputed(
+ ctx.deletion_mode,
+ ctx.pre_computed_integration,
+ ctx.target_branch,
+ ctx.force_worktree,
+ );
+
+ display_info.print_message(branch_name, false)?;
+ display_info.print_hints(branch_name, ctx.deletion_mode, ctx.pre_computed_integration)?;
+ print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;
+
+ spawn_background_removal(
+ repo,
+ ctx.main_path,
+ ctx.worktree_path,
+ display_info.branch_deleted().then_some(branch_name),
+ ctx.force_worktree,
+ branch_name,
+ )?;
+
+ spawn_hooks_after_remove(
+ repo,
+ ctx.main_path,
+ ctx.worktree_path,
+ branch_name,
+ ctx.removed_commit,
+ ctx.verify,
+ ctx.changed_directory,
+ )?;
+ stderr().flush()?;
+ Ok(())
+}
+
+/// Handle output for RemovedWorktree removal
+fn handle_removed_worktree_output(ctx: RemovedWorktreeOutputContext<'_>) -> anyhow::Result<()> {
+ // Use main_path for discovery - the worktree being removed might be cwd,
+ // and git operations after removal need a valid working directory.
+ let repo = worktrunk::git::Repository::at(ctx.main_path)?;
+
+ execute_pre_remove_hooks_if_needed(&repo, &ctx)?;
+ prepare_remove_directory_change(ctx.main_path, ctx.changed_directory)?;
+
+ // Handle detached HEAD case (no branch known)
+ let Some(branch_name) = ctx.branch_name else {
+ return handle_detached_removed_worktree_output(&repo, &ctx);
+ };
+
+ if ctx.foreground {
+ handle_named_removed_worktree_foreground(&repo, &ctx, branch_name)
+ } else {
+ handle_named_removed_worktree_background(&repo, &ctx, branch_name)
}
}
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index d6f8966a8..4a51ecf7a 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -396,12 +396,32 @@ pub struct Cmd {
external_label: Option<String>,
}
+struct ExternalCommandLog {
+ label: Option<String>,
+ cmd_str: String,
+ started_at: Option<Instant>,
+}
+
+impl ExternalCommandLog {
+ fn new(label: Option<String>, cmd_str: String) -> Self {
+ let started_at = label.as_ref().map(|_| Instant::now());
+ Self {
+ label,
+ cmd_str,
+ started_at,
+ }
+ }
+
+ fn record(&self, exit_code: Option<i32>) {
+ if let Some(label) = &self.label {
+ let duration = self.started_at.as_ref().map(Instant::elapsed);
+ crate::command_log::log_command(label, &self.cmd_str, exit_code, duration);
+ }
+ }
+}
+
impl Cmd {
- /// Create a new command builder for the given program.
- ///
- /// The program is executed directly without shell interpretation.
- /// For shell commands (with pipes, redirects, etc.), use [`Cmd::shell()`].
- pub fn new(program: impl Into<String>) -> Self {
+ fn builder(program: impl Into<String>, shell_wrap: bool) -> Self {
Self {
program: program.into(),
args: Vec::new(),
@@ -411,7 +431,7 @@ impl Cmd {
timeout: None,
envs: Vec::new(),
env_removes: Vec::new(),
- shell_wrap: false,
+ shell_wrap,
stdout_cfg: None,
stdin_cfg: None,
forward_signals: false,
@@ -419,6 +439,14 @@ impl Cmd {
}
}
+ /// Create a new command builder for the given program.
+ ///
+ /// The program is executed directly without shell interpretation.
+ /// For shell commands (with pipes, redirects, etc.), use [`Cmd::shell()`].
+ pub fn new(program: impl Into<String>) -> Self {
+ Self::builder(program, false)
+ }
+
/// Create a command builder for a shell command string.
///
/// The command is executed through the platform's shell (`sh -c` on Unix,
@@ -426,20 +454,51 @@ impl Cmd {
///
/// Only valid with `.stream()` — shell commands cannot use `.run()`.
pub fn shell(command: impl Into<String>) -> Self {
- Self {
- program: command.into(),
- args: Vec::new(),
- current_dir: None,
- context: None,
- stdin_data: None,
- timeout: None,
- envs: Vec::new(),
- env_removes: Vec::new(),
- shell_wrap: true,
- stdout_cfg: None,
- stdin_cfg: None,
- forward_signals: false,
- external_label: None,
+ Self::builder(command, true)
+ }
+
+ fn command_string(&self) -> String {
+ if self.shell_wrap || self.args.is_empty() {
+ self.program.clone()
+ } else {
+ format!("{} {}", self.program, self.args.join(" "))
+ }
+ }
+
+ fn direct_command(&self) -> Command {
+ let mut cmd = Command::new(&self.program);
+ cmd.args(&self.args);
+ cmd
+ }
+
+ fn apply_common_settings(&self, cmd: &mut Command) {
+ if let Some(dir) = &self.current_dir {
+ cmd.current_dir(dir);
+ }
+
+ for (key, val) in &self.envs {
+ cmd.env(key, val);
+ }
+ for key in &self.env_removes {
+ cmd.env_remove(key);
+ }
+
+ // Prevent subprocesses from writing shell directives (security).
+ // Applied last to ensure it can't be re-added by user-provided envs.
+ cmd.env_remove(DIRECTIVE_FILE_ENV_VAR);
+ }
+
+ fn log_run_start(&self, cmd_str: &str) {
+ match &self.context {
+ Some(ctx) => log::debug!("$ {} [{}]", cmd_str, ctx),
+ None => log::debug!("$ {}", cmd_str),
+ }
+ }
+
+ fn log_stream_start(&self, cmd_str: &str, exec_mode: &str) {
+ match &self.context {
+ Some(ctx) => log::debug!("$ {} [{}] (streaming, {})", cmd_str, ctx, exec_mode),
+ None => log::debug!("$ {} (streaming, {})", cmd_str, exec_mode),
}
}
@@ -565,18 +624,9 @@ impl Cmd {
"Cmd::shell() commands must use .stream(), not .run()"
);
- // Build command string for logging
- let cmd_str = if self.args.is_empty() {
- self.program.clone()
- } else {
- format!("{} {}", self.program, self.args.join(" "))
- };
-
- // Log command with optional context
- match &self.context {
- Some(ctx) => log::debug!("$ {} [{}]", cmd_str, ctx),
- None => log::debug!("$ {}", cmd_str),
- }
+ let cmd_str = self.command_string();
+ let external_log = ExternalCommandLog::new(self.external_label.clone(), cmd_str.clone());
+ self.log_run_start(&cmd_str);
// Acquire semaphore to limit concurrent commands
let _guard = semaphore().acquire();
@@ -586,24 +636,8 @@ impl Cmd {
let ts = t0.duration_since(*trace_epoch()).as_micros() as u64;
let tid = thread_id_number();
- // Build the Command
- let mut cmd = Command::new(&self.program);
- cmd.args(&self.args);
-
- if let Some(ref dir) = self.current_dir {
- cmd.current_dir(dir);
- }
-
- for (key, val) in &self.envs {
- cmd.env(key, val);
- }
- for key in &self.env_removes {
- cmd.env_remove(key);
- }
-
- // Prevent subprocesses from writing shell directives (security).
- // Applied last to ensure it can't be re-added by user-provided envs.
- cmd.env_remove(DIRECTIVE_FILE_ENV_VAR);
+ let mut cmd = self.direct_command();
+ self.apply_common_settings(&mut cmd);
// Determine effective timeout: explicit > thread-local > none
let effective_timeout = self.timeout.or_else(|| COMMAND_TIMEOUT.with(|t| t.get()));
@@ -684,14 +718,8 @@ impl Cmd {
}
}
- // Log to command log if this is an external command
- if let Some(label) = &self.external_label {
- let (exit_code, duration) = match &result {
- Ok(output) => (output.status.code(), Some(t0.elapsed())),
- Err(_) => (None, Some(t0.elapsed())),
- };
- crate::command_log::log_command(label, &cmd_str, exit_code, duration);
- }
+ let exit_code = result.as_ref().ok().and_then(|output| output.status.code());
+ external_log.record(exit_code);
result
}
@@ -718,54 +746,25 @@ impl Cmd {
std::os::unix::process::CommandExt,
};
- // Extract external label for command logging (must happen before self is consumed).
- // t0 is Some iff external_label is Some — both initialized together so timing is accurate.
- let external_label = self.external_label.take();
- let t0 = external_label.as_ref().map(|_| Instant::now());
-
// Shell-wrapped commands don't use args (the command string is the full command)
assert!(
!self.shell_wrap || self.args.is_empty(),
"Cmd::shell() cannot use .arg() - include arguments in the shell command string"
);
- let working_dir = self
- .current_dir
- .as_deref()
- .unwrap_or_else(|| std::path::Path::new("."));
-
// Build the command - either shell-wrapped or direct
let (mut cmd, exec_mode) = if self.shell_wrap {
let shell = ShellConfig::get()?;
let mode = format!("shell: {}", shell.name);
(shell.command(&self.program), mode)
} else {
- let mut cmd = Command::new(&self.program);
- cmd.args(&self.args);
- (cmd, "direct".to_string())
- };
-
- // Build command string for logging (shell commands have full command in program,
- // non-shell commands may have args)
- let cmd_str = if self.shell_wrap || self.args.is_empty() {
- self.program.clone()
- } else {
- format!("{} {}", self.program, self.args.join(" "))
- };
-
- // Closure for command log entries (deduplicates 4 exit-path logging blocks)
- let log_external = |exit_code: Option<i32>| {
- if let Some(label) = &external_label {
- let duration = t0.map(|t| t.elapsed());
- crate::command_log::log_command(label, &cmd_str, exit_code, duration);
- }
+ (self.direct_command(), "direct".to_string())
};
- // Log command for debugging (output goes to logger, not stdout/stderr)
- match &self.context {
- Some(ctx) => log::debug!("$ {} [{}] (streaming, {})", cmd_str, ctx, exec_mode),
- None => log::debug!("$ {} (streaming, {})", cmd_str, exec_mode),
- }
+ let cmd_str = self.command_string();
+ let external_log = ExternalCommandLog::new(self.external_label.take(), cmd_str.clone());
+ self.log_stream_start(&cmd_str, &exec_mode);
+ self.apply_common_settings(&mut cmd);
#[cfg(not(unix))]
let _ = self.forward_signals;
@@ -794,24 +793,12 @@ impl Cmd {
}
// Apply environment and spawn
- cmd.current_dir(working_dir)
- .stdin(stdin_mode)
+ cmd.stdin(stdin_mode)
.stdout(stdout_mode)
.stderr(std::process::Stdio::inherit()) // Preserve TTY for errors
// Prevent vergen "overridden" warning in nested cargo builds
.env_remove("VERGEN_GIT_DESCRIBE");
- for (key, val) in &self.envs {
- cmd.env(key, val);
- }
- for key in &self.env_removes {
- cmd.env_remove(key);
- }
-
- // Prevent hooks from writing shell directives (security).
- // Applied last to ensure it can't be re-added by user-provided envs.
- cmd.env_remove(DIRECTIVE_FILE_ENV_VAR);
-
let mut child = cmd.spawn().map_err(|e| {
anyhow::Error::from(GitError::Other {
message: format!("Failed to execute command ({}): {}", exec_mode, e),
@@ -870,7 +857,7 @@ impl Cmd {
// Handle signals (Unix only)
#[cfg(unix)]
if let Some(sig) = seen_signal {
- log_external(Some(128 + sig));
+ external_log.record(Some(128 + sig));
return Err(WorktrunkError::ChildProcessExited {
code: 128 + sig,
message: format!("terminated by signal {}", sig),
@@ -883,10 +870,10 @@ impl Cmd {
// SIGPIPE (13) is expected when a pager (less, bat) exits before the
// child finishes writing — not an error from the user's perspective.
if sig == SIGPIPE {
- log_external(Some(0));
+ external_log.record(Some(0));
return Ok(());
}
- log_external(Some(128 + sig));
+ external_log.record(Some(128 + sig));
return Err(WorktrunkError::ChildProcessExited {
code: 128 + sig,
message: format!("terminated by signal {}", sig),
@@ -896,7 +883,7 @@ impl Cmd {
if !status.success() {
let code = status.code().unwrap_or(1);
- log_external(status.code());
+ external_log.record(status.code());
return Err(WorktrunkError::ChildProcessExited {
code,
message: format!("exit status: {}", code),
@@ -904,7 +891,7 @@ impl Cmd {
.into());
}
- log_external(Some(0));
+ external_log.record(Some(0));
Ok(())
}
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 7913015e6..d280feffd 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -2336,69 +2336,36 @@ pub fn add_standard_env_redactions(settings: &mut insta::Settings) {
settings.add_redaction(".env.MOCK_CONFIG_DIR", "[MOCK_CONFIG_DIR]");
}
-/// Create configured insta Settings for snapshot tests
-///
-/// This extracts the common settings configuration while allowing the
-/// `assert_cmd_snapshot!` macro to remain in test files for correct module path capture.
-pub fn setup_snapshot_settings(repo: &TestRepo) -> insta::Settings {
- setup_snapshot_settings_impl(repo.root_path(), None)
-}
-
-/// Internal implementation that optionally includes temp_home filter.
-/// The temp_home filter MUST be added before PROJECT_ID filters to take precedence.
-fn setup_snapshot_settings_impl(root: &Path, temp_home: Option<&Path>) -> insta::Settings {
- let worktrees = HashMap::new(); // Caller doesn't need worktree filters
- setup_snapshot_settings_for_paths_with_home(root, &worktrees, temp_home)
+fn canonical_home_dir() -> Option<PathBuf> {
+ home::home_dir().and_then(|path| canonicalize(&path).ok())
}
-/// Full snapshot settings - path filters AND ANSI cleanup.
-/// Use this with `settings.bind()` for assert_cmd_snapshot! tests.
-/// Clones current settings (which may already have minimal path filters from TestRepo).
-fn setup_snapshot_settings_for_paths(
- root: &Path,
- worktrees: &HashMap<String, PathBuf>,
-) -> insta::Settings {
- setup_snapshot_settings_for_paths_with_home(root, worktrees, None)
-}
-
-/// Internal implementation with optional temp_home support.
-///
-/// When `temp_home` is provided, we create fresh settings rather than cloning current settings.
-/// This is critical because TestRepo's snapshot guard may have already added PROJECT_ID filters,
-/// and cloning would inherit those filters which would be applied BEFORE our TEMP_HOME filter.
-fn setup_snapshot_settings_for_paths_with_home(
- root: &Path,
- worktrees: &HashMap<String, PathBuf>,
- temp_home: Option<&Path>,
-) -> insta::Settings {
- // When temp_home is provided, start fresh to ensure TEMP_HOME filter is applied before
- // any inherited PROJECT_ID filters. Otherwise, clone current settings for consistency.
- let mut settings = if temp_home.is_some() {
- insta::Settings::new()
- } else {
- insta::Settings::clone_current()
- };
- settings.set_snapshot_path("../snapshots");
-
+fn add_snapshot_path_prelude_filters(settings: &mut insta::Settings) {
// Normalize project root path (for test fixtures)
// This must come before repo path filter to avoid partial matches
let project_root = std::env::var("CARGO_MANIFEST_DIR")
.ok()
- .and_then(|p| canonicalize(std::path::Path::new(&p)).ok());
+ .and_then(|path| canonicalize(std::path::Path::new(&path)).ok());
if let Some(root) = project_root {
settings.add_filter(&regex::escape(root.to_str().unwrap()), "[PROJECT_ROOT]");
}
+
// Normalize llvm-cov-target to target for coverage builds (cargo-llvm-cov)
settings.add_filter(r"/target/llvm-cov-target/", "/target/");
// Normalize backslashes FIRST so all subsequent path filters only need forward-slash versions.
// This must come before any path replacement filters.
settings.add_filter(r"\\", "/");
+}
+fn add_repo_and_worktree_path_filters(
+ settings: &mut insta::Settings,
+ root: &Path,
+ worktrees: &HashMap<String, PathBuf>,
+) {
// Normalize paths (canonicalize for macOS /var -> /private/var symlink)
let root_canonical = canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
let root_str = root_canonical.to_str().unwrap();
- // Convert backslashes to forward slashes before escaping (backslash filter already ran)
let root_str_normalized = root_str.replace('\\', "/");
settings.add_filter(&regex::escape(&root_str_normalized), "_REPO_");
// Also add POSIX-style path for Git Bash (C:\foo\bar -> /c/foo/bar)
@@ -2410,15 +2377,14 @@ fn setup_snapshot_settings_for_paths_with_home(
// The optional suffix matches worktree paths like ~/repo.feature
settings.add_filter(r"~/repo(\.[a-zA-Z0-9_-]+)?", "_REPO_$1");
+ let home_dir = canonical_home_dir();
+
// Also handle the case where the real home contains the temp directory (Windows/macOS)
- // Note: canonicalize home_dir too, since on Windows home::home_dir() may return a short path
- // (C:\Users\RUNNER~1) while dunce::canonicalize returns the long path (C:\Users\runneradmin).
- if let Some(home) = home::home_dir().and_then(|h| canonicalize(&h).ok())
- && let Ok(relative) = root_canonical.strip_prefix(&home)
+ if let Some(home) = home_dir.as_ref()
+ && let Ok(relative) = root_canonical.strip_prefix(home)
{
let tilde_path = format!("~/{}", relative.display()).replace('\\', "/");
settings.add_filter(&regex::escape(&tilde_path), "_REPO_");
- // Match worktree paths
let tilde_worktree_pattern = format!(r"{}(\.[a-zA-Z0-9_-]+)", regex::escape(&tilde_path));
settings.add_filter(&tilde_worktree_pattern, "_REPO_$1");
}
@@ -2427,15 +2393,12 @@ fn setup_snapshot_settings_for_paths_with_home(
let canonical = canonicalize(path).unwrap_or_else(|_| path.clone());
let path_str = canonical.to_str().unwrap();
let replacement = format!("_WORKTREE_{}_", name.to_uppercase().replace('-', "_"));
- // Convert backslashes to forward slashes before escaping (backslash filter already ran)
let path_str_normalized = path_str.replace('\\', "/");
settings.add_filter(&regex::escape(&path_str_normalized), &replacement);
- // Also add POSIX-style path for Git Bash (C:\foo\bar -> /c/foo/bar)
settings.add_filter(&regex::escape(&to_posix_path(path_str)), &replacement);
- // Also add tilde-prefixed worktree path filter for Windows
- if let Some(home) = home::home_dir().and_then(|h| canonicalize(&h).ok())
- && let Ok(relative) = canonical.strip_prefix(&home)
+ if let Some(home) = home_dir.as_ref()
+ && let Ok(relative) = canonical.strip_prefix(home)
{
let tilde_path = format!("~/{}", relative.display()).replace('\\', "/");
settings.add_filter(&regex::escape(&tilde_path), &replacement);
@@ -2443,104 +2406,62 @@ fn setup_snapshot_settings_for_paths_with_home(
}
// Windows fallback: use a regex pattern to catch tilde-prefixed Windows temp paths.
- // This handles cases where path formats differ between home::home_dir() and the actual
- // paths used in commands. MUST come after backslash normalization so paths have forward slashes.
- // Pattern: ~/AppData/Local/Temp/.tmpXXXXXX/repo (where XXXXXX varies)
settings.add_filter(r"~/AppData/Local/Temp/\.tmp[^/]+/repo", "_REPO_");
// Windows fallback for POSIX-style paths from Git Bash (used in hook template expansion).
- // Pattern: /c/Users/.../Temp/.tmpXXXXXX/repo and worktrees like /c/.../repo.feature-test
settings.add_filter(
r"/[a-z]/Users/[^/]+/AppData/Local/Temp/\.tmp[^/]+/repo(\.[a-zA-Z0-9_/-]+)?",
"_REPO_$1",
);
+}
+fn add_placeholder_cleanup_filters(settings: &mut insta::Settings) {
// Final cleanup: strip any remaining quotes around placeholders.
- // shell_escape may quote paths containing ~ (Windows short path notation like RUNNER~1).
- // ANSI codes may appear between quotes and content.
- // This pattern matches placeholders with optional suffixes and subpaths:
- // - '_REPO_' -> _REPO_
- // - '_REPO_.feat' -> _REPO_.feat
- // - '_REPO_.name.bak.20250102-000000' -> _REPO_.name.bak.20250102-000000
- // - '_REPO_/.config/wt.toml' -> _REPO_/.config/wt.toml
- // - '_WORKTREE_A_/subpath' -> _WORKTREE_A_/subpath
settings.add_filter(
r"'(?:\x1b\[[0-9;]*m)*(_(?:REPO|WORKTREE_[A-Z0-9_]+)_(?:\.[a-zA-Z0-9_.-]+)?(?:/[^']*)?)(?:\x1b\[[0-9;]*m)*'",
"$1",
);
// Also strip quotes around bracket placeholders like [PROJECT_ID]
- // NOTE: This filter runs BEFORE PROJECT_ID replacement, so it handles
- // cases where ANSI codes appear between quotes and placeholders.
- // A simpler post-replacement filter is added after PROJECT_ID filters.
settings.add_filter(
r"'(?:\x1b\[[0-9;]*m)*(\[[A-Z_]+\])(?:\x1b\[[0-9;]*m)*'",
"$1",
);
- // Also strip quotes around paths that include subdirectories (e.g., '_REPO_/.config/wt.toml')
- // On Windows, shell_escape quotes paths containing ':' so full paths get quoted.
settings.add_filter(
r"'(_(?:REPO|WORKTREE_[A-Z0-9_]+)_(?:\.[a-zA-Z0-9_-]+)?/[^']+)'",
"$1",
);
- // Normalize git diff header prefixes: a/_REPO_ -> a_REPO_, b/_REPO_ -> b_REPO_
- // On Windows, git diff --no-index with absolute paths produces a/C:/... which becomes a/_REPO_
- // On Unix, relative paths produce a/repo/... which becomes a_REPO_
- // Note: [TEMP_HOME] filters are added later, after TEMP_HOME replacement happens.
settings.add_filter(r"(diff --git )a/(_(?:REPO|WORKTREE_[A-Z0-9_]+)_)", "$1a$2");
settings.add_filter(r" b/(_(?:REPO|WORKTREE_[A-Z0-9_]+)_)", " b$1");
settings.add_filter(r"(--- )a/(_(?:REPO|WORKTREE_[A-Z0-9_]+)_)", "$1a$2");
settings.add_filter(r"(\+\+\+ )b/(_(?:REPO|WORKTREE_[A-Z0-9_]+)_)", "$1b$2");
- // Windows git diff may produce headers without "diff --git a" prefix.
- // Pattern: _REPO_/path1 b_REPO_/path2 (just paths with b prefix for second)
- // Match bold ANSI + _REPO_ path + space + b + _REPO_ path
settings.add_filter(
r"(\x1b\[1m)(_(?:REPO|WORKTREE_[A-Z0-9_]+)_/[^\s]+) b(_(?:REPO|WORKTREE_[A-Z0-9_]+)_/[^\s]+)",
"$1diff --git a$2 b$3",
);
- // Windows may have " --git a_REPO_" with leading spaces after ANSI reset (missing "diff" and bold).
- // Match: ANSI reset + one or more spaces + "--git a" pattern
- // Replace with: ANSI reset + space + bold + "diff --git a" to match Unix format
settings.add_filter(
r"(\x1b\[0m) +--git a(_(?:REPO|WORKTREE_[A-Z0-9_]+)_/)",
"$1 \x1b[1mdiff --git a$2",
);
- // Windows may also omit --- a prefix on the source file line
settings.add_filter(r"(--- )(_(?:REPO|WORKTREE_[A-Z0-9_]+)_/)", "$1a$2");
- // Windows may also omit +++ b prefix on the destination file line
settings.add_filter(r"(\+\+\+ )(_(?:REPO|WORKTREE_[A-Z0-9_]+)_/)", "$1b$2");
- // Windows may output bare path for --- line: \x1b[1m_REPO_/...\x1b[m (no "--- a")
- // Add the missing "--- a" prefix.
settings.add_filter(
r"(\x1b\[1m)(_(?:REPO|WORKTREE_[A-Z0-9_]+)_/[^\x1b]+\.toml)(\x1b\[m)",
"$1--- a$2$3",
);
// Normalize syntax highlighting around placeholders.
- // Bash syntax highlighters may split tokens differently on different platforms.
- // Linux CI produces: [2m [0m[2m[32m_REPO_[0m[2m [0m (space, green path, space as separate spans)
- // macOS local produces: [2m _REPO_ [0m (all in one span)
- // The [32m is green color applied to placeholders which the local highlighter doesn't add.
- // Normalize CI format to local format by matching the split pattern and merging.
settings.add_filter(
r"\x1b\[2m \x1b\[0m\x1b\[2m(?:\x1b\[32m)?(_(?:REPO|WORKTREE_[A-Z0-9_]+)_(?:\.[a-zA-Z0-9_-]+)?)(?:\x1b\[0m)?\x1b\[2m \x1b\[0m",
"\x1b[2m $1 \x1b[0m",
);
-
- // Strip green ANSI highlighting from _REPO_ paths.
- // On Windows, tree-sitter may highlight paths with green (\x1b[32m) even when not quoted.
- // Example: \x1b[0m\x1b[2m\x1b[32m_REPO_/.config/wt.toml\x1b[0m\x1b[2m
- // Strip ANSI codes before/after the path when green highlighting is present.
settings.add_filter(
r"(?:\x1b\[\d+m)*\x1b\[32m(_(?:REPO|WORKTREE_[A-Z0-9_]+)_(?:/[^\x1b\s]+)?)(?:\x1b\[\d+m)*",
"$1",
);
+}
- // Normalize WORKTRUNK_CONFIG_PATH temp paths in stdout/stderr output
- // (metadata is handled via redactions below)
- // IMPORTANT: These specific filters must come BEFORE the generic [PROJECT_ID] filters
- // Handles: Unix paths (/tmp/...), Windows paths (C:\...), and shell-escaped quoted paths ('C:\...')
- // Use distinct placeholders for config.toml vs config.toml.new for clarity
+fn add_temp_path_placeholder_filters(settings: &mut insta::Settings) {
settings.add_filter(
r"'?(?:[A-Z]:)?[/\\][^\s']+[/\\]\.tmp[^/\\']+[/\\]test-config\.toml\.new'?",
"[TEST_CONFIG_NEW]",
@@ -2549,196 +2470,158 @@ fn setup_snapshot_settings_for_paths_with_home(
r"'?(?:[A-Z]:)?[/\\][^\s']+[/\\]\.tmp[^/\\']+[/\\]test-config\.toml'?",
"[TEST_CONFIG]",
);
- // Normalize WORKTRUNK_APPROVALS_PATH temp paths in stdout/stderr output
settings.add_filter(
r"'?(?:[A-Z]:)?[/\\][^\s']+[/\\]\.tmp[^/\\']+[/\\]test-approvals\.toml'?",
"[TEST_APPROVALS]",
);
- // Strip ANSI codes that may wrap [TEST_CONFIG*] or [TEST_APPROVALS] placeholders.
- // On Windows, tree-sitter may add ANSI codes around paths even without quotes.
- // Example: \x1b[0m\x1b[2m[TEST_CONFIG_NEW]\x1b[2m
- // Match: optional ANSI codes + [TEST_CONFIG...] + optional ANSI codes -> just the placeholder
settings.add_filter(
r"(?:\x1b\[\d+m)+(\[TEST_(?:CONFIG(?:_NEW)?|APPROVALS)\])(?:\x1b\[\d+m)+",
"$1",
);
-
- // Normalize GIT_CONFIG_GLOBAL temp paths
- // (?:[A-Z]:)? handles Windows drive letters
settings.add_filter(
r"(?:[A-Z]:)?/[^\s]+/\.tmp[^/]+/test-gitconfig",
"[TEST_GIT_CONFIG]",
);
+}
- // TEMP_HOME filter MUST come before PROJECT_ID filters to take precedence.
- // Otherwise, paths like /tmp/.tmpXXX/.config/worktrunk/config.toml would match
- // the PROJECT_ID filter first.
- //
- // We replace the full temp_home path prefix with [TEMP_HOME], so paths like
- // /tmp/.tmpABC/.config/worktrunk/config.toml become [TEMP_HOME]/.config/worktrunk/config.toml
- if let Some(temp_home) = temp_home {
- // Get both the original path and the canonicalized path - they may differ on Windows
- // due to short path names (e.g., RUNNER~1 vs runneradmin) or other normalization.
- let temp_home_original = temp_home.to_string_lossy().replace('\\', "/");
- let temp_home_canonical =
- canonicalize(temp_home).unwrap_or_else(|_| temp_home.to_path_buf());
- let temp_home_str = temp_home_canonical.to_string_lossy().replace('\\', "/");
-
- // On Windows, paths may be quoted by shell_escape due to ':' in drive letters.
- // Add filters for both quoted and unquoted variants, for both original and canonical paths.
- if temp_home_str.contains(':') {
- // Quoted canonical path
+fn add_temp_home_filters(settings: &mut insta::Settings, temp_home: &Path) {
+ // Get both the original path and the canonicalized path - they may differ on Windows
+ // due to short path names (e.g., RUNNER~1 vs runneradmin) or other normalization.
+ let temp_home_original = temp_home.to_string_lossy().replace('\\', "/");
+ let temp_home_canonical = canonicalize(temp_home).unwrap_or_else(|_| temp_home.to_path_buf());
+ let temp_home_str = temp_home_canonical.to_string_lossy().replace('\\', "/");
+
+ if temp_home_str.contains(':') {
+ settings.add_filter(
+ &format!("'{}", regex::escape(&temp_home_str)),
+ "'[TEMP_HOME]",
+ );
+ if temp_home_original != temp_home_str {
settings.add_filter(
- &format!("'{}", regex::escape(&temp_home_str)),
+ &format!("'{}", regex::escape(&temp_home_original)),
"'[TEMP_HOME]",
);
- // Quoted original path (may differ from canonical)
- if temp_home_original != temp_home_str {
- settings.add_filter(
- &format!("'{}", regex::escape(&temp_home_original)),
- "'[TEMP_HOME]",
- );
- }
- }
- // Unquoted canonical path
- settings.add_filter(&regex::escape(&temp_home_str), "[TEMP_HOME]");
- // Unquoted original path (may differ from canonical)
- if temp_home_original != temp_home_str {
- settings.add_filter(&regex::escape(&temp_home_original), "[TEMP_HOME]");
}
+ }
+ settings.add_filter(&regex::escape(&temp_home_str), "[TEMP_HOME]");
+ if temp_home_original != temp_home_str {
+ settings.add_filter(&regex::escape(&temp_home_original), "[TEMP_HOME]");
+ }
- // On macOS, canonicalize returns /private/var/... but git diff output shows /var/...
- // Add both variants to catch all cases
- if temp_home_str.starts_with("/private/") {
- let without_private = &temp_home_str["/private".len()..];
- settings.add_filter(&regex::escape(without_private), "[TEMP_HOME]");
- }
+ if temp_home_str.starts_with("/private/") {
+ let without_private = &temp_home_str["/private".len()..];
+ settings.add_filter(&regex::escape(without_private), "[TEMP_HOME]");
+ }
- // [TEMP_HOME] post-processing filters - must run AFTER the replacement above.
-
- // Strip ANSI sequences immediately before [TEMP_HOME] paths.
- // On Windows, tree-sitter highlights paths with green (\x1b[32m) inside mv commands.
- // The output has: ...code (space) code code [TEMP_HOME]/path code code...
- // We strip ONLY the codes between space and [TEMP_HOME], keeping codes elsewhere.
- // Pattern: (space)(ANSI codes)(optional quote)([TEMP_HOME]) -> (space)(quote)([TEMP_HOME])
- // The optional quote handles Windows where paths may be quoted: 'C:/...'
- settings.add_filter(r"( )(?:\x1b\[[0-9;]*m)+('?)(\[TEMP_HOME\]/)", "$1$2$3");
- // Strip trailing ANSI codes after [TEMP_HOME] paths.
- // Match path followed by one or more ANSI codes.
- settings.add_filter(r"(\[TEMP_HOME\]/[^\x1b\s]+)(?:\x1b\[[0-9;]*m)+", "$1");
-
- // Strip quotes around [TEMP_HOME] paths (Windows shell_escape quotes paths with ':')
- // Also handles git diff quoted format which lacks a/b prefixes.
- settings.add_filter(r"'\[TEMP_HOME\](/[^']+)'", "[TEMP_HOME]$1");
-
- // Normalize git diff header prefixes for [TEMP_HOME]:
- // Unix: a/[TEMP_HOME] -> a[TEMP_HOME], b/[TEMP_HOME] -> b[TEMP_HOME]
- settings.add_filter(r"(diff --git )a/(\[TEMP_HOME\])", "$1a$2");
- settings.add_filter(r" b/(\[TEMP_HOME\])", " b$1");
- settings.add_filter(r"(--- )a/(\[TEMP_HOME\])", "$1a$2");
- settings.add_filter(r"(\+\+\+ )b/(\[TEMP_HOME\])", "$1b$2");
-
- // Windows git diff uses different format for absolute paths.
- // After quote stripping, the diff header may or may not have "diff --git " prefix,
- // and may or may not have a/b prefixes. Normalize to Unix format.
-
- // Pattern 1: Has "diff --git " but no a/b prefixes
- // diff --git [TEMP_HOME]/a [TEMP_HOME]/b -> diff --git a[TEMP_HOME]/a b[TEMP_HOME]/b
- settings.add_filter(
- r"(diff --git )(\[TEMP_HOME\]/[^\s]+) (\[TEMP_HOME\]/)",
- "$1a$2 b$3",
- );
+ settings.add_filter(r"( )(?:\x1b\[[0-9;]*m)+('?)(\[TEMP_HOME\]/)", "$1$2$3");
+ settings.add_filter(r"(\[TEMP_HOME\]/[^\x1b\s]+)(?:\x1b\[[0-9;]*m)+", "$1");
+ settings.add_filter(r"'\[TEMP_HOME\](/[^']+)'", "[TEMP_HOME]$1");
- // Pattern 2: Windows git diff header with only b prefix present.
- // Windows git diff --no-index may produce: path1 bpath2 (without diff --git a)
- // After path replacement: [TEMP_HOME]/a b[TEMP_HOME]/b
- // Add the full header format to match Unix.
- settings.add_filter(
- r"(\x1b\[1m)(\[TEMP_HOME\]/[^\s]+) b(\[TEMP_HOME\]/[^\s]+)",
- "$1diff --git a$2 b$3",
- );
+ settings.add_filter(r"(diff --git )a/(\[TEMP_HOME\])", "$1a$2");
+ settings.add_filter(r" b/(\[TEMP_HOME\])", " b$1");
+ settings.add_filter(r"(--- )a/(\[TEMP_HOME\])", "$1a$2");
+ settings.add_filter(r"(\+\+\+ )b/(\[TEMP_HOME\])", "$1b$2");
- // Pattern 3: Windows may have " --git a[path]" with leading spaces after ANSI (missing "diff" and bold).
- // Match: ANSI reset + one or more spaces + "--git a" pattern
- // Replace with: ANSI reset + space + bold + "diff --git a" to match Unix format
- settings.add_filter(
- r"(\x1b\[0m) +--git a(\[TEMP_HOME\]/)",
- "$1 \x1b[1mdiff --git a$2",
- );
-
- // --- [TEMP_HOME]/... -> --- a[TEMP_HOME]/... (Unix has slash, remove it)
- settings.add_filter(r"(--- )a/(\[TEMP_HOME\]/)", "$1a$2");
- // --- [TEMP_HOME]/... -> --- a[TEMP_HOME]/... (Windows: add missing a prefix)
- settings.add_filter(r"(--- )(\[TEMP_HOME\]/)", "$1a$2");
-
- // +++ [TEMP_HOME]/... -> +++ b[TEMP_HOME]/... (Unix has slash, remove it)
- settings.add_filter(r"(\+\+\+ )b/(\[TEMP_HOME\]/)", "$1b$2");
- // +++ [TEMP_HOME]/... -> +++ b[TEMP_HOME]/... (Windows: add missing b prefix)
- settings.add_filter(r"(\+\+\+ )(\[TEMP_HOME\]/)", "$1b$2");
-
- // Windows git diff may have bare path without --- prefix at all.
- // Match: bold ANSI + bare [TEMP_HOME] path that's NOT preceded by diff/---/+++
- // This catches the case where git outputs just the path on its own line.
- // Look for standalone [TEMP_HOME]/...config.toml (trailing ANSI codes may be stripped).
- // Use negative lookbehind (not supported) - instead match newline + gutter + bold.
- settings.add_filter(
- r"(\x1b\[1m)(\[TEMP_HOME\]/[^\s\x1b]+\.toml)(\x1b\[m|\n|$)",
- "$1--- a$2$3",
- );
- }
+ settings.add_filter(
+ r"(diff --git )(\[TEMP_HOME\]/[^\s]+) (\[TEMP_HOME\]/)",
+ "$1a$2 b$3",
+ );
+ settings.add_filter(
+ r"(\x1b\[1m)(\[TEMP_HOME\]/[^\s]+) b(\[TEMP_HOME\]/[^\s]+)",
+ "$1diff --git a$2 b$3",
+ );
+ settings.add_filter(
+ r"(\x1b\[0m) +--git a(\[TEMP_HOME\]/)",
+ "$1 \x1b[1mdiff --git a$2",
+ );
+ settings.add_filter(r"(--- )a/(\[TEMP_HOME\]/)", "$1a$2");
+ settings.add_filter(r"(--- )(\[TEMP_HOME\]/)", "$1a$2");
+ settings.add_filter(r"(\+\+\+ )b/(\[TEMP_HOME\]/)", "$1b$2");
+ settings.add_filter(r"(\+\+\+ )(\[TEMP_HOME\]/)", "$1b$2");
+ settings.add_filter(
+ r"(\x1b\[1m)(\[TEMP_HOME\]/[^\s\x1b]+\.toml)(\x1b\[m|\n|$)",
+ "$1--- a$2$3",
+ );
+}
- // Normalize temp directory paths in project identifiers (approval prompts)
- // Example: /private/var/folders/wf/.../T/.tmpABC123/origin -> [PROJECT_ID]
- // Note: [^)'\s\x1b]+ stops at ), ', whitespace, or ANSI escape to avoid matching too much
+fn add_project_id_filters(settings: &mut insta::Settings) {
settings.add_filter(
r"/private/var/folders/[^/]+/[^/]+/T/\.[^/]+/[^)'\s\x1b]+",
"[PROJECT_ID]",
);
- // macOS non-canonicalized: /var/folders/.../T/.tmpXXXXXX/path -> [PROJECT_ID]
settings.add_filter(
r"/var/folders/[^/]+/[^/]+/T/\.[^/]+/[^)'\s\x1b]+",
"[PROJECT_ID]",
);
- // macOS nix-shell: /private/tmp/nix-shell.XXX/.tmpYYY/path -> [PROJECT_ID]
settings.add_filter(
r"/private/tmp/(?:[^/]+/)*\.tmp[^/]+/[^)'\s\x1b]+",
"[PROJECT_ID]",
);
- // Linux: /tmp/.tmpXXXXXX/path -> [PROJECT_ID]
- // Also handles nix-shell: /tmp/nix-shell.XXX/.tmpYYY/path
settings.add_filter(r"/tmp/(?:[^/]+/)*\.tmp[^/]+/[^)'\s\x1b]+", "[PROJECT_ID]");
- // Windows: C:/Users/user/AppData/Local/Temp/.tmpXXXXXX/path -> [PROJECT_ID]
- // Handles Windows temp paths with drive letters (after backslash normalization)
settings.add_filter(
r"[A-Z]:/Users/[^/]+/AppData/Local/Temp/\.tmp[^/]+/[^)'\s\x1b]+",
"[PROJECT_ID]",
);
- // Windows quoted paths: shell_escape quotes paths containing ':' (drive letter)
- // Example: 'C:/Users/user/AppData/Local/Temp/.tmpXXXXXX/repo/.config/wt.toml' -> [PROJECT_ID]
settings.add_filter(
r"'[A-Z]:/Users/[^/]+/AppData/Local/Temp/\.tmp[^/]+/[^']+'",
"[PROJECT_ID]",
);
-
- // Generic tilde-prefixed paths that aren't repo or worktree paths.
- // On CI, HOME is a temp directory, so paths under HOME become ~/something.
- // This catches paths like ~/wrong-path that don't follow the repo naming convention.
- // MUST come AFTER specific ~/repo patterns so they match first.
- // Uses _PARENT_ prefix (matching _REPO_ convention) and preserves directory name.
settings.add_filter(r"~/([a-zA-Z0-9_-]+)", "_PARENT_/$1");
-
- // Strip quotes around [PROJECT_ID] after replacement.
- // On Windows, paths inside quotes get replaced but quotes remain: 'C:/...' -> '[PROJECT_ID]'
- // This filter MUST come AFTER PROJECT_ID filters to clean up the result.
settings.add_filter(r"'\[PROJECT_ID\]'", "[PROJECT_ID]");
-
- // Normalize HOME temp directory in snapshots (stdout/stderr content)
- // Matches any temp directory path (without trailing filename)
- // Examples:
- // macOS: HOME: /var/folders/.../T/.tmpXXX
- // Linux: HOME: /tmp/.tmpXXX
- // Windows: HOME: C:\Users\...\Temp\.tmpXXX (after backslash normalization)
settings.add_filter(r"HOME: .*/\.tmp[^/\s]+", "HOME: [TEST_HOME]");
+}
+
+/// Create configured insta Settings for snapshot tests
+///
+/// This extracts the common settings configuration while allowing the
+/// `assert_cmd_snapshot!` macro to remain in test files for correct module path capture.
+pub fn setup_snapshot_settings(repo: &TestRepo) -> insta::Settings {
+ setup_snapshot_settings_impl(repo.root_path(), None)
+}
+
+/// Internal implementation that optionally includes temp_home filter.
+/// The temp_home filter MUST be added before PROJECT_ID filters to take precedence.
+fn setup_snapshot_settings_impl(root: &Path, temp_home: Option<&Path>) -> insta::Settings {
+ let worktrees = HashMap::new(); // Caller doesn't need worktree filters
+ setup_snapshot_settings_for_paths_with_home(root, &worktrees, temp_home)
+}
+
+/// Full snapshot settings - path filters AND ANSI cleanup.
+/// Use this with `settings.bind()` for assert_cmd_snapshot! tests.
+/// Clones current settings (which may already have minimal path filters from TestRepo).
+fn setup_snapshot_settings_for_paths(
+ root: &Path,
+ worktrees: &HashMap<String, PathBuf>,
+) -> insta::Settings {
+ setup_snapshot_settings_for_paths_with_home(root, worktrees, None)
+}
+
+/// Internal implementation with optional temp_home support.
+///
+/// When `temp_home` is provided, we create fresh settings rather than cloning current settings.
+/// This is critical because TestRepo's snapshot guard may have already added PROJECT_ID filters,
+/// and cloning would inherit those filters which would be applied BEFORE our TEMP_HOME filter.
+fn setup_snapshot_settings_for_paths_with_home(
+ root: &Path,
+ worktrees: &HashMap<String, PathBuf>,
+ temp_home: Option<&Path>,
+) -> insta::Settings {
+ // When temp_home is provided, start fresh to ensure TEMP_HOME filter is applied before
+ // any inherited PROJECT_ID filters. Otherwise, clone current settings for consistency.
+ let mut settings = if temp_home.is_some() {
+ insta::Settings::new()
+ } else {
+ insta::Settings::clone_current()
+ };
+ settings.set_snapshot_path("../snapshots");
+ add_snapshot_path_prelude_filters(&mut settings);
+ add_repo_and_worktree_path_filters(&mut settings, root, worktrees);
+ add_placeholder_cleanup_filters(&mut settings);
+ add_temp_path_placeholder_filters(&mut settings);
+ if let Some(temp_home) = temp_home {
+ add_temp_home_filters(&mut settings, temp_home);
+ }
+ add_project_id_filters(&mut settings);
add_standard_env_redactions(&mut settings);
diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rs
index 405a6e283..c106efa72 100644
--- a/tests/integration_tests/shell_wrapper.rs
+++ b/tests/integration_tests/shell_wrapper.rs
@@ -34,13 +34,14 @@
use crate::common::{TestRepo, shell::shell_binary, wt_bin};
use std::process::Command;
+use worktrunk::shell;
+
// Unix-only imports
#[cfg(unix)]
use {
crate::common::{add_pty_filters, canonicalize, wait_for_file_content},
insta::assert_snapshot,
std::{fs, path::PathBuf, sync::LazyLock},
- worktrunk::shell,
};
/// Output from executing a command through a shell wrapper
@@ -182,102 +183,72 @@ fn powershell_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', "''"))
}
-/// Build a shell script that sources the wrapper and runs a command
-fn build_shell_script(shell: &str, repo: &TestRepo, subcommand: &str, args: &[&str]) -> String {
- let wt_bin = wt_bin();
- let wrapper_script = generate_wrapper(repo, shell);
- let mut script = String::new();
+fn wrapper_shell(shell_name: &str) -> shell::Shell {
+ match shell_name {
+ "bash" => shell::Shell::Bash,
+ "fish" => shell::Shell::Fish,
+ "nu" | "nushell" => shell::Shell::Nushell,
+ "zsh" => shell::Shell::Zsh,
+ "powershell" | "pwsh" => shell::Shell::PowerShell,
+ other => panic!("Unsupported shell wrapper test shell: {other}"),
+ }
+}
- // Set environment variables - syntax varies by shell
- // Don't use 'set -e' in bash/zsh - we want to capture failures and their exit codes.
- // This is tested by test_wrapper_handles_command_failure which verifies
- // that command failures return proper exit codes rather than aborting the script.
- // Properly quote paths to handle special characters like single quotes
- let wt_bin_quoted = shell_quote(&wt_bin.display().to_string());
- let config_path_quoted = shell_quote(&repo.test_config_path().display().to_string());
- let approvals_path_quoted = shell_quote(&repo.test_approvals_path().display().to_string());
+fn wrapper_env_vars(shell: shell::Shell, repo: &TestRepo) -> Vec<(&'static str, String)> {
+ let quote = |value: &str| match shell {
+ shell::Shell::PowerShell => powershell_quote(value),
+ _ => shell_quote(value),
+ };
+
+ vec![
+ ("WORKTRUNK_BIN", quote(&wt_bin().display().to_string())),
+ (
+ "WORKTRUNK_CONFIG_PATH",
+ quote(&repo.test_config_path().display().to_string()),
+ ),
+ (
+ "WORKTRUNK_APPROVALS_PATH",
+ quote(&repo.test_approvals_path().display().to_string()),
+ ),
+ (
+ "CLICOLOR_FORCE",
+ match shell {
+ shell::Shell::Nushell | shell::Shell::PowerShell => "'1'".to_string(),
+ _ => "1".to_string(),
+ },
+ ),
+ ]
+}
- match shell {
- "fish" => {
- script.push_str(&format!("set -x WORKTRUNK_BIN {}\n", wt_bin_quoted));
- script.push_str(&format!(
- "set -x WORKTRUNK_CONFIG_PATH {}\n",
- config_path_quoted
- ));
- script.push_str(&format!(
- "set -x WORKTRUNK_APPROVALS_PATH {}\n",
- approvals_path_quoted
- ));
- script.push_str("set -x CLICOLOR_FORCE 1\n");
- }
- "nu" => {
- // Nushell uses $env.VAR syntax for environment variables
- script.push_str(&format!("$env.WORKTRUNK_BIN = {}\n", wt_bin_quoted));
- script.push_str(&format!(
- "$env.WORKTRUNK_CONFIG_PATH = {}\n",
- config_path_quoted
- ));
- script.push_str(&format!(
- "$env.WORKTRUNK_APPROVALS_PATH = {}\n",
- approvals_path_quoted
- ));
- script.push_str("$env.CLICOLOR_FORCE = '1'\n");
- }
- "zsh" => {
- // For zsh, initialize the completion system first
- // This allows static completions (which call compdef) to work in isolated mode
- // We run with --no-rcs to prevent user rc files from touching /dev/tty,
- // but compinit is safe since it only sets up completion functions
- script.push_str("autoload -Uz compinit && compinit -i 2>/dev/null\n");
-
- script.push_str(&format!("export WORKTRUNK_BIN={}\n", wt_bin_quoted));
- script.push_str(&format!(
- "export WORKTRUNK_CONFIG_PATH={}\n",
- config_path_quoted
- ));
- script.push_str(&format!(
- "export WORKTRUNK_APPROVALS_PATH={}\n",
- approvals_path_quoted
- ));
- script.push_str("export CLICOLOR_FORCE=1\n");
- }
- "powershell" | "pwsh" => {
- // PowerShell uses $env: for environment variables
- let wt_bin_ps = powershell_quote(&wt_bin.display().to_string());
- let config_path_ps = powershell_quote(&repo.test_config_path().display().to_string());
- let approvals_path_ps =
- powershell_quote(&repo.test_approvals_path().display().to_string());
- script.push_str(&format!("$env:WORKTRUNK_BIN = {}\n", wt_bin_ps));
- script.push_str(&format!(
- "$env:WORKTRUNK_CONFIG_PATH = {}\n",
- config_path_ps
- ));
- script.push_str(&format!(
- "$env:WORKTRUNK_APPROVALS_PATH = {}\n",
- approvals_path_ps
- ));
- script.push_str("$env:CLICOLOR_FORCE = '1'\n");
- }
- _ => {
- // bash
- script.push_str(&format!("export WORKTRUNK_BIN={}\n", wt_bin_quoted));
- script.push_str(&format!(
- "export WORKTRUNK_CONFIG_PATH={}\n",
- config_path_quoted
- ));
- script.push_str(&format!(
- "export WORKTRUNK_APPROVALS_PATH={}\n",
- approvals_path_quoted
- ));
- script.push_str("export CLICOLOR_FORCE=1\n");
+fn append_shell_env_exports(script: &mut String, shell: shell::Shell, vars: &[(&str, String)]) {
+ if matches!(shell, shell::Shell::Zsh) {
+ script.push_str("autoload -Uz compinit && compinit -i 2>/dev/null\n");
+ }
+
+ for (key, value) in vars {
+ match shell {
+ shell::Shell::Fish => script.push_str(&format!("set -x {key} {value}\n")),
+ shell::Shell::Nushell => script.push_str(&format!("$env.{key} = {value}\n")),
+ shell::Shell::PowerShell => script.push_str(&format!("$env:{key} = {value}\n")),
+ shell::Shell::Bash | shell::Shell::Zsh => {
+ script.push_str(&format!("export {key}={value}\n"))
+ }
}
}
+}
- // Include the shell wrapper code
- // For PowerShell: The wrapper_script is PowerShell code included inline
- // For bash/zsh/fish: The wrapper is shell code sourced via eval
- script.push_str(&wrapper_script);
+fn append_wrapper_setup(script: &mut String, shell_name: &str, repo: &TestRepo) {
+ let shell = wrapper_shell(shell_name);
+ let env_vars = wrapper_env_vars(shell, repo);
+ append_shell_env_exports(script, shell, &env_vars);
+ script.push_str(&generate_wrapper(repo, shell_name));
script.push('\n');
+}
+
+/// Build a shell script that sources the wrapper and runs a command
+fn build_shell_script(shell: &str, repo: &TestRepo, subcommand: &str, args: &[&str]) -> String {
+ let mut script = String::new();
+ append_wrapper_setup(&mut script, shell, repo);
// Build the command
script.push_str("wt ");
@@ -1590,49 +1561,8 @@ approved-commands = ["echo 'fish background task'"]
let worktrunk_source = canonicalize(&env::current_dir().unwrap()).unwrap();
// Build a shell script that runs from the worktrunk source directory
- let wt_bin = wt_bin();
- let wrapper_script = generate_wrapper(&repo, shell);
let mut script = String::new();
-
- // Set environment variables (use shell_quote to handle paths with special chars)
- let wt_bin_quoted = shell_quote(&wt_bin.display().to_string());
- let config_quoted = shell_quote(&repo.test_config_path().display().to_string());
- let approvals_quoted = shell_quote(&repo.test_approvals_path().display().to_string());
- match shell {
- "fish" => {
- script.push_str(&format!("set -x WORKTRUNK_BIN {}\n", wt_bin_quoted));
- script.push_str(&format!("set -x WORKTRUNK_CONFIG_PATH {}\n", config_quoted));
- script.push_str(&format!(
- "set -x WORKTRUNK_APPROVALS_PATH {}\n",
- approvals_quoted
- ));
- script.push_str("set -x CLICOLOR_FORCE 1\n");
- }
- "zsh" => {
- script.push_str("autoload -Uz compinit && compinit -i 2>/dev/null\n");
- script.push_str(&format!("export WORKTRUNK_BIN={}\n", wt_bin_quoted));
- script.push_str(&format!("export WORKTRUNK_CONFIG_PATH={}\n", config_quoted));
- script.push_str(&format!(
- "export WORKTRUNK_APPROVALS_PATH={}\n",
- approvals_quoted
- ));
- script.push_str("export CLICOLOR_FORCE=1\n");
- }
- _ => {
- // bash
- script.push_str(&format!("export WORKTRUNK_BIN={}\n", wt_bin_quoted));
- script.push_str(&format!("export WORKTRUNK_CONFIG_PATH={}\n", config_quoted));
- script.push_str(&format!(
- "export WORKTRUNK_APPROVALS_PATH={}\n",
- approvals_quoted
- ));
- script.push_str("export CLICOLOR_FORCE=1\n");
- }
- }
-
- // Source the wrapper
- script.push_str(&wrapper_script);
- script.push('\n');
+ append_wrapper_setup(&mut script, shell, &repo);
// Try to run wt --source with an invalid subcommand
// The --source flag triggers cargo build (which succeeds)
@@ -1776,19 +1706,8 @@ approved-commands = ["echo 'bash background'"]
);
// Build the setup script that defines the wt function
- let wt_bin = wt_bin();
- let wrapper_script = generate_wrapper(&repo, "bash");
- let wt_bin_quoted = shell_quote(&wt_bin.display().to_string());
- let config_quoted = shell_quote(&repo.test_config_path().display().to_string());
- let approvals_quoted = shell_quote(&repo.test_approvals_path().display().to_string());
- let setup_script = format!(
- "export WORKTRUNK_BIN={}\n\
- export WORKTRUNK_CONFIG_PATH={}\n\
- export WORKTRUNK_APPROVALS_PATH={}\n\
- export CLICOLOR_FORCE=1\n\
- {}",
- wt_bin_quoted, config_quoted, approvals_quoted, wrapper_script
- );
+ let mut setup_script = String::new();
+ append_wrapper_setup(&mut setup_script, "bash", &repo);
let config_path = repo.test_config_path().to_string_lossy().to_string();
let approvals_path = repo.test_approvals_path().to_string_lossy().to_string();
@@ -1839,9 +1758,6 @@ approved-commands = ["echo 'bash background'"]
/// Note: Completions are inline in the wrapper script (lazy loading)
#[rstest]
fn test_bash_completions_registered(repo: TestRepo) {
- let wt_bin = wt_bin();
- let wrapper_script = generate_wrapper(&repo, "bash");
-
// Use a marker file to avoid PTY output race conditions.
// PTY buffer flushing is unreliable on CI, so we write to a file and poll for it.
let marker_file = repo.root_path().join(".completions_test_marker");
@@ -1849,16 +1765,11 @@ approved-commands = ["echo 'bash background'"]
// Script that sources wrapper and checks if completion is registered
// (completions are inline in the wrapper via lazy loading)
- let wt_bin_quoted = shell_quote(&wt_bin.display().to_string());
- let config_quoted = shell_quote(&repo.test_config_path().display().to_string());
- let approvals_quoted = shell_quote(&repo.test_approvals_path().display().to_string());
let marker_quoted = shell_quote(&marker_path);
- let script = format!(
+ let mut script = String::new();
+ append_wrapper_setup(&mut script, "bash", &repo);
+ script.push_str(&format!(
r#"
- export WORKTRUNK_BIN={}
- export WORKTRUNK_CONFIG_PATH={}
- export WORKTRUNK_APPROVALS_PATH={}
- {}
# Check if wt completion is registered and write result to marker file
if complete -p wt 2>/dev/null; then
echo "__COMPLETION_REGISTERED__" > {}
@@ -1866,13 +1777,8 @@ approved-commands = ["echo 'bash background'"]
echo "__NO_COMPLETION__" > {}
fi
"#,
- wt_bin_quoted,
- config_quoted,
- approvals_quoted,
- wrapper_script,
- marker_quoted,
- marker_quoted,
- );
+ marker_quoted, marker_quoted,
+ ));
let final_script = format!("( {} ) 2>&1", script);
let config_path = repo.test_config_path().to_string_lossy().to_string();
@@ -1901,8 +1807,6 @@ approved-commands = ["echo 'bash background'"]
/// Test that fish completions are properly registered
#[rstest]
fn test_fish_completions_registered(repo: TestRepo) {
- let wt_bin = wt_bin();
- let wrapper_script = generate_wrapper(&repo, "fish");
let completions_script = generate_completions(&repo, "fish");
// Use a marker file to avoid PTY output race conditions.
@@ -1911,17 +1815,12 @@ approved-commands = ["echo 'bash background'"]
let marker_path = marker_file.to_string_lossy().to_string();
// Script that sources wrapper, completions, and checks if completion is registered
- let wt_bin_quoted = shell_quote(&wt_bin.display().to_string());
- let config_quoted = shell_quote(&repo.test_config_path().display().to_string());
- let approvals_quoted = shell_quote(&repo.test_approvals_path().display().to_string());
let marker_quoted = shell_quote(&marker_path);
- let script = format!(
+ let mut script = String::new();
+ append_wrapper_setup(&mut script, "fish", &repo);
+ script.push_str(&completions_script);
+ script.push_str(&format!(
r#"
- set -x WORKTRUNK_BIN {}
- set -x WORKTRUNK_CONFIG_PATH {}
- set -x WORKTRUNK_APPROVALS_PATH {}
- {}
- {}
# Check if wt completions are registered and write result to marker file
if complete -c wt 2>/dev/null | grep -q .
echo "__COMPLETION_REGISTERED__" > {}
@@ -1929,14 +1828,8 @@ approved-commands = ["echo 'bash background'"]
echo "__NO_COMPLETION__" > {}
end
"#,
- wt_bin_quoted,
- config_quoted,
- approvals_quoted,
- wrapper_script,
- completions_script,
- marker_quoted,
- marker_quoted,
- );
+ marker_quoted, marker_quoted,
+ ));
let final_script = format!("begin\n{}\nend 2>&1", script);
let config_path = repo.test_config_path().to_string_lossy().to_string();