Tuesday, May 3, 2011

Amending a Git commit to a shared repo

Hey everyone,

I have a local git repo which I recently made a commit to, then pushed to a shared repo. Only after I pushed it to the shared repo did I realize I made an ugly mistake. I amended it locally no problem after I fixed my source with:

git commit -C HEAD -a --amend

After that, I tried another git push origin and I get the following error:

! [rejected]        mybranch -> mybranch (non-fast forward)

What's the best way to rectify this situation?

From stackoverflow
  • How about git reset?

  • git doesn't (by default) allow you to push to a branch anything that "rewinds" the branch tip. In other words, if the current branch head is not a direct parent or ancestor of the branch tip then the push will be refused.

    You can try to push anyway by using the -f option to git push or by using a refspec with a leading '+', e.g. git push origin +mybranch:mybranch .

    Usually remote repositories will still not let this happen because you risk losing commits if different people can indiscriminately push branch tips that don't include commits that they don't have locally.

    You can override this behaviour by changing the configuration parameter receive.denyNonFastForwards on the remote repository (assuming that you have the appropraite access to the remote repository).

    If you don't have such access you may be able to achieve this by deleting the remote branch and recreating it.

    e.g.

    git push origin :mybranch
    git push origin mybranch
    

    Note that more recent versions of git include a configuration parameter receive.denyDeletes that will, if set, prevent this potentially dangerous workaround from working.

    araqnid : Nice, I didn't know about denyNonFastForwards: I'd assumed you needed a hook to enforce that.
  • If you want to force the push, you can ... ehm ... pass --force to push.

    However, it is generally considered bad form to rewrite history on a public repository.

  • Assuming your shared repo allows, just prefix the branch name with a plus sign to force the non-fast-forward push:

    git push origin +mybranch
    
  • In this case it's probably best just to make a second commit with the fix. Since you've already altered the original first commit in your local repository, you'll probably want to pull it from the shared repository and move HEAD so that your altered commit can be garbage-collected.

0 comments:

Post a Comment