Search code examples
gitgit-merge

How do I perform GitHub’s “Rebase and merge” in git with a single command?


Essentially, I want to merge a feature branch into main when the two branches have diverged and I can't fast-forward the merge.

If doing this manually, I would checkout the feature branch, rebase it onto main, switch back and merge the result. This, however, changes the feature branch, changes the working directory unnecessarily, and is just a little too much work for what is a straightforward option on GitHub.

What would be a good and safe way to do git rebase-and-merge without these drawbacks?


Solution

  • To answer my own question, this simple command appears to cover most use cases:

    git cherry-pick --ff HEAD..feature
    

    Here, HEAD..feature will select commits that are in feature branch but not in the current one. The option --ff will ensure that, if possible, a fast-forward will be performed, as otherwise cherry-pick always creates a new, distinct commit.

    The command will replay the sequence of commits on top of the current branch, stopping on conflicts. You can use --continue after resolving them, --skip commits and even --abort to cancel the operation and return to the pre-sequence state.