Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

#!/usr/bin/bash
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...