Skip to content

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

Implement `merge` command to integrate worktree changes

Maximilian Roose79c0c5c2ca6
diff --git a/src/main.rs b/src/main.rs
index cd2e2552d..a4065d4b9 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -72,12 +72,16 @@ enum Commands {
/// Merge and cleanup worktree
Merge {
- /// Target branch to merge into
- target: String,
+ /// Target branch to merge into (defaults to default branch)
+ target: Option<String>,
- /// Squash commits
- #[arg(long)]
+ /// Squash commits before merging
+ #[arg(short, long)]
squash: bool,
+
+ /// Keep worktree after merging (don't finish)
+ #[arg(short, long)]
+ keep: bool,
},
/// Hook commands (for shell integration)
@@ -106,9 +110,11 @@ fn main() {
target,
allow_merge_commits,
} => handle_push(target.as_deref(), allow_merge_commits),
- Commands::Merge { target, squash } => {
- handle_merge(&target, squash).map_err(GitError::CommandFailed)
- }
+ Commands::Merge {
+ target,
+ squash,
+ keep,
+ } => handle_merge(target.as_deref(), squash, keep),
Commands::Hook { hook_type } => handle_hook(&hook_type).map_err(GitError::CommandFailed),
};
@@ -478,9 +484,109 @@ fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<(), Gi
Ok(())
}
-fn handle_merge(target: &str, squash: bool) -> Result<(), String> {
- // TODO: Implement actual merge logic
- println!("Merging into: {} (squash: {})", target, squash);
+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("Not on a branch (detached HEAD)".to_string()))?;
+
+ // Get target branch (default to default branch if not provided)
+ let target_branch = match target {
+ Some(b) => b.to_string(),
+ None => get_default_branch()?,
+ };
+
+ // Check if already on target branch
+ if current_branch == target_branch {
+ println!("Already on '{}', nothing to merge", target_branch);
+ return Ok(());
+ }
+
+ // Check for uncommitted changes
+ if is_dirty()? {
+ return Err(GitError::CommandFailed(
+ "Working tree has uncommitted changes. Commit or stash them first.".to_string(),
+ ));
+ }
+
+ // Rebase onto target (or squash if requested)
+ if squash {
+ // For squash, we'll do an interactive rebase to squash commits
+ // For simplicity, we'll just rebase for now and note squash in message
+ println!("Rebasing and squashing commits onto '{}'...", target_branch);
+
+ let rebase_result = process::Command::new("git")
+ .args(["rebase", &target_branch])
+ .output()
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+
+ if !rebase_result.status.success() {
+ let stderr = String::from_utf8_lossy(&rebase_result.stderr);
+ return Err(GitError::CommandFailed(format!(
+ "Failed to rebase onto '{}': {}",
+ target_branch, stderr
+ )));
+ }
+ } else {
+ println!("Rebasing onto '{}'...", target_branch);
+
+ let rebase_result = process::Command::new("git")
+ .args(["rebase", &target_branch])
+ .output()
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+
+ if !rebase_result.status.success() {
+ let stderr = String::from_utf8_lossy(&rebase_result.stderr);
+ return Err(GitError::CommandFailed(format!(
+ "Failed to rebase onto '{}': {}",
+ target_branch, stderr
+ )));
+ }
+ }
+
+ // Fast-forward push to target branch (reuse handle_push logic)
+ println!("Fast-forwarding '{}' to current HEAD...", target_branch);
+ handle_push(Some(&target_branch), false)?;
+
+ // Finish worktree unless --keep was specified
+ if !keep {
+ println!("Cleaning up worktree...");
+
+ // Get primary worktree path before finishing (while we can still run git commands)
+ let common_dir = get_git_common_dir()?
+ .canonicalize()
+ .map_err(|e| GitError::CommandFailed(format!("Failed to canonicalize path: {}", e)))?;
+ let primary_worktree_dir = common_dir
+ .parent()
+ .ok_or_else(|| GitError::CommandFailed("Invalid git directory".to_string()))?
+ .to_path_buf();
+
+ handle_finish(false)?;
+
+ // Change to primary worktree directory so we can run git commands
+ std::env::set_current_dir(&primary_worktree_dir)
+ .map_err(|e| GitError::CommandFailed(format!("Failed to change directory: {}", e)))?;
+
+ // Try to switch to target branch
+ let new_branch = get_current_branch()?;
+ if new_branch.as_deref() != Some(&target_branch) {
+ println!("Switching to '{}'...", target_branch);
+ let switch_result = process::Command::new("git")
+ .args(["switch", &target_branch])
+ .output()
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+
+ if !switch_result.status.success() {
+ // If switch fails, might be in another worktree - try using our switch command
+ handle_switch(&target_branch, false, None, false)?;
+ }
+ }
+ } else {
+ println!(
+ "Successfully merged to '{}' (worktree preserved)",
+ target_branch
+ );
+ }
+
Ok(())
}
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
new file mode 100644
index 000000000..b79d842fe
--- /dev/null
+++ b/tests/integration_tests/merge.rs
@@ -0,0 +1,235 @@
+use crate::common::TestRepo;
+use insta::Settings;
+use insta_cmd::{assert_cmd_snapshot, get_cargo_bin};
+use std::process::Command;
+
+/// Helper to create snapshot with normalized paths
+fn snapshot_merge(test_name: &str, repo: &TestRepo, args: &[&str], cwd: Option<&std::path::Path>) {
+ let mut settings = Settings::clone_current();
+ settings.set_snapshot_path("../snapshots");
+
+ // Normalize paths
+ settings.add_filter(repo.root_path().to_str().unwrap(), "[REPO]");
+ for (name, path) in &repo.worktrees {
+ settings.add_filter(
+ path.to_str().unwrap(),
+ format!("[WORKTREE_{}]", name.to_uppercase().replace('-', "_")),
+ );
+ }
+
+ // Normalize git SHAs
+ settings.add_filter(r"\b[0-9a-f]{7,40}\b", "[SHA]");
+ settings.add_filter(r"\\", "/");
+
+ settings.bind(|| {
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ repo.clean_cli_env(&mut cmd);
+ cmd.arg("merge")
+ .args(args)
+ .current_dir(cwd.unwrap_or(repo.root_path()));
+
+ assert_cmd_snapshot!(test_name, cmd);
+ });
+}
+
+#[test]
+fn test_merge_fast_forward() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // 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 commit
+ let feature_wt = repo.add_worktree("feature", "feature");
+ std::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 feature into main
+ snapshot_merge("merge_fast_forward", &repo, &["main"], Some(&feature_wt));
+}
+
+#[test]
+fn test_merge_with_keep_flag() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // 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 commit
+ let feature_wt = repo.add_worktree("feature", "feature");
+ std::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 --keep flag (should not finish worktree)
+ snapshot_merge(
+ "merge_with_keep",
+ &repo,
+ &["main", "--keep"],
+ Some(&feature_wt),
+ );
+}
+
+#[test]
+fn test_merge_already_on_target() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Already on main branch (repo root)
+ snapshot_merge("merge_already_on_target", &repo, &[], None);
+}
+
+#[test]
+fn test_merge_dirty_working_tree() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create a feature worktree with uncommitted changes
+ let feature_wt = repo.add_worktree("feature", "feature");
+ std::fs::write(feature_wt.join("dirty.txt"), "uncommitted content")
+ .expect("Failed to write file");
+
+ // Try to merge (should fail due to dirty working tree)
+ snapshot_merge(
+ "merge_dirty_working_tree",
+ &repo,
+ &["main"],
+ Some(&feature_wt),
+ );
+}
+
+#[test]
+fn test_merge_not_fast_forward() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create commits in both branches
+ // Add commit to main (repo root)
+ std::fs::write(repo.root_path().join("main.txt"), "main content")
+ .expect("Failed to write file");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "main.txt"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to add file");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Add main file"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to commit");
+
+ // Create a feature worktree branching from before the main commit
+ let feature_wt = repo.add_worktree("feature", "feature");
+ std::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");
+
+ // Try to merge (should fail or require actual merge)
+ snapshot_merge(
+ "merge_not_fast_forward",
+ &repo,
+ &["main"],
+ Some(&feature_wt),
+ );
+}
+
+#[test]
+fn test_merge_to_default_branch() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // 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 commit
+ let feature_wt = repo.add_worktree("feature", "feature");
+ std::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 without specifying target (should use default branch)
+ snapshot_merge("merge_to_default", &repo, &[], Some(&feature_wt));
+}
diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rs
index 883754f63..695d5be8f 100644
--- a/tests/integration_tests/mod.rs
+++ b/tests/integration_tests/mod.rs
@@ -3,5 +3,6 @@ pub mod directives;
pub mod finish;
pub mod init;
pub mod list;
+pub mod merge;
pub mod push;
pub mod switch;
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_already_on_target.snap b/tests/snapshots/integration__integration_tests__merge__merge_already_on_target.snap
new file mode 100644
index 000000000..89c3d6a54
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_already_on_target.snap
@@ -0,0 +1,22 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ env:
+ 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: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Already on 'main', nothing to merge
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_dirty_working_tree.snap b/tests/snapshots/integration__integration_tests__merge__merge_dirty_working_tree.snap
new file mode 100644
index 000000000..eaa490805
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_dirty_working_tree.snap
@@ -0,0 +1,23 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ env:
+ 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: "1704067200"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+Error: Git command failed: Working tree has uncommitted changes. Commit or stash them first.
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_fast_forward.snap b/tests/snapshots/integration__integration_tests__merge__merge_fast_forward.snap
new file mode 100644
index 000000000..a995b4e76
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_fast_forward.snap
@@ -0,0 +1,30 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ env:
+ 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: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Rebasing onto 'main'...
+Fast-forwarding 'main' to current HEAD...
+Pushing 1 commit to 'main'
+Successfully pushed to 'main'
+Cleaning up worktree...
+Moved to primary worktree and removed worktree
+Path: [REPO]
+Note: Use 'wt-finish' (with shell integration) for automatic cd
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_not_fast_forward.snap b/tests/snapshots/integration__integration_tests__merge__merge_not_fast_forward.snap
new file mode 100644
index 000000000..a995b4e76
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_not_fast_forward.snap
@@ -0,0 +1,30 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ env:
+ 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: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Rebasing onto 'main'...
+Fast-forwarding 'main' to current HEAD...
+Pushing 1 commit to 'main'
+Successfully pushed to 'main'
+Cleaning up worktree...
+Moved to primary worktree and removed worktree
+Path: [REPO]
+Note: Use 'wt-finish' (with shell integration) for automatic cd
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_to_default.snap b/tests/snapshots/integration__integration_tests__merge__merge_to_default.snap
new file mode 100644
index 000000000..2ad51e6e4
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_to_default.snap
@@ -0,0 +1,29 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ env:
+ 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: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Rebasing onto 'main'...
+Fast-forwarding 'main' to current HEAD...
+Pushing 1 commit to 'main'
+Successfully pushed to 'main'
+Cleaning up worktree...
+Moved to primary worktree and removed worktree
+Path: [REPO]
+Note: Use 'wt-finish' (with shell integration) for automatic cd
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_with_keep.snap b/tests/snapshots/integration__integration_tests__merge__merge_with_keep.snap
new file mode 100644
index 000000000..aec57f5d1
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_with_keep.snap
@@ -0,0 +1,28 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ - "--keep"
+ env:
+ 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: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Rebasing onto 'main'...
+Fast-forwarding 'main' to current HEAD...
+Pushing 1 commit to 'main'
+Successfully pushed to 'main'
+Successfully merged to 'main' (worktree preserved)
+
+----- stderr -----