Block a git branch from being pushed

houbysoft picture houbysoft · Jul 11, 2011 · Viewed 17.6k times · Source

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.

Answer

Steve Bennett picture Steve Bennett · May 27, 2015

Here's how the pre-push hook approach works, with a branch called dontpushthis.

Create this file as .git/hooks/pre-push:

if [[ `grep 'dontpushthis'` ]]; then 
  echo "You really don't want to push this branch. Aborting."
  exit 1
fi

This works because the list of refs being pushed is passed on standard input. So this will also catch git push --all.

Make it executable.

Do this in every local repository.

When you try to push to that branch, you'll see:

$ git checkout dontpushthis
$ git push
You really don't want to push this branch. Aborting.
error: failed to push some refs to 'https://github.com/stevage/test.git'

Obviously this is as simple as it looks, and only prevents pushing the branch named "dontpushthis". So it's useful if you're trying to avoid directly pushing to an important branch, such as master.

If you're trying to solve the problem of preventing confidential information leaking, it might not be sufficient. For example, if you created a sub-branch from dontpushthis, that branch would not be detected. You'd need more sophisticated detection - you could look to see whether any of the commits on the "dontpushthis" branch were present on the current branch, for instance.

A safer solution

Looking at the question again, I think a better solution in this case would be:

  1. Have one repo which is public
  2. Clone that to a new working directory which is private
  3. Remove the remote (git remote rm origin) from that working directory.
  4. To merge public changes, just do git pull https://github.com/myproj/mypublicrepo

This way, the private repo working directory never has anywhere it could push to. You essentially have a one-way valve of public information to private, but not back.