worktrunk icon indicating copy to clipboard operation
worktrunk copied to clipboard

allow merging a non-current worktree

Open max-sixty opened this issue 8 months ago • 16 comments

currently, we allow most commands to operate in worktrees other than the current

is wt merge the only exception?

what are some options for allowing this?

max-sixty avatar Mar 21 '26 06:03 max-sixty

Thanks for the suggestion! I searched the codebase and confirmed that wt merge is currently the main command that requires operating from the current worktree.

The restriction is architectural — merge performs sequential state changes on the working tree (commit staged changes → squash → rebase → merge into target → remove source worktree), and several of these steps need direct working tree access (e.g., committing dirty state, conflict handling during rebase). By contrast, commands like remove can operate on non-current worktrees because they don't modify the working tree's content before acting.

Some options that came to mind from reading the code:

  1. cd + merge approach: For "clean" merges (no --commit, no dirty state), the command could cd into the target worktree internally and operate there — similar to how remove dispatches differently for current vs non-current worktrees via resolve_worktree_arg.

  2. Git-level merge without worktree: For fast-forward or simple merges, it's possible to do the merge purely with git plumbing (update refs) without needing the working tree at all. This would only work for the non-interactive, non-conflicting case.

  3. Temporary checkout: Temporarily check out the source branch in the target worktree, perform the merge, then restore — but this adds complexity and edge cases.

I'll leave it for a maintainer to evaluate the right approach and priority.

worktrunk-bot avatar Mar 21 '26 06:03 worktrunk-bot

well, sure, this would work similarly to wt remove

again: is this the only command requires a specific cwd?

what would be a good name for an option we could use to set it to be a different worktree?

max-sixty avatar Mar 26 '26 05:03 max-sixty

Looking more carefully, wt merge is the main one, but several wt step subcommands also implicitly operate on the current worktree: commit, squash, rebase, diff, copy-ignored, promote, prune, relocate. They all use Repository::current() or CommandEnv::for_action() to discover which worktree they're in, with no argument to override it.

That said, merge is the only top-level command with this constraint — the step subcommands are lower-level building blocks that users typically run while already in the worktree they're working on, so the need is less pressing there.

For naming the option: --branch feels natural since worktrunk addresses worktrees by branch name. It parallels how remove takes branch names as positional args. Usage would read as wt merge --branch feature-x (merge the feature-x worktree into target).

Alternatively, a positional approach like wt merge feature-x could work — but target already occupies the positional slot, so it'd need to be disambiguated. --branch (or -b) keeps it unambiguous and is consistent with git conventions.

worktrunk-bot avatar Mar 26 '26 05:03 worktrunk-bot

let's draft this for a minor command to start, like wt step commit

would --base be an alternative to --branch given we already use it? or it adds more confusion than conformity?

max-sixty avatar Mar 26 '26 05:03 max-sixty

I think --base would add confusion — in wt switch, --base means "the branch to fork from," which is a different concept from "the worktree to operate on." Reusing it here would overload the term.

