Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: multi-dimensional simplifications (hooks, caching, sorting) (#404)
Maximilian Roos4453f4b1a4d2
diff --git a/.claude/rules/caching-strategy.md b/.claude/rules/caching-strategy.mdindex c924724be..73034151c 100644--- a/.claude/rules/caching-strategy.md+++ b/.claude/rules/caching-strategy.md@@ -22,6 +22,7 @@ Everything else (remote URLs, project config, branch metadata) is read-only.- `current_branch()` — we don't switch branches within a worktree- `project_identifier()` — derived from remote URL- `primary_remote()` — git config, doesn't change+- `default_branch()` — from git config or detection, doesn't change**Not cached (intentionally):**- `is_dirty()` — changes as we stage/commitdiff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 1d1406a23..127280c8d 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -88,38 +88,31 @@ pub fn prepare_hook_commands(let display_path = display_path.map(|p| p.to_path_buf());- if let Some(config) = user_config {- // Skip user commands if filter specifies project source- if parsed_filter- .as_ref()- .is_none_or(|f| f.matches_source(HookSource::User))- {- let prepared = prepare_commands(config, ctx, extra_vars, hook_type)?;- let filtered = filter_by_name(prepared, parsed_filter.as_ref().map(|f| f.name));- commands.extend(filtered.into_iter().map(|p| SourcedCommand {- prepared: p,- source: HookSource::User,- hook_type,- display_path: display_path.clone(),- }));- }- }+ // Process user config first, then project config (execution order)+ let sources = [+ (HookSource::User, user_config),+ (HookSource::Project, project_config),+ ];++ for (source, config) in sources {+ let Some(config) = config else { continue };- if let Some(config) = project_config {- // Skip project commands if filter specifies user source- if parsed_filter+ // Skip if filter specifies a different source+ if !parsed_filter.as_ref()- .is_none_or(|f| f.matches_source(HookSource::Project))+ .is_none_or(|f| f.matches_source(source)){- let prepared = prepare_commands(config, ctx, extra_vars, hook_type)?;- let filtered = filter_by_name(prepared, parsed_filter.as_ref().map(|f| f.name));- commands.extend(filtered.into_iter().map(|p| SourcedCommand {- prepared: p,- source: HookSource::Project,- hook_type,- display_path: display_path.clone(),- }));+ continue;}++ let prepared = prepare_commands(config, ctx, extra_vars, hook_type)?;+ let filtered = filter_by_name(prepared, parsed_filter.as_ref().map(|f| f.name));+ commands.extend(filtered.into_iter().map(|p| SourcedCommand {+ prepared: p,+ source,+ hook_type,+ display_path: display_path.clone(),+ }));}Ok(commands)@@ -208,27 +201,24 @@ pub(crate) fn check_name_filter_matched(let parsed = ParsedFilter::parse(filter_str);let mut available = Vec::new();- // Only show commands from sources that match the filter- if parsed.matches_source(HookSource::User)- && let Some(config) = user_config- {- available.extend(- config- .commands()- .iter()- .filter_map(|c| c.name.as_ref().map(|n| format!("user:{n}"))),- );- }- if parsed.matches_source(HookSource::Project)- && let Some(config) = project_config- {+ // Collect available commands from sources that match the filter+ let sources = [+ (HookSource::User, user_config),+ (HookSource::Project, project_config),+ ];+ for (source, config) in sources {+ let Some(config) = config else { continue };+ if !parsed.matches_source(source) {+ continue;+ }available.extend(config.commands().iter()- .filter_map(|c| c.name.as_ref().map(|n| format!("project:{n}"))),+ .filter_map(|c| c.name.as_ref().map(|n| format!("{source}:{n}"))),);}+return Err(worktrunk::git::GitError::HookCommandNotFound {name: filter_str.to_string(),available,diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rsindex 6e5be9eb0..032bac183 100644--- a/src/commands/list/collect.rs+++ b/src/commands/list/collect.rs@@ -1181,13 +1181,16 @@ fn sort_by_timestamp_desc_with_cache<T, F>(whereF: Fn(&T) -> &str,{- let mut indexed: Vec<_> = items.into_iter().enumerate().collect();- let item_timestamps: Vec<i64> = indexed- .iter()- .map(|(_, item)| *timestamps.get(get_sha(item)).unwrap_or(&0))+ // Embed timestamp in tuple to avoid parallel Vec and index lookups+ let mut with_ts: Vec<_> = items+ .into_iter()+ .map(|item| {+ let ts = *timestamps.get(get_sha(&item)).unwrap_or(&0);+ (item, ts)+ }).collect();- indexed.sort_by_key(|(idx, _)| std::cmp::Reverse(item_timestamps[*idx]));- indexed.into_iter().map(|(_, item)| item).collect()+ with_ts.sort_by_key(|(_, ts)| std::cmp::Reverse(*ts));+ with_ts.into_iter().map(|(item, _)| item).collect()}/// Sort worktrees: current first, main second, then by timestamp descending.@@ -1198,24 +1201,24 @@ fn sort_worktrees_with_cache(current_path: Option<&std::path::PathBuf>,timestamps: &std::collections::HashMap<String, i64>,) -> Vec<Worktree> {- let mut indexed: Vec<_> = worktrees.into_iter().enumerate().collect();- let wt_timestamps: Vec<i64> = indexed- .iter()- .map(|(_, wt)| *timestamps.get(&wt.head).unwrap_or(&0))+ // Embed timestamp and priority in tuple to avoid parallel Vec and index lookups+ let mut with_sort_key: Vec<_> = worktrees+ .into_iter()+ .map(|wt| {+ let priority = if current_path.is_some_and(|cp| &wt.path == cp) {+ 0 // Current first+ } else if wt.path == main_worktree.path {+ 1 // Main second+ } else {+ 2 // Rest by timestamp+ };+ let ts = *timestamps.get(&wt.head).unwrap_or(&0);+ (wt, priority, ts)+ }).collect();- indexed.sort_by_key(|(idx, wt)| {- let priority = if current_path.is_some_and(|cp| &wt.path == cp) {- 0 // Current first- } else if wt.path == main_worktree.path {- 1 // Main second- } else {- 2 // Rest by timestamp- };- (priority, std::cmp::Reverse(wt_timestamps[*idx]))- });-- indexed.into_iter().map(|(_, wt)| wt).collect()+ with_sort_key.sort_by_key(|(_, priority, ts)| (*priority, std::cmp::Reverse(*ts)));+ with_sort_key.into_iter().map(|(wt, _, _)| wt).collect()}// ============================================================================diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 4315b64d0..e8f9b4117 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -75,6 +75,8 @@ struct RepoCache {is_bare: OnceCell<bool>,/// Project config (loaded from .config/wt.toml, cached per Repository instance)project_config: OnceCell<Option<ProjectConfig>>,+ /// Default branch (main, master, etc.) - cached from git config or detection+ default_branch: OnceCell<String>,}/// Repository context for git operations.@@ -406,18 +408,25 @@ impl Repository {////// Detection results are cached to `worktrunk.default-branch` for future calls.pub fn default_branch(&self) -> anyhow::Result<String> {- // Fast path: check worktrunk's own cache (single git config read)- if let Ok(branch) = self.run_command(&["config", "--get", "worktrunk.default-branch"]) {- let branch = branch.trim();- if !branch.is_empty() {- return Ok(branch.to_string());- }- }+ self.cache+ .default_branch+ .get_or_try_init(|| {+ // Fast path: check worktrunk's persistent cache (git config)+ if let Ok(branch) =+ self.run_command(&["config", "--get", "worktrunk.default-branch"])+ {+ let branch = branch.trim();+ if !branch.is_empty() {+ return Ok(branch.to_string());+ }+ }- // Detect and cache the default branch- let branch = self.detect_default_branch()?;- let _ = self.run_command(&["config", "worktrunk.default-branch", &branch]);- Ok(branch)+ // Detect and persist to git config for future processes+ let branch = self.detect_default_branch()?;+ let _ = self.run_command(&["config", "worktrunk.default-branch", &branch]);+ Ok(branch)+ })+ .cloned()}/// Detect the default branch without using worktrunk's cache.