Skip to content

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

Implement `push` command to update target branches

Maximilian Roos26da4cffa8ed
diff --git a/src/git.rs b/src/git.rs
index ea9217710..e69ae02a6 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -346,6 +346,80 @@ pub fn is_in_worktree_in(path: &std::path::Path) -> Result<bool, GitError> {
Ok(git_dir != common_dir)
}
+/// Check if base_branch is an ancestor of HEAD (i.e., would be a fast-forward)
+pub fn is_ancestor(base_branch: &str, head: &str) -> Result<bool, GitError> {
+ is_ancestor_in(std::path::Path::new("."), base_branch, head)
+}
+
+/// Check if base is an ancestor of head in the repository at the given path
+pub fn is_ancestor_in(path: &std::path::Path, base: &str, head: &str) -> Result<bool, GitError> {
+ let output = std::process::Command::new("git")
+ .args(["merge-base", "--is-ancestor", base, head])
+ .current_dir(path)
+ .output()
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+
+ Ok(output.status.success())
+}
+
+/// Count commits between base and head
+pub fn count_commits(base: &str, head: &str) -> Result<usize, GitError> {
+ count_commits_in(std::path::Path::new("."), base, head)
+}
+
+/// Count commits between base and head in the repository at the given path
+pub fn count_commits_in(path: &std::path::Path, base: &str, head: &str) -> Result<usize, GitError> {
+ let range = format!("{}..{}", base, head);
+ let stdout = run_git_command(&["rev-list", "--count", &range], Some(path))?;
+ stdout
+ .trim()
+ .parse()
+ .map_err(|e| GitError::ParseError(format!("Failed to parse commit count: {}", e)))
+}
+
+/// Check if there are merge commits in the range base..head
+pub fn has_merge_commits(base: &str, head: &str) -> Result<bool, GitError> {
+ has_merge_commits_in(std::path::Path::new("."), base, head)
+}
+
+/// Check if there are merge commits in the range base..head at the given path
+pub fn has_merge_commits_in(
+ path: &std::path::Path,
+ base: &str,
+ head: &str,
+) -> Result<bool, GitError> {
+ let range = format!("{}..{}", base, head);
+ let output = std::process::Command::new("git")
+ .args(["rev-list", "--merges", &range])
+ .current_dir(path)
+ .output()
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ return Err(GitError::CommandFailed(stderr.to_string()));
+ }
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ Ok(!stdout.trim().is_empty())
+}
+
+/// Get files changed between base and head
+pub fn get_changed_files(base: &str, head: &str) -> Result<Vec<String>, GitError> {
+ get_changed_files_in(std::path::Path::new("."), base, head)
+}
+
+/// Get files changed between base and head at the given path
+pub fn get_changed_files_in(
+ path: &std::path::Path,
+ base: &str,
+ head: &str,
+) -> Result<Vec<String>, GitError> {
+ let range = format!("{}..{}", base, head);
+ let stdout = run_git_command(&["diff", "--name-only", &range], Some(path))?;
+ Ok(stdout.lines().map(|s| s.to_string()).collect())
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/main.rs b/src/main.rs
index 0b8f23b3e..cd2e2552d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,8 +1,9 @@
use clap::{Parser, Subcommand};
use std::process;
use worktrunk::git::{
- GitError, branch_exists, get_current_branch, get_default_branch, get_git_common_dir,
- get_worktree_root, is_dirty, is_in_worktree, list_worktrees, worktree_for_branch,
+ GitError, branch_exists, count_commits, get_changed_files, get_current_branch,
+ get_default_branch, get_git_common_dir, get_worktree_root, has_merge_commits, is_ancestor,
+ is_dirty, is_dirty_in, is_in_worktree, list_worktrees, worktree_for_branch,
};
use worktrunk::shell;
@@ -61,8 +62,12 @@ enum Commands {
/// Push changes between worktrees
Push {
- /// Target worktree
- target: String,
+ /// Target branch (defaults to default branch)
+ target: Option<String>,
+
+ /// Allow pushing merge commits (non-linear history)
+ #[arg(long)]
+ allow_merge_commits: bool,
},
/// Merge and cleanup worktree
@@ -97,7 +102,10 @@ fn main() {
internal,
} => handle_switch(&branch, create, base.as_deref(), internal),
Commands::Finish { internal } => handle_finish(internal),
- Commands::Push { target } => handle_push(&target).map_err(GitError::CommandFailed),
+ Commands::Push {
+ target,
+ allow_merge_commits,
+ } => handle_push(target.as_deref(), allow_merge_commits),
Commands::Merge { target, squash } => {
handle_merge(&target, squash).map_err(GitError::CommandFailed)
}
@@ -353,9 +361,120 @@ fn handle_finish(internal: bool) -> Result<(), GitError> {
Ok(())
}
-fn handle_push(target: &str) -> Result<(), String> {
- // TODO: Implement actual push logic
- println!("Pushing to worktree: {}", target);
+fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<(), GitError> {
+ // 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 it's a fast-forward
+ if !is_ancestor(&target_branch, "HEAD")? {
+ return Err(GitError::CommandFailed(format!(
+ "Not a fast-forward from '{}' to HEAD. The target branch has commits not in your current branch.",
+ target_branch
+ )));
+ }
+
+ // Check for merge commits unless allowed
+ if !allow_merge_commits && has_merge_commits(&target_branch, "HEAD")? {
+ return Err(GitError::CommandFailed(
+ "Found merge commits in push range. Use --allow-merge-commits to push non-linear history.".to_string(),
+ ));
+ }
+
+ // Configure receive.denyCurrentBranch if needed
+ let deny_config_output = process::Command::new("git")
+ .args(["config", "receive.denyCurrentBranch"])
+ .output()
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+
+ let current_config = String::from_utf8_lossy(&deny_config_output.stdout);
+ if current_config.trim() != "updateInstead" {
+ process::Command::new("git")
+ .args(["config", "receive.denyCurrentBranch", "updateInstead"])
+ .output()
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ }
+
+ // Find worktree for target branch
+ let target_worktree = worktree_for_branch(&target_branch)?;
+
+ if let Some(ref wt_path) = target_worktree {
+ // Check if target worktree is dirty
+ if is_dirty_in(wt_path)? {
+ // Get files changed in the push
+ let push_files = get_changed_files(&target_branch, "HEAD")?;
+
+ // Get files changed in the worktree
+ let wt_status_output = process::Command::new("git")
+ .args(["status", "--porcelain"])
+ .current_dir(wt_path)
+ .output()
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+
+ let wt_files: Vec<String> = String::from_utf8_lossy(&wt_status_output.stdout)
+ .lines()
+ .filter_map(|line| {
+ // Parse porcelain format: "XY filename"
+ let parts: Vec<&str> = line.splitn(2, ' ').collect();
+ parts.get(1).map(|s| s.trim().to_string())
+ })
+ .collect();
+
+ // Find overlapping files
+ let overlapping: Vec<String> = push_files
+ .iter()
+ .filter(|f| wt_files.contains(f))
+ .cloned()
+ .collect();
+
+ if !overlapping.is_empty() {
+ eprintln!("Cannot push: conflicting uncommitted changes in:");
+ for file in &overlapping {
+ eprintln!(" - {}", file);
+ }
+ return Err(GitError::CommandFailed(format!(
+ "Commit or stash changes in {} first",
+ wt_path.display()
+ )));
+ }
+ }
+ }
+
+ // Count commits and show info
+ let commit_count = count_commits(&target_branch, "HEAD")?;
+ if commit_count > 0 {
+ let commit_text = if commit_count == 1 {
+ "commit"
+ } else {
+ "commits"
+ };
+ println!(
+ "Pushing {} {} to '{}'",
+ commit_count, commit_text, target_branch
+ );
+ }
+
+ // Get git common dir for the push
+ let git_common_dir = get_git_common_dir()?;
+
+ // Perform the push
+ let push_result = process::Command::new("git")
+ .args([
+ "push",
+ git_common_dir.to_str().unwrap(),
+ &format!("HEAD:{}", target_branch),
+ ])
+ .output()
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+
+ if !push_result.status.success() {
+ let stderr = String::from_utf8_lossy(&push_result.stderr);
+ return Err(GitError::CommandFailed(format!("Push failed: {}", stderr)));
+ }
+
+ println!("Successfully pushed to '{}'", target_branch);
Ok(())
}
diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rs
index 7a6b323f6..883754f63 100644
--- a/tests/integration_tests/mod.rs
+++ b/tests/integration_tests/mod.rs
@@ -3,4 +3,5 @@ pub mod directives;
pub mod finish;
pub mod init;
pub mod list;
+pub mod push;
pub mod switch;
diff --git a/tests/integration_tests/push.rs b/tests/integration_tests/push.rs
new file mode 100644
index 000000000..758a25bd6
--- /dev/null
+++ b/tests/integration_tests/push.rs
@@ -0,0 +1,184 @@
+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_push(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("push")
+ .args(args)
+ .current_dir(cwd.unwrap_or(repo.root_path()));
+
+ assert_cmd_snapshot!(test_name, cmd);
+ });
+}
+
+#[test]
+fn test_push_fast_forward() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create a worktree for main (checking out existing branch)
+ 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");
+
+ // Make a commit in a feature worktree
+ let feature_wt = repo.add_worktree("feature", "feature");
+ std::fs::write(feature_wt.join("test.txt"), "test content").expect("Failed to write file");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "test.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 test file"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to commit");
+
+ // Push from feature to main
+ snapshot_push("push_fast_forward", &repo, &["main"], Some(&feature_wt));
+}
+
+#[test]
+fn test_push_not_fast_forward() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create commits in both worktrees
+ // The repo root is already the main worktree
+ 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");
+
+ 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 push from feature to main (should fail - not fast-forward)
+ snapshot_push("push_not_fast_forward", &repo, &["main"], Some(&feature_wt));
+}
+
+#[test]
+fn test_push_to_default_branch() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("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");
+
+ 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");
+
+ // Push without specifying target (should use default branch)
+ snapshot_push("push_to_default", &repo, &[], Some(&feature_wt));
+}
+
+#[test]
+fn test_push_with_dirty_target() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Make main worktree (repo root) dirty with a conflicting file
+ std::fs::write(repo.root_path().join("conflict.txt"), "old content")
+ .expect("Failed to write file");
+
+ let feature_wt = repo.add_worktree("feature", "feature");
+ std::fs::write(feature_wt.join("conflict.txt"), "new content").expect("Failed to write file");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "conflict.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 conflict file"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to commit");
+
+ // Try to push (should fail due to conflicting changes)
+ snapshot_push("push_dirty_target", &repo, &["main"], Some(&feature_wt));
+}
diff --git a/tests/snapshots/integration__integration_tests__push__push_dirty_target.snap b/tests/snapshots/integration__integration_tests__push__push_dirty_target.snap
new file mode 100644
index 000000000..c72f2e4ce
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__push__push_dirty_target.snap
@@ -0,0 +1,25 @@
+---
+source: tests/integration_tests/push.rs
+info:
+ program: wt
+ args:
+ - push
+ - 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 -----
+Cannot push: conflicting uncommitted changes in:
+ - conflict.txt
+Error: Git command failed: Commit or stash changes in [REPO] first
diff --git a/tests/snapshots/integration__integration_tests__push__push_fast_forward.snap b/tests/snapshots/integration__integration_tests__push__push_fast_forward.snap
new file mode 100644
index 000000000..d6c09cacb
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__push__push_fast_forward.snap
@@ -0,0 +1,24 @@
+---
+source: tests/integration_tests/push.rs
+info:
+ program: wt
+ args:
+ - push
+ - 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 -----
+Pushing 1 commit to 'main'
+Successfully pushed to 'main'
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__push__push_not_fast_forward.snap b/tests/snapshots/integration__integration_tests__push__push_not_fast_forward.snap
new file mode 100644
index 000000000..d6c09cacb
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__push__push_not_fast_forward.snap
@@ -0,0 +1,24 @@
+---
+source: tests/integration_tests/push.rs
+info:
+ program: wt
+ args:
+ - push
+ - 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 -----
+Pushing 1 commit to 'main'
+Successfully pushed to 'main'
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__push__push_to_default.snap b/tests/snapshots/integration__integration_tests__push__push_to_default.snap
new file mode 100644
index 000000000..6d3d57754
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__push__push_to_default.snap
@@ -0,0 +1,23 @@
+---
+source: tests/integration_tests/push.rs
+info:
+ program: wt
+ args:
+ - push
+ 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 -----
+Pushing 1 commit to 'main'
+Successfully pushed to 'main'
+
+----- stderr -----