Search code examples
gitrebasegit-rebase

Why should we avoid using the rebase command on a branch that has been pushed?


I am looking for a simple example on why should we avoid using the rebase command on a branch that has been pushed when there are multiple people working with the project. I have read that it confuses the other developers, but a simple exaple would help me to visualize why this is a problem.


Solution

  • In short because the rebase changes sha1 ids of commits, its like rewriting the history. Here is an example:

    Say, you have master that has commits A1 and A2.

    >> git log master
     => A1, A2
    >> git checkout -b mybranch 
    >>> work..work..work
    >> git commit mybranch
    >>> work..work..work
    >> git commit mybranch
    // at this point mybranch contains A1, A2, A3, A4
    >> git log mybranch
    => A1, A2, A3,A4
    
    
    >> git push mybranch origin/mybranch
    
    // now (its critical ! ) other users __checkout__ mybranch on their machines (and get commits A1, A2, A3, A4) of course
    //////// 
    // a couple of hours/days later ...
    // ...meanwhile other people worked on master so now it looks like this:
    >> git checkout master
    >> git log
    => A1, A2, B1,B2 // commits B1 and B2 are new!!!
    // and now let rebase:
    >> git checkout mybranch
    >> git rebase master
    >> git log mybranch
    => A1, A2, B1, B2, A3', A4'
    

    Note at this point A3 went to be A3' (its sha1 has changed), and A4 went to be A4' Now you can forcefully push this history (a new history that rewrote the history with original A3 and A4 commits). git push -- force mybranch

    However, what will your colleagues do at this point? If they checkout mybranch by git pull mybranch are they supposed to get both A3 and A3' (the same goes for A4 and A4')?

    This is very problematic unless they delete their local copy of mybranch and pull as if has never existed on their local machines.