Search code examples
gitgithub

github fork : your branch is 5 commits ahead how to clean this without pushing


I forked a project on github, in order to send pull requests. The problem is that my way to do was very ... dirty.

I worked on a local copy of the fork, created a branch for my modifications and merge it on the master. Then I pushed the master on the github fork in order to create a pull request.

The problem is that recently, my pull request have been rejected. So now I am 5 commits ahead from the original master. What are the solutions in order to be even with the original repository?

Should I have to checkout the upstream master in a new-branch and make the new master with it (how to do this?)

Or is it better to delete my github fork (I have previous accepted commits) and recreate it (you can see the github repos here)https://github.com/cedlemo/ruby-gnome2


Solution

  • First, you should always make your PR form a branch, not from master.
    master is for mirroring upstream/master, with 'upstream' being the name of the original repository that you forked.

    In your case, make sure that:

    • make sure that upstream exists (git remote -v),
    • make a branch in order to reference your current patches, and
    • reset master to upstream/master:

    Before:

      z--z (upstream/master, with new commits)
     /
    z--y--y--y (master with local patches, origin/master)
    

    Memorize current work:

    git checkout master
    git checkout -b mybranch
    # Or, With git 2.23+
    git switch -c myBranch master
    
    # if remote "upstream" does not yet exist
    git remote add upstream /url/original/repo
    git fetch upstream
    
    # reset master to upstream/master
    git checkout master
    git reset --hard upstream/master
    git push --force
    
      y--y--y (mybranch)
     /
    z--z--z   (master, upstream/master, origin/master)
    
    # replay the patches (even they are rejected for now) on top of master
    git switch mybranch
    git rebase master
    git push -u origin mybranch
    
            y'--y'--y' (mybranch, origin/mybranch)
           /
    z--z--z   (master, upstream/master, origin/master)
    

    Here: git reset --hard upstream/master will reset master HEAD on the updated upstream/master, in order for master to reflect the exact same history as the one in the original repository.

    But since some commits where previously done on master and pushed on the fork (origin/master), you would need to replace that history with the new master state. Hence the git push --force.

    Rebasing mybranch allows for those current patches to be based on the most up-to-date commit of the original repository.