Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add --no-rebase flag to wt merge (#194)
Maximilian Roos72926ecb1f55
diff --git a/docs/content/merge.md b/docs/content/merge.mdindex 2c8b4cdce..ca4debe53 100644--- a/docs/content/merge.md+++ b/docs/content/merge.md@@ -83,7 +83,10 @@ Options:Skip commit squashing--no-commit- Skip commit, squash, and rebase+ Skip commit and squash++ --no-rebase+ Skip rebase (fail if not already rebased)--no-removeKeep worktree after mergediff --git a/src/cli.rs b/src/cli.rsindex aa013e54e..7890bbe78 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -2274,14 +2274,22 @@ Use `--no-commit` to skip all git operations (steps 1-2) and only run hooks and#[arg(long = "no-squash", overrides_with = "squash")]no_squash: bool,- /// Force commit, squash, and rebase+ /// Force commit and squash#[arg(long, overrides_with = "no_commit", hide = true)]commit: bool,- /// Skip commit, squash, and rebase+ /// Skip commit and squash#[arg(long = "no-commit", overrides_with = "commit")]no_commit: bool,+ /// Force rebasing onto target+ #[arg(long, overrides_with = "no_rebase", hide = true)]+ rebase: bool,++ /// Skip rebase (fail if not already rebased)+ #[arg(long = "no-rebase", overrides_with = "rebase")]+ no_rebase: bool,+/// Force worktree removal after merge#[arg(long, overrides_with = "no_remove", hide = true)]remove: bool,diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 40917da36..416643d47 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -12,6 +12,18 @@ use super::project_config::collect_commands_for_hooks;use super::repository_ext::RepositoryCliExt;use super::worktree::{MergeOperations, RemoveResult, handle_push};+/// Options for the merge command+pub struct MergeOptions<'a> {+ pub target: Option<&'a str>,+ pub squash: bool,+ pub commit: bool,+ pub rebase: bool,+ pub remove: bool,+ pub verify: bool,+ pub force: bool,+ pub stage_mode: super::commit::StageMode,+}+/// Reason why a worktree was preserved (not removed) after mergeenum PreserveReason {/// User explicitly passed --no-remove@@ -72,15 +84,18 @@ impl<'a> MergeCommandCollector<'a> {}}-pub fn handle_merge(- target: Option<&str>,- squash: bool,- commit: bool,- remove: bool,- verify: bool,- force: bool,- stage_mode: super::commit::StageMode,-) -> anyhow::Result<()> {+pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {+ let MergeOptions {+ target,+ squash,+ commit,+ rebase,+ remove,+ verify,+ force,+ stage_mode,+ } = opts;+let env = CommandEnv::for_action("merge")?;let repo = &env.repo;let config = &env.config;@@ -166,14 +181,22 @@ pub fn handle_merge(false};- // Rebase onto target (skip if --no-commit) - track whether rebasing occurred- let rebased = if commit {+ // Rebase onto target - track whether rebasing occurred+ let rebased = if rebase {+ // Auto-rebase onto targetmatches!(super::standalone::handle_rebase(Some(&target_branch))?,super::standalone::RebaseResult::Rebased)} else {- false+ // --no-rebase: verify already rebased, fail if not+ if !repo.is_rebased_onto(&target_branch)? {+ return Err(worktrunk::git::GitError::NotRebased {+ target_branch: target_branch.clone(),+ }+ .into());+ }+ false // Already rebased, no rebase occurred};// Run pre-merge checks unless --no-verify was specifieddiff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 81215a941..ead9ff5d7 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -29,7 +29,7 @@ pub use configure_shell::{pub use for_each::step_for_each;pub use init::handle_init;pub use list::handle_list;-pub use merge::{execute_pre_remove_commands, handle_merge};+pub use merge::{MergeOptions, execute_pre_remove_commands, handle_merge};#[cfg(unix)]pub use select::handle_select;pub use standalone::{diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 0b8847378..ac5316487 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -48,6 +48,11 @@ pub trait RepositoryCliExt {target_worktree: Option<&PathBuf>,target_branch: &str,) -> anyhow::Result<Option<TargetWorktreeStash>>;++ /// Check if HEAD is rebased onto the target branch.+ ///+ /// Returns true if the merge-base equals the target's SHA (HEAD is based on target).+ fn is_rebased_onto(&self, target: &str) -> anyhow::Result<bool>;}impl RepositoryCliExt for Repository {@@ -282,6 +287,12 @@ impl RepositoryCliExt for Repository {Ok(Some(TargetWorktreeStash::new(wt_path, stash_ref)))}++ fn is_rebased_onto(&self, target: &str) -> anyhow::Result<bool> {+ let merge_base = self.merge_base("HEAD", target)?;+ let target_sha = self.run_command(&["rev-parse", target])?.trim().to_string();+ Ok(merge_base == target_sha)+ }}fn load_project_config_at(repo_root: &Path) -> anyhow::Result<Option<ProjectConfig>> {diff --git a/src/config/user.rs b/src/config/user.rsindex e0164cef5..1987e57a1 100644--- a/src/config/user.rs+++ b/src/config/user.rs@@ -310,6 +310,12 @@ pub struct MergeConfig {#[serde(skip_serializing_if = "Option::is_none")]pub commit: Option<bool>,+ /// Rebase onto target branch before merging (default: true)+ ///+ /// When false, merge fails if branch is not already rebased.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub rebase: Option<bool>,+/// Remove worktree after merge (default: true)#[serde(skip_serializing_if = "Option::is_none")]pub remove: Option<bool>,diff --git a/src/git/error.rs b/src/git/error.rsindex 3005223f7..8d9e66241 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -105,6 +105,9 @@ pub enum GitError {target_branch: String,git_output: String,},+ NotRebased {+ target_branch: String,+ },PushFailed {error: String,},@@ -408,6 +411,17 @@ impl std::fmt::Display for GitError {}}+ GitError::NotRebased { target_branch } => {+ write!(+ f,+ "{}\n\n{}",+ error_message(cformat!("Branch not rebased onto <bold>{target_branch}</>")),+ hint_message(cformat!(+ "Run <bright-black>wt rebase</> first or remove <bright-black>--no-rebase</>"+ ))+ )+ }+GitError::PushFailed { error } => {let header = error_message("Push failed");write!(f, "{}", format_error_block(header, error))diff --git a/src/main.rs b/src/main.rsindex cdc6ec3c0..bea96463a 100644--- a/src/main.rs+++ b/src/main.rs@@ -27,11 +27,11 @@ use commands::command_executor::CommandContext;use commands::handle_select;use commands::worktree::{SwitchResult, handle_push};use commands::{- ConfigAction, RebaseResult, SquashResult, add_approvals, approve_hooks, clear_approvals,- compute_worktree_path, handle_config_create, handle_config_show, handle_configure_shell,- handle_hook_show, handle_init, handle_list, handle_merge, handle_rebase, handle_remove,- handle_remove_by_path, handle_remove_current, handle_show_theme, handle_squash,- handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,+ ConfigAction, MergeOptions, RebaseResult, SquashResult, add_approvals, approve_hooks,+ clear_approvals, compute_worktree_path, handle_config_create, handle_config_show,+ handle_configure_shell, handle_hook_show, handle_init, handle_list, handle_merge,+ handle_rebase, handle_remove, handle_remove_by_path, handle_remove_current, handle_show_theme,+ handle_squash, handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,handle_state_show, handle_switch, handle_unconfigure_shell, resolve_worktree_path_first,run_hook, step_commit, step_for_each,};@@ -1447,6 +1447,8 @@ fn main() {no_squash,commit,no_commit,+ rebase,+ no_rebase,remove,no_remove,verify,@@ -1469,12 +1471,14 @@ fn main() {let merge_config = config.merge.as_ref();let squash_default = merge_config.and_then(|m| m.squash).unwrap_or(true);let commit_default = merge_config.and_then(|m| m.commit).unwrap_or(true);+ let rebase_default = merge_config.and_then(|m| m.rebase).unwrap_or(true);let remove_default = merge_config.and_then(|m| m.remove).unwrap_or(true);let verify_default = merge_config.and_then(|m| m.verify).unwrap_or(true);// CLI flags override config, config overrides defaultslet squash_final = flag_pair(squash, no_squash).unwrap_or(squash_default);let commit_final = flag_pair(commit, no_commit).unwrap_or(commit_default);+ let rebase_final = flag_pair(rebase, no_rebase).unwrap_or(rebase_default);let remove_final = flag_pair(remove, no_remove).unwrap_or(remove_default);let verify_final = flag_pair(verify, no_verify).unwrap_or(verify_default);@@ -1483,15 +1487,16 @@ fn main() {.or_else(|| config.commit.and_then(|c| c.stage)).unwrap_or_default();- handle_merge(- target.as_deref(),- squash_final,- commit_final,- remove_final,- verify_final,+ handle_merge(MergeOptions {+ target: target.as_deref(),+ squash: squash_final,+ commit: commit_final,+ rebase: rebase_final,+ remove: remove_final,+ verify: verify_final,force,- stage_final,- )+ stage_mode: stage_final,+ })}),};diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex 9a6af2cb6..f118b77b4 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -1820,6 +1820,59 @@ fn test_merge_rebase_true_rebase(mut repo: TestRepo) {);}+// =============================================================================+// --no-rebase tests+// =============================================================================++#[rstest]+fn test_merge_no_rebase_when_already_rebased(merge_scenario: (TestRepo, PathBuf)) {+ // Feature branch is based on main (no divergence), so --no-rebase should succeed+ let (repo, feature_wt) = merge_scenario;++ snapshot_merge(+ "merge_no_rebase_already_rebased",+ &repo,+ &["main", "--no-rebase"],+ Some(&feature_wt),+ );+}++#[rstest]+fn test_merge_no_rebase_when_not_rebased(mut repo: TestRepo) {+ // Create a feature worktree with a commit+ let feature_wt = repo.add_worktree_with_commit(+ "not-rebased-test",+ "feature.txt",+ "feature content",+ "Add feature",+ );++ // Advance main with a new commit (makes feature branch diverge)+ fs::write(repo.root_path().join("main-update.txt"), "main content").unwrap();++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "main-update.txt"])+ .current_dir(repo.root_path())+ .output()+ .unwrap();++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Update main"])+ .current_dir(repo.root_path())+ .output()+ .unwrap();++ // --no-rebase should fail because feature is not rebased onto main+ snapshot_merge(+ "merge_no_rebase_not_rebased",+ &repo,+ &["main", "--no-rebase"],+ Some(&feature_wt),+ );+}+#[rstest]fn test_merge_primary_on_different_branch(mut repo: TestRepo) {repo.switch_primary_to("develop");diff --git a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap b/tests/snapshots/integration__integration_tests__help__help_merge_long.snapindex 0c62cd151..90064a93e 100644--- a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_merge_long.snap@@ -34,7 +34,10 @@ Usage: [1m[36mwt merge[0m [36m[OPTIONS][0m [36m[TARGET]Skip commit squashing[1m[36m--no-commit- Skip commit, squash, and rebase+ Skip commit and squash++ [1m[36m--no-rebase+ Skip rebase (fail if not already rebased)[1m[36m--no-removeKeep worktree after mergediff --git a/tests/snapshots/integration__integration_tests__help__help_merge_short.snap b/tests/snapshots/integration__integration_tests__help__help_merge_short.snapindex 59eb15c99..fa0e4d19b 100644--- a/tests/snapshots/integration__integration_tests__help__help_merge_short.snap+++ b/tests/snapshots/integration__integration_tests__help__help_merge_short.snap@@ -26,7 +26,8 @@ Usage: [1m[36mwt merge[0m [36m[OPTIONS][0m [36m[TARGET][1m[32mOptions:[1m[36m--no-squash[0m Skip commit squashing- [1m[36m--no-commit[0m Skip commit, squash, and rebase+ [1m[36m--no-commit[0m Skip commit and squash+ [1m[36m--no-rebase[0m Skip rebase (fail if not already rebased)[1m[36m--no-remove[0m Keep worktree after merge[1m[36m--no-verify[0m Skip hooks[1m[36m-f[0m, [1m[36m--force[0m Skip approval promptsdiff --git a/tests/snapshots/integration__integration_tests__merge__merge_no_commit_not_fast_forward.snap b/tests/snapshots/integration__integration_tests__merge__merge_no_commit_not_fast_forward.snapindex 5e5e6fdf0..f6ec57fbc 100644--- a/tests/snapshots/integration__integration_tests__merge__merge_no_commit_not_fast_forward.snap+++ b/tests/snapshots/integration__integration_tests__merge__merge_no_commit_not_fast_forward.snap@@ -25,12 +25,16 @@ info:WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"----success: false-exit_code: 1+success: true+exit_code: 0----- stdout ---------- stderr ------β [31mCan't push to local [1mmain[22m branch: it has newer commits[39m-[107m [0m * [33m1b32c68[m Add main file--π‘ [2mRun [90mwt merge[39m again to incorporate these changes[22m+π [36mRebasing onto [1mmain[22m...[39m+β [32mRebased onto [1mmain[22m[39m+π [36mMerging 1 commit to [1mmain[22m @ [2m430212e[22m (no commit/squash needed)[39m+[107m [0m * [33m430212e[m Add feature file+[107m [0m feature.txt | 1 [32m+[m+[107m [0m 1 file changed, 1 insertion(+)+β [32mMerged to [1mmain[22m [90m(1 commit, 1 file, [32m+1[39m[39m[90m)[39m[39m+βͺ Worktree preserved (--no-remove)diff --git a/tests/snapshots/integration__integration_tests__merge__merge_no_rebase_already_rebased.snap b/tests/snapshots/integration__integration_tests__merge__merge_no_rebase_already_rebased.snapnew file mode 100644index 000000000..813b7ef1a--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__merge_no_rebase_already_rebased.snap@@ -0,0 +1,37 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - merge+ - main+ - "--no-rebase"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ PATH: "[PATH]"+ SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+π [36mMerging 1 commit to [1mmain[22m @ [2mfc12499[22m (no commit/squash/rebase needed)[39m+[107m [0m * [33mfc12499[m Add feature file+[107m [0m feature.txt | 1 [32m+[m+[107m [0m 1 file changed, 1 insertion(+)+β [32mMerged to [1mmain[22m [90m(1 commit, 1 file, [32m+1[39m[39m[90m)[39m[39m+π [36m[36mRemoving [1mfeature[22m worktree & branch in background (same commit as main)[39m[39mdiff --git a/tests/snapshots/integration__integration_tests__merge__merge_no_rebase_not_rebased.snap b/tests/snapshots/integration__integration_tests__merge__merge_no_rebase_not_rebased.snapnew file mode 100644index 000000000..84e6b79d7--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__merge_no_rebase_not_rebased.snap@@ -0,0 +1,34 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - merge+ - main+ - "--no-rebase"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ PATH: "[PATH]"+ SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+β [31mBranch not rebased onto [1mmain[22m[39m++π‘ [2mRun [90mwt rebase[39m first or remove [90m--no-rebase[39m[22m