Skip to content

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

feat(hooks): Add pre-commit and pre-squash merge hooks

Maximilian Roosdd62a785c719
diff --git a/README.md b/README.md
index 8e28d1165..62c7ca18e 100644
--- a/README.md
+++ b/README.md
@@ -124,6 +124,14 @@ Projects can define commands that run automatically when creating or switching t
"dev server" = "npm run dev"
"type check" = "npm run type-check -- --watch"
+# Validation before committing changes (blocking, fail-fast)
+[pre-commit-command]
+"format" = "cargo fmt -- --check"
+
+# Validation before squashing commits (blocking, fail-fast)
+[pre-squash-command]
+"tests" = "cargo test"
+
# Validation before merging (blocking, fail-fast)
[pre-merge-command]
"tests" = "npm test"
@@ -139,7 +147,9 @@ Projects can define commands that run automatically when creating or switching t
- **`post-create-command`**: Runs sequentially after creating a worktree. Use for setup tasks like installing dependencies.
- **`post-start-command`**: Runs in parallel as background processes after switching to a worktree. Use for dev servers and watchers.
-- **`pre-merge-command`**: Runs sequentially before merging. All commands must succeed for the merge to proceed. Use for validation (tests, lints).
+- **`pre-merge-command`**: Runs first, before any other hooks or git operations during `wt merge`. All commands must succeed for the merge to proceed. Use for validation (tests, lints) that must pass regardless of merge strategy.
+- **`pre-commit-command`**: Runs after pre-merge but before committing uncommitted changes (when not using `--squash`). All commands must succeed for the commit to proceed. Use for format checks and quick validations.
+- **`pre-squash-command`**: Runs after pre-merge but before squashing commits (when using `--squash`). All commands must succeed for the squash to proceed. Use for tests that should pass before creating the final squashed commit.
- **`post-merge-command`**: Runs sequentially in the main worktree after a successful merge and push. Use for deployment, notifications, or updating global state.
Template variables expand at runtime:
@@ -147,23 +157,25 @@ Template variables expand at runtime:
- `{branch}` - Current branch
- `{worktree}` - Absolute path to worktree
- `{repo_root}` - Absolute path to repository root
-- `{target}` - Target branch (pre-merge-command and post-merge-command only)
+- `{target}` - Target branch (pre-squash-command, pre-merge-command, and post-merge-command only)
### Available Hooks
-Worktrunk provides four lifecycle hooks for project automation:
+Worktrunk provides six lifecycle hooks for project automation:
| Hook | When It Runs | Execution | Failure Behavior |
|------|--------------|-----------|------------------|
| **post-create-command** | After `git worktree add` completes | Sequential, blocking | Logs warning, continues with remaining commands |
| **post-start-command** | After post-create completes | Parallel, non-blocking (background processes) | Logs warning, doesn't affect switch result |
-| **pre-merge-command** | Before committing/rebasing during `wt merge` | Sequential, blocking, fail-fast | Terminates merge immediately |
+| **pre-commit-command** | Before committing changes during `wt merge` (when not squashing) | Sequential, blocking, fail-fast | Terminates merge immediately |
+| **pre-squash-command** | Before squashing commits during `wt merge --squash` | Sequential, blocking, fail-fast | Terminates merge immediately |
+| **pre-merge-command** | Before any commits/rebasing during `wt merge` | Sequential, blocking, fail-fast | Terminates merge immediately |
| **post-merge-command** | After successful merge and push to target branch, before cleanup | Sequential, blocking | Logs warning, continues with remaining commands |
**Skipping hooks:**
- Use `--no-hooks` to skip all project hooks
- `wt switch --no-hooks` skips post-create and post-start
-- `wt merge --no-hooks` skips pre-merge-command
+- `wt merge --no-hooks` skips pre-commit, pre-squash, and pre-merge commands
**Security:**
Commands require approval on first run. Approved commands are saved globally per project. Use `--force` to bypass approval prompts.
diff --git a/src/commands/dev.rs b/src/commands/dev.rs
index 6d4d14ad6..d2e8c2cea 100644
--- a/src/commands/dev.rs
+++ b/src/commands/dev.rs
@@ -2,7 +2,10 @@ use worktrunk::config::{ProjectConfig, WorktrunkConfig};
use worktrunk::git::{GitError, GitResultExt, Repository};
use worktrunk::styling::{AnstyleStyle, HINT, HINT_EMOJI};
-use super::merge::{execute_post_merge_commands, run_pre_merge_commands};
+use super::merge::{
+ execute_post_merge_commands, run_pre_commit_commands, run_pre_merge_commands,
+ run_pre_squash_commands,
+};
use super::worktree::{execute_post_create_commands, execute_post_start_commands_sequential};
// Re-export HookType from main
@@ -36,6 +39,30 @@ pub fn handle_dev_run_hook(hook_type: HookType, force: bool) -> Result<(), GitEr
check_hook_configured(&project_config.post_start_command, hook_type)?;
execute_post_start_commands_sequential(&worktree_path, &repo, &config, &branch, force)
}
+ HookType::PreCommit => {
+ check_hook_configured(&project_config.pre_commit_command, hook_type)?;
+ run_pre_commit_commands(
+ &project_config,
+ &branch,
+ &worktree_path,
+ &repo,
+ &config,
+ force,
+ )
+ }
+ HookType::PreSquash => {
+ check_hook_configured(&project_config.pre_squash_command, hook_type)?;
+ let target_branch = repo.default_branch().unwrap_or_else(|_| "main".to_string());
+ run_pre_squash_commands(
+ &project_config,
+ &branch,
+ &target_branch,
+ &worktree_path,
+ &repo,
+ &config,
+ force,
+ )
+ }
HookType::PreMerge => {
check_hook_configured(&project_config.pre_merge_command, hook_type)?;
let target_branch = repo.default_branch().unwrap_or_else(|_| "main".to_string());
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index bad595720..87d610e05 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -61,13 +61,19 @@ pub fn handle_merge(
.git_context("Failed to stage changes")?;
} else {
// Commit immediately when not squashing
- handle_commit_changes(&config.commit_generation)?;
+ handle_commit_changes(&config.commit_generation, &current_branch, no_hooks, force)?;
}
}
// Squash commits if requested
if squash {
- handle_squash(&target_branch, &config.commit_generation)?;
+ handle_squash(
+ &target_branch,
+ &config.commit_generation,
+ &current_branch,
+ no_hooks,
+ force,
+ )?;
}
// Rebase onto target
@@ -275,8 +281,26 @@ fn commit_with_generated_message(
/// Commit uncommitted changes with LLM-generated message
fn handle_commit_changes(
commit_generation_config: &worktrunk::config::CommitGenerationConfig,
+ current_branch: &str,
+ no_hooks: bool,
+ force: bool,
) -> Result<(), GitError> {
let repo = Repository::current();
+ let config = WorktrunkConfig::load().git_context("Failed to load config")?;
+
+ // Run pre-commit hook unless --no-hooks was specified
+ if !no_hooks && let Ok(Some(project_config)) = ProjectConfig::load(&repo.worktree_root()?) {
+ let worktree_path =
+ std::env::current_dir().git_context("Failed to get current directory")?;
+ run_pre_commit_commands(
+ &project_config,
+ current_branch,
+ &worktree_path,
+ &repo,
+ &config,
+ force,
+ )?;
+ }
// Stage all changes including untracked files
repo.run_command(&["add", "-A"])
@@ -288,8 +312,27 @@ fn handle_commit_changes(
fn handle_squash(
target_branch: &str,
commit_generation_config: &worktrunk::config::CommitGenerationConfig,
+ current_branch: &str,
+ no_hooks: bool,
+ force: bool,
) -> Result<Option<usize>, GitError> {
let repo = Repository::current();
+ let config = WorktrunkConfig::load().git_context("Failed to load config")?;
+
+ // Run pre-squash hook unless --no-hooks was specified
+ if !no_hooks && let Ok(Some(project_config)) = ProjectConfig::load(&repo.worktree_root()?) {
+ let worktree_path =
+ std::env::current_dir().git_context("Failed to get current directory")?;
+ run_pre_squash_commands(
+ &project_config,
+ current_branch,
+ target_branch,
+ &worktree_path,
+ &repo,
+ &config,
+ force,
+ )?;
+ }
// Get merge base with target branch
let merge_base = repo.merge_base("HEAD", target_branch)?;
@@ -520,3 +563,126 @@ pub fn execute_post_merge_commands(
Ok(())
}
+
+/// Run pre-commit commands sequentially (blocking, fail-fast)
+pub fn run_pre_commit_commands(
+ project_config: &ProjectConfig,
+ current_branch: &str,
+ worktree_path: &std::path::Path,
+ repo: &Repository,
+ config: &WorktrunkConfig,
+ force: bool,
+) -> Result<(), GitError> {
+ let Some(pre_commit_config) = &project_config.pre_commit_command else {
+ return Ok(());
+ };
+
+ let repo_root = repo.main_worktree_root()?;
+ let ctx = CommandContext::new(
+ repo,
+ config,
+ current_branch,
+ worktree_path,
+ &repo_root,
+ force,
+ );
+ let commands = prepare_project_commands(
+ pre_commit_config,
+ &ctx,
+ false,
+ &[],
+ "Pre-commit commands",
+ |_name, command| {
+ let dim = AnstyleStyle::new().dimmed();
+ crate::output::progress(format!("{dim}Skipping command: {command}{dim:#}")).ok();
+ },
+ )?;
+
+ if commands.is_empty() {
+ return Ok(());
+ }
+
+ // Execute each command sequentially
+ for prepared in commands {
+ let header = if let Some(name) = &prepared.name {
+ format!("πŸ”„ {CYAN}Running pre-commit command {CYAN_BOLD}{name}{CYAN_BOLD:#}:{CYAN:#}")
+ } else {
+ format!("πŸ”„ {CYAN}Running pre-commit command:{CYAN:#}")
+ };
+ crate::output::progress(header)?;
+ crate::output::progress(format_bash_with_gutter(&prepared.expanded, ""))?;
+
+ if let Err(e) = execute_command_in_worktree(worktree_path, &prepared.expanded) {
+ return Err(GitError::PreCommitCommandFailed {
+ command_name: prepared.name.clone(),
+ error: e.to_string(),
+ });
+ }
+ }
+
+ crate::output::flush()?;
+
+ Ok(())
+}
+
+/// Run pre-squash commands sequentially (blocking, fail-fast)
+pub fn run_pre_squash_commands(
+ project_config: &ProjectConfig,
+ current_branch: &str,
+ target_branch: &str,
+ worktree_path: &std::path::Path,
+ repo: &Repository,
+ config: &WorktrunkConfig,
+ force: bool,
+) -> Result<(), GitError> {
+ let Some(pre_squash_config) = &project_config.pre_squash_command else {
+ return Ok(());
+ };
+
+ let repo_root = repo.main_worktree_root()?;
+ let ctx = CommandContext::new(
+ repo,
+ config,
+ current_branch,
+ worktree_path,
+ &repo_root,
+ force,
+ );
+ let commands = prepare_project_commands(
+ pre_squash_config,
+ &ctx,
+ false,
+ &[("target", target_branch)],
+ "Pre-squash commands",
+ |_name, command| {
+ let dim = AnstyleStyle::new().dimmed();
+ crate::output::progress(format!("{dim}Skipping command: {command}{dim:#}")).ok();
+ },
+ )?;
+
+ if commands.is_empty() {
+ return Ok(());
+ }
+
+ // Execute each command sequentially
+ for prepared in commands {
+ let header = if let Some(name) = &prepared.name {
+ format!("πŸ”„ {CYAN}Running pre-squash command {CYAN_BOLD}{name}{CYAN_BOLD:#}:{CYAN:#}")
+ } else {
+ format!("πŸ”„ {CYAN}Running pre-squash command:{CYAN:#}")
+ };
+ crate::output::progress(header)?;
+ crate::output::progress(format_bash_with_gutter(&prepared.expanded, ""))?;
+
+ if let Err(e) = execute_command_in_worktree(worktree_path, &prepared.expanded) {
+ return Err(GitError::PreSquashCommandFailed {
+ command_name: prepared.name.clone(),
+ error: e.to_string(),
+ });
+ }
+ }
+
+ crate::output::flush()?;
+
+ Ok(())
+}
diff --git a/src/config.rs b/src/config.rs
index 23d86ccb9..c1143acb9 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -86,13 +86,13 @@ pub struct CommitGenerationConfig {
///
/// # Template Variables
///
-/// Commands support template variable expansion:
+/// 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
///
-/// Additionally, `pre-merge-command` commands support:
+/// Merge-related commands (`pre-squash-command`, `pre-merge-command`, `post-merge-command`) also support:
/// - `{target}` - Target branch for the merge (e.g., "main")
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct ProjectConfig {
@@ -110,6 +110,22 @@ pub struct ProjectConfig {
#[serde(default, rename = "post-start-command")]
pub post_start_command: Option<CommandConfig>,
+ /// Commands to execute before committing changes (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
+ ///
+ /// Available template variables: `{repo}`, `{branch}`, `{worktree}`, `{repo_root}`
+ #[serde(default, rename = "pre-commit-command")]
+ pub pre_commit_command: Option<CommandConfig>,
+
+ /// Commands to execute before squashing commits (blocking, fail-fast validation)
+ /// Supports string (single command), array (sequential), or table (named, sequential)
+ /// All commands must exit with code 0 for squash to proceed
+ ///
+ /// Available template variables: `{repo}`, `{branch}`, `{worktree}`, `{repo_root}`, `{target}`
+ #[serde(default, rename = "pre-squash-command")]
+ pub pre_squash_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
diff --git a/src/git.rs b/src/git.rs
index 72756ef88..f521331f6 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -22,6 +22,16 @@ pub enum GitError {
DetachedHead,
/// Working tree has untracked files
UntrackedFiles,
+ /// Pre-commit command failed
+ PreCommitCommandFailed {
+ command_name: Option<String>,
+ error: String,
+ },
+ /// Pre-squash command failed
+ PreSquashCommandFailed {
+ command_name: Option<String>,
+ error: String,
+ },
/// Pre-merge command failed
PreMergeCommandFailed {
command_name: Option<String>,
@@ -84,6 +94,42 @@ impl std::fmt::Display for GitError {
)
}
+ // Pre-commit command failed
+ GitError::PreCommitCommandFailed {
+ command_name,
+ error,
+ } => {
+ let error_bold = ERROR.bold();
+ match command_name {
+ Some(name) => write!(
+ f,
+ "{ERROR_EMOJI} {ERROR}Pre-commit command failed: {error_bold}{name}{error_bold:#}{ERROR:#}\n\n{error}\n\n{HINT_EMOJI} {HINT}Use --no-hooks to skip pre-commit commands{HINT:#}"
+ ),
+ None => write!(
+ f,
+ "{ERROR_EMOJI} {ERROR}Pre-commit command failed{ERROR:#}\n\n{error}\n\n{HINT_EMOJI} {HINT}Use --no-hooks to skip pre-commit commands{HINT:#}"
+ ),
+ }
+ }
+
+ // Pre-squash command failed
+ GitError::PreSquashCommandFailed {
+ command_name,
+ error,
+ } => {
+ let error_bold = ERROR.bold();
+ match command_name {
+ Some(name) => write!(
+ f,
+ "{ERROR_EMOJI} {ERROR}Pre-squash command failed: {error_bold}{name}{error_bold:#}{ERROR:#}\n\n{error}\n\n{HINT_EMOJI} {HINT}Use --no-hooks to skip pre-squash commands{HINT:#}"
+ ),
+ None => write!(
+ f,
+ "{ERROR_EMOJI} {ERROR}Pre-squash command failed{ERROR:#}\n\n{error}\n\n{HINT_EMOJI} {HINT}Use --no-hooks to skip pre-squash commands{HINT:#}"
+ ),
+ }
+ }
+
// Pre-merge command failed
GitError::PreMergeCommandFailed {
command_name,
diff --git a/src/main.rs b/src/main.rs
index e23de6da3..b876ef0be 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -57,6 +57,8 @@ enum ConfigCommand {
pub enum HookType {
PostCreate,
PostStart,
+ PreCommit,
+ PreSquash,
PreMerge,
PostMerge,
}
@@ -67,6 +69,8 @@ impl HookType {
match self {
HookType::PostCreate => "post-create",
HookType::PostStart => "post-start",
+ HookType::PreCommit => "pre-commit",
+ HookType::PreSquash => "pre-squash",
HookType::PreMerge => "pre-merge",
HookType::PostMerge => "post-merge",
}
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 19797ae94..3c0dd3059 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -1282,3 +1282,187 @@ deploy = "echo 'Deploying branch {branch}' > deploy.txt"
"Deploy command should have created marker file"
);
}
+
+#[test]
+fn test_merge_pre_commit_command_success() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create project config with pre-commit command
+ let config_dir = repo.root_path().join(".config");
+ fs::create_dir_all(&config_dir).expect("Failed to create config dir");
+ fs::write(
+ config_dir.join("wt.toml"),
+ r#"pre-commit-command = "echo 'Pre-commit check passed'""#,
+ )
+ .expect("Failed to write config");
+
+ repo.commit("Add config");
+
+ // Create a worktree for main
+ let main_wt = repo.root_path().parent().unwrap().join("test-repo.main-wt");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["worktree", "add", main_wt.to_str().unwrap(), "main"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to add worktree");
+
+ // Create a feature worktree and make a change
+ let feature_wt = repo.add_worktree("feature", "feature");
+ fs::write(feature_wt.join("feature.txt"), "feature content").expect("Failed to write file");
+
+ // Merge with --force (changes uncommitted, should trigger pre-commit hook)
+ snapshot_merge(
+ "merge_pre_commit_command_success",
+ &repo,
+ &["main", "--force"],
+ Some(&feature_wt),
+ );
+}
+
+#[test]
+fn test_merge_pre_commit_command_failure() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create project config with failing pre-commit command
+ let config_dir = repo.root_path().join(".config");
+ fs::create_dir_all(&config_dir).expect("Failed to create config dir");
+ fs::write(
+ config_dir.join("wt.toml"),
+ r#"pre-commit-command = "exit 1""#,
+ )
+ .expect("Failed to write config");
+
+ repo.commit("Add config");
+
+ // Create a worktree for main
+ let main_wt = repo.root_path().parent().unwrap().join("test-repo.main-wt");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["worktree", "add", main_wt.to_str().unwrap(), "main"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to add worktree");
+
+ // Create a feature worktree and make a change
+ let feature_wt = repo.add_worktree("feature", "feature");
+ fs::write(feature_wt.join("feature.txt"), "feature content").expect("Failed to write file");
+
+ // Merge with --force - pre-commit command should fail and block merge
+ snapshot_merge(
+ "merge_pre_commit_command_failure",
+ &repo,
+ &["main", "--force"],
+ Some(&feature_wt),
+ );
+}
+
+#[test]
+fn test_merge_pre_squash_command_success() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create project config with pre-squash command
+ let config_dir = repo.root_path().join(".config");
+ fs::create_dir_all(&config_dir).expect("Failed to create config dir");
+ fs::write(
+ config_dir.join("wt.toml"),
+ r#"pre-squash-command = "echo 'Pre-squash check passed'""#,
+ )
+ .expect("Failed to write config");
+
+ repo.commit("Add config");
+
+ // Create a worktree for main
+ let main_wt = repo.root_path().parent().unwrap().join("test-repo.main-wt");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["worktree", "add", main_wt.to_str().unwrap(), "main"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to add worktree");
+
+ // Create a feature worktree and make commits
+ let feature_wt = repo.add_worktree("feature", "feature");
+ fs::write(feature_wt.join("feature.txt"), "feature content").expect("Failed to write file");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "feature.txt"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to add file");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Add feature file"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to commit");
+
+ // Merge with --squash and --force
+ snapshot_merge(
+ "merge_pre_squash_command_success",
+ &repo,
+ &["main", "--squash", "--force"],
+ Some(&feature_wt),
+ );
+}
+
+#[test]
+fn test_merge_pre_squash_command_failure() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create project config with failing pre-squash command
+ let config_dir = repo.root_path().join(".config");
+ fs::create_dir_all(&config_dir).expect("Failed to create config dir");
+ fs::write(
+ config_dir.join("wt.toml"),
+ r#"pre-squash-command = "exit 1""#,
+ )
+ .expect("Failed to write config");
+
+ repo.commit("Add config");
+
+ // Create a worktree for main
+ let main_wt = repo.root_path().parent().unwrap().join("test-repo.main-wt");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["worktree", "add", main_wt.to_str().unwrap(), "main"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to add worktree");
+
+ // Create a feature worktree and make commits
+ let feature_wt = repo.add_worktree("feature", "feature");
+ fs::write(feature_wt.join("feature.txt"), "feature content").expect("Failed to write file");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "feature.txt"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to add file");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Add feature file"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to commit");
+
+ // Merge with --squash and --force - pre-squash command should fail and block merge
+ snapshot_merge(
+ "merge_pre_squash_command_failure",
+ &repo,
+ &["main", "--squash", "--force"],
+ Some(&feature_wt),
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snap
index 29c380c7e..a4aa11a19 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpcKkzLk/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpbevAR4/test-config.toml
---
success: true
exit_code: 0
@@ -343,7 +343,7 @@ _wt() {
return 0
;;
wt__dev__run__hook)
- opts="-f -v -h --force --verbose --help post-create post-start pre-merge post-merge"
+ opts="-f -v -h --force --verbose --help post-create post-start pre-commit pre-squash pre-merge post-merge"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 3 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
index 2b344d563..d33ba5b4e 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
@@ -18,7 +18,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpk3RZ0C/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpMCL1XL/test-config.toml
---
success: true
exit_code: 0
@@ -345,7 +345,7 @@ _wt() {
return 0
;;
wt__dev__run__hook)
- opts="-f -v -h --force --verbose --help post-create post-start pre-merge post-merge"
+ opts="-f -v -h --force --verbose --help post-create post-start pre-commit pre-squash pre-merge post-merge"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 3 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index bf37d3096..355cc5267 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpIY93iE/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpLp28xJ/test-config.toml
---
success: true
exit_code: 0
@@ -242,7 +242,7 @@ _arguments "${_arguments_options[@]}" : \
'--verbose[Enable verbose output (show git commands and debug info)]' \
'-h[Print help]' \
'--help[Print help]' \
-':hook_type -- Hook type to run:(post-create post-start pre-merge post-merge)' \
+':hook_type -- Hook type to run:(post-create post-start pre-commit pre-squash pre-merge post-merge)' \
&& ret=0
;;
esac
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_pre_commit_command_failure.snap b/tests/snapshots/integration__integration_tests__merge__merge_pre_commit_command_failure.snap
new file mode 100644
index 000000000..ef633c0f3
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_pre_commit_command_failure.snap
@@ -0,0 +1,34 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ - "--force"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpyVyDrw/test-config.toml
+---
+success: false
+exit_code: 1
+----- stdout -----
+πŸ”„ Running pre-commit command:
+  exit 1
+
+
+----- stderr -----
+❌ Pre-commit command failed
+
+Command failed with exit code: exit status: 1
+
+πŸ’‘ Use --no-hooks to skip pre-commit commands
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_pre_commit_command_success.snap b/tests/snapshots/integration__integration_tests__merge__merge_pre_commit_command_success.snap
new file mode 100644
index 000000000..62ce75908
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_pre_commit_command_success.snap
@@ -0,0 +1,48 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ - "--force"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp0nZSev/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+πŸ”„ Running pre-commit command:
+  echo 'Pre-commit check passed'
+
+πŸ”„ Committing changes... (1 file, +1)
+πŸ”„ Generating commit message...
+πŸ’‘ Using fallback commit message. Run 'wt config help' to configure LLM-generated messages
+  WIP: Auto-commit before merge
+
+βœ… Committed changes @ [SHA]
+πŸ”„ Rebasing onto main...
+πŸ”„ Merging 1 commit to main @ [SHA]
+
+* [SHA] (HEAD -> feature) WIP: Auto-commit before merge
+
+ feature.txt | 1 +
+ 1 file changed, 1 insertion(+)
+
+βœ… Merged to main (1 commit, 1 file, +1) 
+πŸ”„ Cleaning up worktree...
+
+βœ… Returned to primary at [REPO]
+
+----- stderr -----
+Pre-commit check passed
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_pre_squash_command_failure.snap b/tests/snapshots/integration__integration_tests__merge__merge_pre_squash_command_failure.snap
new file mode 100644
index 000000000..988084293
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_pre_squash_command_failure.snap
@@ -0,0 +1,35 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ - "--squash"
+ - "--force"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpVn5J0G/test-config.toml
+---
+success: false
+exit_code: 1
+----- stdout -----
+πŸ”„ Running pre-squash command:
+  exit 1
+
+
+----- stderr -----
+❌ Pre-squash command failed
+
+Command failed with exit code: exit status: 1
+
+πŸ’‘ Use --no-hooks to skip pre-squash commands
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_pre_squash_command_success.snap b/tests/snapshots/integration__integration_tests__merge__merge_pre_squash_command_success.snap
new file mode 100644
index 000000000..3c6e0b735
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_pre_squash_command_success.snap
@@ -0,0 +1,44 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ - "--squash"
+ - "--force"
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp2Pp0c4/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+πŸ”„ Running pre-squash command:
+  echo 'Pre-squash check passed'
+
+πŸ’‘ Only 1 commit since main - no squashing needed
+πŸ”„ Rebasing onto main...
+πŸ”„ Merging 1 commit to main @ [SHA]
+
+* [SHA] (HEAD -> feature) Add feature file
+
+ feature.txt | 1 +
+ 1 file changed, 1 insertion(+)
+
+βœ… Merged to main (1 commit, 1 file, +1) 
+πŸ”„ Cleaning up worktree...
+
+βœ… Returned to primary at [REPO]
+
+----- stderr -----
+Pre-squash check passed