git - 致命: This operation must be run in a work tree on pre-receive hook

标签 git bash githooks git-diff

处理中pre-receive ,当我点击 pre-receive 钩子(Hook)时,我得到了 fatal: This operation must be run in a work tree 异常。我确信钩子(Hook)正在击中,因为我可以通过该钩子(Hook)打印我自己的消息。

#!/usr/bin/env bash

FILES=`git diff --name-only --diff-filter=d HEAD~1`
for COMMIT in $FILES;
  do
      case $COMMIT in
      *.txt|*.pdf|*.docx)
        echo "Hello there! We have restricted committing that filetype.
        exit 1
        ;;
      esac
done
exit 0

我的钩子(Hook)代码是否错误或者有其他问题?但是this hook运行完美。

最佳答案

HEAD (如果它存在)不会指向您在裸存储库中所期望的内容(当有人运行 HEAD 时,它指向 git clone 的初始值)。

从预接收 Hook 中,您必须从 STDIN 读取提交哈希列表。知道你应该查看哪些提交:

from git help githooks :

pre-receive

...

This hook executes once for the receive operation. It takes no arguments, but for each ref to be updated it receives on standard input a line of the format:

<old-value> SP <new-value> SP <ref-name> LF

where <old-value> is the old object name stored in the ref, <new-value> is the new object name to be stored in the ref and <ref-name> is the full name of the ref. When creating a new ref, <old-value> is 40 0.

所以你的脚本可以做类似的事情:

#/usr/bin/env bash

# read lines from stdin, assign first value to 'old', second to 'new',
#   third to 'refname' :
while read old new refname; do

  # use $old $new and $refname inside this block
  FILES=`git diff --name-only --diff-filter=d $old $new`

  ...
done

关于git - 致命: This operation must be run in a work tree on pre-receive hook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46645485/

相关文章:

git - 如何查看作者的所有代码更改?

git - 根据 git status 为 SublimeText TreeView 中的文件着色?

bash - ROS 安装 : no such file or directory

git - git-review 是如何工作的?

php - 如何在 PHP 上的 PhpStorm 中创建正确的 git hook?

git - Git 如何访问我的 GitHub 凭据?

bash - 如何在 shell 脚本中创建别名?

bash - 从命令行 bash 运行时无法从 crontab 运行 bash 脚本

ruby-on-rails - 创建成为可执行 chmod 777 gihook 文件的文件

git - 将一个提交分成 2 个并获取结果差异