【问题标题】:How to use git hook pre-commit to stop commits to master如何使用 git hook pre-commit 停止提交到 master
【发布时间】:2011-12-16 22:24:43
【问题描述】:

除非我确定,否则我想阻止自己意外地向主分支提交某些内容。所以我尝试了这个脚本来确定我在哪个分支上但是有一个问题。当我创建一个新分支时,即使我在另一个分支上,git name-rev 也会返回 master

$ git branch
  ignore
  master
* set_support
$ git name-rev --name-only HEAD
master

这是我的脚本。

#!/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

对于 Mark:我根据最新的稳定标签和相同的结果重建了 git。它仅在向新分支提交后才有效。

$ 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

【问题讨论】:

  • 你使用的是什么版本的 git,在哪个操作系统上? git branch 后跟 git name-rev HEAD 的结果看起来像一个(令人惊讶的)错误,如果你真的准确地复制和粘贴了。
  • 我从源代码构建 git - 最后一次构建是 $ git describe v1.7.7-rc3 $ git --version git version 1.7.7-rc3 $ uname -a Linux iceweasel.bluedreamer 2.6.40.3-0 .fc15.x86_64 #1 SMP 2011 年 8 月 16 日星期二 04:10:59 UTC x86_64 x86_64 x86_64 GNU/Linux

标签: git bash githooks


【解决方案1】:

此命令用于查找提交的友好名称。发生的事情是 HEAD 首先解析到提交的 sha1,然后确定名称。我猜它是任意选择 master 的名字,因为它首先出现在 git log --decorate 会遇到的地方。

我只会在您的测试中解析git branch 的输出:

"`git branch | grep \* | cut -f2 -d' '` == "master"

或者更直接的方式是:

$(git symbolic-ref HEAD 2>/dev/null) == "refs/heads/master"

【讨论】:

  • 酷 - 谢谢亚当 - 我做了一个小改动,但现在如果 [ "$(git symbolic-ref HEAD 2>/dev/null)" == "refs/heads/master" ]
【解决方案2】:

作为替代方案,您可以按照this answer 中的建议使用git rev-parse。所以 if 表达式是:

"$(git rev-parse --abbrev-ref HEAD)" == "master"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 2013-02-19
    • 1970-01-01
    • 2014-06-27
    相关资源
    最近更新 更多