Skip to content

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

feat(push): Stash target worktree changes during push

Maximilian Roos646779cc266b
diff --git a/src/cli.rs b/src/cli.rs
index 73e3e28cc..7d0e532dd 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -104,6 +104,9 @@ pub enum StandaloneCommand {
},
/// Push changes to target branch
+ ///
+ /// Automatically stashes non-conflicting edits in the target worktree before
+ /// the push and restores them afterward so other agents' changes stay intact.
Push {
/// Target branch (defaults to default branch)
target: Option<String>,
@@ -384,7 +387,8 @@ The merge operation follows a strict order designed for fail-fast execution:
6. Push to target
Fast-forward pushes to target branch. Rejects non-fast-forward pushes (ensures
- linear history).
+ linear history). Temporarily stashes non-conflicting local edits in the target
+ worktree so they don't block the push, then restores them after success.
7. Clean up worktree and branch
Removes current worktree, deletes the branch, and switches primary worktree to target
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index d734034ad..e74428459 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -99,9 +99,12 @@
//! The shell wrapper is generated by `wt init <shell>` from templates in `templates/`.
use std::path::PathBuf;
+use std::time::{SystemTime, UNIX_EPOCH};
use worktrunk::config::{CommandPhase, WorktrunkConfig};
use worktrunk::git::{GitError, GitResultExt, Repository};
-use worktrunk::styling::{CYAN, CYAN_BOLD, GREEN, GREEN_BOLD, WARNING, format_with_gutter};
+use worktrunk::styling::{
+ CYAN, CYAN_BOLD, GREEN, GREEN_BOLD, WARNING, WARNING_BOLD, format_with_gutter,
+};
use super::hooks::{HookFailureStrategy, HookPipeline};
use super::project_config::load_project_config;
@@ -418,19 +421,19 @@ fn remove_worktree_by_name(
})
}
-/// Check for conflicting uncommitted changes in target worktree
-fn check_worktree_conflicts(
+/// Auto-stash dirty target worktree changes when safe (no overlapping files)
+fn prepare_target_worktree(
repo: &Repository,
- target_worktree: &Option<std::path::PathBuf>,
+ target_worktree: Option<&std::path::PathBuf>,
target_branch: &str,
-) -> Result<(), GitError> {
+) -> Result<Option<TargetWorktreeStash>, GitError> {
let Some(wt_path) = target_worktree else {
- return Ok(());
+ return Ok(None);
};
let wt_repo = Repository::at(wt_path);
if !wt_repo.is_dirty()? {
- return Ok(());
+ return Ok(None);
}
// Get files changed in the push
@@ -462,7 +465,90 @@ fn check_worktree_conflicts(
});
}
- Ok(())
+ // Generate unique stash label so we can restore the exact entry even if others are created
+ let nanos = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_nanos();
+ let stash_name = format!(
+ "worktrunk autostash::{}::{}::{}",
+ target_branch,
+ std::process::id(),
+ nanos
+ );
+
+ crate::output::progress(format!(
+ "{CYAN}Stashing changes in {CYAN_BOLD}{}{CYAN_BOLD:#}{CYAN}...{CYAN:#}",
+ wt_path.display()
+ ))?;
+
+ let stash_output =
+ wt_repo.run_command(&["stash", "push", "--include-untracked", "-m", &stash_name])?;
+
+ if stash_output.contains("No local changes to save") {
+ return Ok(None);
+ }
+
+ let list_output = wt_repo.run_command(&["stash", "list", "--format=%gd%x00%gs%x00"])?;
+ let mut parts = list_output.split('\0');
+ let mut stash_ref = None;
+ while let Some(id) = parts.next() {
+ if id.is_empty() {
+ continue;
+ }
+ if let Some(message) = parts.next()
+ && (message == stash_name || message.ends_with(&stash_name))
+ {
+ stash_ref = Some(id.to_string());
+ break;
+ }
+ }
+
+ let Some(stash_ref) = stash_ref else {
+ return Err(GitError::CommandFailed(format!(
+ "Failed to locate autostash entry '{}'",
+ stash_name
+ )));
+ };
+
+ Ok(Some(TargetWorktreeStash::new(wt_path, stash_ref)))
+}
+
+/// Auto-restores stashed changes in the target worktree after push completes
+struct TargetWorktreeStash {
+ repo: Repository,
+ path: std::path::PathBuf,
+ stash_ref: String,
+}
+
+impl TargetWorktreeStash {
+ fn new(path: &std::path::Path, stash_ref: String) -> Self {
+ Self {
+ repo: Repository::at(path),
+ path: path.to_path_buf(),
+ stash_ref,
+ }
+ }
+
+ fn restore(self) -> Result<(), GitError> {
+ crate::output::progress(format!(
+ "{CYAN}Restoring stashed changes in {CYAN_BOLD}{}{CYAN_BOLD:#}{CYAN}...{CYAN:#}",
+ self.path.display()
+ ))?;
+
+ if let Err(_e) = self
+ .repo
+ .run_command(&["stash", "pop", "--quiet", &self.stash_ref])
+ {
+ crate::output::warning(format!(
+ "{WARNING}Failed to restore stash {WARNING_BOLD}{stash_ref}{WARNING_BOLD:#}{WARNING} - run 'git stash pop {stash_ref}' in {WARNING_BOLD}{path}{WARNING_BOLD:#}{WARNING:#}",
+ stash_ref = self.stash_ref,
+ path = self.path.display(),
+ ))?;
+ }
+
+ Ok(())
+ }
}
/// Execute post-create commands sequentially (blocking)
@@ -556,6 +642,11 @@ pub fn execute_post_start_commands_sequential(
/// The `committed`, `squashed`, and `rebased` parameters are optional flags indicating
/// whether those operations occurred in the merge workflow. Pass `None` for standalone
/// push operations where these concepts don't apply.
+///
+/// During the push stage we temporarily `git stash` non-overlapping changes in the
+/// target worktree (if present) so that concurrent edits there do not block the
+/// fast-forward. The stash is restored afterward and we bail out early if any file
+/// overlaps with the push range.
pub fn handle_push(
target: Option<&str>,
allow_merge_commits: bool,
@@ -616,9 +707,10 @@ pub fn handle_push(
repo.set_config("receive.denyCurrentBranch", "updateInstead")?;
}
- // Check for conflicting changes in target worktree
+ // Check for conflicting changes in target worktree (auto-stash safe changes)
let target_worktree = repo.worktree_for_branch(&target_branch)?;
- check_worktree_conflicts(&repo, &target_worktree, &target_branch)?;
+ let mut target_worktree_stash =
+ prepare_target_worktree(&repo, target_worktree.as_ref(), &target_branch)?;
// Count commits and show what will be pushed
let commit_count = repo.count_commits(&target_branch, "HEAD")?;
@@ -713,10 +805,18 @@ pub fn handle_push(
// Perform the push
let push_target = format!("HEAD:{}", target_branch);
- repo.run_command(&["push", git_common_dir.to_str().unwrap(), &push_target])
- .map_err(|e| GitError::PushFailed {
+ if let Err(e) = repo.run_command(&["push", git_common_dir.to_str().unwrap(), &push_target]) {
+ if let Some(stash) = target_worktree_stash.take() {
+ stash.restore()?;
+ }
+ return Err(GitError::PushFailed {
error: e.to_string(),
- })?;
+ });
+ }
+
+ if let Some(stash) = target_worktree_stash.take() {
+ stash.restore()?;
+ }
// Show success message after push completes
if commit_count > 0 {
diff --git a/tests/integration_tests/config_list.rs b/tests/integration_tests/config_list.rs
index 71deaafa4..6deaa7a09 100644
--- a/tests/integration_tests/config_list.rs
+++ b/tests/integration_tests/config_list.rs
@@ -161,10 +161,10 @@ fn test_config_list_outside_git_repo() {
success: true
exit_code: 0
----- stdout -----
- ⚪ Global Config: [TEMP_HOME]/.config/worktrunk/config.toml
-   worktree-path = "../{main-worktree}.{branch}"
+ ⚪ Global Config: [TEMP_HOME]/.config/worktrunk/config.toml
+ worktree-path = "../{main-worktree}.{branch}"
- ⚪ Project Config: Not in a git repository
+ ⚪ Project Config: Not in a git repository
----- stderr -----
"#);
diff --git a/tests/integration_tests/push.rs b/tests/integration_tests/push.rs
index 833902771..ab28a3fc6 100644
--- a/tests/integration_tests/push.rs
+++ b/tests/integration_tests/push.rs
@@ -162,7 +162,86 @@ fn test_push_with_dirty_target() {
.expect("Failed to commit");
// Try to push (should fail due to conflicting changes)
- snapshot_push("push_dirty_target", &repo, &["main"], Some(&feature_wt));
+ snapshot_push(
+ "push_dirty_target_overlap",
+ &repo,
+ &["main"],
+ Some(&feature_wt),
+ );
+
+ // Ensure target worktree still has original file content and no stash was created
+ let main_contents =
+ std::fs::read_to_string(repo.root_path().join("conflict.txt")).expect("read conflict file");
+ assert_eq!(main_contents, "old content");
+
+ let mut git_cmd = Command::new("git");
+ repo.configure_git_cmd(&mut git_cmd);
+ let stash_list = git_cmd
+ .args(["stash", "list"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to list stashes");
+ assert!(
+ String::from_utf8_lossy(&stash_list.stdout)
+ .trim()
+ .is_empty()
+ );
+}
+
+#[test]
+fn test_push_dirty_target_autostash() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Make main worktree (repo root) dirty with a non-conflicting file
+ std::fs::write(repo.root_path().join("notes.txt"), "temporary notes")
+ .expect("Failed to write file");
+
+ 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 should succeed by auto-stashing the non-conflicting target changes
+ snapshot_push(
+ "push_dirty_target_autostash",
+ &repo,
+ &["main"],
+ Some(&feature_wt),
+ );
+
+ // Ensure the target worktree content is restored
+ let notes = std::fs::read_to_string(repo.root_path().join("notes.txt"))
+ .expect("read notes file after autostash");
+ assert_eq!(notes, "temporary notes");
+
+ // Autostash should clean up after itself
+ let mut git_cmd = Command::new("git");
+ repo.configure_git_cmd(&mut git_cmd);
+ let stash_list = git_cmd
+ .args(["stash", "list"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to list stashes");
+ assert!(
+ String::from_utf8_lossy(&stash_list.stdout)
+ .trim()
+ .is_empty()
+ );
}
#[test]
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index f7318da97..118dc435b 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -15,7 +15,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpZuEIMN/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp0hMTyP/test-config.toml
---
success: true
exit_code: 0
@@ -257,7 +257,7 @@ complete -c wt -n "__fish_wt_using_subcommand beta; and __fish_seen_subcommand_f
complete -c wt -n "__fish_wt_using_subcommand beta; and __fish_seen_subcommand_from squash" -s h -l help -d 'Print help'
complete -c wt -n "__fish_wt_using_subcommand beta; and __fish_seen_subcommand_from push" -l allow-merge-commits -d 'Allow pushing merge commits (non-linear history)'
complete -c wt -n "__fish_wt_using_subcommand beta; and __fish_seen_subcommand_from push" -s v -l verbose -d 'Enable verbose output (show git commands and debug info)'
-complete -c wt -n "__fish_wt_using_subcommand beta; and __fish_seen_subcommand_from push" -s h -l help -d 'Print help'
+complete -c wt -n "__fish_wt_using_subcommand beta; and __fish_seen_subcommand_from push" -s h -l help -d 'Print help (see more with \'--help\')'
complete -c wt -n "__fish_wt_using_subcommand beta; and __fish_seen_subcommand_from rebase" -s v -l verbose -d 'Enable verbose output (show git commands and debug info)'
complete -c wt -n "__fish_wt_using_subcommand beta; and __fish_seen_subcommand_from rebase" -s h -l help -d 'Print help'
complete -c wt -n "__fish_wt_using_subcommand beta; and __fish_seen_subcommand_from ask-approvals" -s f -l force -d 'Skip command approval prompts'
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index ebbb4e12b..55e75c11b 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -15,7 +15,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmphanjUv/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpda32N5/test-config.toml
---
success: true
exit_code: 0
@@ -299,8 +299,8 @@ _arguments "${_arguments_options[@]}" : \
'--allow-merge-commits[Allow pushing merge commits (non-linear history)]' \
'-v[Enable verbose output (show git commands and debug info)]' \
'--verbose[Enable verbose output (show git commands and debug info)]' \
-'-h[Print help]' \
-'--help[Print help]' \
+'-h[Print help (see more with '\''--help'\'')]' \
+'--help[Print help (see more with '\''--help'\'')]' \
'::target -- Target branch (defaults to default branch):_default' \
&& ret=0
;;
diff --git a/tests/snapshots/integration__integration_tests__push__push_dirty_target_autostash.snap b/tests/snapshots/integration__integration_tests__push__push_dirty_target_autostash.snap
new file mode 100644
index 000000000..0e93bd6d1
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__push__push_dirty_target_autostash.snap
@@ -0,0 +1,33 @@
+---
+source: tests/integration_tests/push.rs
+info:
+ program: wt
+ args:
+ - beta
+ - push
+ - main
+ 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
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpE1EiyT/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+🔄 Stashing changes in [REPO]...
+🔄 Pushing 1 commit to main @ [SHA]
+
+  * [SHA] (HEAD -> feature) Add feature file
+  feature.txt | 1 +
+  1 file changed, 1 insertion(+)
+🔄 Restoring stashed changes in [REPO]...
+✅ Pushed to main (1 commit, 1 file, +1)
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__push__push_dirty_target.snap b/tests/snapshots/integration__integration_tests__push__push_dirty_target_overlap.snap
similarity index 91%
rename from tests/snapshots/integration__integration_tests__push__push_dirty_target.snap
rename to tests/snapshots/integration__integration_tests__push__push_dirty_target_overlap.snap
index 9822ff64c..ae217e8bb 100644
--- a/tests/snapshots/integration__integration_tests__push__push_dirty_target.snap
+++ b/tests/snapshots/integration__integration_tests__push__push_dirty_target_overlap.snap
@@ -13,11 +13,10 @@ info:
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/.tmp74mSi8/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmphd1oIj/test-config.toml
---
success: false
exit_code: 1