Git: move changes between branches without working directory change

Viewed 9451

Use-case: every time I want to move commit from one git branch to another I perform the following sequence of actions:

  1. [commit into working branch]
  2. git checkout branch-to-merge-into
  3. git cherry-pick target-commit
  4. git push
  5. git checkout working-branch

That works fine with the only exception - every time I perform 'git checkout' git working directory content is changed (expected) and that causes my IDE (IntelliJ IDEA) to perform inner state update (because monitored file system sub-tree is modified externally). That really annoys especially in case of big number of small commits.

I see two ways to go:

  1. perform 'mass cherry picks', i.e. perform big number of commits; move them to another branch, say, at working day end;
  2. have a second local git repository and perform cherry picks on it, i.e. every time actual commit and push is performed to the working branch, go to that second repository, pull the changes and perform cherry pick there;

I don't like the first approach because its possible to forget to move particular commit. The second one looks a bit... unnatural.

Basically, it would be perfect if I could say git 'move this commit from branch with name branchX to the branch branchX+1' without working directory update.

Question: is it possible to perform the above?

3 Answers

One option for this is to use git-worktree. For example you can:

worktree_dir=$(mktemp -d)
git worktree add "$worktree_dir" branch-to-merge-into
git -C "$worktree_dir" cherry-pick target-commit
git -C "$worktree_dir" push
git worktree remove "$worktree_dir"

As long as no other worktree has branch-to-merge-into checked out, this should work without disrupting your local checkout at all.

Related