Wednesday, August 12, 2015

Revert Commit into a Branch

Suppose you accidentally push file changes in the form of a git commit to your master branch, but you intended to first create a branch of those changes and push the branch.

Here's how to fix that....

git reset HEAD~1 --hard                                        # move the head back before your commit
git push -f                                                    # make git accept it
git fetch                                                      # get latest 
git reset origin/master                                        # undo non-pushed commit
git checkout -b NEW_BRANCH_NAME                                # create new branch for file changes
git stash save 'moving committed changes to NEW_BRANCH_NAME'   # workstation looks like it did before you made changes
git cherry-pick COMMIT_HASH                                    # grab your changes via cherry-pick
git push -u origin NEW_BRANCH_NAME                             # push NEW_BRANCH_NAME with changes to remote repo


You will probably want to run make note of the git hash created by the original commit BEFORE running these commands. You can run the following to get that hash value: $ git log

This assumes you want to push your changes into a NEW_BRANCH_NAME, which will likely get merged into the master branch after a pull request and code review.

Assuming this works, you should delete the stash you made using $ git stash drop

References

Is it possible to retroactively turn a set of commits into a branch?
Squash my last X commits together using Git

This work is licensed under the Creative Commons Attribution 3.0 Unported License.

No comments:

Post a Comment