By Regina
I accidentally pushed some code changes directly to the main
branch without creating a separate feature branch. Is there a way to undo this and recover the previous state of the branch? What can I do to revert or reset the commit without causing any issues for other collaborators?
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Accepted Answer
Hey there! 👋
No worries, you can definitely recover from this! Here’s what you can do depending on the situation:
If you just need to undo your last commit and don’t mind losing the changes, you can reset the branch to the previous state before the push:
git reset --hard HEAD^
This will remove the last commit locally. After that, force-push the branch to update it on the remote:
git push origin main --force
If the commit was already pushed and you don’t want to rewrite history (especially if others are working on the same branch), it’s better to use git revert
to create a new commit that undoes the changes:
git revert HEAD
Then, push the new commit:
git push origin main
This way, you don’t mess with the history and keep everything safe for your team!
Going forward, I recommend setting up branch protections for your main
branch to avoid direct pushes. You can configure it to require pull requests for merging into main
, which helps prevent accidental pushes in the future!
Here’s a quick link on how to set branch protections: Branch protection rules on GitHub
Let me know how it goes!
- Bobby
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.