When do you use Git rebase instead of Git merge?

后端 未结 17 2660
独厮守ぢ
独厮守ぢ 2020-11-21 11:25

When is it recommended to use Git rebase vs. Git merge?

Do I still need to merge after a successful rebase?

17条回答
  •  迷失自我
    2020-11-21 12:19

    To complement my own answer mentioned by TSamper,

    • a rebase is quite often a good idea to do before a merge, because the idea is that you integrate in your branch Y the work of the branch B upon which you will merge.
      But again, before merging, you resolve any conflict in your branch (i.e.: "rebase", as in "replay my work in my branch starting from a recent point from the branch B).
      If done correctly, the subsequent merge from your branch to branch B can be fast-forward.

    • a merge directly impacts the destination branch B, which means the merges better be trivial, otherwise that branch B can be long to get back to a stable state (time for you solve all the conflicts)


    the point of merging after a rebase?

    In the case that I describe, I rebase B onto my branch, just to have the opportunity to replay my work from a more recent point from B, but while staying into my branch.
    In this case, a merge is still needed to bring my "replayed" work onto B.

    The other scenario (described in Git Ready for instance), is to bring your work directly in B through a rebase (which does conserve all your nice commits, or even give you the opportunity to re-order them through an interactive rebase).
    In that case (where you rebase while being in the B branch), you are right: no further merge is needed:

    A Git tree at default when we have not merged nor rebased

    rebase1

    we get by rebasing:

    rebase3

    That second scenario is all about: how do I get new-feature back into master.

    My point, by describing the first rebase scenario, is to remind everyone that a rebase can also be used as a preliminary step to that (that being "get new-feature back into master").
    You can use rebase to first bring master "in" the new-feature branch: the rebase will replay new-feature commits from the HEAD master, but still in the new-feature branch, effectively moving your branch starting point from an old master commit to HEAD-master.
    That allows you to resolve any conflicts in your branch (meaning, in isolation, while allowing master to continue to evolve in parallel if your conflict resolution stage takes too long).
    Then you can switch to master and merge new-feature (or rebase new-feature onto master if you want to preserve commits done in your new-feature branch).

    So:

    • "rebase vs. merge" can be viewed as two ways to import a work on, say, master.
    • But "rebase then merge" can be a valid workflow to first resolve conflict in isolation, then bring back your work.

提交回复
热议问题