Git:防止主分支提交 [英] Git: Prevent commits in master branch
问题描述
master
分支和一个 dev
。 我想确保
master
分支始终有效,所以我所做的所有工作都应该位于 dev
branch。 然而,当我使用 - no-ff
合并我的更改时,我倾向于留在 master
分支中,并继续在其中工作(因为我忘了签出我的 dev
分支)。
我可以为 master
分支建立一条规则,其中规定我不能提交,并且快-forward合并,但只有 - no-ff
从另一个分支合并?
这必须适用于私人托管(不是GitHub和BitBucket)。
是的,这是可能的。您必须创建拒绝提交到主分支的预提交挂钩。当您调用 merge 命令时,Git不会调用预提交钩子,因此该钩子将仅拒绝常规提交。
- 转至您的存储库。使用以下内容创建文件 .git / hooks / pre-commit :
$ b#!/ bin / sh
分支=$(git rev-parse --abbrev-ref HEAD)
if [$ branch=master];那么
echo你不能直接提交给master分支
exit 1
fi
使其成为可执行文件( Windows 不要求):
> $ chmod + x .git / hooks / pre-commit
要禁用 fast-forwad 合并,您还必须将以下选项添加到 .git / config 文件中:
[branchmaster]
mergeoptions = --no-ff
如果您还想保护远程的主分支,请选中此答案:如何限制访问git上的master分支
(For simplicity) I have a master
branch and a dev
in my Git-repo.
I want to ensure the master
branch is always working, so all work I do should be in the dev
branch.
However, when I merge my changes in with a --no-ff
merge, I tend to stay in the master
branch, and just continue working in it (because I forget to checkout my dev
branch).
Can I put up a rule for the master
branch, which states I can't do commits, and fast-forward merges, but only --no-ff
merges from another branch?
This must work for private hosted repositories (ergo not GitHub and BitBucket).
Yes, it is possible. You must create pre-commit hook which rejects commits to master branch. Git doesn't call pre-commit hook when you call merge command, so this hook will be rejecting only regular commits.
- Go to your repository.
Create file .git/hooks/pre-commit with following content:
#!/bin/sh branch="$(git rev-parse --abbrev-ref HEAD)" if [ "$branch" = "master" ]; then echo "You can't commit directly to master branch" exit 1 fi
Make it executable (not required on Windows):
$ chmod +x .git/hooks/pre-commit
To disable fast-forwad merges you must also add following option to your .git/config file:
[branch "master"]
mergeoptions = --no-ff
If you want also protect master branch on your remote, check this answer: How to restrict access to master branch on git
这篇关于Git:防止主分支提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!