Skip to content

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

Refactor config loading and worktree path formatting

Maximilian Roos6b1ce4c91a41
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 4316eeecb..f931aa62a 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -1,4 +1,4 @@
-use worktrunk::config::load_config;
+use worktrunk::config::WorktrunkConfig;
use worktrunk::error_format::format_error;
use worktrunk::git::{GitError, Repository, run_git_command};
@@ -123,7 +123,7 @@ fn handle_squash(target_branch: &str) -> Result<(), GitError> {
let subjects = repo.commit_subjects(&range)?;
// Load config and generate commit message
- let config = load_config()
+ let config = WorktrunkConfig::load()
.map_err(|e| GitError::CommandFailed(format!("Failed to load config: {}", e)))?;
let commit_message = crate::llm::generate_squash_message(target_branch, &subjects, &config.llm);
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 81f86d492..a9d261b4e 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -1,6 +1,6 @@
use std::path::Path;
use std::process;
-use worktrunk::config::format_worktree_path;
+use worktrunk::config::WorktrunkConfig;
use worktrunk::error_format::{format_error, format_error_with_bold, format_hint};
use worktrunk::git::{GitError, Repository, run_git_command};
@@ -9,7 +9,7 @@ pub fn handle_switch(
create: bool,
base: Option<&str>,
internal: bool,
- worktree_path_template: &str,
+ config: &WorktrunkConfig,
) -> Result<(), GitError> {
let repo = Repository::current();
@@ -55,7 +55,7 @@ pub fn handle_switch(
.to_str()
.ok_or_else(|| GitError::CommandFailed("Invalid UTF-8 in path".to_string()))?;
- let worktree_name = format_worktree_path(worktree_path_template, repo_name, branch);
+ let worktree_name = config.format_path(repo_name, branch);
let worktree_path = repo_root.join(worktree_name);
// Create the worktree
diff --git a/src/config.rs b/src/config.rs
index 29382a4c9..e86ca634c 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -66,31 +66,61 @@ impl Default for WorktrunkConfig {
}
}
-fn get_config_path() -> Option<PathBuf> {
- ProjectDirs::from("", "", "worktrunk").map(|dirs| dirs.config_dir().join("config.toml"))
-}
+impl WorktrunkConfig {
+ /// Load configuration from config file and environment variables.
+ ///
+ /// Configuration is loaded in the following order (later sources override earlier ones):
+ /// 1. Default values
+ /// 2. Config file (~/.config/worktrunk/config.toml on Linux/macOS)
+ /// 3. Environment variables (WORKTRUNK_*)
+ pub fn load() -> Result<Self, ConfigError> {
+ let defaults = Self::default();
-pub fn load_config() -> Result<WorktrunkConfig, ConfigError> {
- let defaults = WorktrunkConfig::default();
+ let mut builder = Config::builder()
+ .set_default("worktree-path", defaults.worktree_path)?
+ .set_default("llm.command", defaults.llm.command.unwrap_or_default())?
+ .set_default("llm.args", defaults.llm.args)?;
+
+ // Add config file if it exists
+ if let Some(config_path) = get_config_path()
+ && config_path.exists()
+ {
+ builder = builder.add_source(File::from(config_path));
+ }
- let mut builder = Config::builder()
- .set_default("worktree-path", defaults.worktree_path)?
- .set_default("llm.command", defaults.llm.command.unwrap_or_default())?
- .set_default("llm.args", defaults.llm.args)?;
+ // Add environment variables with WORKTRUNK prefix
+ builder = builder.add_source(config::Environment::with_prefix("WORKTRUNK").separator("_"));
- // Add config file if it exists
- if let Some(config_path) = get_config_path()
- && config_path.exists()
- {
- builder = builder.add_source(File::from(config_path));
+ let config: Self = builder.build()?.try_deserialize()?;
+ validate_worktree_path(&config.worktree_path)?;
+ Ok(config)
}
- // Add environment variables with WORKTRUNK prefix
- builder = builder.add_source(config::Environment::with_prefix("WORKTRUNK").separator("_"));
+ /// Format a worktree path using this configuration's template.
+ ///
+ /// # Arguments
+ /// * `repo` - Repository name (replaces {repo} in template)
+ /// * `branch` - Branch name (replaces {branch} in template, slashes sanitized to dashes)
+ ///
+ /// # Examples
+ /// ```
+ /// use worktrunk::config::WorktrunkConfig;
+ ///
+ /// let config = WorktrunkConfig::default();
+ /// let path = config.format_path("myproject", "feature/foo");
+ /// assert_eq!(path, "../myproject.feature-foo");
+ /// ```
+ pub fn format_path(&self, repo: &str, branch: &str) -> String {
+ // Sanitize branch name by replacing path separators to prevent directory traversal
+ let safe_branch = branch.replace(['/', '\\'], "-");
+ self.worktree_path
+ .replace("{repo}", repo)
+ .replace("{branch}", &safe_branch)
+ }
+}
- let config: WorktrunkConfig = builder.build()?.try_deserialize()?;
- validate_worktree_path(&config.worktree_path)?;
- Ok(config)
+fn get_config_path() -> Option<PathBuf> {
+ ProjectDirs::from("", "", "worktrunk").map(|dirs| dirs.config_dir().join("config.toml"))
}
fn validate_worktree_path(template: &str) -> Result<(), ConfigError> {
@@ -111,14 +141,6 @@ fn validate_worktree_path(template: &str) -> Result<(), ConfigError> {
Ok(())
}
-pub fn format_worktree_path(template: &str, repo: &str, branch: &str) -> String {
- // Sanitize branch name by replacing path separators to prevent directory traversal
- let safe_branch = branch.replace(['/', '\\'], "-");
- template
- .replace("{repo}", repo)
- .replace("{branch}", &safe_branch)
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -140,47 +162,64 @@ mod tests {
#[test]
fn test_load_config_defaults() {
// Without a config file or env vars, should return defaults
- let config = load_config().unwrap();
+ let config = WorktrunkConfig::load().unwrap();
assert_eq!(config.worktree_path, "../{repo}.{branch}");
}
#[test]
fn test_format_worktree_path() {
+ let config = WorktrunkConfig {
+ worktree_path: "{repo}.{branch}".to_string(),
+ llm: LlmConfig::default(),
+ };
assert_eq!(
- format_worktree_path("{repo}.{branch}", "myproject", "feature-x"),
+ config.format_path("myproject", "feature-x"),
"myproject.feature-x"
);
}
#[test]
fn test_format_worktree_path_custom_template() {
+ let config = WorktrunkConfig {
+ worktree_path: "{repo}-{branch}".to_string(),
+ llm: LlmConfig::default(),
+ };
assert_eq!(
- format_worktree_path("{repo}-{branch}", "myproject", "feature-x"),
+ config.format_path("myproject", "feature-x"),
"myproject-feature-x"
);
}
#[test]
fn test_format_worktree_path_only_branch() {
- assert_eq!(
- format_worktree_path("{branch}", "myproject", "feature-x"),
- "feature-x"
- );
+ let config = WorktrunkConfig {
+ worktree_path: "{branch}".to_string(),
+ llm: LlmConfig::default(),
+ };
+ assert_eq!(config.format_path("myproject", "feature-x"), "feature-x");
}
#[test]
fn test_format_worktree_path_with_slashes() {
// Slashes should be replaced with dashes to prevent directory traversal
+ let config = WorktrunkConfig {
+ worktree_path: "{repo}.{branch}".to_string(),
+ llm: LlmConfig::default(),
+ };
assert_eq!(
- format_worktree_path("{repo}.{branch}", "myproject", "feature/foo"),
+ config.format_path("myproject", "feature/foo"),
"myproject.feature-foo"
);
}
#[test]
fn test_format_worktree_path_with_multiple_slashes() {
+ let config = WorktrunkConfig {
+ worktree_path: "{branch}".to_string(),
+ llm: LlmConfig::default(),
+ };
assert_eq!(
- format_worktree_path("{branch}", "myproject", "feature/sub/task"),
+ config.format_path("myproject", "feature/sub/task"),
"feature-sub-task"
);
}
@@ -188,8 +227,12 @@ mod tests {
#[test]
fn test_format_worktree_path_with_backslashes() {
// Windows-style path separators should also be sanitized
+ let config = WorktrunkConfig {
+ worktree_path: "{branch}".to_string(),
+ llm: LlmConfig::default(),
+ };
assert_eq!(
- format_worktree_path("{branch}", "myproject", "feature\\foo"),
+ config.format_path("myproject", "feature\\foo"),
"feature-foo"
);
}
diff --git a/src/main.rs b/src/main.rs
index 70dc977c9..cae5b28f2 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,6 +1,6 @@
use clap::{CommandFactory, Parser, Subcommand};
use std::process;
-use worktrunk::config::load_config;
+use worktrunk::config::WorktrunkConfig;
use worktrunk::git::GitError;
mod commands;
@@ -117,17 +117,9 @@ fn main() {
create,
base,
internal,
- } => load_config()
+ } => WorktrunkConfig::load()
.map_err(|e| GitError::CommandFailed(format!("Failed to load config: {}", e)))
- .and_then(|config| {
- handle_switch(
- &branch,
- create,
- base.as_deref(),
- internal,
- &config.worktree_path,
- )
- }),
+ .and_then(|config| handle_switch(&branch, create, base.as_deref(), internal, &config)),
Commands::Remove { internal } => handle_remove(internal),
Commands::Push {
target,