【问题标题】:How to add a GIT pre-push hook to disallow pushing a Mock functionality如何添加 GIT 预推送挂钩以禁止推送 Mock 功能
【发布时间】:2020-12-13 07:42:06
【问题描述】:

我想编写一个 Git 预推送挂钩来撤销在我的 MyProj\Controllers 目录中名为 XXXController.cs 的文件中推送 [Mock][MockAttribute] develop 分支上的存储库。 如何在 bash 或任何其他语言中做到这一点?谢谢。

【问题讨论】:

  • 这听起来很容易做到。你已经尝试过什么?
  • 我对 bash 和使用高级 Git 命令一无所知

标签: bash git hook


【解决方案1】:

我不确定pre-push 钩子是否适用于此,因为pre-commit 可能是更好的选择,但这里有一个用 Bash 编写的简单钩子,它简单地查找 [Mock][MockAttribute]发生:

#!/bin/bash

# read the input from git (local refs and remote refs are "ignored" by reading into the _ variable)
while read _ LOCAL_OID _ REMOTE_OID; do
    #echo "running the pre-push check for the range $REMOTE_OID..$LOCAL_OID" >&2
    # git-rev-list produces commit IDs only, so process each commit id line by line
    while read OID; do
        #echo "verifying $OID" >&2
        # figure out files changed in the commit identified by the OID variable
        while read STATUS FILE_PATH; do
            # and if it's either added or modified ...
            case "$STATUS" in
            A|M)
                #echo "checking $FILE_PATH" >&2
                # ... run the check (-q produces no output but sets exit code only)
                git show "$OID:$FILE_PATH" | grep -qP '\[Mock(?:Attribute)?\]'
                # if grep found anything, 0 is returned, so we consider the check failed
                if test $? == '0'; then
                    echo -e "\e[31m$OID:$FILE_PATH does not pass the check\e[0m" >&2
                    exit 1
                fi
                ;;
            *)
                #echo "ignoring $FILE_PATH" >&2
                ;;
            esac
        done < <(git diff-tree --no-commit-id --name-status -r "$OID")
    done < <(git rev-list --reverse "$REMOTE_OID..$LOCAL_OID")
done

exit 0

当然,使用grep 不是进行此类检查的可靠方法,但可能有来自 .NET 世界的更合适的工具来执行此操作。

【讨论】:

  • 谢谢@fluffy。我试过了,但出现了一个错误:错误:无法生成 .git/hooks/pre-push:没有这样的文件或目录错误:.git/hooks/pre-push 的 waitpid 失败:没有子进程
  • @Morteza 您使用的是 Windows 机器吗?我刚刚搜索了一些可能失败的原因。另外,如果你用像#!/bin/bashecho 'all ok'这样的简单的仅回显脚本替换钩子,它是如何工作的?
  • 是的,我有一台 windows 机器,但我的机器上安装了 Git-Bash。
  • @Morteza 我不再是 Windows 用户,但请用谷歌搜索 Error: waitpid for .git/hooks/pre-push failed: No child processes,它会导致类似 superuser.com/questions/1465176/… 的结果——也许某些解决方案可能有效,但这绝对是现在跑题了。
猜你喜欢
  • 2015-04-03
  • 2018-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-30
  • 1970-01-01
  • 1970-01-01
  • 2013-07-22
相关资源
最近更新 更多