Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to prevent myself pushing locally to remote master, like the way Github can prevent pushing to master?

Tags:

git

github

I want to turn on locally for myself a protection that stops me accidentally pushing to master (or any branch in particular).

Github can allow blocking pushing to master but I want to have that locally for companies or repos that do not have the protection.

It's a tricky question for a search engine too, because there's so many other git related questions out there, I thought here was the best place to ask.

like image 220
MintDeparture Avatar asked Sep 18 '25 22:09

MintDeparture


2 Answers

There's a way that doesn't involve mucking with hooks: In your .git/config you can set up a separate remote for pushing to your branch (source). If you set that to a nonexisting remote:

[branch "main"]
        remote = origin
        pushRemote = no-push-to-main
        merge = refs/heads/main

then git push on that branch will fail:

$ git push
fatal: 'no-push-to-main' 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.

The error message can be confusing so it's a good idea to pick a helpful name for your fake remote.

like image 80
dojoe Avatar answered Sep 21 '25 11:09

dojoe


You can use the pre-push hook. This hook is a client-side hook that is called whenever you try to push some commits on a remote repo. Basically it is an executable file called pre-push that you must create in the folder .git/hooks/. It receives the remote name and the url of the remote as parameters, while on the stdin it receives a line (or more) in this form:

<local ref> SP <local object name> SP <remote ref> SP <remote object name> LF

For instance, if the command git push origin master:foreign were run the hook would receive a line like the following:

refs/heads/master 67890 refs/heads/foreign 12345

In your case, the content of the pre-push executable could be:

#!/bin/sh

while read local_ref local_sha remote_ref remote_sha
do
    if [ "$remote_ref" = "refs/heads/master" ]
    then
        echo "You cannot push to master"
        exit 1
    fi
done

exit 0
like image 22
Marco Luzzara Avatar answered Sep 21 '25 10:09

Marco Luzzara