Git预提交挂钩无法按预期运行

时间:2019-08-20 14:08:41

标签: git githooks

我已将我的仓库配置为使用hooks目录而不是.git/hooks目录,以便它可以是managed from within the repo

我想运行sed在提交之前修改密码。我在hooks/pre-commit脚本中使用了此代码,该脚本也已使其可执行。

#!/bin/bash

FNAME=smbclient.conf
sed -i -e 's/password=.*/password=See_Thycotic/g' ${FNAME}

grep -c See_Thycotic ${FNAME}
if [ "$?" -ne "0" ] ; then
    echo Failed to redact password in ${FNAME}
    exit 1
fi
echo Password was redacted in ${FNAME} before commit

当我运行此命令时:

git commit smbclient.conf -m "changed something"

我看到了此消息(符合预期):

1
Password was redacted in smbclient.conf before commit

问题是文件在pre-commit脚本更改内容之前已提交。如果再运行git status,它会告诉我modified: smbclient.conf

1)如何在提交之前更改此文件,然后又提交它?

2)仅提交smbclient.conf文件而不提交其他文件时,是否可以运行预提交脚本?

1 个答案:

答案 0 :(得分:1)

1) 如果pre-commit文件是由git add $FNAME更新的,则应该让$FNAME钩子执行sed

2) 不能。无法定义仅对特定文件执行的预提交挂钩。

执行此操作的正确方法可能是让脚本在每次提交时都运行,但首先应按照以下方式进行操作:

    if [[ "$(git diff --name-only --staged -- $FNAME)" == "" ]] #If $FNAME file is not updated in this commit
    then
        exit 0 #Stop execution of this hook, and consider hook execution successful
    fi

    #Rest of pre-commit hook script here