Working with version control system like Git is very much useful for any software developer.
In certain scenario’s, you’re permitted with write access to the original remote upstream git repository when you’re provided with project management tools by ZenHub or similar tools.
While working on forked repository having a write access to original remote repository, there are chances that you might have accidentally pushed commits to the original repository which you shouldn’t be.
This is sometime which is risky to merge accidentally a piece of code directly to the original repository.
I’ve also accidentally pushed some accidental commit to upstream repository. So, I was always looking for some work-arounds to prevent accidental remote push in Git.
I’ve came across to a better solution which will prevent you from pushing accidental commits to your upstream repository.
Before proceeding further, let me clarify some terminology with you:
- origin – the forked repository
- upstream – the original repository
As shown in screenshot (1), you can check the list of remotes with fetch and push capabilities to identify which remote push you want to disable.
In this case, I want to prevent remote push to upstream and replace it with the origin so that whenever I accidentally push to remote upstream then Git will understand and push those changes to origin instead of upstream.
How to prevent accidental remote push to upstream?
You need to execute remote push set url git command to prevent or disabled accidental remote push.
For example, I’ve implemented the command to push to remote origin even if I’ve accidentally used command to push remote upstream.
where, upstream is my remote and url is my forked repository of wp-cli
Now, executing the remotes list command will show you the updated git remotes list as per the screenshot (3).
Do It Yourself – Accidental Commit Prevention
Do some code changes and commit the code. Now, push that commit to upstream as per the screenshot (4).
But, when Git will process the command, it will show you that the commit is pushed to remote origin instead of remote upstream.
Hence, whenever you’ll accidentally push commit to upstream it will always go to your origin.
This guide to accidental git remote push will help you be at the safer side when you’re provided the write access to the original repository.
There are chances of messing up the original repository due to accidental pushing of commits to remote upstream which can lead to loss of valuable data and lots of rework.
P.S. Please feel free to share this Git Trick to your friends/colleagues.