There are times when we want to have two remotes for the same repository on our local machine. We may want to avoid pushing in-progress changes to one of the remotes because it is public or a production environment.

The trick to prevent accidentally pushing in-development changes to the wrong environment is to use the git command for changing remote’s URL.

# git command to change remote's URL 
$ git remote set-url --push <REMOTE_NAME> <NEW_URL>

By adding the --push flag to the command, only the push URL is manipulated. So it is still possible to pull from that remote. Then, we want to set the push URL to anything that won’t be a real endpoint such as no_push. Now, when someone accidentally pushes their changes, the URL is invalid and will fail.

# git command to disable the push
$ git remote set-url --push <REMOTE_NAME> no_push
# Example
$ git remote set-url --push prod no_push

# git command to list the remote repositories
$ git remote -v
origin	<https://github.com/user/repo_forked.git> (fetch)
origin	<https://github.com/user/repo_forked.git> (push)
prod	<https://github.com/user/repo.git> (fetch)
prod	no_push (push)

# When one accidentally push changes to prod with push URL set to no_push 
$ git push prod
fatal: 'no_push' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

If you need to push code to that remote in the future, you can simply re-enable the push by doing the following.

$ git remote set-url --push <REMOTE_NAME> <REPO_URL>
# Example
$ git remote set-url --push prod <https://github.com/user/repo.git>

# git command to list the remotes
$ git remote -v
origin	<https://github.com/user/repo_forked.git> (fetch)
origin	<https://github.com/user/repo_forked.git> (push)
prod	<https://github.com/user/repo.git> (fetch)
prod	<https://github.com/user/repo.git> (push)

In a nutshell, spending a few minutes on prevention will save you from some hassle in the future, and by thinking out of the box, it is possible to solve problems with the existing tool even though it was created for other purposes.

And if you have questions about an embedded project you’re working on, Dojo Five can help you with all aspects of your devops for embedded journey! We are always happy to hear about cool projects or interesting problems to solve, so don’t hesitate to reach out and chat with us on LinkedIn or through email!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.