Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Share command environment, config loading, and staged change detection helpers
Maximilian Roosd9f790356a17
diff --git a/src/commands/beta.rs b/src/commands/beta.rsindex d540e2898..29c8b2468 100644--- a/src/commands/beta.rs+++ b/src/commands/beta.rs@@ -1,31 +1,29 @@use worktrunk::HookType;-use worktrunk::config::{ProjectConfig, WorktrunkConfig};use worktrunk::git::{GitError, GitResultExt, Repository};use worktrunk::styling::{- AnstyleStyle, CYAN, CYAN_BOLD, GREEN_BOLD, HINT, HINT_BOLD, HINT_EMOJI, eprintln,- format_with_gutter,+ AnstyleStyle, CYAN, CYAN_BOLD, GREEN_BOLD, HINT, HINT_EMOJI, eprintln, format_with_gutter,};+use super::context::CommandEnv;use super::merge::{commit_staged_changes, execute_post_merge_commands, format_commit_message_for_display,run_pre_commit_commands, run_pre_merge_commands, show_llm_config_hint_if_needed,};+use super::project_config::{load_project_config, require_project_config};use super::worktree::{execute_post_create_commands, execute_post_start_commands_sequential};/// Handle `wt beta run-hook` commandpub fn handle_beta_run_hook(hook_type: HookType, force: bool) -> Result<(), GitError> {// Derive context from current environment- let repo = Repository::current();- let worktree_path = std::env::current_dir()- .map_err(|e| GitError::CommandFailed(format!("Failed to get current directory: {}", e)))?;- let branch = repo- .current_branch()- .git_context("Failed to get current branch")?- .ok_or_else(|| GitError::CommandFailed("Not on a branch (detached HEAD)".to_string()))?;- let config = WorktrunkConfig::load().git_context("Failed to load config")?;+ let CommandEnv {+ repo,+ branch,+ config,+ worktree_path,+ } = CommandEnv::current()?;// Load project config (show helpful error if missing)- let project_config = load_project_config(&repo)?;+ let project_config = require_project_config(&repo)?;// TODO: Add support for custom variable overrides (e.g., --var key=value)// This would allow testing hooks with different contexts without being in that context@@ -83,28 +81,6 @@ pub fn handle_beta_run_hook(hook_type: HookType, force: bool) -> Result<(), GitE}}-fn load_project_config(repo: &Repository) -> Result<ProjectConfig, GitError> {- let repo_root = repo.worktree_root()?;- let config_path = repo_root.join(".config").join("wt.toml");-- match ProjectConfig::load(&repo_root).git_context("Failed to load project config")? {- Some(cfg) => Ok(cfg),- None => {- // No project config found - show helpful error- use worktrunk::styling::ERROR;- use worktrunk::styling::ERROR_EMOJI;- eprintln!("{ERROR_EMOJI} {ERROR}No project configuration found{ERROR:#}",);- eprintln!(- "{HINT_EMOJI} {HINT}Create a config file at: {HINT_BOLD}{}{HINT_BOLD:#}{HINT:#}",- config_path.display()- );- Err(GitError::CommandFailed(- "No project configuration found".to_string(),- ))- }- }-}-fn check_hook_configured<T>(hook: &Option<T>, hook_type: HookType) -> Result<(), GitError> {if hook.is_none() {eprintln!(@@ -119,16 +95,15 @@ fn check_hook_configured<T>(hook: &Option<T>, hook_type: HookType) -> Result<(),/// Handle `wt beta commit` commandpub fn handle_beta_commit(force: bool, no_verify: bool) -> Result<(), GitError> {- let repo = Repository::current();- let config = WorktrunkConfig::load().git_context("Failed to load config")?;- let current_branch = repo- .current_branch()?- .ok_or_else(|| GitError::CommandFailed("Not on a branch (detached HEAD)".to_string()))?;+ let CommandEnv {+ repo,+ branch: current_branch,+ config,+ worktree_path,+ } = CommandEnv::current()?;// Run pre-commit hook unless --no-verify was specified- if !no_verify && let Ok(Some(project_config)) = ProjectConfig::load(&repo.worktree_root()?) {- let worktree_path =- std::env::current_dir().git_context("Failed to get current directory")?;+ if !no_verify && let Some(project_config) = load_project_config(&repo)? {// No target branch context for standalone commitsrun_pre_commit_commands(&project_config,@@ -161,19 +136,18 @@ pub fn handle_beta_squash(no_verify: bool,auto_trust: bool,) -> Result<bool, GitError> {- let repo = Repository::current();- let config = WorktrunkConfig::load().git_context("Failed to load config")?;- let current_branch = repo- .current_branch()?- .ok_or_else(|| GitError::CommandFailed("Not on a branch (detached HEAD)".to_string()))?;+ let CommandEnv {+ repo,+ branch: current_branch,+ config,+ worktree_path,+ } = CommandEnv::current()?;// Get target branch (default to default branch if not provided)let target_branch = repo.resolve_target_branch(target)?;// Run pre-commit hook unless --no-verify was specified- if !no_verify && let Ok(Some(project_config)) = ProjectConfig::load(&repo.worktree_root()?) {- let worktree_path =- std::env::current_dir().git_context("Failed to get current directory")?;+ if !no_verify && let Some(project_config) = load_project_config(&repo)? {run_pre_commit_commands(&project_config,¤t_branch,@@ -192,10 +166,8 @@ pub fn handle_beta_squash(// Count commits since merge baselet commit_count = repo.count_commits(&merge_base, "HEAD")?;- // Check if there are staged changes (git diff --cached returns 0 if no changes, 1 if changes exist)- let no_staged_changes =- repo.run_command_check(&["diff", "--cached", "--quiet", "--exit-code"])?;- let has_staged = !no_staged_changes;+ // Check if there are staged changes in addition to commits+ let has_staged = repo.has_staged_changes()?;// Handle different scenariosif commit_count == 0 && !has_staged {@@ -276,9 +248,7 @@ pub fn handle_beta_squash(.git_context("Failed to reset to merge base")?;// Check if there are actually any changes to commit- let no_staged_changes =- repo.run_command_check(&["diff", "--cached", "--quiet", "--exit-code"])?;- if no_staged_changes {+ if !repo.has_staged_changes()? {let dim = AnstyleStyle::new().dimmed();crate::output::info(format!("{dim}No changes after squashing {commit_count} {commit_text} (commits resulted in no net changes){dim:#}"@@ -396,7 +366,7 @@ pub fn handle_beta_ask_approvals(force: bool, show_all: bool) -> Result<(), GitElet config = WorktrunkConfig::load().git_context("Failed to load config")?;// Load project config (show helpful error if missing)- let project_config = load_project_config(&repo)?;+ let project_config = require_project_config(&repo)?;// Collect all commands from the project configlet mut commands = Vec::new();diff --git a/src/commands/context.rs b/src/commands/context.rsnew file mode 100644index 000000000..92b99726c--- /dev/null+++ b/src/commands/context.rs@@ -0,0 +1,42 @@+use std::path::PathBuf;+use worktrunk::config::WorktrunkConfig;+use worktrunk::git::{GitError, GitResultExt, Repository};++/// Shared execution context for command handlers that operate on the current worktree.+///+/// Centralizes the common “repo + branch + config + cwd” setup so individual handlers+/// can focus on their core logic while sharing consistent error messaging.+///+/// This helper is used for commands that explicitly act on “where the user is standing”+/// (e.g., `beta` and `merge`) and therefore need all of these pieces together. Commands that+/// inspect multiple worktrees or run without a config/branch requirement (`list`, `select`,+/// some `worktree` helpers) still call `Repository::current()` directly so they can operate in+/// broader contexts without forcing config loads or branch resolution.+pub struct CommandEnv {+ pub repo: Repository,+ pub branch: String,+ pub config: WorktrunkConfig,+ pub worktree_path: PathBuf,+}++impl CommandEnv {+ /// Load the command environment from the current process context.+ pub fn current() -> Result<Self, GitError> {+ let repo = Repository::current();+ let worktree_path = std::env::current_dir().map_err(|e| {+ GitError::CommandFailed(format!("Failed to get current directory: {}", e))+ })?;+ let branch = repo+ .current_branch()+ .git_context("Failed to get current branch")?+ .ok_or(GitError::DetachedHead)?;+ let config = WorktrunkConfig::load().git_context("Failed to load config")?;++ Ok(Self {+ repo,+ branch,+ config,+ worktree_path,+ })+ }+}diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex d6640a727..43c7954c6 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -1,3 +1,4 @@+use std::path::Path;use worktrunk::HookType;use worktrunk::config::{Command, CommandPhase, ProjectConfig, WorktrunkConfig};use worktrunk::git::{GitError, GitResultExt, Repository};@@ -8,6 +9,8 @@ use worktrunk::styling::{use super::command_approval::approve_command_batch;use super::command_executor::{CommandContext, prepare_project_commands};+use super::context::CommandEnv;+use super::project_config::load_project_config;use super::worktree::handle_push;use crate::output::execute_command_in_worktree;@@ -29,9 +32,7 @@ impl<'a> MergeCommandCollector<'a> {/// Returns original (unexpanded) commands for approval matchingfn collect(self) -> Result<CollectedCommands, GitError> {let mut all_commands = Vec::new();- let project_config = match ProjectConfig::load(&self.repo.worktree_root()?)- .git_context("Failed to load project config")?- {+ let project_config = match load_project_config(self.repo)? {Some(cfg) => cfg,None => return Ok((all_commands, self.repo.project_identifier()?)),};@@ -111,10 +112,12 @@ pub fn handle_merge(force: bool,tracked_only: bool,) -> Result<(), GitError> {- let repo = Repository::current();-- // Get current branch- let current_branch = repo.current_branch()?.ok_or(GitError::DetachedHead)?;+ let CommandEnv {+ repo,+ branch: current_branch,+ config,+ worktree_path,+ } = CommandEnv::current()?;// Validate --no-commit: requires clean working treeif no_commit && repo.is_dirty()? {@@ -143,9 +146,6 @@ pub fn handle_merge(return Ok(());}- // Load config for LLM integration- let config = WorktrunkConfig::load().git_context("Failed to load config")?;-// Collect and approve all commands upfront for batch permission requestlet (all_commands, project_id) = MergeCommandCollector {repo: &repo,@@ -177,7 +177,9 @@ pub fn handle_merge(} else {// Commit immediately when not squashinghandle_commit_changes(- &config.commit_generation,+ &repo,+ &config,+ &worktree_path,¤t_branch,Some(&target_branch),no_verify,@@ -206,9 +208,7 @@ pub fn handle_merge(// Run pre-merge checks unless --no-verify was specified// Do this after commit/squash/rebase to validate the final state that will be pushed- if !no_verify && let Ok(Some(project_config)) = ProjectConfig::load(&repo.worktree_root()?) {- let worktree_path =- std::env::current_dir().git_context("Failed to get current directory")?;+ if !no_verify && let Some(project_config) = load_project_config(&repo)? {run_pre_merge_commands(&project_config,¤t_branch,@@ -417,28 +417,25 @@ pub fn commit_staged_changes(Ok(())}-/// Commit uncommitted changes with LLM-generated message+/// Commit uncommitted changes with LLM-generated message.+#[allow(clippy::too_many_arguments)]fn handle_commit_changes(- commit_generation_config: &worktrunk::config::CommitGenerationConfig,+ repo: &Repository,+ config: &WorktrunkConfig,+ worktree_path: &Path,current_branch: &str,target_branch: Option<&str>,no_verify: bool,force: bool,tracked_only: bool,) -> Result<(), GitError> {- let repo = Repository::current();- let config = WorktrunkConfig::load().git_context("Failed to load config")?;-- // Run pre-commit hook unless --no-verify was specified- if !no_verify && let Ok(Some(project_config)) = ProjectConfig::load(&repo.worktree_root()?) {- let worktree_path =- std::env::current_dir().git_context("Failed to get current directory")?;+ if !no_verify && let Some(project_config) = load_project_config(repo)? {run_pre_commit_commands(&project_config,current_branch,- &worktree_path,- &repo,- &config,+ worktree_path,+ repo,+ config,force,target_branch,true, // auto_trust: commands already approved in merge batch@@ -447,7 +444,7 @@ fn handle_commit_changes(// Warn about untracked files before staging (only if using git add -A)if !tracked_only {- show_untracked_warning(&repo)?;+ show_untracked_warning(repo)?;}// Stage changes@@ -460,7 +457,7 @@ fn handle_commit_changes(}// Show "no squashing needed" since we're committing directly (not in squash mode)- commit_staged_changes(commit_generation_config, true)+ commit_staged_changes(&config.commit_generation, true)}fn handle_squash(target_branch: &str, no_verify: bool, force: bool) -> Result<bool, GitError> {@@ -536,9 +533,7 @@ pub fn execute_post_merge_commands(use worktrunk::styling::WARNING;// Load project config from the main worktree path directly- let project_config = match ProjectConfig::load(main_worktree_path)- .git_context("Failed to load project config")?- {+ let project_config = match load_project_config(repo)? {Some(cfg) => cfg,None => return Ok(()),};diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 649e6bc7e..e5f6ae2e9 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -4,10 +4,12 @@ mod command_executor;pub mod completion;pub mod config;pub mod configure_shell;+pub mod context;pub mod init;pub mod list;pub mod merge;pub mod process;+pub mod project_config;#[cfg(unix)]pub mod select;pub mod worktree;diff --git a/src/commands/project_config.rs b/src/commands/project_config.rsnew file mode 100644index 000000000..a5ca3a1aa--- /dev/null+++ b/src/commands/project_config.rs@@ -0,0 +1,35 @@+use std::path::Path;+use worktrunk::config::ProjectConfig;+use worktrunk::git::{GitError, GitResultExt, Repository};++fn load_project_config_at(repo_root: &Path) -> Result<Option<ProjectConfig>, GitError> {+ ProjectConfig::load(repo_root).git_context("Failed to load project config")+}++/// Load the project configuration if it exists.+pub fn load_project_config(repo: &Repository) -> Result<Option<ProjectConfig>, GitError> {+ let repo_root = repo.worktree_root()?;+ load_project_config_at(&repo_root)+}++/// Load the project configuration, emitting a helpful hint if missing.+pub fn require_project_config(repo: &Repository) -> Result<ProjectConfig, GitError> {+ let repo_root = repo.worktree_root()?;+ let config_path = repo_root.join(".config").join("wt.toml");++ match load_project_config_at(&repo_root)? {+ Some(cfg) => Ok(cfg),+ None => {+ use worktrunk::styling::{ERROR, ERROR_EMOJI, HINT, HINT_BOLD, HINT_EMOJI, eprintln};++ eprintln!("{ERROR_EMOJI} {ERROR}No project configuration found{ERROR:#}",);+ eprintln!(+ "{HINT_EMOJI} {HINT}Create a config file at: {HINT_BOLD}{}{HINT_BOLD:#}{HINT:#}",+ config_path.display()+ );+ Err(GitError::CommandFailed(+ "No project configuration found".to_string(),+ ))+ }+ }+}diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 2cba7b2bb..111921e23 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -99,7 +99,7 @@//! The shell wrapper is generated by `wt init <shell>` from templates in `templates/`.use std::path::PathBuf;-use worktrunk::config::{CommandPhase, ProjectConfig, WorktrunkConfig};+use worktrunk::config::{CommandPhase, WorktrunkConfig};use worktrunk::git::{GitError, GitResultExt, Repository};use worktrunk::styling::{CYAN, CYAN_BOLD, GREEN, GREEN_BOLD, WARNING, WARNING_BOLD, format_bash_with_gutter,@@ -107,6 +107,7 @@ use worktrunk::styling::{};use super::command_executor::{CommandContext, prepare_project_commands};+use super::project_config::load_project_config;use crate::commands::process::spawn_detached;use crate::output::execute_command_in_worktree;@@ -469,12 +470,6 @@ fn check_worktree_conflicts(Ok(())}-/// Helper to load project config with error handling-fn load_project_config(repo: &Repository) -> Result<Option<ProjectConfig>, GitError> {- let repo_root = repo.worktree_root()?;- ProjectConfig::load(&repo_root).git_context("Failed to load project config")-}-/// Execute post-create commands sequentially (blocking)pub fn execute_post_create_commands(worktree_path: &std::path::Path,diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex ee98070e9..ebe044223 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -540,6 +540,13 @@ impl Repository {.unwrap_or_default()}+ /// Determine whether there are staged changes in the index.+ ///+ /// Returns `Ok(true)` when staged changes are present, `Ok(false)` otherwise.+ pub fn has_staged_changes(&self) -> Result<bool, GitError> {+ Ok(!self.run_command_check(&["diff", "--cached", "--quiet", "--exit-code"])?)+ }+/// Get all branch names (local branches only).pub fn all_branches(&self) -> Result<Vec<String>, GitError> {let stdout = self.run_command(&["branch", "--format=%(refname:short)"])?;