You are busy developing and committed all code to the your central github repository. But then something happened and you need undo the commit on github.
You have two options:
- Reversing a commit
- Removing the commit (reset head)
In this article I´m showing you Option 2: Removing the commit, also called resetting the head.
Resetting the head to undo the last commit on github needs to be executed locally first and then force pushed to the target repository.
You have two options to reset:
Resetting hard means undoing the last commit and loosing the code.
Resetting soft means that the last commit is undone and the code changes are applied to the source code in the directory.
In my experience you want to use the soft option.
The process to undo your last commit on github looks like this:
- Enter the directory where the source code is
- Execute “git reset –hard HEAD~” to use the hard option or “git reset –soft HEAD~”.
- Execute “git push –force $branch” to push your changes to your github repository.
You did undo the last commit on github
Undoing a commit after it was pushed to the github repository can lead to problems. If you have e.g. automatic deployments based on code changes it might need fixing directly on the server.
Or other developers pulled your code and worked based on it. They need to fix their code versions (potentially git rebase)
You undo a commit on GitHub with either by reversing a commit or by resetting the head of the branch.
Imagine git like a stack of commits. By resetting the head you pop the last commit from the stack and thus remove it.
Then you can either use the code (e.g. when you committed to develop instead of the feature branch) (soft option) or you don´t care about the code at all (hard option).
Git as a version control system is widely used for software development, especially in the open source community.
Knowing and understanding how it works is therefore really important.
By understanding that you can undo a commit (on GitHub) by resetting the head you made one big step forward towards being able to handle most situations as developer.
As resetting the head has an impact on anyone using the branch it´s considered kinda dangerous. And if you need to do it too often on code that is already published it shows something is wrong with your process.
It happens to me once in a while that I need to use this option myself, although it´s usually on my local code. There I can potentially ignore the impact. Because this happens when I accidentally commit to the develop branch. So I reset the the head softly, checkout a new feature branch and commit my code again.
Let me know if it helped.