[英]How to use git hook pre-commit to stop commits to master
I want to stop myself accidently commiting something to the master branch unless I am sure. 除非我确定,否则我想阻止自己意外地向主分公司提交一些东西。 So I tried this script to determine which branch I am on but there is a problem. 所以我尝试使用这个脚本来确定我所在的分支但存在问题。 When I create a new branch git name-rev returns master even though I am on the other branch 当我创建一个新的分支git name-rev返回master时,即使我在另一个分支上
$ git branch
ignore
master
* set_support
$ git name-rev --name-only HEAD
master
This is my script. 这是我的剧本。
#!/bin/sh
# Check to see if we are on master branch. Stop accidental commits
if [ "`git name-rev --name-only HEAD`" == "master" ]
then
if [ -f i_want_to_commit_to_master ]
then
rm i_want_to_commit_to_master
exit 0
else
echo "Cannot commit to master branch Adrian"
echo "Remember to create file 'touch i_want_to_commit_to_master' to commit to master"
fi
exit 1
fi
exit 0
For Mark: I rebuilt git against latest stable tag and same results. 对于马克:我重建了针对最新稳定标签和相同结果的git。 It only works after a commit is made to the new branch. 它仅在对新分支进行提交后才有效。
$ mkdir gittest
$ cd gittest
$ git init
Initialized empty Git repository in /home/adrian/gittest/.git/
$ touch file1
$ git add file1
$ git commit
[master (root-commit) 7c56424] New file
0 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 file1
$ git branch
* master
$ git checkout -b new_branch
Switched to a new branch 'new_branch'
$ git name-rev --name-only HEAD
master
$ git --version
git version 1.7.7.1
$ git branch
master
* new_branch
$ touch file2
$ git add file2
$ git commit
[new_branch 1e038fb] new file
0 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 file2
$ git name-rev --name-only HEAD
new_branch
This command is used to find a friendly name of a commit. 此命令用于查找提交的友好名称。 What is happening is that HEAD is resolving to the sha1 of the commit first and then a name is determined. 发生的事情是HEAD首先解析为提交的sha1,然后确定名称。 I'm guessing it is arbitrarily picking master for the name as it comes up first in what git log --decorate
would come across. 我猜它是随意挑选名字的主人,因为它首先出现在git log --decorate
会遇到的地方。
I would just parse the output of git branch
in your test: 我只是在你的测试中解析git branch
的输出:
"`git branch | grep \* | cut -f2 -d' '` == "master"
or a more direct way would be: 或者更直接的方式是:
$(git symbolic-ref HEAD 2>/dev/null) == "refs/heads/master"
As an alternative you could use git rev-parse
as suggested in this answer . 作为替代方案,您可以使用本答案中建议的git rev-parse
。 So the if expression would be: 所以if表达式将是:
"$(git rev-parse --abbrev-ref HEAD)" == "master"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.