Skip to content

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

Refactor to remove unused parameters and simplify APIs

Maximilian Roos65b27110a209
diff --git a/src/commands/list/progressive_table.rs b/src/commands/list/progressive_table.rs
index 9e36dd053..07b8c230f 100644
--- a/src/commands/list/progressive_table.rs
+++ b/src/commands/list/progressive_table.rs
@@ -56,17 +56,17 @@ impl ProgressiveTable {
// Build initial lines: header + rows + spacer + footer
let mut lines = Vec::with_capacity(row_count + 3);
- lines.push(truncate_visible(&header, max_width, "…"));
+ lines.push(truncate_visible(&header, max_width));
for skeleton in skeletons {
- lines.push(truncate_visible(&skeleton, max_width, "…"));
+ lines.push(truncate_visible(&skeleton, max_width));
}
// Spacer (blank line)
lines.push(String::new());
// Footer
- lines.push(truncate_visible(&initial_footer, max_width, "…"));
+ lines.push(truncate_visible(&initial_footer, max_width));
Self {
lines,
@@ -103,7 +103,7 @@ impl ProgressiveTable {
return Ok(());
}
- let truncated = truncate_visible(&content, self.max_width, "…");
+ let truncated = truncate_visible(&content, self.max_width);
// Line index: header (0) + row_idx
let line_idx = row_idx + 1;
@@ -124,7 +124,7 @@ impl ProgressiveTable {
/// Update the footer message.
pub fn update_footer(&mut self, content: String) -> std::io::Result<()> {
- let truncated = truncate_visible(&content, self.max_width, "…");
+ let truncated = truncate_visible(&content, self.max_width);
// Footer is the last line
let footer_idx = self.lines.len() - 1;
diff --git a/src/completion.rs b/src/completion.rs
index 04fb07db7..335d285df 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -9,7 +9,7 @@ use clap_complete::env::CompleteEnv;
use crate::cli;
use crate::display::format_relative_time_short;
use worktrunk::config::{ProjectConfig, WorktrunkConfig};
-use worktrunk::git::{BranchCategory, Repository};
+use worktrunk::git::{BranchCategory, HookType, Repository};
/// Handle shell-initiated completion requests via `COMPLETE=$SHELL wt`
pub fn maybe_handle_env_completion() -> bool {
@@ -211,25 +211,18 @@ fn complete_hook_commands() -> Vec<CompletionCandidate> {
})
});
- let Some(hook_type) = hook_type else {
+ let Some(hook_type_str) = hook_type else {
+ return Vec::new();
+ };
+ let Ok(hook_type) = hook_type_str.parse::<HookType>() else {
return Vec::new();
};
let mut candidates = Vec::new();
- // Load user config and add user hook names
- if let Ok(user_config) = WorktrunkConfig::load() {
- let user_command_config = match hook_type {
- "post-create" => &user_config.hooks.post_create,
- "post-start" => &user_config.hooks.post_start,
- "pre-commit" => &user_config.hooks.pre_commit,
- "pre-merge" => &user_config.hooks.pre_merge,
- "post-merge" => &user_config.hooks.post_merge,
- "pre-remove" => &user_config.hooks.pre_remove,
- _ => &None,
- };
-
- if let Some(config) = user_command_config {
+ // Helper to extract named commands from a hook config
+ let add_named_commands =
+ |candidates: &mut Vec<_>, config: &worktrunk::config::CommandConfig| {
candidates.extend(
config
.commands()
@@ -237,33 +230,22 @@ fn complete_hook_commands() -> Vec<CompletionCandidate> {
.filter_map(|cmd| cmd.name.as_ref())
.map(|name| CompletionCandidate::new(name.clone())),
);
- }
+ };
+
+ // Load user config and add user hook names
+ if let Ok(user_config) = WorktrunkConfig::load()
+ && let Some(config) = user_config.hooks.get(hook_type)
+ {
+ add_named_commands(&mut candidates, config);
}
// Load project config and add project hook names
let repo = Repository::current();
if let Ok(repo_root) = repo.worktree_root()
&& let Ok(Some(project_config)) = ProjectConfig::load(repo_root)
+ && let Some(config) = project_config.hooks.get(hook_type)
{
- let project_command_config = match hook_type {
- "post-create" => &project_config.hooks.post_create,
- "post-start" => &project_config.hooks.post_start,
- "pre-commit" => &project_config.hooks.pre_commit,
- "pre-merge" => &project_config.hooks.pre_merge,
- "post-merge" => &project_config.hooks.post_merge,
- "pre-remove" => &project_config.hooks.pre_remove,
- _ => &None,
- };
-
- if let Some(config) = project_command_config {
- candidates.extend(
- config
- .commands()
- .iter()
- .filter_map(|cmd| cmd.name.as_ref())
- .map(|name| CompletionCandidate::new(name.clone())),
- );
- }
+ add_named_commands(&mut candidates, config);
}
candidates
diff --git a/src/git/diff.rs b/src/git/diff.rs
index b124e3a96..35a1e73d3 100644
--- a/src/git/diff.rs
+++ b/src/git/diff.rs
@@ -49,15 +49,11 @@ impl LineDiff {
pub fn is_empty(&self) -> bool {
self.added == 0 && self.deleted == 0
}
-
- pub fn into_tuple(self) -> (usize, usize) {
- (self.added, self.deleted)
- }
}
impl From<LineDiff> for (usize, usize) {
fn from(diff: LineDiff) -> Self {
- diff.into_tuple()
+ (diff.added, diff.deleted)
}
}
@@ -175,15 +171,6 @@ mod tests {
assert!(!diff.is_empty());
}
- #[test]
- fn test_line_diff_into_tuple() {
- let diff = LineDiff {
- added: 10,
- deleted: 5,
- };
- assert_eq!(diff.into_tuple(), (10, 5));
- }
-
#[test]
fn test_line_diff_from_tuple() {
let diff: LineDiff = (10, 5).into();
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 1102a89dc..979ee4465 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -282,7 +282,7 @@ pub(crate) use parse::DefaultBranchName;
// They're accessible as git::HookType, git::Worktree, and git::WorktreeList without needing re-export.
/// Hook types for git operations
-#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, strum::Display)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, strum::Display, strum::EnumString)]
#[strum(serialize_all = "kebab-case")]
pub enum HookType {
PostCreate,
diff --git a/src/git/test.rs b/src/git/test.rs
index 2dc14a444..2060d35a0 100644
--- a/src/git/test.rs
+++ b/src/git/test.rs
@@ -198,7 +198,7 @@ fn test_line_diff_from_numstat(
let result = LineDiff::from_numstat(input);
assert!(result.is_ok());
- let (added, deleted) = result.unwrap().into_tuple();
+ let (added, deleted): (usize, usize) = result.unwrap().into();
assert_eq!(added, expected_added);
assert_eq!(deleted, expected_deleted);
}
diff --git a/src/llm.rs b/src/llm.rs
index eb83b9d5e..a47857630 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -333,6 +333,38 @@ enum TemplateType {
Squash,
}
+/// Load template from inline, file, or default
+fn load_template(
+ inline: Option<&String>,
+ file: Option<&String>,
+ default: &str,
+ file_type_name: &str,
+) -> anyhow::Result<String> {
+ match (inline, file) {
+ (Some(inline), None) => Ok(inline.clone()),
+ (None, Some(path)) => {
+ let expanded_path = PathBuf::from(shellexpand::tilde(path).as_ref());
+ std::fs::read_to_string(&expanded_path).map_err(|e| {
+ anyhow::Error::from(worktrunk::git::GitError::Other {
+ message: format!(
+ "Failed to read {} '{}': {}",
+ file_type_name,
+ format_path_for_display(&expanded_path),
+ e
+ ),
+ })
+ })
+ }
+ (None, None) => Ok(default.to_string()),
+ (Some(_), Some(_)) => {
+ unreachable!(
+ "Config validation should prevent both {} options",
+ file_type_name
+ )
+ }
+ }
+}
+
/// Build prompt from template using minijinja
///
/// Template variables available to both commit and squash templates:
@@ -351,52 +383,24 @@ fn build_prompt(
) -> anyhow::Result<String> {
// Get template source based on type
let (template, type_name) = match template_type {
- TemplateType::Commit => {
- let tmpl = match (&config.template, &config.template_file) {
- (Some(inline), None) => inline.clone(),
- (None, Some(path)) => {
- let expanded_path = PathBuf::from(shellexpand::tilde(path).as_ref());
- std::fs::read_to_string(&expanded_path).map_err(|e| {
- anyhow::Error::from(worktrunk::git::GitError::Other {
- message: format!(
- "Failed to read template-file '{}': {}",
- format_path_for_display(&expanded_path),
- e
- ),
- })
- })?
- }
- (None, None) => DEFAULT_TEMPLATE.to_string(),
- (Some(_), Some(_)) => {
- unreachable!("Config validation should prevent both template and template-file")
- }
- };
- (tmpl, "Template")
- }
- TemplateType::Squash => {
- let tmpl = match (&config.squash_template, &config.squash_template_file) {
- (Some(inline), None) => inline.clone(),
- (None, Some(path)) => {
- let expanded_path = PathBuf::from(shellexpand::tilde(path).as_ref());
- std::fs::read_to_string(&expanded_path).map_err(|e| {
- anyhow::Error::from(worktrunk::git::GitError::Other {
- message: format!(
- "Failed to read squash-template-file '{}': {}",
- format_path_for_display(&expanded_path),
- e
- ),
- })
- })?
- }
- (None, None) => DEFAULT_SQUASH_TEMPLATE.to_string(),
- (Some(_), Some(_)) => {
- unreachable!(
- "Config validation should prevent both squash-template and squash-template-file"
- )
- }
- };
- (tmpl, "Squash template")
- }
+ TemplateType::Commit => (
+ load_template(
+ config.template.as_ref(),
+ config.template_file.as_ref(),
+ DEFAULT_TEMPLATE,
+ "template-file",
+ )?,
+ "Template",
+ ),
+ TemplateType::Squash => (
+ load_template(
+ config.squash_template.as_ref(),
+ config.squash_template_file.as_ref(),
+ DEFAULT_SQUASH_TEMPLATE,
+ "squash-template-file",
+ )?,
+ "Squash template",
+ ),
};
// Validate non-empty
diff --git a/src/path.rs b/src/path.rs
index 7eefc6b28..951a9297b 100644
--- a/src/path.rs
+++ b/src/path.rs
@@ -84,9 +84,7 @@ fn find_cygpath_from_shell(shell: &crate::shell_exec::ShellConfig) -> Option<Pat
/// Uses the `home` crate which handles platform-specific detection:
/// - Unix: `$HOME` environment variable
/// - Windows: `USERPROFILE` or `HOMEDRIVE`/`HOMEPATH`
-pub fn home_dir() -> Option<PathBuf> {
- home::home_dir()
-}
+pub use home::home_dir;
/// Format a filesystem path for user-facing output.
///
diff --git a/src/shell.rs b/src/shell.rs
index fb4559e20..776e8131b 100644
--- a/src/shell.rs
+++ b/src/shell.rs
@@ -281,10 +281,6 @@ pub struct ShellInit {
}
impl ShellInit {
- pub fn new(shell: Shell) -> Self {
- Self::with_prefix(shell, "wt".to_string())
- }
-
pub fn with_prefix(shell: Shell, cmd: String) -> Self {
Self { shell, cmd }
}
@@ -532,7 +528,7 @@ mod tests {
// Test that shell init generates valid output for each shell
let shells = [Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell];
for shell in shells {
- let init = ShellInit::new(shell);
+ let init = ShellInit::with_prefix(shell, "wt".to_string());
let result = init.generate();
assert!(result.is_ok(), "Failed to generate for {:?}", shell);
let output = result.unwrap();
diff --git a/src/styling/line.rs b/src/styling/line.rs
index 8650422ab..555337aea 100644
--- a/src/styling/line.rs
+++ b/src/styling/line.rs
@@ -7,9 +7,14 @@ use anstyle::Style;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
/// Truncate a styled string to a visible width budget, preserving escapes.
-/// Escape sequences (ANSI/OSC) are zero-width; ellipsis is added when truncating.
+/// Escape sequences (ANSI/OSC) are zero-width; ellipsis ("…") is added when truncating.
/// Appends ESC[0m on truncation to avoid style bleed.
-pub fn truncate_visible(rendered: &str, max_width: usize, ellipsis: &str) -> String {
+pub fn truncate_visible(rendered: &str, max_width: usize) -> String {
+ truncate_visible_with_ellipsis(rendered, max_width, "…")
+}
+
+/// Truncate a styled string with a custom ellipsis character.
+fn truncate_visible_with_ellipsis(rendered: &str, max_width: usize, ellipsis: &str) -> String {
if max_width == 0 {
return String::new();
}
@@ -145,7 +150,7 @@ impl StyledLine {
return self;
}
let rendered = self.render();
- let truncated = truncate_visible(&rendered, max_width, "…");
+ let truncated = truncate_visible(&rendered, max_width);
let mut new_line = StyledLine::new();
new_line.push_raw(truncated);
new_line
@@ -231,7 +236,7 @@ mod tests {
#[test]
fn test_truncate_visible_preserves_budget_and_resets() {
let colored = "\u{1b}[31mhello\u{1b}[0m";
- let out = truncate_visible(colored, 3, "…");
+ let out = truncate_visible(colored, 3);
assert_eq!(visible_width(&out), 3);
assert!(out.ends_with("\u{1b}[0m"));
}
@@ -239,7 +244,7 @@ mod tests {
#[test]
fn test_truncate_visible_handles_wide_emoji() {
let rocket = "🚀";
- let out = truncate_visible(rocket, 1, "…");
+ let out = truncate_visible(rocket, 1);
assert_eq!(visible_width(&out), 1);
assert!(out.ends_with("\u{1b}[0m"));
}
@@ -247,14 +252,14 @@ mod tests {
#[test]
fn test_truncate_visible_zero_width() {
let text = "hello world";
- let out = truncate_visible(text, 0, "…");
+ let out = truncate_visible(text, 0);
assert!(out.is_empty(), "Zero width should return empty string");
}
#[test]
fn test_truncate_visible_no_truncation_needed() {
let text = "short";
- let out = truncate_visible(text, 100, "…");
+ let out = truncate_visible(text, 100);
assert_eq!(out, text, "No truncation should return original string");
}
@@ -262,7 +267,7 @@ mod tests {
fn test_truncate_visible_zero_budget() {
// When max_width equals ellipsis width, budget becomes 0
let text = "hello";
- let out = truncate_visible(text, 1, "…");
+ let out = truncate_visible(text, 1);
assert!(
visible_width(&out) <= 1,
"Output should be within max_width"