Search code examples
gitbranchprivate

Block a git branch from being pushed


Here's the situation:

I have a public repository for my open-source app on github.com. However, now I'd like to write some specific code that will not be public (I might use it in a commercial version of my application).

I figured I could use the same repository, and I'd create a "private" branch in my git repository that I wouldn't push.

But, mistakes happen. Is there some way to forbid git from ever pushing a branch to remote servers?

If there's a better way to handle this situation, I would of course welcome any suggestions.


Solution

  • A slightly hackish solution: Make a dummy branch on GitHub with the same name as your real branch, and make sure it would not be a fast forward merge. That way, the push operation will fail.

    Here's an example.

    $ git clone [email protected]:user/repo.git
    $ cd repo
    $ git checkout -b secret
    $ echo "This is just a dummy to prevent fast-forward merges" > dummy.txt
    $ git add .
    $ git commit -m "Dummy"
    $ git push origin secret
    

    Now that the dummy branch is set up, we can recreate it locally to diverge from the one on GitHub.

    $ git checkout master
    $ git branch -D secret
    $ git checkout -b secret
    $ echo "This diverges from the GitHub branch" > new-stuff.txt
    $ git add .
    $ git commit -m "New stuff"
    

    Now if we accidentally try to push, it will fail with a non-fast forward merge error:

    $ git push origin secret
    To [email protected]:user/repo.git
    ! [rejected]        secret -> secret (non-fast forward)
    error: failed to push some refs to ‘[email protected]:user/repo.git’