Thursday, 11 May 2023

[git] Undo pushed but unmerged git commit

Problem

You were a bit hasty and committed and pushed something you should not have, e.g., as it has happened to me, into the wrong branch. Now, you want to undo the commit also in the remote repository, but not loose the changes you made.

Solution

Technically, you want, to my understanding

  1. Make HEAD point to the previous commit.
  2. Clean the index from the wrong commit.
  3. Push to the remote repository.
So, you would want to
  • $ git reset --mixed HEAD~
    where ~ stands for the parent commit, to go back more than commit, issue multiple times. The mixed option is the standard and therewith optional.
  • git push
    And this is the rather tricky part, because git might to refuse. In that case, you have two potentially dangerous options and you might want to double check with
    git help push
    I presume if you are on your own branch and nobody is working on it (as it should be?), you are safe with any of the options. Please don't sue me.
    • --force-with-lease
      This will overwrite the changes others are pushing while you are pushing (at least that is what I have understood).
    • --force
      This will overwrite ALL changes others might have pushed inbetween your wrong commit and this fixing.

No comments:

Post a Comment

[git] Create a local branch from another branch

From the active branch git checkout -b <LOCAL_BRANCH> From a donator branch git checkout -b <LOCAL_BRANCH> <DONATING_BRANCH...