Some alternatives:

  • --worktree / -w — most literal, says exactly what it does: wt step commit -w feature-x
  • --branch / -b — since worktrees are addressed by branch name, this is natural: wt step commit -b feature-x
  • Positional — wt step commit feature-x (commit has no positional args today, so it's unambiguous)

--worktree is the most self-documenting and avoids any overlap with existing flags. It also generalizes cleanly if we later add it to merge or other step subcommands.

For drafting on wt step commit — that's a good starting point since its current args are simple (just --yes, --no-hooks, --message, --show-prompt, --edit). I can put together a draft if you'd like.

worktrunk-bot avatar Mar 26 '26 05:03 worktrunk-bot

yes, please do

can you list where we use --base?

max-sixty avatar Mar 26 '26 05:03 max-sixty

--base is only used in wt switch:

  • wt switch --create <branch> --base <base> (-b short form) — the branch to fork from when creating a new branch. Defined in src/cli/mod.rs:393-394. Also referenced in help text examples, error messages for pr:/mr: conflicts, and completions.

No other command uses --base. I agree it would be confusing here — "base" implies "where to branch from," not "where to operate."


Here's a draft for adding --worktree / -w to wt step commit. The approach is to add a new CommandEnv::for_worktree() constructor that resolves a named worktree instead of using the current one.

CLI (src/cli/step.rs) — add to the Commit variant:

Commit {
    /// Worktree to commit in (branch name)
    ///
    /// Defaults to current worktree.
    #[arg(short, long, add = crate::completion::worktree_only_completer())]
    worktree: Option<String>,

    // ... existing fields unchanged ...
},

CommandEnv (src/commands/context.rs) — new constructor:

/// Load the command environment for a specific worktree (by branch name).
pub fn for_worktree(action: &str, config: UserConfig, branch: &str) -> anyhow::Result<Self> {
    let repo = Repository::current()?;
    let path = repo
        .worktree_for_branch(branch)?
        .ok_or_else(|| anyhow::anyhow!("no worktree for branch '{branch}'"))?;
    let wt = repo.worktree_at(&path);
    let worktree_path = wt.root()?;

    Ok(Self {
        repo,
        branch: Some(branch.to_string()),
        config,
        worktree_path,
    })
}

step_commit (src/commands/step_commands.rs) — accept the new param and branch on it:

pub fn step_commit(
    yes: bool,
    verify: bool,
    stage: Option<StageMode>,
    show_prompt: bool,
    worktree: Option<String>,
) -> anyhow::Result<()> {
    // ... config loading unchanged ...

    let env = match worktree {
        Some(ref wt) => CommandEnv::for_worktree("commit", config, wt)?,
        None => CommandEnv::for_action("commit", config)?,
    };

    // ... rest unchanged — CommitOptions flows through CommandContext ...
}

Dispatcher (src/main.rs:254-261) — pass through the new field.

The key insight is that once CommandEnv loads the right worktree_path and branch, everything downstream (CommitOptions, hook approval, staging, LLM prompt) automatically operates on that worktree via CommandContext. No deeper changes needed.

Want me to go ahead and implement this?

worktrunk-bot avatar Mar 26 '26 05:03 worktrunk-bot

re base, we also have base_worktree_path?

I don't think we should use worktree (vs branch), since some of these are going to need to take branches. we should always be addressing the branch, regardless of the final name

yes, please draft a PR

max-sixty avatar Mar 26 '26 05:03 max-sixty

Good call on --branch over --worktree — agreed that we should always address by branch name since that's worktrunk's model.

Re base_worktree_path: that's a template variable for hooks, not a CLI flag, so no naming conflict with --base. But --base still carries "fork from" semantics from wt switch --base, so --branch avoids the overload.

Drafted PR: #1750

  • Adds --branch / -b to wt step commit
  • Adds CommandEnv::for_branch() that resolves worktree path from branch name
  • Updates the commit pipeline to use the context's worktree path for all git operations (staging, status, commit) instead of hardcoding current_worktree()

The same pattern can be extended to other step subcommands from here.

worktrunk-bot avatar Mar 26 '26 06:03 worktrunk-bot

I need this as well. Would also be cool to have a keyboard shortcut within wt switch to merge. Btw. if worktree is created with different base than default branch, is this information stored anywhere, so it could be merge back to the base from which it was created without having to specify it?

adrian-gierakowski avatar Apr 07 '26 19:04 adrian-gierakowski

Re your question about base branch storage: currently worktrunk does not persist which branch a worktree was forked from. When you run wt switch --create <branch> --base <base>, the --base is used only at creation time (to run git branch) and then discarded. After that, merge target resolution falls back to the configured default branch.

So today, if you created a branch from something other than the default branch, you'd need to specify the target explicitly when merging (e.g., wt merge --branch <target> once #1637 lands, or by switching to the worktree first).

Storing the creation base per-worktree and using it as the default merge target could be a nice follow-up — worth its own issue if you're interested.

worktrunk-bot avatar Apr 07 '26 19:04 worktrunk-bot

Btw. if worktree is created with different base than default branch, is this information stored anywhere, so it could be merge back to the base from which it was created without having to specify it?

worth a new issue around stacked branches. I think this could be quite useful, but also could be a big scope increase. I'd like to let people use hooks & vars themselves to experiment with this

@worktrunk-bot to what extent could a hook set a vars with the base branch?

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

A post-start hook can do this directly — {{ base }} is available during wt switch --create, and wt config state vars set persists per-branch vars. So a one-liner in wt.toml captures it:

post-start = [
  "wt config state vars set base_branch='{{ base }}'",
]

After that, {{ vars.base_branch }} is available in all future hooks for that worktree. A merge alias could reference it:

[step]
merge-base = "wt merge {{ vars.base_branch }}"

Limitations:

  • Only works for worktrees created after the hook is added (no backfill for existing ones)
  • If --base isn't specified, {{ base }} resolves to the default branch, so it'd store that — which is already the merge default, making it redundant in that case. It's most useful when --base is explicitly set to something else

worktrunk-bot avatar Apr 07 '26 19:04 worktrunk-bot

@worktrunk-bot can you copy that comment to https://github.com/max-sixty/worktrunk/issues/1983? totally my fault, but this issue went off track

max-sixty avatar Apr 07 '26 20:04 max-sixty

Done — cross-posted to #1983.

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

This shipped in #4360 (merged 2026-10-11): wt merge --branch <source> [target] (short form -b) merges another worktree's branch without switching to it, following the wt step commit --branch interface from #1750. It runs the full pipeline (commit, squash, rebase, target advance, hooks, cleanup) in the source worktree and leaves the caller's directory alone. Integration tests live in tests/integration_tests/merge_source.rs.

I confirmed it on current main. From the primary worktree, wt merge --branch feat --yes merged feat into main and removed the feat worktree. The PR didn't use a closing keyword, so I'm closing this now.

worktrunk-bot avatar Nov 22 '26 09:11 worktrunk-bot