Skip to content

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

Add `git-squash` fish function and `wt merge --squash` option

Maximilian Roosd2fdd28c4bcb
diff --git a/fish-functions/git-squash.fish b/fish-functions/git-squash.fish
new file mode 100644
index 000000000..88bfbadb8
--- /dev/null
+++ b/fish-functions/git-squash.fish
@@ -0,0 +1,124 @@
+function git-squash -d "Squash all commits since branching from specified branch (default: main)"
+ argparse -n git-squash 'r/rebase' 'A/all' -- $argv
+ or return 1
+
+ # Get target branch - use argument or default branch
+ set -l target_branch
+ if test (count $argv) -gt 0
+ set target_branch $argv[1]
+ else
+ set target_branch (git default-branch)
+ if test -z "$target_branch"
+ echo (set_color red)"❌ Failed to determine default branch"(set_color normal) >&2
+ return 1
+ end
+ end
+
+ # Get merge base
+ set -l merge_base (git merge-base HEAD "$target_branch")
+ if test -z "$merge_base"
+ echo (set_color red)"❌ Failed to find merge base with "(set_color red --bold)"$target_branch"(set_color normal) >&2
+ return 1
+ end
+
+ # Get current branch name for context
+ set -l current_branch (git rev-parse --abbrev-ref HEAD)
+ if test -z "$current_branch"
+ echo (set_color red)"❌ Failed to determine current branch"(set_color normal) >&2
+ return 1
+ end
+
+ # Check if there are any commits to squash
+ set -l commit_count (git rev-list --count "$merge_base..HEAD")
+
+ # Check if we have staged changes
+ set -l has_staged_changes 0
+ if not git diff --cached --quiet --exit-code
+ set has_staged_changes 1
+ end
+
+ # Check if we have unstaged changes
+ set -l has_unstaged_changes 0
+ if not git diff --quiet --exit-code
+ set has_unstaged_changes 1
+ end
+
+ # Handle -A flag to add all changes
+ if set -ql _flag_all; and test "$has_unstaged_changes" -eq 1
+ echo (set_color yellow)"🟡 Adding all changes (including unstaged)"(set_color normal) >&2
+ git add -A
+ or begin
+ echo (set_color red)"❌ Failed to add all changes"(set_color normal) >&2
+ return 1
+ end
+ # After adding, everything is staged
+ set has_staged_changes 1
+ set has_unstaged_changes 0
+ end
+
+ # Handle different squashing scenarios
+ if test "$commit_count" -eq 0; and test "$has_staged_changes" -eq 0
+ # No commits and no staged changes - nothing to squash (but might still rebase)
+ echo (set_color -d)"💬 No commits to squash - already at merge base"(set_color normal) >&2
+
+ else if test "$commit_count" -eq 0; and test "$has_staged_changes" -eq 1
+ # Just staged changes, no commits - delegate to git-commit-llm
+ git-commit-llm
+ or return 1
+
+ else if test "$commit_count" -eq 1; and test "$has_staged_changes" -eq 0
+ # Single commit, no staged changes - nothing to do
+ echo (set_color -d)"💬 Only 1 commit since "(set_color -d --bold)"$target_branch"(set_color normal -d)" - no squashing needed"(set_color normal) >&2
+
+ else
+ # One or more commits (possibly with staged changes) - squash them all together
+ if test "$commit_count" -eq 1; and test "$has_staged_changes" -eq 1
+ echo (set_color cyan)"🔄 Amending staged changes into the existing commit"(set_color normal) >&2
+ end
+
+ # Get commit context before resetting
+ set -l commit_context (__git_build_commit_context "$merge_base..HEAD")
+
+ # Reset to the merge base (this stages all the changes)
+ git reset --soft $merge_base
+ or begin
+ echo (set_color red)"❌ Failed to reset to merge base"(set_color normal) >&2
+ return 1
+ end
+
+ # Generate commit message from the staged changes
+ set -l commit_message
+ printf "Squashing commits on branch '%s' since %s\n\n%s" "$current_branch" "$target_branch" "$commit_context" | \
+ git-llm-message "Generate a commit message that combines these changes into one cohesive message." | \
+ read -z commit_message
+ or begin
+ echo (set_color red)"❌ Failed to generate commit message"(set_color normal) >&2
+ return 1
+ end
+
+ # Commit with the generated message
+ printf "%s\n\nCo-authored-by: Claude <[email protected]>\n" "$commit_message" | git commit -F -
+ or begin
+ echo (set_color red)"❌ Failed to create commit"(set_color normal) >&2
+ return 1
+ end
+
+ if test "$commit_count" -ne 1; or test "$has_staged_changes" -ne 1
+ echo (set_color green)"✅ Successfully squashed $commit_count commit(s) into one"(set_color normal) >&2
+ end
+ end
+
+ # Rebase if requested (happens for both single and multiple commits)
+ if set -ql _flag_rebase
+ # Check if we're already up to date with target branch
+ if git merge-base --is-ancestor "$target_branch" HEAD
+ echo (set_color -d)"💬 Already up to date with "(set_color -d --bold)"$target_branch"(set_color normal -d)" "(set_color normal) >&2
+ else
+ echo (set_color cyan)"🔄 Rebasing onto "(set_color cyan --bold)"$target_branch"(set_color normal)(set_color cyan)"..."(set_color normal) >&2
+ if not git rebase $target_branch
+ echo (set_color red)"❌ Failed to rebase onto "(set_color red --bold)"$target_branch"(set_color normal) >&2
+ return 1
+ end
+ end
+ end
+end
diff --git a/src/git.rs b/src/git.rs
index 372b8bb4e..167b9f45b 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -560,6 +560,49 @@ pub fn get_available_branches() -> Result<Vec<String>, GitError> {
.collect())
}
+/// Get the merge base between two commits
+pub fn get_merge_base(commit1: &str, commit2: &str) -> Result<String, GitError> {
+ get_merge_base_in(std::env::current_dir().unwrap().as_path(), commit1, commit2)
+}
+
+pub fn get_merge_base_in(
+ path: &std::path::Path,
+ commit1: &str,
+ commit2: &str,
+) -> Result<String, GitError> {
+ let output = run_git_command(&["merge-base", commit1, commit2], Some(path))?;
+ Ok(output.trim().to_string())
+}
+
+/// Get commit subjects (first line of commit message) from a range
+pub fn get_commit_subjects(range: &str) -> Result<Vec<String>, GitError> {
+ get_commit_subjects_in(std::env::current_dir().unwrap().as_path(), range)
+}
+
+pub fn get_commit_subjects_in(
+ path: &std::path::Path,
+ range: &str,
+) -> Result<Vec<String>, GitError> {
+ let output = run_git_command(&["log", "--format=%s", range], Some(path))?;
+ Ok(output.lines().map(|s| s.to_string()).collect())
+}
+
+/// Check if there are staged changes
+pub fn has_staged_changes() -> Result<bool, GitError> {
+ has_staged_changes_in(std::env::current_dir().unwrap().as_path())
+}
+
+pub fn has_staged_changes_in(path: &std::path::Path) -> Result<bool, GitError> {
+ let output = Command::new("git")
+ .args(["diff", "--cached", "--quiet", "--exit-code"])
+ .current_dir(path)
+ .output()
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+
+ // exit code 0 = no changes, 1 = has changes
+ Ok(!output.status.success())
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/main.rs b/src/main.rs
index 53a6d25d3..f46444376 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -7,10 +7,11 @@ use worktrunk::config::{format_worktree_path, load_config};
use worktrunk::error_format::{format_error, format_error_with_bold, format_hint, format_warning};
use worktrunk::git::{
GitError, Worktree, branch_exists, count_commits, get_ahead_behind_in, get_all_branches,
- get_available_branches, get_branch_diff_stats_in, get_changed_files, get_commit_timestamp_in,
- get_current_branch, get_current_branch_in, get_default_branch, get_git_common_dir,
- get_working_tree_diff_stats_in, get_worktree_root, has_merge_commits, is_ancestor, is_dirty,
- is_dirty_in, is_in_worktree, list_worktrees, worktree_for_branch,
+ get_available_branches, get_branch_diff_stats_in, get_changed_files, get_commit_subjects,
+ get_commit_timestamp_in, get_current_branch, get_current_branch_in, get_default_branch,
+ get_git_common_dir, get_merge_base, get_working_tree_diff_stats_in, get_worktree_root,
+ has_merge_commits, has_staged_changes, is_ancestor, is_dirty, is_dirty_in, is_in_worktree,
+ list_worktrees, worktree_for_branch,
};
use worktrunk::shell;
@@ -83,6 +84,10 @@ enum Commands {
/// Target branch to merge into (defaults to default branch)
target: Option<String>,
+ /// Squash all commits into one before merging
+ #[arg(short, long)]
+ squash: bool,
+
/// Keep worktree after merging (don't remove)
#[arg(short, long)]
keep: bool,
@@ -133,7 +138,11 @@ fn main() {
target,
allow_merge_commits,
} => handle_push(target.as_deref(), allow_merge_commits),
- Commands::Merge { target, keep } => handle_merge(target.as_deref(), keep),
+ Commands::Merge {
+ target,
+ squash,
+ keep,
+ } => handle_merge(target.as_deref(), squash, keep),
Commands::Hook { hook_type } => handle_hook(&hook_type).map_err(GitError::CommandFailed),
Commands::Complete { args } => handle_complete(args),
};
@@ -786,7 +795,87 @@ fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<(), Gi
Ok(())
}
-fn handle_merge(target: Option<&str>, keep: bool) -> Result<(), GitError> {
+fn handle_squash(target_branch: &str) -> Result<(), GitError> {
+ // Get merge base with target branch
+ let merge_base = get_merge_base("HEAD", target_branch)?;
+
+ // Count commits since merge base
+ let commit_count = count_commits(&merge_base, "HEAD")?;
+
+ // Check if there are staged changes
+ let has_staged = has_staged_changes()?;
+
+ // Handle different scenarios
+ if commit_count == 0 && !has_staged {
+ // No commits and no staged changes - nothing to squash
+ println!("No commits to squash - already at merge base");
+ return Ok(());
+ }
+
+ if commit_count == 0 && has_staged {
+ // Just staged changes, no commits - would need to commit but this shouldn't happen in merge flow
+ return Err(GitError::CommandFailed(format_error(
+ "Staged changes without commits - please commit them first",
+ )));
+ }
+
+ if commit_count == 1 && !has_staged {
+ // Single commit, no staged changes - nothing to do
+ println!(
+ "Only 1 commit since '{}' - no squashing needed",
+ target_branch
+ );
+ return Ok(());
+ }
+
+ // One or more commits (possibly with staged changes) - squash them
+ println!("Squashing {} commits into one...", commit_count);
+
+ // Get commit subjects for the squash message
+ let range = format!("{}..HEAD", merge_base);
+ let subjects = get_commit_subjects(&range)?;
+
+ // Build deterministic commit message
+ let mut commit_message = format!("Squash commits from {}\n\n", target_branch);
+ commit_message.push_str("Combined commits:\n");
+ for subject in subjects.iter().rev() {
+ // Reverse so they're in chronological order
+ commit_message.push_str(&format!("- {}\n", subject));
+ }
+
+ // Reset to merge base (soft reset stages all changes)
+ let reset_result = process::Command::new("git")
+ .args(["reset", "--soft", &merge_base])
+ .output()
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+
+ if !reset_result.status.success() {
+ let stderr = String::from_utf8_lossy(&reset_result.stderr);
+ return Err(GitError::CommandFailed(format!(
+ "Failed to reset to merge base: {}",
+ stderr
+ )));
+ }
+
+ // Commit with the generated message
+ let commit_result = process::Command::new("git")
+ .args(["commit", "-m", &commit_message])
+ .output()
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+
+ if !commit_result.status.success() {
+ let stderr = String::from_utf8_lossy(&commit_result.stderr);
+ return Err(GitError::CommandFailed(format!(
+ "Failed to create squash commit: {}",
+ stderr
+ )));
+ }
+
+ println!("Successfully squashed {} commits into one", commit_count);
+ Ok(())
+}
+
+fn handle_merge(target: Option<&str>, squash: bool, keep: bool) -> Result<(), GitError> {
// Get current branch
let current_branch = get_current_branch()?
.ok_or_else(|| GitError::CommandFailed(format_error("Not on a branch (detached HEAD)")))?;
@@ -810,6 +899,11 @@ fn handle_merge(target: Option<&str>, keep: bool) -> Result<(), GitError> {
)));
}
+ // Squash commits if requested
+ if squash {
+ handle_squash(&target_branch)?;
+ }
+
// Rebase onto target
println!("Rebasing onto '{}'...", target_branch);
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snap
index 4f4b75c4b..c3a32dd41 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap
@@ -200,7 +200,7 @@ _wt() {
return 0
;;
wt__merge)
- opts="-k -h --keep --help [TARGET]"
+ opts="-s -k -h --squash --keep --help [TARGET]"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash_all_options.snap b/tests/snapshots/integration__integration_tests__init__init_bash_all_options.snap
index 195458040..47e892289 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash_all_options.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash_all_options.snap
@@ -217,7 +217,7 @@ _wt() {
return 0
;;
wt__merge)
- opts="-k -h --keep --help [TARGET]"
+ opts="-s -k -h --squash --keep --help [TARGET]"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; 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 bd22d33bd..1a254b523 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
@@ -202,7 +202,7 @@ _wt() {
return 0
;;
wt__merge)
- opts="-k -h --keep --help [TARGET]"
+ opts="-s -k -h --squash --keep --help [TARGET]"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash_prompt_hook.snap b/tests/snapshots/integration__integration_tests__init__init_bash_prompt_hook.snap
index 8efcd6453..00b9af0f8 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash_prompt_hook.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash_prompt_hook.snap
@@ -215,7 +215,7 @@ _wt() {
return 0
;;
wt__merge)
- opts="-k -h --keep --help [TARGET]"
+ opts="-s -k -h --squash --keep --help [TARGET]"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index cc98f1099..8cb53039f 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -116,6 +116,7 @@ complete -c wt -n "__fish_wt_using_subcommand remove" -l internal -d 'Use intern
complete -c wt -n "__fish_wt_using_subcommand remove" -s h -l help -d 'Print help'
complete -c wt -n "__fish_wt_using_subcommand push" -l allow-merge-commits -d 'Allow pushing merge commits (non-linear history)'
complete -c wt -n "__fish_wt_using_subcommand push" -s h -l help -d 'Print help'
+complete -c wt -n "__fish_wt_using_subcommand merge" -s s -l squash -d 'Squash all commits into one before merging'
complete -c wt -n "__fish_wt_using_subcommand merge" -s k -l keep -d 'Keep worktree after merging (don\'t remove)'
complete -c wt -n "__fish_wt_using_subcommand merge" -s h -l help -d 'Print help'
complete -c wt -n "__fish_wt_using_subcommand hook" -s h -l help -d 'Print help'
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish_prompt_hook.snap b/tests/snapshots/integration__integration_tests__init__init_fish_prompt_hook.snap
index 2bda04329..2c205282e 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish_prompt_hook.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish_prompt_hook.snap
@@ -124,6 +124,7 @@ complete -c wt -n "__fish_wt_using_subcommand remove" -l internal -d 'Use intern
complete -c wt -n "__fish_wt_using_subcommand remove" -s h -l help -d 'Print help'
complete -c wt -n "__fish_wt_using_subcommand push" -l allow-merge-commits -d 'Allow pushing merge commits (non-linear history)'
complete -c wt -n "__fish_wt_using_subcommand push" -s h -l help -d 'Print help'
+complete -c wt -n "__fish_wt_using_subcommand merge" -s s -l squash -d 'Squash all commits into one before merging'
complete -c wt -n "__fish_wt_using_subcommand merge" -s k -l keep -d 'Keep worktree after merging (don\'t remove)'
complete -c wt -n "__fish_wt_using_subcommand merge" -s h -l help -d 'Print help'
complete -c wt -n "__fish_wt_using_subcommand hook" -s h -l help -d 'Print help'
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index 17f43988e..3d4a64480 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -147,6 +147,8 @@ _arguments "${_arguments_options[@]}" : \
;;
(merge)
_arguments "${_arguments_options[@]}" : \
+'-s[Squash all commits into one before merging]' \
+'--squash[Squash all commits into one before merging]' \
'-k[Keep worktree after merging (don'\''t remove)]' \
'--keep[Keep worktree after merging (don'\''t remove)]' \
'-h[Print help]' \