Skip to content

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

refactor: collapse duplicated code paths onto single sources (#2932)

Maximilian Roosfe530718fcbe
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 35c1af8b8..5f4758a68 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -54,19 +54,6 @@ impl PreparedStep {
}
}
-/// Per-step announcement policy — replaces the per-command match on origin.
-///
-/// Hook steps render a per-command `Running {type} {label} @ {path}` line plus
-/// the bash gutter. Alias steps suppress per-command rendering because the
-/// caller emits a single summary line for the whole pipeline.
-pub enum AnnouncePolicy {
- Hook {
- hook_type: HookType,
- display_path: Option<PathBuf>,
- },
- None,
-}
-
/// Wraps a command failure (FailFast path) into the final error.
///
/// Receives the failing command, the message extracted from the inner error,
@@ -105,8 +92,11 @@ pub struct ForegroundStep {
/// Whether `Concurrent` steps actually run concurrently. When `false`,
/// concurrent commands execute serially (deprecated pre-* table form).
pub concurrent: bool,
- /// How to announce each command before execution.
- pub announce: AnnouncePolicy,
+ /// Which pipeline this step belongs to. Drives how each command is
+ /// announced before execution: hooks render a per-command "Running …"
+ /// line plus the bash gutter; aliases stay silent (the caller emits one
+ /// pipeline summary line).
+ pub announce: PipelineKind,
/// Pipe `context_json` to the child's stdin (hooks); when `false`, inherit
/// the parent's stdin so interactive children keep the controlling tty
/// (aliases).
@@ -464,7 +454,7 @@ pub fn execute_pipeline_foreground(
/// Run every command in a concurrent group via the prefixed-line executor.
///
-/// Announces each command up front (per the step's `AnnouncePolicy` — hooks
+/// Announces each command up front (per the step's `PipelineKind` — hooks
/// render per-command announcements, aliases only announce the outer group),
/// expands all templates sequentially (template expansion reads git config;
/// racing on reads would produce inconsistent state), then dispatches to
@@ -573,16 +563,16 @@ fn run_one_command(
}
}
-/// Announce a command before execution, formatted per the step's policy.
+/// Announce a command before execution, formatted per the step's pipeline kind.
///
-/// Hook policies emit a per-command "Running …" line plus the bash gutter.
-/// Alias policies (`AnnouncePolicy::None`) emit nothing — the alias caller
-/// renders a single pipeline summary externally.
-fn announce_command(cmd: &PreparedCommand, policy: &AnnouncePolicy) {
- let AnnouncePolicy::Hook {
+/// Hook pipelines emit a per-command "Running …" line plus the bash gutter.
+/// Alias pipelines emit nothing — the alias caller renders a single pipeline
+/// summary externally.
+fn announce_command(cmd: &PreparedCommand, kind: &PipelineKind) {
+ let PipelineKind::Hook {
hook_type,
display_path,
- } = policy
+ } = kind
else {
return;
};
diff --git a/src/commands/hook_plan.rs b/src/commands/hook_plan.rs
index 9070a6a3e..1d5df3b69 100644
--- a/src/commands/hook_plan.rs
+++ b/src/commands/hook_plan.rs
@@ -89,33 +89,40 @@ pub struct HookPlan {
/// `add` is the only place `load_project_config()`'s result feeds command
/// selection for the covered hook types — `pub(crate)` and called only from
/// command gates.
-pub struct HookPlanBuilder {
+pub struct HookPlanBuilder<'a> {
entries: Vec<PlanEntry>,
+ project_config: Option<&'a ProjectConfig>,
+ user: &'a UserConfig,
+ project_id: Option<&'a str>,
}
-impl HookPlanBuilder {
- pub fn new() -> Self {
+impl<'a> HookPlanBuilder<'a> {
+ /// The gate resolves the selection context once: `project_config` (the
+ /// gate's snapshot) plus `user` config supply every `add`'s command lookup,
+ /// and `project_id` scopes the user-config hooks. Every covered hook selects
+ /// from the invoking worktree's config — the same context — so `add` only
+ /// names the anchor and the hook types.
+ pub fn new(
+ project_config: Option<&'a ProjectConfig>,
+ user: &'a UserConfig,
+ project_id: Option<&'a str>,
+ ) -> Self {
Self {
entries: Vec::new(),
+ project_config,
+ user,
+ project_id,
}
}
- /// Select `hook_types` anchored at `anchor`, from the already-resolved
- /// `project_config` (the gate snapshots it) plus user config.
- ///
- /// `project_id` scopes the user-config hook lookup. Source identity is
- /// preserved so source-scoped behavior survives into execution.
- pub fn add(
- &mut self,
- anchor: &Path,
- hook_types: &[HookType],
- project_config: Option<&ProjectConfig>,
- user: &UserConfig,
- project_id: Option<&str>,
- ) -> &mut Self {
- let user_hooks = user.hooks(project_id);
+ /// Select `hook_types` anchored at `anchor` from the builder's resolved
+ /// config context. Source identity is preserved so source-scoped behavior
+ /// survives into execution.
+ pub fn add(&mut self, anchor: &Path, hook_types: &[HookType]) -> &mut Self {
+ let user_hooks = self.user.hooks(self.project_id);
for &hook_type in hook_types {
- let (user_cfg, proj_cfg) = lookup_hook_configs(&user_hooks, project_config, hook_type);
+ let (user_cfg, proj_cfg) =
+ lookup_hook_configs(&user_hooks, self.project_config, hook_type);
let mut selection: Selection = Vec::new();
if let Some(cfg) = user_cfg {
selection.push((HookSource::User, cfg.clone()));
@@ -157,12 +164,6 @@ impl HookPlanBuilder {
}
}
-impl Default for HookPlanBuilder {
- fn default() -> Self {
- Self::new()
- }
-}
-
impl HookPlan {
/// The project-source templates the prompt must show, deduped by template
/// so the same command across several anchors prompts once (the common
@@ -432,14 +433,8 @@ mod tests {
let user = UserConfig::default();
let gate_cfg = project_cfg(r#"post-merge = "echo approved""#);
- let mut builder = HookPlanBuilder::new();
- builder.add(
- Path::new("/dest"),
- &[HookType::PostMerge],
- Some(&gate_cfg),
- &user,
- None,
- );
+ let mut builder = HookPlanBuilder::new(Some(&gate_cfg), &user, None);
+ builder.add(Path::new("/dest"), &[HookType::PostMerge]);
// `--yes` ⇒ approved without writing approvals.
let plan = builder
.finish()
@@ -476,14 +471,8 @@ mod tests {
};
let proj = project_cfg(r#"pre-remove = "echo project-hook""#);
- let mut builder = HookPlanBuilder::new();
- builder.add(
- Path::new("/wt"),
- &[HookType::PreRemove],
- Some(&proj),
- &user,
- None,
- );
+ let mut builder = HookPlanBuilder::new(Some(&proj), &user, None);
+ builder.add(Path::new("/wt"), &[HookType::PreRemove]);
let plan = builder
.finish()
// Empty approvals ⇒ the project pipeline is unapproved.
@@ -509,14 +498,8 @@ mod tests {
&approvals_path,
)
.unwrap();
- let mut builder = HookPlanBuilder::new();
- builder.add(
- Path::new("/wt"),
- &[HookType::PreRemove],
- Some(&proj),
- &user,
- None,
- );
+ let mut builder = HookPlanBuilder::new(Some(&proj), &user, None);
+ builder.add(Path::new("/wt"), &[HookType::PreRemove]);
let plan = builder.finish().approve_readonly(&approvals, Some("proj"));
let sel = plan.lookup(HookType::PreRemove, Path::new("/wt"));
assert_eq!(
@@ -537,22 +520,10 @@ mod tests {
};
let proj = project_cfg(r#"post-merge = "echo p""#);
- let mut builder = HookPlanBuilder::new();
+ let mut builder = HookPlanBuilder::new(Some(&proj), &user, None);
// Same (PostMerge, /dest) added twice — the interleave-prone path.
- builder.add(
- Path::new("/dest"),
- &[HookType::PostMerge],
- Some(&proj),
- &user,
- None,
- );
- builder.add(
- Path::new("/dest"),
- &[HookType::PostMerge],
- Some(&proj),
- &user,
- None,
- );
+ builder.add(Path::new("/dest"), &[HookType::PostMerge]);
+ builder.add(Path::new("/dest"), &[HookType::PostMerge]);
let plan = builder
.finish()
.approve(Some("proj"), true)
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index b539c5e1f..2bedf0e62 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -76,9 +76,8 @@ use worktrunk::styling::{
};
use super::command_executor::{
- AnnouncePolicy, CommandContext, FailureStrategy, ForegroundStep, PipelineKind, PreparedCommand,
- PreparedStep, alias_error_wrapper, execute_pipeline_foreground, hook_error_wrapper,
- prepare_steps,
+ CommandContext, FailureStrategy, ForegroundStep, PipelineKind, PreparedCommand, PreparedStep,
+ alias_error_wrapper, execute_pipeline_foreground, hook_error_wrapper, prepare_steps,
};
use super::hook_announcement::{SourcedStep, format_pipeline_summary};
use crate::commands::process::{HookLog, spawn_detached_exec};
@@ -709,30 +708,16 @@ pub(crate) fn sourced_steps_to_foreground(
}
_ => DirectivePassthrough::inherit_from_env(),
};
- let (announce, pipe_stdin, redirect_stdout_to_stderr, error_wrapper) = match kind {
- PipelineKind::Hook {
- hook_type,
- display_path,
- } => (
- AnnouncePolicy::Hook {
- hook_type: *hook_type,
- display_path: display_path.clone(),
- },
- true,
- true,
- hook_error_wrapper(*hook_type),
- ),
- PipelineKind::Alias { name } => (
- AnnouncePolicy::None,
- false,
- false,
- alias_error_wrapper(name.clone()),
- ),
+ let (pipe_stdin, redirect_stdout_to_stderr, error_wrapper) = match kind {
+ PipelineKind::Hook { hook_type, .. } => {
+ (true, true, hook_error_wrapper(*hook_type))
+ }
+ PipelineKind::Alias { name } => (false, false, alias_error_wrapper(name.clone())),
};
ForegroundStep {
step: sourced.step,
concurrent: sourced.is_pipeline,
- announce,
+ announce: kind.clone(),
pipe_stdin,
redirect_stdout_to_stderr,
error_wrapper,
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index bd17e053f..bc38e2641 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -1041,21 +1041,13 @@ pub fn collect(
// Calculate layout from items (worktrees, local branches, and remote branches).
// The picker passes an explicit width because the list only gets part of the
// terminal — the rest belongs to the preview pane.
- let layout = match list_width {
- Some(width) => super::layout::calculate_layout_with_width(
- &all_items,
- &effective_skip_tasks,
- width,
- &main_worktree.path,
- url_template.as_deref(),
- ),
- None => super::layout::calculate_layout_from_basics(
- &all_items,
- &effective_skip_tasks,
- &main_worktree.path,
- url_template.as_deref(),
- ),
- };
+ let layout = super::layout::calculate_layout_with_width(
+ &all_items,
+ &effective_skip_tasks,
+ list_width.unwrap_or_else(crate::display::terminal_width),
+ &main_worktree.path,
+ url_template.as_deref(),
+ );
// Single-line invariant: use safe width to prevent line wrapping
let max_width = crate::display::terminal_width();
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index ad5016e9f..102f9e404 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -192,7 +192,7 @@ use anstyle::Style;
use unicode_width::UnicodeWidthStr;
use worktrunk::styling::{ADDITION, DELETION, Stream, supports_hyperlinks};
-use crate::display::{shorten_path, terminal_width};
+use crate::display::shorten_path;
use super::collect::{TaskKind, parse_port_from_url};
use super::columns::{COLUMN_SPECS, ColumnKind, ColumnSpec, column_display_index};
@@ -648,7 +648,7 @@ fn build_estimated_widths(
/// Allocate columns using priority-based allocation logic.
///
-/// This is the core allocation algorithm used by `calculate_layout_from_basics()`
+/// This is the core allocation algorithm used by `calculate_layout_with_width()`
/// with pre-allocated width estimates for expensive-to-compute columns.
fn allocate_columns_with_priority(
metadata: &LayoutMetadata,
@@ -880,7 +880,10 @@ fn allocate_columns_with_priority(
}
}
-/// Calculate responsive layout from basic worktree info.
+/// Calculate responsive layout for an explicit terminal width.
+///
+/// (Contexts like skim pass a width smaller than the full terminal because the
+/// list only gets part of it; the rest belongs to the preview pane.)
///
/// Uses pre-allocated width estimates for expensive-to-compute columns (status, diffs, time, CI).
/// This is faster than scanning all data and provides consistent layout between buffered and
@@ -900,22 +903,6 @@ fn allocate_columns_with_priority(
/// - CI: 1 char (indicator symbol)
/// - Message: flexible (20-100 chars)
/// - URL: estimated from template + longest branch
-pub fn calculate_layout_from_basics(
- items: &[super::model::ListItem],
- skip_tasks: &HashSet<TaskKind>,
- main_worktree_path: &Path,
- url_template: Option<&str>,
-) -> LayoutConfig {
- calculate_layout_with_width(
- items,
- skip_tasks,
- terminal_width(),
- main_worktree_path,
- url_template,
- )
-}
-
-/// Calculate layout with explicit width (for contexts like skim where available width differs)
pub fn calculate_layout_with_width(
items: &[super::model::ListItem],
skip_tasks: &HashSet<TaskKind>,
@@ -974,6 +961,7 @@ pub fn calculate_layout_with_width(
#[cfg(test)]
mod tests {
use super::*;
+ use crate::display::terminal_width;
use worktrunk::git::LineDiff;
#[test]
@@ -1353,7 +1341,13 @@ mod tests {
.into_iter()
.collect();
let main_worktree_path = PathBuf::from("/test");
- let layout = calculate_layout_from_basics(&items, &skip_tasks, &main_worktree_path, None);
+ let layout = calculate_layout_with_width(
+ &items,
+ &skip_tasks,
+ terminal_width(),
+ &main_worktree_path,
+ None,
+ );
assert!(
!layout.columns.is_empty(),
@@ -1458,7 +1452,13 @@ mod tests {
.into_iter()
.collect();
let main_worktree_path = PathBuf::from("/home/user/project");
- let layout = calculate_layout_from_basics(&items, &skip_tasks, &main_worktree_path, None);
+ let layout = calculate_layout_with_width(
+ &items,
+ &skip_tasks,
+ terminal_width(),
+ &main_worktree_path,
+ None,
+ );
assert!(
layout
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 33ea65def..700e43560 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -107,6 +107,12 @@ fn approve_merge_plan(
) -> anyhow::Result<Option<ApprovedHookPlan>> {
let pid = Some(project_id);
+ // `--no-hooks` (`!verify`) selects no hook, so the gate skips the config
+ // read entirely.
+ if !verify {
+ return Ok(Some(ApprovedHookPlan::empty()));
+ }
+
// Every feature-worktree hook shares one anchor: the feature worktree's
// canonical root, the exact path `finish_after_merge` records as
// `RemoveResult::worktree_path` and `handle_merge` passes as the
@@ -116,51 +122,25 @@ fn approve_merge_plan(
// looked up.
let mut feature_hooks = Vec::new();
let will_create_commit = repo.current_worktree().is_dirty()? || squash_enabled;
- if commit && verify && will_create_commit {
+ if commit && will_create_commit {
feature_hooks.push(HookType::PreCommit);
feature_hooks.push(HookType::PostCommit);
}
- if verify {
- feature_hooks.push(HookType::PreMerge);
- }
- if verify && will_remove {
+ feature_hooks.push(HookType::PreMerge);
+ if will_remove {
feature_hooks.push(HookType::PreRemove);
feature_hooks.push(HookType::PostRemove);
}
- // Every merge hook resolves against the invoking worktree's
- // `.config/wt.toml` — the feature worktree `wt merge` ran in. Read once,
- // inside the `verify` gate: `--no-hooks` selects no hook, so the gate needs
- // no config.
- let mut builder = HookPlanBuilder::new();
- if verify {
- let project_config = repo.load_project_config()?;
- builder.add(
- feature_root,
- &feature_hooks,
- project_config.as_ref(),
- config,
- pid,
- );
- // `post-merge` runs in the destination, and `post-switch` lands the
- // user there (the feature worktree is removed) — both still selected
- // from the invoking worktree's config.
- builder.add(
- destination_path,
- &[HookType::PostMerge],
- project_config.as_ref(),
- config,
- pid,
- );
- if will_remove {
- builder.add(
- destination_path,
- &[HookType::PostSwitch],
- project_config.as_ref(),
- config,
- pid,
- );
- }
+ let project_config = repo.load_project_config()?;
+ let mut builder = HookPlanBuilder::new(project_config.as_ref(), config, pid);
+ builder.add(feature_root, &feature_hooks);
+ // `post-merge` runs in the destination, and `post-switch` lands the user
+ // there (the feature worktree is removed) — both still selected from the
+ // invoking worktree's config.
+ builder.add(destination_path, &[HookType::PostMerge]);
+ if will_remove {
+ builder.add(destination_path, &[HookType::PostSwitch]);
}
builder.finish().approve(pid, yes)
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 183304efa..8449ebeea 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -439,21 +439,9 @@ fn approved_removal_plan(
let user = repo.user_config();
let project_config = repo.load_project_config()?;
- let mut builder = HookPlanBuilder::new();
- builder.add(
- worktree_path,
- &[HookType::PreRemove, HookType::PostRemove],
- project_config.as_ref(),
- user,
- pid,
- );
- builder.add(
- main_path,
- &[HookType::PostSwitch],
- project_config.as_ref(),
- user,
- pid,
- );
+ let mut builder = HookPlanBuilder::new(project_config.as_ref(), user, pid);
+ builder.add(worktree_path, &[HookType::PreRemove, HookType::PostRemove]);
+ builder.add(main_path, &[HookType::PostSwitch]);
Ok(builder.finish().approve_readonly(approvals, pid))
}
diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rs
index 2f04a3c22..46708680b 100644
--- a/src/commands/step/prune.rs
+++ b/src/commands/step/prune.rs
@@ -604,20 +604,14 @@ fn build_pessimistic_plan(
user_config: &UserConfig,
project_id: Option<&str>,
) -> anyhow::Result<HookPlan> {
- let mut builder = HookPlanBuilder::new();
+ let mut builder = HookPlanBuilder::new(project_config, user_config, project_id);
let mut has_current = false;
for item in check_items {
let CheckSource::Linked { wt_idx } = &item.source else {
continue;
};
let wt = &worktrees[*wt_idx];
- builder.add(
- &wt.path,
- &[HookType::PreRemove, HookType::PostRemove],
- project_config,
- user_config,
- project_id,
- );
+ builder.add(&wt.path, &[HookType::PreRemove, HookType::PostRemove]);
let wt_path = dunce::canonicalize(&wt.path).unwrap_or_else(|_| wt.path.clone());
if wt_path == *current_root {
has_current = true;
@@ -625,13 +619,7 @@ fn build_pessimistic_plan(
}
if has_current {
let primary = repo.home_path()?;
- builder.add(
- &primary,
- &[HookType::PostSwitch],
- project_config,
- user_config,
- project_id,
- );
+ builder.add(&primary, &[HookType::PostSwitch]);
}
Ok(builder.finish())
}
@@ -650,8 +638,8 @@ fn unapproved_for_hook(
let Ok(home) = repo.home_path() else {
return Vec::new();
};
- let mut b = HookPlanBuilder::new();
- b.add(&home, &[hook_type], project_config, user_config, project_id);
+ let mut b = HookPlanBuilder::new(project_config, user_config, project_id);
+ b.add(&home, &[hook_type]);
b.finish()
.unapproved_project_commands(approvals, project_id)
}
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 85542de6f..37e97f7dc 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -1404,13 +1404,10 @@ fn approve_switch_hooks(
let project_id = repo.project_identifier().ok();
let pid = project_id.as_deref();
let project_config = repo.load_project_config()?;
- let mut builder = HookPlanBuilder::new();
+ let mut builder = HookPlanBuilder::new(project_config.as_ref(), config, pid);
builder.add(
plan.worktree_path(),
switch_post_hook_types(plan.is_create()),
- project_config.as_ref(),
- config,
- pid,
);
match builder.finish().approve(pid, yes)? {
Some(approved) => Ok((true, approved)),
diff --git a/src/git/error.rs b/src/git/error.rs
index 83c1229df..b09f12ad9 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -1208,73 +1208,57 @@ impl GitError {
}
GitError::RefCreateConflict {
- ref_type,
- number,
- branch,
+ ref_type, number, ..
} => {
- let name = ref_type.name();
let syntax = ref_type.syntax();
+ let title = self.title();
write!(
f,
"{}\n{}",
- error_message(cformat!(
- "Cannot create branch for <bold>{syntax}{number}</> — {name} already has branch <bold>{branch}</>"
- )),
+ error_message(&title),
hint_message(cformat!(
"To switch to the existing branch, run <underline>wt switch {syntax}{number}</>"
))
)
}
- GitError::RefBaseConflict { ref_type, number } => {
- let syntax = ref_type.syntax();
+ GitError::RefBaseConflict { ref_type, .. } => {
let name_plural = ref_type.name_plural();
+ let title = self.title();
write!(
f,
"{}\n{}",
- error_message(cformat!(
- "Cannot use <bold>--base</> with <bold>{syntax}{number}</>"
- )),
+ error_message(&title),
hint_message(cformat!(
"{name_plural} already have a base; remove <underline>--base</>"
))
)
}
- GitError::BranchTracksDifferentRef {
- branch,
- ref_type,
- number,
- } => {
+ GitError::BranchTracksDifferentRef { branch, .. } => {
// The ref's branch name conflicts with an existing local branch.
// We can't use a different local name because git push requires
// the local and remote branch names to match (with push.default=current).
let escaped = escape(Cow::Borrowed(branch.as_str()));
let old_name = format!("{branch}-old");
let escaped_old = escape(Cow::Borrowed(&old_name));
- let name = ref_type.name();
- let symbol = ref_type.symbol();
+ let title = self.title();
write!(
f,
"{}\n{}",
- error_message(cformat!(
- "Branch <bold>{branch}</> exists but doesn't track {name} {symbol}{number}"
- )),
+ error_message(&title),
hint_message(cformat!(
"To free the name, run <underline>git branch -m -- {escaped} {escaped_old}</>"
))
)
}
- GitError::NoRemoteForRepo {
- owner,
- repo,
- suggested_url,
- } => {
+ GitError::NoRemoteForRepo { suggested_url, .. } => {
+ let title = self.title();
write!(
f,
"{}\n{}",
- error_message(cformat!("No remote found for <bold>{owner}/{repo}</>")),
+ error_message(&title),
hint_message(cformat!(
"Add the remote: <underline>git remote add upstream {suggested_url}</>"
))
diff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rs
index aa85c09e0..56595366d 100644
--- a/src/git/repository/remotes.rs
+++ b/src/git/repository/remotes.rs
@@ -186,22 +186,26 @@ impl Repository {
owner: &str,
repo: &str,
) -> Option<String> {
- let matches = |url: &str| -> bool {
- let Some(parsed) = GitRemoteUrl::parse(url) else {
- return false;
- };
+ self.find_remote(|parsed| {
parsed.owner().eq_ignore_ascii_case(owner)
&& parsed.repo().eq_ignore_ascii_case(repo)
&& host.is_none_or(|h| parsed.host().eq_ignore_ascii_case(h))
- };
+ })
+ }
+ /// Return the first remote whose URL (raw or `insteadOf`-effective) parses
+ /// and satisfies `matches`. Each remote is checked against its raw URL and,
+ /// when it differs, its effective URL — so a custom hostname rewritten to a
+ /// real forge still matches.
+ fn find_remote(&self, matches: impl Fn(&GitRemoteUrl) -> bool) -> Option<String> {
+ let test = |url: &str| GitRemoteUrl::parse(url).is_some_and(|parsed| matches(&parsed));
for (remote_name, raw_url) in self.all_remote_urls() {
- if matches(&raw_url) {
+ if test(&raw_url) {
return Some(remote_name);
}
if let Some(effective_url) = self.effective_remote_url(&remote_name)
&& effective_url != raw_url
- && matches(&effective_url)
+ && test(&effective_url)
{
return Some(remote_name);
}
@@ -224,10 +228,7 @@ impl Repository {
project: &str,
repo_name: &str,
) -> Option<String> {
- let matches = |url: &str| -> bool {
- let Some(parsed) = GitRemoteUrl::parse(url) else {
- return false;
- };
+ self.find_remote(|parsed| {
parsed
.azure_organization()
.is_some_and(|o| o.eq_ignore_ascii_case(organization))
@@ -235,21 +236,7 @@ impl Repository {
.azure_project()
.is_some_and(|p| p.eq_ignore_ascii_case(project))
&& parsed.repo().eq_ignore_ascii_case(repo_name)
- };
-
- for (remote_name, raw_url) in self.all_remote_urls() {
- if matches(&raw_url) {
- return Some(remote_name);
- }
- if let Some(effective_url) = self.effective_remote_url(&remote_name)
- && effective_url != raw_url
- && matches(&effective_url)
- {
- return Some(remote_name);
- }
- }
-
- None
+ })
}
/// Find a remote that points to the same project as the given URL.
diff --git a/src/main.rs b/src/main.rs
index 6fc82a6e7..67eaec339 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -930,28 +930,16 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
let project_id = repo.project_identifier().ok();
let pid = project_id.as_deref();
let project_config = repo.load_project_config()?;
- let mut builder = HookPlanBuilder::new();
+ let mut builder = HookPlanBuilder::new(project_config.as_ref(), &config, pid);
for &wt_path in removed_worktree_paths {
- builder.add(
- wt_path,
- &[HookType::PreRemove, HookType::PostRemove],
- project_config.as_ref(),
- &config,
- pid,
- );
+ builder.add(wt_path, &[HookType::PreRemove, HookType::PostRemove]);
}
let mut seen_dests = std::collections::HashSet::new();
for &dest in destination_paths {
if !seen_dests.insert(dest) {
continue;
}
- builder.add(
- dest,
- &[HookType::PostSwitch],
- project_config.as_ref(),
- &config,
- pid,
- );
+ builder.add(dest, &[HookType::PostSwitch]);
}
match builder.finish().approve(pid, yes)? {
Some(plan) => Ok(plan),
diff --git a/src/shell/paths.rs b/src/shell/paths.rs
index 13c147852..f9ca4f583 100644
--- a/src/shell/paths.rs
+++ b/src/shell/paths.rs
@@ -5,6 +5,7 @@
use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};
use std::path::PathBuf;
+use std::sync::OnceLock;
use crate::path::home_dir;
@@ -27,17 +28,26 @@ fn parse_nu_config_output(stdout: &[u8]) -> Option<PathBuf> {
(!path.as_os_str().is_empty()).then_some(path)
}
-/// Query `nu` for its default config directory.
+/// Query `nu` for its default config directory, spawning `nu` at most once per process.
///
/// Returns `Some(path)` if the `nu` binary is in PATH and reports its config dir,
-/// `None` otherwise (not installed, PATH issues, timeout, etc.).
+/// `None` otherwise (not installed, PATH issues, timeout, etc.). The result is
+/// memoised: a single `wt config shell install` resolves both the write path
+/// (`nushell_config_dir`) and the installed-state candidates
+/// (`nushell_config_candidates`), which would otherwise each spawn `nu` for the
+/// same answer.
fn query_nu_config_dir() -> Option<PathBuf> {
- let output = crate::shell_exec::Cmd::new("nu")
- .args(["-c", "echo $nu.default-config-dir"])
- .run()
- .ok()
- .filter(|o| o.status.success())?;
- parse_nu_config_output(&output.stdout)
+ static CACHE: OnceLock<Option<PathBuf>> = OnceLock::new();
+ CACHE
+ .get_or_init(|| {
+ let output = crate::shell_exec::Cmd::new("nu")
+ .args(["-c", "echo $nu.default-config-dir"])
+ .run()
+ .ok()
+ .filter(|o| o.status.success())?;
+ parse_nu_config_output(&output.stdout)
+ })
+ .clone()
}
/// Resolve the nushell config directory from a queried path or platform defaults.
@@ -71,7 +81,10 @@ fn nushell_config_dir(home: &std::path::Path) -> PathBuf {
/// - We need to find the config file regardless of which path was used
///
/// Returns paths in priority order: queried path first, then fallbacks.
-/// Callers that pick `first()` to write get the same path as `nushell_config_dir()`.
+/// When the `nu` query succeeds, `first()` is the queried path — the same path
+/// `nushell_config_dir()` writes to. (Their fallbacks differ when the query
+/// fails: `nushell_config_dir()` prefers the platform config dir, this prefers
+/// `$XDG_CONFIG_HOME`/`~/.config`.)
fn nushell_config_candidates(home: &std::path::Path) -> Vec<PathBuf> {
let mut candidates = vec![];