worktrunk icon indicating copy to clipboard operation
worktrunk copied to clipboard

Worktree friction: copy staged and unstaged changes when creating new worktree

Open frederik-suerig opened this issue 9 months ago • 14 comments

The friction

When I'm on the main branch and start working on changes, I sometimes realize mid-way that this should be a separate branch/worktree. However, if I have unstaged (or staged) changes and want to switch to a new worktree, there's no way to bring those changes along.

The changes are stuck in my current worktree, and I have to manually move them over before I can continue working in the new worktree.

Current workaround

Use git stash to temporarily store changes, switch to the new worktree, then pop them:

# In main worktree with uncommitted changes
git stash --include-untracked
wt switch --create feature-xyz
git stash pop

This is clunky and error-prone; it's easy to forget to pop, or to accidentally pop in the wrong worktree if you have multiple stashes.

Ideal solution

Two mutually exclusive flags for wt switch --create: --copy-staged: Copy only staged changes to the new worktree --copy-changes: Copy all changes (staged + unstaged) to the new worktree

# Copy only what's staged
wt switch --create feature-xyz --copy-staged

# Copy everything (staged + unstaged)
wt switch --create feature-xyz --copy-changes

Important constraints:

  • These flags only make sense with --create (new worktree from a base branch) --copy-staged and --copy-changes should be mutually exclusive
  • Both should conflict with --base if the base branch differs from the current branch, as the changes might not apply cleanly
  • After copying, the original worktree should remain unchanged (changes are copied, not moved)

frederik-suerig avatar Feb 05 '26 15:02 frederik-suerig

would be keen to see whether others have similar issues. we should have a fairly high bar for new options; and my sense is that this might fall the wrong side

