Home > database >  How can I have git-checkout merge local modifications only if there's no conflict?
How can I have git-checkout merge local modifications only if there's no conflict?

Time:08-18

When I use git checkout -m, it merges local modifications, which makes life easier when a file has changed between two commits but in a completely separate place from where my local modifications are. However, this becomes a messy merge conflict that has to be resolved when there is indeed a conflict, and I can't simply go back to the previous branch. I also don't want to have to use git stash push and git stash pop all the time, as that is cumbersome. Any ideas what to do?

CodePudding user response:

Use the stash:

git stash save
git checkout where-I-want-to-go
git stash pop

If it fails when running git stash pop (which is where the conflict might arise) you simply run back to where you were before, as if nothing had happened:

git checkout -f - # with single -.  yep, this takes you back, just like that
git stash pop # just as if you didn't move anywhere

CodePudding user response:

The alternative is to use git worktree in order to manage multiple worktrees (one per branch)

That way, you don't have to checkout/switch branches, you go to a different folder, and you can import changes you want from one folder to the other if you need to.

CodePudding user response:

You might consider what I do overly cumbersome as well, but:

  1. Attempt git switch right-branch. If this works, great. If not, proceed to...
  2. Run git commit -m temp-commit-do-not-use.
  3. Run git switch right-branch.
  4. Run git cherry-pick -n wrong-branch. Resolve conflicts if any. Commit (replacing the "temp-commit-do-not-use" message of course).
  5. Run git switch wrong-branch and git reset --hard HEAD^ to remove the temporary do-not-use-this-commit commit.

Consider also using git worktree (as VonC suggests), since you can then open one window on right-branch and one on wrong-branch and swap back and forth just by moving your mouse.

  • Related