git - 将 Git Hook 放入存储库

标签 git hook githooks

.git/hooks 放入项目存储库(例如,使用符号链接(symbolic link))是否被认为是一种不好的做法?如果是,向不同 Git 用户提供相同 Hook 的最佳方式是什么?

最佳答案

我大体同意with Scy ,加上一些额外的建议,足以值得单独回答。

首先,您应该编写一个脚本来创建适当的符号链接(symbolic link),尤其是当这些 Hook 是关于执行策略或创建有用的通知时。如果人们只需键入 bin/create-hook-symlinks,他们将更有可能使用 Hook ,而不是必须自己动手。

其次,直接符号链接(symbolic link) Hook 会阻止用户添加自己的个人 Hook 。例如,我更喜欢示例预提交 Hook ,它确保我没有任何空白错误。解决这个问题的一个好方法是在您的存储库中放入一个钩子(Hook)包装器脚本,并将所有钩子(Hook)符号链接(symbolic link)到它。

包装器然后可以检查 $0(假设它是一个 Bash 脚本;否则相当于 argv[0])以确定调用它的钩子(Hook),然后在您的存储库中调用适当的 Hook ,以及适当的用户 Hook ,它们必须重命名,将所有参数传递给每个 Hook 。快速示例:

#!/bin/bash
if [ -x $0.local ]; then
    $0.local "$@" || exit $?
fi
if [ -x tracked_hooks/$(basename $0) ]; then
    tracked_hooks/$(basename $0) "$@" || exit $?
fi

安装脚本会将所有预先存在的 Hook 移到一边(将 .local 附加到它们的名称中),并将所有已知的 Hook 名称符号链接(symbolic link)到上述脚本:

#!/bin/bash
HOOK_NAMES="applypatch-msg pre-applypatch post-applypatch pre-commit prepare-commit-msg commit-msg post-commit pre-rebase post-checkout post-merge pre-receive update post-receive post-update pre-auto-gc"
# assuming the script is in a bin directory, one level into the repo
HOOK_DIR=$(git rev-parse --show-toplevel)/.git/hooks

for hook in $HOOK_NAMES; do
    # If the hook already exists, is executable, and is not a symlink
    if [ ! -h $HOOK_DIR/$hook -a -x $HOOK_DIR/$hook ]; then
        mv $HOOK_DIR/$hook $HOOK_DIR/$hook.local
    fi
    # create the symlink, overwriting the file if it exists
    # probably the only way this would happen is if you're using an old version of git
    # -- back when the sample hooks were not executable, instead of being named ____.sample
    ln -s -f ../../bin/hooks-wrapper $HOOK_DIR/$hook
done

关于git - 将 Git Hook 放入存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3462955/

相关文章:

git - 将更改推送到 OpenShift

c++ - 可以按序号挂接 IAT 函数吗?

git - 使用裸存储库 Hook 将服务器恢复到过去的提交

git - 如何通过 HTTP 协议(protocol)设置 git hook 以在远程服务器上自动开发

Git 远程/共享预提交 Hook

git - 对象未正确排序

git - Windows客户端的TortoiseGit和GitHub可以共存吗?

git - 我如何拆分埋藏在历史中的 Git 提交?

linux - 响应在内核的 NetFilter 中接收到的数据包

java - 什么是 "hook"以及如何用 Java 编写一个?以及如何与内核通信以了解用户按下的键/向操作系统注册