(fwiw I used to have this problem more often, but now basically never do anything on main. but also don't want to overfit on my own experience)

max-sixty avatar Feb 05 '26 23:02 max-sixty

@max-sixty first of all, great tool! I was battling today with setting up (it may or may not have involved LLMs) my own workflow until I discovered this by accident and am happy to see a solid solution out there. Can't wait to properly try it out.

That being said, I also ran into the above issue. I will give your suggestion a try (which is not using main really) and if I still bump into same issues as @frederik-suerig I will reach out 🙏🏻

pkey avatar Mar 11 '26 20:03 pkey

Would love this feature @max-sixty - already annoyed it doesn't do this, since this is the natural behaviour for git checkout -b ...

ortonomy avatar Mar 16 '26 14:03 ortonomy

@worktrunk-bot can you give an example of an alias that would do this?

max-sixty avatar Apr 11 '26 06:04 max-sixty

Here are two shell functions that compose the existing commands. I tested them in a scratch repo with a file that had staged + unstaged + untracked changes simultaneously, confirming the original worktree is left unchanged and the new one ends up in an equivalent state.

# Copy all changes (staged + unstaged + untracked) to a new worktree.
wtcp() {
    local src dst staged unstaged untracked
    src=$(pwd)
    staged=$(mktemp) || return 1
    unstaged=$(mktemp) || { rm -f "$staged"; return 1; }
    git diff --cached > "$staged"
    git diff > "$unstaged"
    untracked=$(git ls-files --others --exclude-standard)

    wt switch --create "$@" || { rm -f "$staged" "$unstaged"; return 1; }

    dst=$(pwd)
    if [ "$dst" = "$src" ]; then
        echo "wtcp: shell integration required (wt config shell install)" >&2
        rm -f "$staged" "$unstaged"; return 1
    fi

    [ -s "$staged" ]   && git apply --index "$staged"
    [ -s "$unstaged" ] && git apply "$unstaged"
    printf '%s\n' "$untracked" | while IFS= read -r f; do
        [ -z "$f" ] && continue
        mkdir -p "$dst/$(dirname "$f")"
        cp -p "$src/$f" "$dst/$f"
    done
    rm -f "$staged" "$unstaged"
}

# Copy only staged changes.
wtcps() {
    local src staged
    src=$(pwd)
    staged=$(mktemp) || return 1
    git diff --cached > "$staged"
    wt switch --create "$@" || { rm -f "$staged"; return 1; }
    [ "$(pwd)" = "$src" ] && { echo "wtcps: shell integration required" >&2; rm -f "$staged"; return 1; }
    [ -s "$staged" ] && git apply --index "$staged"
    rm -f "$staged"
}

Usage: wtcp feature-xyz / wtcps feature-xyz. Extra flags pass through to wt switch --create.

Notes from testing:

  • wtcp preserves the staged/unstaged split — staged hunks stay staged in the new worktree, unstaged stay unstaged. Untracked files are copied via cp, honoring .gitignore through git ls-files --exclude-standard.
  • wtcps matches the proposed --copy-staged exactly — only git diff --cached content is carried over.
  • Both rely on wt switch's shell integration so the cd into the new worktree takes effect inside the function; the functions bail out with an error if it isn't active.
  • If you pass --base <other> and it differs from current HEAD, git apply may reject hunks that don't match — the same constraint the issue calls out for a native flag.

worktrunk-bot avatar Apr 11 '26 06:04 worktrunk-bot

@worktrunk-bot please create worktrunk aliases

max-sixty avatar Apr 11 '26 14:04 max-sixty

Here are two [aliases] entries that compose wt switch --create with git's stash/diff plumbing. I tested both end-to-end against a scratch repo with mixed staged + unstaged + untracked changes.

# .config/wt.toml or ~/.config/worktrunk/config.toml
[aliases]
# Take all in-progress changes (staged + unstaged + untracked) along to a new
# worktree. Source becomes clean.
#   wt step move-changes --var to=feature-xyz
move-changes = '''if git diff --quiet HEAD && test -z "$(git ls-files --others --exclude-standard)"; then wt switch --create {{ to }}; else git stash push --include-untracked --quiet && wt switch --create {{ to }} --execute='git stash pop --index'; fi'''

# Copy only staged changes to a new worktree. Source is unchanged.
#   wt step copy-staged --var to=feature-xyz
copy-staged = '''if git diff --cached --quiet; then wt switch --create {{ to }}; else p=$(mktemp) && git diff --cached > "$p" && wt switch --create {{ to }} --execute="git apply --index '$p' && rm '$p'"; fi'''

How they work:

  • move-changes stashes everything (--include-untracked), creates the new worktree, then uses --execute='git stash pop --index' so the pop runs in the new worktree. --index preserves the staged-vs-unstaged split. The git diff --quiet HEAD gate skips the stash dance when the source is already clean — avoiding spurious git stash pop noise and making sure we never accidentally pop a pre-existing stash.
  • copy-staged writes git diff --cached to a tempfile and applies it in the new worktree via git apply --index. The source worktree is left untouched (true copy semantics, matching the issue's --copy-staged description). Unlike git stash --staged, the diff approach handles files where staged and unstaged hunks overlap.

One important caveat: wt step aliases can't change the parent shell's directory — by design, wt step strips WORKTRUNK_DIRECTIVE_FILE from alias subprocesses, so the inner wt switch --create can't propagate a cd back through shell integration. After the alias, follow up with wt switch <branch> to land in the new worktree, or chain it on one line:

wt step move-changes --var to=feature-xyz --yes && wt switch feature-xyz

The trailing wt switch writes the cd directive normally. Inside the alias you'll also see a Cannot change directory — shell integration not installed warning from the inner wt switch — that's the same env-stripping at work, and it's harmless here.

Tested cases (scratch repo, git status --porcelain on each side after the alias):

Scenario move-changes copy-staged
Clean source source/new both clean source/new both clean
Staged + unstaged + untracked source clean, new has MM + ?? source unchanged, new has M (staged only, no untracked)
Untracked-only source clean, new has ?? n/a
Empty staged area n/a source/new both clean

If --base differs from HEAD, git apply / git stash pop may reject hunks that don't match — same constraint the issue calls out for a native flag.

worktrunk-bot avatar Apr 11 '26 14:04 worktrunk-bot

open an issue re being able to change paths from an alias, either explicitly or at least continuing let the cd pass through from an inner command

max-sixty avatar Apr 11 '26 14:04 max-sixty

Opened #2075.

worktrunk-bot avatar Apr 11 '26 14:04 worktrunk-bot

ok, that merged; now please update the suggested worktrunk aliases to be better

max-sixty avatar Apr 11 '26 18:04 max-sixty

Now that #2077 is in main, an inner wt switch --create inside an alias body propagates its cd to the parent shell (docs) — so the chained wt step <alias> && wt switch <branch> workaround is gone, and we can fold the third variant from the issue (--copy-changes) in too. Updated [aliases]:

# .config/wt.toml or ~/.config/worktrunk/config.toml
[aliases]
# Move all in-progress changes (staged + unstaged + untracked) to a new
# worktree. Source becomes clean.
#   wt step move-changes --var to=feature-xyz
move-changes = '''if git diff --quiet HEAD && test -z "$(git ls-files --others --exclude-standard)"; then wt switch --create {{ to }}; else git stash push --include-untracked --quiet && wt switch --create {{ to }} --execute='git stash pop --index'; fi'''

# Copy all changes (staged + unstaged + untracked) to a new worktree.
# Source is unchanged.
#   wt step copy-changes --var to=feature-xyz
copy-changes = '''if git diff --quiet HEAD && test -z "$(git ls-files --others --exclude-standard)"; then wt switch --create {{ to }}; else git stash push --include-untracked --quiet && git stash apply --index --quiet && wt switch --create {{ to }} --execute='git stash pop --index'; fi'''

# Copy only staged changes to a new worktree. Source is unchanged.
#   wt step copy-staged --var to=feature-xyz
copy-staged = '''if git diff --cached --quiet; then wt switch --create {{ to }}; else p=$(mktemp) && git diff --cached > "$p" && wt switch --create {{ to }} --execute="git apply --index '$p' && rm '$p'"; fi'''

Usage: wt step move-changes --var to=feature-xyz (similarly for the others). Add --yes to skip the project-config approval prompt on first run.

How they work:

  • move-changes stashes everything (--include-untracked), creates the new worktree, then --execute='git stash pop --index' runs the pop in the new worktree. --index preserves the staged-vs-unstaged split. The clean-state guard avoids touching a pre-existing stash.
  • copy-changes is the same dance plus an immediate git stash apply --index --quiet after the push, which restores the source worktree without dropping the stash. The new worktree pops the same stash via --execute. Net effect: identical states on both sides, untracked files included, no tempfile.
  • copy-staged writes git diff --cached to a tempfile and applies it in the new worktree via git apply --index. Diff (rather than git stash --staged) handles files where staged and unstaged hunks overlap on the same lines.

Tested end-to-end against a scratch repo (git status --porcelain on each side after the alias + sourcing the cd directive in the parent shell):

Scenario move-changes copy-changes copy-staged
Clean source source/new clean source/new clean source/new clean
Staged + unstaged + untracked source clean, new MM + ?? source MM + ??, new MM + ?? source unchanged, new M only
Untracked-only source clean, new ?? source ??, new ?? n/a

If --base differs from HEAD, git apply / git stash pop may reject hunks that don't match — same constraint the issue calls out for a native flag.

worktrunk-bot avatar Apr 11 '26 18:04 worktrunk-bot

OK great, add these examples to the new Extending worktrunk page and then close this

max-sixty avatar Apr 11 '26 19:04 max-sixty

Opened #2083 with all three aliases added to the Extending Worktrunk → Aliases → Recipe section. Closing per request — reopen if the PR needs to go a different direction.

worktrunk-bot avatar Apr 11 '26 20:04 worktrunk-bot

Opened #2084.

worktrunk-bot avatar Apr 11 '26 20:04 worktrunk-bot