Skip to content

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

refactor: Split config module into focused files

Maximilian Roos1dd45fdf1c0a
diff --git a/src/config/commands.rs b/src/config/commands.rs
new file mode 100644
index 000000000..b929b47fa
--- /dev/null
+++ b/src/config/commands.rs
@@ -0,0 +1,175 @@
+//! Command configuration types for project hooks
+//!
+//! Handles parsing and representation of commands that run during various phases
+//! of worktree and merge operations.
+
+use indexmap::IndexMap;
+use serde::{Deserialize, Serialize};
+
+/// Phase in which a command executes
+#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display, strum::AsRefStr)]
+#[strum(serialize_all = "kebab-case")]
+pub enum CommandPhase {
+ /// After creating a worktree (blocking)
+ PostCreate,
+ /// After creating a worktree (background)
+ PostStart,
+ /// Before committing during merge (blocking, fail-fast)
+ PreCommit,
+ /// Before merging (blocking, fail-fast)
+ PreMerge,
+ /// After successful merge (blocking)
+ PostMerge,
+}
+
+/// Represents a command with its template and optionally expanded form
+#[derive(Debug, Clone, PartialEq)]
+pub struct Command {
+ /// Optional name for the command (e.g., "build", "test", or auto-numbered "1", "2")
+ pub name: Option<String>,
+ /// Template string that may contain variables like {branch}, {worktree}
+ pub template: String,
+ /// Expanded command with variables substituted (same as template if not expanded yet)
+ pub expanded: String,
+ /// Phase in which this command executes
+ pub phase: CommandPhase,
+}
+
+impl Command {
+ /// Create a new command from a template (not yet expanded)
+ pub fn new(name: Option<String>, template: String, phase: CommandPhase) -> Self {
+ Self {
+ name,
+ expanded: template.clone(),
+ template,
+ phase,
+ }
+ }
+
+ /// Create a command with both template and expanded forms
+ pub fn with_expansion(
+ name: Option<String>,
+ template: String,
+ expanded: String,
+ phase: CommandPhase,
+ ) -> Self {
+ Self {
+ name,
+ template,
+ expanded,
+ phase,
+ }
+ }
+}
+
+/// Configuration for commands - canonical representation
+///
+/// Internally stores commands as `Vec<Command>` for uniform processing.
+/// Deserializes from three TOML formats:
+/// - Single string: `post-create-command = "npm install"`
+/// - Array: `post-create-command = ["npm install", "npm test"]`
+/// - Named table: `[post-create-command]` followed by `install = "npm install"`
+///
+/// **Order preservation:** Named commands preserve TOML insertion order (requires
+/// `preserve_order` feature on toml crate and IndexMap for deserialization). This
+/// allows users to control execution order explicitly.
+///
+/// This canonical form eliminates branching at call sites - code just iterates over commands.
+#[derive(Debug, Clone, PartialEq)]
+pub struct CommandConfig {
+ commands: Vec<Command>,
+}
+
+impl CommandConfig {
+ /// Returns the commands as a slice
+ pub fn commands(&self) -> &[Command] {
+ &self.commands
+ }
+
+ /// Returns commands with the specified phase
+ pub fn commands_with_phase(&self, phase: CommandPhase) -> Vec<Command> {
+ self.commands
+ .iter()
+ .map(|cmd| Command {
+ phase,
+ ..cmd.clone()
+ })
+ .collect()
+ }
+}
+
+// Custom deserialization to handle 3 TOML formats
+impl<'de> Deserialize<'de> for CommandConfig {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ #[derive(Deserialize)]
+ #[serde(untagged)]
+ enum CommandConfigToml {
+ Single(String),
+ Multiple(Vec<String>),
+ Named(IndexMap<String, String>),
+ }
+
+ let toml = CommandConfigToml::deserialize(deserializer)?;
+ let commands = match toml {
+ CommandConfigToml::Single(cmd) => {
+ // Phase will be set later when commands are collected
+ vec![Command::new(None, cmd, CommandPhase::PostCreate)]
+ }
+ CommandConfigToml::Multiple(cmds) => cmds
+ .into_iter()
+ .map(|template| Command::new(None, template, CommandPhase::PostCreate))
+ .collect(),
+ CommandConfigToml::Named(map) => {
+ // IndexMap preserves insertion order from TOML
+ map.into_iter()
+ .map(|(name, template)| {
+ Command::new(Some(name), template, CommandPhase::PostCreate)
+ })
+ .collect()
+ }
+ };
+ Ok(CommandConfig { commands })
+ }
+}
+
+// Serialize back to most appropriate format
+impl Serialize for CommandConfig {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer,
+ {
+ use serde::ser::SerializeMap;
+
+ // If single unnamed command, serialize as string
+ if self.commands.len() == 1 && self.commands[0].name.is_none() {
+ return self.commands[0].template.serialize(serializer);
+ }
+
+ // If all commands are unnamed or numbered 1,2,3..., serialize as array
+ let all_numbered = self
+ .commands
+ .iter()
+ .enumerate()
+ .all(|(i, cmd)| cmd.name.as_ref().is_none_or(|n| n == &(i + 1).to_string()));
+
+ if all_numbered {
+ let templates: Vec<_> = self.commands.iter().map(|cmd| &cmd.template).collect();
+ return templates.serialize(serializer);
+ }
+
+ // Otherwise serialize as named map
+ // At this point, all commands must have names (from Named TOML format)
+ let mut map = serializer.serialize_map(Some(self.commands.len()))?;
+ for cmd in &self.commands {
+ let key = cmd
+ .name
+ .as_ref()
+ .expect("named format requires all commands to have names");
+ map.serialize_entry(key, &cmd.template)?;
+ }
+ map.end()
+ }
+}
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
new file mode 100644
index 000000000..70aca74ee
--- /dev/null
+++ b/src/config/expansion.rs
@@ -0,0 +1,110 @@
+//! Template expansion utilities for worktrunk
+//!
+//! Provides functions for expanding template variables in paths and commands with
+//! proper shell escaping to prevent injection vulnerabilities.
+
+use std::path::PathBuf;
+
+/// Expand template variables in a string
+///
+/// All templates support:
+/// - `{main-worktree}` - Main worktree directory name
+/// - `{branch}` - Branch name (sanitized: slashes → dashes)
+///
+/// Additional variables can be provided via the `extra` parameter.
+///
+/// # Examples
+/// ```
+/// use worktrunk::config::expand_template;
+/// use std::collections::HashMap;
+///
+/// let result = expand_template("path/{main-worktree}/{branch}", "myrepo", "feature/foo", &HashMap::new());
+/// assert_eq!(result, "path/myrepo/feature-foo");
+/// ```
+pub fn expand_template(
+ template: &str,
+ main_worktree: &str,
+ branch: &str,
+ extra: &std::collections::HashMap<&str, &str>,
+) -> String {
+ use shell_escape::escape;
+ use std::borrow::Cow;
+
+ // Sanitize branch name by replacing path separators
+ let safe_branch = branch.replace(['/', '\\'], "-");
+
+ // Shell-escape all variables to prevent issues with spaces and special characters
+ let escaped_worktree = escape(Cow::Borrowed(main_worktree));
+ let escaped_branch = escape(Cow::Borrowed(safe_branch.as_str()));
+
+ let mut result = template
+ .replace("{main-worktree}", &escaped_worktree)
+ .replace("{branch}", &escaped_branch);
+
+ // Apply any extra variables (also escaped)
+ for (key, value) in extra {
+ let escaped_value = escape(Cow::Borrowed(*value));
+ result = result.replace(&format!("{{{}}}", key), &escaped_value);
+ }
+
+ result
+}
+
+/// Expand tilde in file paths to home directory (cross-platform)
+///
+/// Uses shellexpand for proper tilde expansion following shell conventions.
+///
+/// # Examples
+/// ```
+/// use worktrunk::config::expand_tilde;
+///
+/// let path = expand_tilde("~/config/file.txt");
+/// // Unix: /home/user/config/file.txt
+/// // Windows: C:\Users\user\config\file.txt
+/// ```
+pub fn expand_tilde(path: &str) -> PathBuf {
+ PathBuf::from(shellexpand::tilde(path).as_ref())
+}
+
+/// Expand command template variables
+///
+/// Convenience function for expanding command templates with common variables.
+///
+/// Supported variables:
+/// - `{repo}` - Repository name
+/// - `{branch}` - Branch name (sanitized)
+/// - `{worktree}` - Path to the worktree
+/// - `{repo_root}` - Path to the main repository root
+/// - `{target}` - Target branch (for merge commands, optional)
+///
+/// # Examples
+/// ```
+/// use worktrunk::config::expand_command_template;
+/// use std::path::Path;
+///
+/// let cmd = expand_command_template(
+/// "cp {repo_root}/target {worktree}/target",
+/// "myrepo",
+/// "feature",
+/// Path::new("/path/to/worktree"),
+/// Path::new("/path/to/repo"),
+/// None,
+/// );
+/// ```
+pub fn expand_command_template(
+ command: &str,
+ repo_name: &str,
+ branch: &str,
+ worktree_path: &std::path::Path,
+ repo_root: &std::path::Path,
+ target_branch: Option<&str>,
+) -> String {
+ let mut extra = std::collections::HashMap::new();
+ extra.insert("worktree", worktree_path.to_str().unwrap_or(""));
+ extra.insert("repo_root", repo_root.to_str().unwrap_or(""));
+ if let Some(target) = target_branch {
+ extra.insert("target", target);
+ }
+
+ expand_template(command, repo_name, branch, &extra)
+}
diff --git a/src/config/mod.rs b/src/config/mod.rs
index d420d7532..0fc12bf56 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -36,761 +36,18 @@
//! User config controls "how worktrunk behaves for me", project config controls
//! "what commands run for this project".
-use config::{Config, ConfigError, File};
-use indexmap::IndexMap;
-use serde::{Deserialize, Serialize};
-use std::path::PathBuf;
-use toml;
-
-#[cfg(not(test))]
-use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};
-
+mod commands;
+mod expansion;
+mod project;
#[cfg(test)]
mod test;
+mod user;
-/// User-level configuration for worktree path formatting and LLM integration.
-///
-/// This config is stored at `~/.config/worktrunk/config.toml` (or platform equivalent)
-/// and is NOT checked into git. Each developer maintains their own user config.
-///
-/// The `worktree-path` template is relative to the repository root.
-/// Supported variables:
-/// - `{main-worktree}` - Main worktree directory name
-/// - `{branch}` - Branch name (slashes replaced with dashes)
-///
-/// # Examples
-///
-/// ```toml
-/// # Default - parent directory siblings
-/// worktree-path = "../{main-worktree}.{branch}"
-///
-/// # Inside repo (clean, no redundant directory)
-/// worktree-path = ".worktrees/{branch}"
-///
-/// # Repository-namespaced (useful for shared directories with multiple repos)
-/// worktree-path = "../worktrees/{main-worktree}/{branch}"
-///
-/// # Commit generation configuration
-/// [commit-generation]
-/// command = "llm" # Command to invoke for generating commit messages (e.g., "llm", "claude")
-/// args = ["-s"] # Arguments to pass to the command
-///
-/// # Per-project configuration
-/// [projects."github.com/user/repo"]
-/// approved-commands = ["npm install", "npm test"]
-/// ```
-///
-/// Config file location:
-/// - Linux: `$XDG_CONFIG_HOME/worktrunk/config.toml` or `~/.config/worktrunk/config.toml`
-/// - macOS: `$XDG_CONFIG_HOME/worktrunk/config.toml` or `~/.config/worktrunk/config.toml`
-/// - Windows: `%APPDATA%\worktrunk\config.toml`
-///
-/// Environment variable: `WORKTRUNK_WORKTREE_PATH`
-#[derive(Debug, Serialize, Deserialize)]
-pub struct WorktrunkConfig {
- #[serde(rename = "worktree-path")]
- pub worktree_path: String,
-
- #[serde(default, rename = "commit-generation")]
- pub commit_generation: CommitGenerationConfig,
-
- /// Per-project configuration (approved commands, etc.)
- /// Uses BTreeMap for deterministic serialization order and better diff readability
- #[serde(default)]
- pub projects: std::collections::BTreeMap<String, UserProjectConfig>,
-}
-
-/// Configuration for commit message generation
-#[derive(Debug, Serialize, Deserialize, Clone, Default)]
-pub struct CommitGenerationConfig {
- /// Command to invoke for generating commit messages (e.g., "llm", "claude")
- #[serde(default)]
- pub command: Option<String>,
-
- /// Arguments to pass to the command
- #[serde(default)]
- pub args: Vec<String>,
-
- /// Inline template for commit message prompt
- /// Available variables: {{ git_diff }}, {{ branch }}, {{ recent_commits }}, {{ repo }}
- #[serde(default)]
- pub template: Option<String>,
-
- /// Path to template file (mutually exclusive with template)
- /// Supports tilde expansion (e.g., "~/.config/worktrunk/commit-template.txt")
- #[serde(default, rename = "template-file")]
- pub template_file: Option<String>,
-
- /// Inline template for squash commit message prompt
- /// Available variables: {{ commits }}, {{ target_branch }}, {{ branch }}, {{ repo }}
- #[serde(default, rename = "squash-template")]
- pub squash_template: Option<String>,
-
- /// Path to squash template file (mutually exclusive with squash-template)
- /// Supports tilde expansion (e.g., "~/.config/worktrunk/squash-template.txt")
- #[serde(default, rename = "squash-template-file")]
- pub squash_template_file: Option<String>,
-}
-
-impl CommitGenerationConfig {
- /// Returns true if an LLM command is configured
- pub fn is_configured(&self) -> bool {
- self.command
- .as_ref()
- .map(|s| !s.trim().is_empty())
- .unwrap_or(false)
- }
-}
-
-/// Project-specific configuration with hooks and commands.
-///
-/// This config is stored at `<repo>/.config/wt.toml` within the repository and
-/// IS checked into git. It defines project-specific commands that run automatically
-/// during worktree operations. All developers working on the project share this config.
-///
-/// # Template Variables
-///
-/// All commands support these template variables:
-/// - `{repo}` - Repository name (e.g., "my-project")
-/// - `{branch}` - Branch name (e.g., "feature-foo")
-/// - `{worktree}` - Absolute path to the worktree
-/// - `{repo_root}` - Absolute path to the repository root
-///
-/// Merge-related commands (`pre-commit-command`, `pre-merge-command`, `post-merge-command`) also support:
-/// - `{target}` - Target branch for the merge (e.g., "main")
-#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
-pub struct ProjectConfig {
- /// Commands to execute sequentially before worktree is ready (blocking)
- /// Supports string (single command), array (sequential), or table (named, sequential)
- ///
- /// Available template variables: `{repo}`, `{branch}`, `{worktree}`, `{repo_root}`
- #[serde(default, rename = "post-create-command")]
- pub post_create_command: Option<CommandConfig>,
-
- /// Commands to execute in parallel as background processes (non-blocking)
- /// Supports string (single), array (parallel), or table (named, parallel)
- ///
- /// Available template variables: `{repo}`, `{branch}`, `{worktree}`, `{repo_root}`
- #[serde(default, rename = "post-start-command")]
- pub post_start_command: Option<CommandConfig>,
-
- /// Commands to execute before committing changes during merge (blocking, fail-fast validation)
- /// Supports string (single command), array (sequential), or table (named, sequential)
- /// All commands must exit with code 0 for commit to proceed
- /// Runs before any commit operation during `wt merge` (both squash and no-squash modes)
- ///
- /// Available template variables: `{repo}`, `{branch}`, `{worktree}`, `{repo_root}`, `{target}`
- #[serde(default, rename = "pre-commit-command")]
- pub pre_commit_command: Option<CommandConfig>,
-
- /// Commands to execute before merging (blocking, fail-fast validation)
- /// Supports string (single command), array (sequential), or table (named, sequential)
- /// All commands must exit with code 0 for merge to proceed
- ///
- /// Available template variables: `{repo}`, `{branch}`, `{worktree}`, `{repo_root}`, `{target}`
- #[serde(default, rename = "pre-merge-command")]
- pub pre_merge_command: Option<CommandConfig>,
-
- /// Commands to execute after successful merge in the main worktree (blocking)
- /// Supports string (single command), array (sequential), or table (named, sequential)
- /// Runs after push succeeds but before cleanup
- ///
- /// Available template variables: `{repo}`, `{branch}`, `{worktree}`, `{repo_root}`, `{target}`
- #[serde(default, rename = "post-merge-command")]
- pub post_merge_command: Option<CommandConfig>,
-}
-
-/// Phase in which a command executes
-#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display, strum::AsRefStr)]
-#[strum(serialize_all = "kebab-case")]
-pub enum CommandPhase {
- /// After creating a worktree (blocking)
- PostCreate,
- /// After creating a worktree (background)
- PostStart,
- /// Before committing during merge (blocking, fail-fast)
- PreCommit,
- /// Before merging (blocking, fail-fast)
- PreMerge,
- /// After successful merge (blocking)
- PostMerge,
-}
-
-/// Represents a command with its template and optionally expanded form
-#[derive(Debug, Clone, PartialEq)]
-pub struct Command {
- /// Optional name for the command (e.g., "build", "test", or auto-numbered "1", "2")
- pub name: Option<String>,
- /// Template string that may contain variables like {branch}, {worktree}
- pub template: String,
- /// Expanded command with variables substituted (same as template if not expanded yet)
- pub expanded: String,
- /// Phase in which this command executes
- pub phase: CommandPhase,
-}
-
-impl Command {
- /// Create a new command from a template (not yet expanded)
- pub fn new(name: Option<String>, template: String, phase: CommandPhase) -> Self {
- Self {
- name,
- expanded: template.clone(),
- template,
- phase,
- }
- }
-
- /// Create a command with both template and expanded forms
- pub fn with_expansion(
- name: Option<String>,
- template: String,
- expanded: String,
- phase: CommandPhase,
- ) -> Self {
- Self {
- name,
- template,
- expanded,
- phase,
- }
- }
-}
-
-/// Configuration for commands - canonical representation
-///
-/// Internally stores commands as `Vec<Command>` for uniform processing.
-/// Deserializes from three TOML formats:
-/// - Single string: `post-create-command = "npm install"`
-/// - Array: `post-create-command = ["npm install", "npm test"]`
-/// - Named table: `[post-create-command]` followed by `install = "npm install"`
-///
-/// **Order preservation:** Named commands preserve TOML insertion order (requires
-/// `preserve_order` feature on toml crate and IndexMap for deserialization). This
-/// allows users to control execution order explicitly.
-///
-/// This canonical form eliminates branching at call sites - code just iterates over commands.
-#[derive(Debug, Clone, PartialEq)]
-pub struct CommandConfig {
- commands: Vec<Command>,
-}
-
-impl CommandConfig {
- /// Returns the commands as a slice
- pub fn commands(&self) -> &[Command] {
- &self.commands
- }
-
- /// Returns commands with the specified phase
- pub fn commands_with_phase(&self, phase: CommandPhase) -> Vec<Command> {
- self.commands
- .iter()
- .map(|cmd| Command {
- phase,
- ..cmd.clone()
- })
- .collect()
- }
-}
-
-// Custom deserialization to handle 3 TOML formats
-impl<'de> Deserialize<'de> for CommandConfig {
- fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where
- D: serde::Deserializer<'de>,
- {
- #[derive(Deserialize)]
- #[serde(untagged)]
- enum CommandConfigToml {
- Single(String),
- Multiple(Vec<String>),
- Named(IndexMap<String, String>),
- }
-
- let toml = CommandConfigToml::deserialize(deserializer)?;
- let commands = match toml {
- CommandConfigToml::Single(cmd) => {
- // Phase will be set later when commands are collected
- vec![Command::new(None, cmd, CommandPhase::PostCreate)]
- }
- CommandConfigToml::Multiple(cmds) => cmds
- .into_iter()
- .map(|template| Command::new(None, template, CommandPhase::PostCreate))
- .collect(),
- CommandConfigToml::Named(map) => {
- // IndexMap preserves insertion order from TOML
- map.into_iter()
- .map(|(name, template)| {
- Command::new(Some(name), template, CommandPhase::PostCreate)
- })
- .collect()
- }
- };
- Ok(CommandConfig { commands })
- }
-}
-
-// Serialize back to most appropriate format
-impl Serialize for CommandConfig {
- fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where
- S: serde::Serializer,
- {
- use serde::ser::SerializeMap;
-
- // If single unnamed command, serialize as string
- if self.commands.len() == 1 && self.commands[0].name.is_none() {
- return self.commands[0].template.serialize(serializer);
- }
-
- // If all commands are unnamed or numbered 1,2,3..., serialize as array
- let all_numbered = self
- .commands
- .iter()
- .enumerate()
- .all(|(i, cmd)| cmd.name.as_ref().is_none_or(|n| n == &(i + 1).to_string()));
-
- if all_numbered {
- let templates: Vec<_> = self.commands.iter().map(|cmd| &cmd.template).collect();
- return templates.serialize(serializer);
- }
-
- // Otherwise serialize as named map
- // At this point, all commands must have names (from Named TOML format)
- let mut map = serializer.serialize_map(Some(self.commands.len()))?;
- for cmd in &self.commands {
- let key = cmd
- .name
- .as_ref()
- .expect("named format requires all commands to have names");
- map.serialize_entry(key, &cmd.template)?;
- }
- map.end()
- }
-}
-
-/// Per-project user configuration
-///
-/// Stored in the user's config file under `[projects."project-id"]`.
-/// Contains project-specific settings that are user preferences, not checked into git.
-///
-/// # TOML Format
-/// ```toml
-/// [projects."github.com/user/repo"]
-/// approved-commands = ["npm install", "npm test"]
-/// ```
-///
-/// # Future Extensibility
-/// This structure is designed to accommodate additional per-project settings:
-/// - default-target-branch
-/// - auto-squash preferences
-/// - project-specific hooks
-#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
-pub struct UserProjectConfig {
- /// Commands that have been approved for automatic execution in this project
- #[serde(
- default,
- rename = "approved-commands",
- skip_serializing_if = "Vec::is_empty"
- )]
- pub approved_commands: Vec<String>,
-}
-
-impl Default for WorktrunkConfig {
- fn default() -> Self {
- Self {
- worktree_path: "../{main-worktree}.{branch}".to_string(),
- commit_generation: CommitGenerationConfig::default(),
- projects: std::collections::BTreeMap::new(),
- }
- }
-}
-
-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 (see struct documentation for platform-specific paths)
- /// 3. Environment variables (WORKTRUNK_*)
- pub fn load() -> Result<Self, ConfigError> {
- let defaults = Self::default();
-
- let mut builder = Config::builder()
- .set_default("worktree-path", defaults.worktree_path)?
- .set_default(
- "commit-generation.command",
- defaults.commit_generation.command.unwrap_or_default(),
- )?
- .set_default("commit-generation.args", defaults.commit_generation.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));
- }
-
- // Add environment variables with WORKTRUNK prefix
- builder = builder.add_source(config::Environment::with_prefix("WORKTRUNK").separator("_"));
-
- let config: Self = builder.build()?.try_deserialize()?;
-
- // Validate worktree path
- if config.worktree_path.is_empty() {
- return Err(ConfigError::Message("worktree-path cannot be empty".into()));
- }
- if std::path::Path::new(&config.worktree_path).is_absolute() {
- return Err(ConfigError::Message(
- "worktree-path must be relative, not absolute".into(),
- ));
- }
-
- // Validate commit generation config
- if config.commit_generation.template.is_some()
- && config.commit_generation.template_file.is_some()
- {
- return Err(ConfigError::Message(
- "commit-generation.template and commit-generation.template-file are mutually exclusive".into(),
- ));
- }
-
- if config.commit_generation.squash_template.is_some()
- && config.commit_generation.squash_template_file.is_some()
- {
- return Err(ConfigError::Message(
- "commit-generation.squash-template and commit-generation.squash-template-file are mutually exclusive".into(),
- ));
- }
-
- Ok(config)
- }
-
- /// Format a worktree path using this configuration's template.
- ///
- /// # Arguments
- /// * `main_worktree` - Main worktree directory name (replaces {main-worktree} 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, main_worktree: &str, branch: &str) -> String {
- expand_template(
- &self.worktree_path,
- main_worktree,
- branch,
- &std::collections::HashMap::new(),
- )
- }
-}
-
-pub fn get_config_path() -> Option<PathBuf> {
- // Check for test override first (WORKTRUNK_CONFIG_PATH env var)
- if let Ok(path) = std::env::var("WORKTRUNK_CONFIG_PATH") {
- return Some(PathBuf::from(path));
- }
-
- // In test builds, WORKTRUNK_CONFIG_PATH must be set to prevent polluting user config
- #[cfg(test)]
- panic!(
- "WORKTRUNK_CONFIG_PATH not set in test. Tests must use TestRepo which sets this automatically, \
- or set it manually to an isolated test config path."
- );
-
- // Production: use standard config location
- // choose_base_strategy uses:
- // - XDG on Linux (respects XDG_CONFIG_HOME, falls back to ~/.config)
- // - XDG on macOS (~/.config instead of ~/Library/Application Support)
- // - Windows conventions on Windows (%APPDATA%)
- #[cfg(not(test))]
- {
- let strategy = choose_base_strategy().ok()?;
- Some(strategy.config_dir().join("worktrunk").join("config.toml"))
- }
-}
-
-/// Expand template variables in a string
-///
-/// All templates support:
-/// - `{main-worktree}` - Main worktree directory name
-/// - `{branch}` - Branch name (sanitized: slashes → dashes)
-///
-/// Additional variables can be provided via the `extra` parameter.
-///
-/// # Examples
-/// ```
-/// use worktrunk::config::expand_template;
-/// use std::collections::HashMap;
-///
-/// let result = expand_template("path/{main-worktree}/{branch}", "myrepo", "feature/foo", &HashMap::new());
-/// assert_eq!(result, "path/myrepo/feature-foo");
-/// ```
-pub fn expand_template(
- template: &str,
- main_worktree: &str,
- branch: &str,
- extra: &std::collections::HashMap<&str, &str>,
-) -> String {
- use shell_escape::escape;
- use std::borrow::Cow;
-
- // Sanitize branch name by replacing path separators
- let safe_branch = branch.replace(['/', '\\'], "-");
-
- // Shell-escape all variables to prevent issues with spaces and special characters
- let escaped_worktree = escape(Cow::Borrowed(main_worktree));
- let escaped_branch = escape(Cow::Borrowed(safe_branch.as_str()));
-
- let mut result = template
- .replace("{main-worktree}", &escaped_worktree)
- .replace("{branch}", &escaped_branch);
-
- // Apply any extra variables (also escaped)
- for (key, value) in extra {
- let escaped_value = escape(Cow::Borrowed(*value));
- result = result.replace(&format!("{{{}}}", key), &escaped_value);
- }
-
- result
-}
-
-/// Expand tilde in file paths to home directory (cross-platform)
-///
-/// Uses shellexpand for proper tilde expansion following shell conventions.
-///
-/// # Examples
-/// ```
-/// use worktrunk::config::expand_tilde;
-///
-/// let path = expand_tilde("~/config/file.txt");
-/// // Unix: /home/user/config/file.txt
-/// // Windows: C:\Users\user\config\file.txt
-/// ```
-pub fn expand_tilde(path: &str) -> PathBuf {
- PathBuf::from(shellexpand::tilde(path).as_ref())
-}
-
-/// Expand command template variables
-///
-/// Convenience function for expanding command templates with common variables.
-///
-/// Supported variables:
-/// - `{repo}` - Repository name
-/// - `{branch}` - Branch name (sanitized)
-/// - `{worktree}` - Path to the worktree
-/// - `{repo_root}` - Path to the main repository root
-/// - `{target}` - Target branch (for merge commands, optional)
-///
-/// # Examples
-/// ```
-/// use worktrunk::config::expand_command_template;
-/// use std::path::Path;
-///
-/// let cmd = expand_command_template(
-/// "cp {repo_root}/target {worktree}/target",
-/// "myrepo",
-/// "feature",
-/// Path::new("/path/to/worktree"),
-/// Path::new("/path/to/repo"),
-/// None,
-/// );
-/// ```
-pub fn expand_command_template(
- command: &str,
- repo_name: &str,
- branch: &str,
- worktree_path: &std::path::Path,
- repo_root: &std::path::Path,
- target_branch: Option<&str>,
-) -> String {
- let mut extra = std::collections::HashMap::new();
- extra.insert("worktree", worktree_path.to_str().unwrap_or(""));
- extra.insert("repo_root", repo_root.to_str().unwrap_or(""));
- if let Some(target) = target_branch {
- extra.insert("target", target);
- }
-
- expand_template(command, repo_name, branch, &extra)
-}
-
-impl ProjectConfig {
- /// Load project configuration from .config/wt.toml in the repository root
- pub fn load(repo_root: &std::path::Path) -> Result<Option<Self>, ConfigError> {
- let config_path = repo_root.join(".config").join("wt.toml");
-
- if !config_path.exists() {
- return Ok(None);
- }
-
- // Load directly with toml crate to preserve insertion order (with preserve_order feature)
- let contents = std::fs::read_to_string(&config_path)
- .map_err(|e| ConfigError::Message(format!("Failed to read config file: {}", e)))?;
-
- let config: ProjectConfig = toml::from_str(&contents)
- .map_err(|e| ConfigError::Message(format!("Failed to parse TOML: {}", e)))?;
-
- Ok(Some(config))
- }
-}
-
-impl WorktrunkConfig {
- /// Check if a command is approved for the given project
- pub fn is_command_approved(&self, project: &str, command: &str) -> bool {
- self.projects
- .get(project)
- .map(|p| p.approved_commands.iter().any(|c| c == command))
- .unwrap_or(false)
- }
-
- /// Add an approved command and save to config file
- pub fn approve_command(&mut self, project: String, command: String) -> Result<(), ConfigError> {
- // Don't add duplicates
- if self.is_command_approved(&project, &command) {
- return Ok(());
- }
-
- self.projects
- .entry(project)
- .or_default()
- .approved_commands
- .push(command);
- self.save()
- }
-
- /// Add an approved command and save to a specific config file (for testing)
- ///
- /// This is the same as `approve_command()` but saves to an explicit path
- /// instead of the default user config location. Use this in tests to avoid
- /// polluting the user's actual config.
- pub fn approve_command_to(
- &mut self,
- project: String,
- command: String,
- config_path: &std::path::Path,
- ) -> Result<(), ConfigError> {
- // Don't add duplicates
- if self.is_command_approved(&project, &command) {
- return Ok(());
- }
-
- self.projects
- .entry(project)
- .or_default()
- .approved_commands
- .push(command);
- self.save_to(config_path)
- }
-
- /// Revoke an approved command and save to config file
- ///
- /// Removes the specified command from the project's approved commands list.
- /// If this results in an empty project entry, the project is removed entirely.
- pub fn revoke_command(&mut self, project: &str, command: &str) -> Result<(), ConfigError> {
- if let Some(project_config) = self.projects.get_mut(project) {
- let len_before = project_config.approved_commands.len();
- project_config.approved_commands.retain(|c| c != command);
- let changed = len_before != project_config.approved_commands.len();
-
- // Clean up empty project entries
- if project_config.approved_commands.is_empty() {
- self.projects.remove(project);
- }
-
- if changed {
- self.save()?;
- }
- }
- Ok(())
- }
-
- /// Remove all approvals for a project and save to config file
- ///
- /// Removes the entire project entry from the configuration.
- pub fn revoke_project(&mut self, project: &str) -> Result<(), ConfigError> {
- if self.projects.remove(project).is_some() {
- self.save()?;
- }
- Ok(())
- }
-
- /// Revoke an approved command and save to a specific config file (for testing)
- ///
- /// This is the same as `revoke_command()` but saves to an explicit path
- /// instead of the default user config location. Use this in tests to avoid
- /// polluting the user's actual config.
- #[doc(hidden)]
- pub fn revoke_command_to(
- &mut self,
- project: &str,
- command: &str,
- config_path: &std::path::Path,
- ) -> Result<(), ConfigError> {
- if let Some(project_config) = self.projects.get_mut(project) {
- let len_before = project_config.approved_commands.len();
- project_config.approved_commands.retain(|c| c != command);
- let changed = len_before != project_config.approved_commands.len();
-
- // Clean up empty project entries
- if project_config.approved_commands.is_empty() {
- self.projects.remove(project);
- }
-
- if changed {
- self.save_to(config_path)?;
- }
- }
- Ok(())
- }
-
- /// Remove all approvals for a project and save to a specific config file (for testing)
- ///
- /// This is the same as `revoke_project()` but saves to an explicit path
- /// instead of the default user config location. Use this in tests to avoid
- /// polluting the user's actual config.
- #[doc(hidden)]
- pub fn revoke_project_to(
- &mut self,
- project: &str,
- config_path: &std::path::Path,
- ) -> Result<(), ConfigError> {
- if self.projects.remove(project).is_some() {
- self.save_to(config_path)?;
- }
- Ok(())
- }
-
- /// Save the current configuration to the default config file location
- pub fn save(&self) -> Result<(), ConfigError> {
- let config_path = get_config_path()
- .ok_or_else(|| ConfigError::Message("Could not determine config path".to_string()))?;
- self.save_to(&config_path)
- }
-
- /// Save the current configuration to a specific file path
- ///
- /// Use this in tests to save to a temporary location instead of the user's config.
- pub fn save_to(&self, config_path: &std::path::Path) -> Result<(), ConfigError> {
- // Create parent directory if it doesn't exist
- if let Some(parent) = config_path.parent() {
- std::fs::create_dir_all(parent).map_err(|e| {
- ConfigError::Message(format!("Failed to create config directory: {}", e))
- })?;
- }
-
- let toml_string = toml::to_string_pretty(self)
- .map_err(|e| ConfigError::Message(format!("Failed to serialize config: {}", e)))?;
-
- std::fs::write(config_path, toml_string)
- .map_err(|e| ConfigError::Message(format!("Failed to write config file: {}", e)))?;
-
- Ok(())
- }
-}
+// Re-export public types
+pub use commands::{Command, CommandConfig, CommandPhase};
+pub use expansion::{expand_command_template, expand_template, expand_tilde};
+pub use project::ProjectConfig;
+pub use user::{CommitGenerationConfig, UserProjectConfig, WorktrunkConfig, get_config_path};
#[cfg(test)]
mod tests {
@@ -1409,7 +666,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
#[test]
fn test_expand_tilde_without_tilde() {
let result = expand_tilde("/absolute/path");
- assert_eq!(result, PathBuf::from("/absolute/path"));
+ assert_eq!(result, std::path::PathBuf::from("/absolute/path"));
}
#[test]
diff --git a/src/config/project.rs b/src/config/project.rs
new file mode 100644
index 000000000..30fde6b54
--- /dev/null
+++ b/src/config/project.rs
@@ -0,0 +1,86 @@
+//! Project-level configuration
+//!
+//! Configuration that is checked into the repository and shared across all developers.
+
+use config::ConfigError;
+use serde::{Deserialize, Serialize};
+
+use super::commands::CommandConfig;
+
+/// Project-specific configuration with hooks and commands.
+///
+/// This config is stored at `<repo>/.config/wt.toml` within the repository and
+/// IS checked into git. It defines project-specific commands that run automatically
+/// during worktree operations. All developers working on the project share this config.
+///
+/// # Template Variables
+///
+/// All commands support these template variables:
+/// - `{repo}` - Repository name (e.g., "my-project")
+/// - `{branch}` - Branch name (e.g., "feature-foo")
+/// - `{worktree}` - Absolute path to the worktree
+/// - `{repo_root}` - Absolute path to the repository root
+///
+/// Merge-related commands (`pre-commit-command`, `pre-merge-command`, `post-merge-command`) also support:
+/// - `{target}` - Target branch for the merge (e.g., "main")
+#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
+pub struct ProjectConfig {
+ /// Commands to execute sequentially before worktree is ready (blocking)
+ /// Supports string (single command), array (sequential), or table (named, sequential)
+ ///
+ /// Available template variables: `{repo}`, `{branch}`, `{worktree}`, `{repo_root}`
+ #[serde(default, rename = "post-create-command")]
+ pub post_create_command: Option<CommandConfig>,
+
+ /// Commands to execute in parallel as background processes (non-blocking)
+ /// Supports string (single), array (parallel), or table (named, parallel)
+ ///
+ /// Available template variables: `{repo}`, `{branch}`, `{worktree}`, `{repo_root}`
+ #[serde(default, rename = "post-start-command")]
+ pub post_start_command: Option<CommandConfig>,
+
+ /// Commands to execute before committing changes during merge (blocking, fail-fast validation)
+ /// Supports string (single command), array (sequential), or table (named, sequential)
+ /// All commands must exit with code 0 for commit to proceed
+ /// Runs before any commit operation during `wt merge` (both squash and no-squash modes)
+ ///
+ /// Available template variables: `{repo}`, `{branch}`, `{worktree}`, `{repo_root}`, `{target}`
+ #[serde(default, rename = "pre-commit-command")]
+ pub pre_commit_command: Option<CommandConfig>,
+
+ /// Commands to execute before merging (blocking, fail-fast validation)
+ /// Supports string (single command), array (sequential), or table (named, sequential)
+ /// All commands must exit with code 0 for merge to proceed
+ ///
+ /// Available template variables: `{repo}`, `{branch}`, `{worktree}`, `{repo_root}`, `{target}`
+ #[serde(default, rename = "pre-merge-command")]
+ pub pre_merge_command: Option<CommandConfig>,
+
+ /// Commands to execute after successful merge in the main worktree (blocking)
+ /// Supports string (single command), array (sequential), or table (named, sequential)
+ /// Runs after push succeeds but before cleanup
+ ///
+ /// Available template variables: `{repo}`, `{branch}`, `{worktree}`, `{repo_root}`, `{target}`
+ #[serde(default, rename = "post-merge-command")]
+ pub post_merge_command: Option<CommandConfig>,
+}
+
+impl ProjectConfig {
+ /// Load project configuration from .config/wt.toml in the repository root
+ pub fn load(repo_root: &std::path::Path) -> Result<Option<Self>, ConfigError> {
+ let config_path = repo_root.join(".config").join("wt.toml");
+
+ if !config_path.exists() {
+ return Ok(None);
+ }
+
+ // Load directly with toml crate to preserve insertion order (with preserve_order feature)
+ let contents = std::fs::read_to_string(&config_path)
+ .map_err(|e| ConfigError::Message(format!("Failed to read config file: {}", e)))?;
+
+ let config: ProjectConfig = toml::from_str(&contents)
+ .map_err(|e| ConfigError::Message(format!("Failed to parse TOML: {}", e)))?;
+
+ Ok(Some(config))
+ }
+}
diff --git a/src/config/user.rs b/src/config/user.rs
new file mode 100644
index 000000000..770d8684e
--- /dev/null
+++ b/src/config/user.rs
@@ -0,0 +1,404 @@
+//! User-level configuration
+//!
+//! Personal preferences and per-project approved commands, not checked into git.
+
+use config::{Config, ConfigError, File};
+use serde::{Deserialize, Serialize};
+use std::path::PathBuf;
+
+#[cfg(not(test))]
+use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};
+
+use super::expansion::expand_template;
+
+/// User-level configuration for worktree path formatting and LLM integration.
+///
+/// This config is stored at `~/.config/worktrunk/config.toml` (or platform equivalent)
+/// and is NOT checked into git. Each developer maintains their own user config.
+///
+/// The `worktree-path` template is relative to the repository root.
+/// Supported variables:
+/// - `{main-worktree}` - Main worktree directory name
+/// - `{branch}` - Branch name (slashes replaced with dashes)
+///
+/// # Examples
+///
+/// ```toml
+/// # Default - parent directory siblings
+/// worktree-path = "../{main-worktree}.{branch}"
+///
+/// # Inside repo (clean, no redundant directory)
+/// worktree-path = ".worktrees/{branch}"
+///
+/// # Repository-namespaced (useful for shared directories with multiple repos)
+/// worktree-path = "../worktrees/{main-worktree}/{branch}"
+///
+/// # Commit generation configuration
+/// [commit-generation]
+/// command = "llm" # Command to invoke for generating commit messages (e.g., "llm", "claude")
+/// args = ["-s"] # Arguments to pass to the command
+///
+/// # Per-project configuration
+/// [projects."github.com/user/repo"]
+/// approved-commands = ["npm install", "npm test"]
+/// ```
+///
+/// Config file location:
+/// - Linux: `$XDG_CONFIG_HOME/worktrunk/config.toml` or `~/.config/worktrunk/config.toml`
+/// - macOS: `$XDG_CONFIG_HOME/worktrunk/config.toml` or `~/.config/worktrunk/config.toml`
+/// - Windows: `%APPDATA%\worktrunk\config.toml`
+///
+/// Environment variable: `WORKTRUNK_WORKTREE_PATH`
+#[derive(Debug, Serialize, Deserialize)]
+pub struct WorktrunkConfig {
+ #[serde(rename = "worktree-path")]
+ pub worktree_path: String,
+
+ #[serde(default, rename = "commit-generation")]
+ pub commit_generation: CommitGenerationConfig,
+
+ /// Per-project configuration (approved commands, etc.)
+ /// Uses BTreeMap for deterministic serialization order and better diff readability
+ #[serde(default)]
+ pub projects: std::collections::BTreeMap<String, UserProjectConfig>,
+}
+
+/// Configuration for commit message generation
+#[derive(Debug, Serialize, Deserialize, Clone, Default)]
+pub struct CommitGenerationConfig {
+ /// Command to invoke for generating commit messages (e.g., "llm", "claude")
+ #[serde(default)]
+ pub command: Option<String>,
+
+ /// Arguments to pass to the command
+ #[serde(default)]
+ pub args: Vec<String>,
+
+ /// Inline template for commit message prompt
+ /// Available variables: {{ git_diff }}, {{ branch }}, {{ recent_commits }}, {{ repo }}
+ #[serde(default)]
+ pub template: Option<String>,
+
+ /// Path to template file (mutually exclusive with template)
+ /// Supports tilde expansion (e.g., "~/.config/worktrunk/commit-template.txt")
+ #[serde(default, rename = "template-file")]
+ pub template_file: Option<String>,
+
+ /// Inline template for squash commit message prompt
+ /// Available variables: {{ commits }}, {{ target_branch }}, {{ branch }}, {{ repo }}
+ #[serde(default, rename = "squash-template")]
+ pub squash_template: Option<String>,
+
+ /// Path to squash template file (mutually exclusive with squash-template)
+ /// Supports tilde expansion (e.g., "~/.config/worktrunk/squash-template.txt")
+ #[serde(default, rename = "squash-template-file")]
+ pub squash_template_file: Option<String>,
+}
+
+impl CommitGenerationConfig {
+ /// Returns true if an LLM command is configured
+ pub fn is_configured(&self) -> bool {
+ self.command
+ .as_ref()
+ .map(|s| !s.trim().is_empty())
+ .unwrap_or(false)
+ }
+}
+
+/// Per-project user configuration
+///
+/// Stored in the user's config file under `[projects."project-id"]`.
+/// Contains project-specific settings that are user preferences, not checked into git.
+///
+/// # TOML Format
+/// ```toml
+/// [projects."github.com/user/repo"]
+/// approved-commands = ["npm install", "npm test"]
+/// ```
+///
+/// # Future Extensibility
+/// This structure is designed to accommodate additional per-project settings:
+/// - default-target-branch
+/// - auto-squash preferences
+/// - project-specific hooks
+#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
+pub struct UserProjectConfig {
+ /// Commands that have been approved for automatic execution in this project
+ #[serde(
+ default,
+ rename = "approved-commands",
+ skip_serializing_if = "Vec::is_empty"
+ )]
+ pub approved_commands: Vec<String>,
+}
+
+impl Default for WorktrunkConfig {
+ fn default() -> Self {
+ Self {
+ worktree_path: "../{main-worktree}.{branch}".to_string(),
+ commit_generation: CommitGenerationConfig::default(),
+ projects: std::collections::BTreeMap::new(),
+ }
+ }
+}
+
+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 (see struct documentation for platform-specific paths)
+ /// 3. Environment variables (WORKTRUNK_*)
+ pub fn load() -> Result<Self, ConfigError> {
+ let defaults = Self::default();
+
+ let mut builder = Config::builder()
+ .set_default("worktree-path", defaults.worktree_path)?
+ .set_default(
+ "commit-generation.command",
+ defaults.commit_generation.command.unwrap_or_default(),
+ )?
+ .set_default("commit-generation.args", defaults.commit_generation.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));
+ }
+
+ // Add environment variables with WORKTRUNK prefix
+ builder = builder.add_source(config::Environment::with_prefix("WORKTRUNK").separator("_"));
+
+ let config: Self = builder.build()?.try_deserialize()?;
+
+ // Validate worktree path
+ if config.worktree_path.is_empty() {
+ return Err(ConfigError::Message("worktree-path cannot be empty".into()));
+ }
+ if std::path::Path::new(&config.worktree_path).is_absolute() {
+ return Err(ConfigError::Message(
+ "worktree-path must be relative, not absolute".into(),
+ ));
+ }
+
+ // Validate commit generation config
+ if config.commit_generation.template.is_some()
+ && config.commit_generation.template_file.is_some()
+ {
+ return Err(ConfigError::Message(
+ "commit-generation.template and commit-generation.template-file are mutually exclusive".into(),
+ ));
+ }
+
+ if config.commit_generation.squash_template.is_some()
+ && config.commit_generation.squash_template_file.is_some()
+ {
+ return Err(ConfigError::Message(
+ "commit-generation.squash-template and commit-generation.squash-template-file are mutually exclusive".into(),
+ ));
+ }
+
+ Ok(config)
+ }
+
+ /// Format a worktree path using this configuration's template.
+ ///
+ /// # Arguments
+ /// * `main_worktree` - Main worktree directory name (replaces {main-worktree} 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, main_worktree: &str, branch: &str) -> String {
+ expand_template(
+ &self.worktree_path,
+ main_worktree,
+ branch,
+ &std::collections::HashMap::new(),
+ )
+ }
+
+ /// Check if a command is approved for the given project
+ pub fn is_command_approved(&self, project: &str, command: &str) -> bool {
+ self.projects
+ .get(project)
+ .map(|p| p.approved_commands.iter().any(|c| c == command))
+ .unwrap_or(false)
+ }
+
+ /// Add an approved command and save to config file
+ pub fn approve_command(&mut self, project: String, command: String) -> Result<(), ConfigError> {
+ // Don't add duplicates
+ if self.is_command_approved(&project, &command) {
+ return Ok(());
+ }
+
+ self.projects
+ .entry(project)
+ .or_default()
+ .approved_commands
+ .push(command);
+ self.save()
+ }
+
+ /// Add an approved command and save to a specific config file (for testing)
+ ///
+ /// This is the same as `approve_command()` but saves to an explicit path
+ /// instead of the default user config location. Use this in tests to avoid
+ /// polluting the user's actual config.
+ pub fn approve_command_to(
+ &mut self,
+ project: String,
+ command: String,
+ config_path: &std::path::Path,
+ ) -> Result<(), ConfigError> {
+ // Don't add duplicates
+ if self.is_command_approved(&project, &command) {
+ return Ok(());
+ }
+
+ self.projects
+ .entry(project)
+ .or_default()
+ .approved_commands
+ .push(command);
+ self.save_to(config_path)
+ }
+
+ /// Revoke an approved command and save to config file
+ ///
+ /// Removes the specified command from the project's approved commands list.
+ /// If this results in an empty project entry, the project is removed entirely.
+ pub fn revoke_command(&mut self, project: &str, command: &str) -> Result<(), ConfigError> {
+ if let Some(project_config) = self.projects.get_mut(project) {
+ let len_before = project_config.approved_commands.len();
+ project_config.approved_commands.retain(|c| c != command);
+ let changed = len_before != project_config.approved_commands.len();
+
+ // Clean up empty project entries
+ if project_config.approved_commands.is_empty() {
+ self.projects.remove(project);
+ }
+
+ if changed {
+ self.save()?;
+ }
+ }
+ Ok(())
+ }
+
+ /// Remove all approvals for a project and save to config file
+ ///
+ /// Removes the entire project entry from the configuration.
+ pub fn revoke_project(&mut self, project: &str) -> Result<(), ConfigError> {
+ if self.projects.remove(project).is_some() {
+ self.save()?;
+ }
+ Ok(())
+ }
+
+ /// Revoke an approved command and save to a specific config file (for testing)
+ ///
+ /// This is the same as `revoke_command()` but saves to an explicit path
+ /// instead of the default user config location. Use this in tests to avoid
+ /// polluting the user's actual config.
+ #[doc(hidden)]
+ pub fn revoke_command_to(
+ &mut self,
+ project: &str,
+ command: &str,
+ config_path: &std::path::Path,
+ ) -> Result<(), ConfigError> {
+ if let Some(project_config) = self.projects.get_mut(project) {
+ let len_before = project_config.approved_commands.len();
+ project_config.approved_commands.retain(|c| c != command);
+ let changed = len_before != project_config.approved_commands.len();
+
+ // Clean up empty project entries
+ if project_config.approved_commands.is_empty() {
+ self.projects.remove(project);
+ }
+
+ if changed {
+ self.save_to(config_path)?;
+ }
+ }
+ Ok(())
+ }
+
+ /// Remove all approvals for a project and save to a specific config file (for testing)
+ ///
+ /// This is the same as `revoke_project()` but saves to an explicit path
+ /// instead of the default user config location. Use this in tests to avoid
+ /// polluting the user's actual config.
+ #[doc(hidden)]
+ pub fn revoke_project_to(
+ &mut self,
+ project: &str,
+ config_path: &std::path::Path,
+ ) -> Result<(), ConfigError> {
+ if self.projects.remove(project).is_some() {
+ self.save_to(config_path)?;
+ }
+ Ok(())
+ }
+
+ /// Save the current configuration to the default config file location
+ pub fn save(&self) -> Result<(), ConfigError> {
+ let config_path = get_config_path()
+ .ok_or_else(|| ConfigError::Message("Could not determine config path".to_string()))?;
+ self.save_to(&config_path)
+ }
+
+ /// Save the current configuration to a specific file path
+ ///
+ /// Use this in tests to save to a temporary location instead of the user's config.
+ pub fn save_to(&self, config_path: &std::path::Path) -> Result<(), ConfigError> {
+ // Create parent directory if it doesn't exist
+ if let Some(parent) = config_path.parent() {
+ std::fs::create_dir_all(parent).map_err(|e| {
+ ConfigError::Message(format!("Failed to create config directory: {}", e))
+ })?;
+ }
+
+ let toml_string = toml::to_string_pretty(self)
+ .map_err(|e| ConfigError::Message(format!("Failed to serialize config: {}", e)))?;
+
+ std::fs::write(config_path, toml_string)
+ .map_err(|e| ConfigError::Message(format!("Failed to write config file: {}", e)))?;
+
+ Ok(())
+ }
+}
+
+pub fn get_config_path() -> Option<PathBuf> {
+ // Check for test override first (WORKTRUNK_CONFIG_PATH env var)
+ if let Ok(path) = std::env::var("WORKTRUNK_CONFIG_PATH") {
+ return Some(PathBuf::from(path));
+ }
+
+ // In test builds, WORKTRUNK_CONFIG_PATH must be set to prevent polluting user config
+ #[cfg(test)]
+ panic!(
+ "WORKTRUNK_CONFIG_PATH not set in test. Tests must use TestRepo which sets this automatically, \
+ or set it manually to an isolated test config path."
+ );
+
+ // Production: use standard config location
+ // choose_base_strategy uses:
+ // - XDG on Linux (respects XDG_CONFIG_HOME, falls back to ~/.config)
+ // - XDG on macOS (~/.config instead of ~/Library/Application Support)
+ // - Windows conventions on Windows (%APPDATA%)
+ #[cfg(not(test))]
+ {
+ let strategy = choose_base_strategy().ok()?;
+ Some(strategy.config_dir().join("worktrunk").join("config.toml"))
+ }
+}