I am a developer contributing to a specific repo. We have been instructed never to push to branch1
. I don't want to by mistakenly push to said branch. Is there any way to do this (possibly through some config file or something else)?

- 61
- 5
-
3You can create your own `pre-push` hook, and in that hook, look over the names you're going to ask the other Git to set. If any of those are the one you don't want to ever ask it to set, you can have your `pre-push` hook abort the push operation. Note that this is 100% voluntary on *your* side: if you remove or bypass the hook, you can still push to that branch. – torek Jun 07 '21 at 05:43
-
2Since this is tagged with *GitHub*, you can set [protected branch rules](https://docs.github.com/en/github/administering-a-repository/defining-the-mergeability-of-pull-requests/about-protected-branches) which is available in public repositories with GitHub Free, and in public and private repositories with GitHub Pro/Team/Enterprise. – Matt Jun 07 '21 at 06:31
2 Answers
This is just a workaround for your problem.
You can delete the branch locally git branch -d <branch1>
, and when need it back for some reason git checkout <branch1>
.
Also, you can read this post: How to restrict access to master branch on git

- 450
- 8
- 17
-
I actually need that branch on local to sync latest changes and create new branches off it, so cannot delete it. I just want to restrict myself pushing to it – codealpha98 Jun 07 '21 at 10:54
As @matt said on the comments, wrt GitHub you can create branch protection rules to state (for example) that PRs are required to push to this branch - I assume that is your pattern.
What this does not stop is some scenario where you accidentally change branch1 locally, any new branch created off this new branch1 would contain those commits. You would be able to push those changes quite happily to github (it is on a branch) and create a PR with them.
Now whether this is an issue depends on whether you actually meant to include the changes (and just put them on branch1 first) or not - perhaps the accidental pushes were another change completely. Assuming PR reviews are occurring, you would like to think that the PR reviewer would pick up stuff that is not relevant:)
In my experience, with a disciplined and experienced team, the above very rarely happens and is not generally worth bothering about. Far more likely, inexperienced team members branch routinely from and old version of main/master etc, which often has greater problems because their change will be out of date.
If you are really worried about this, I would suggest changing your usage a bit: don't branch off branch1 locally but instead branch off origin/branch1. Yes you could delete branch1 itself. Note you would need to use "git fetch" and not "git pull" to ensure the origin branches (including origin/branch1) are up to date.

- 1,676
- 2
- 17
- 28