首页 > 解决方案 > Git 预提交挂钩未按预期工作

问题描述

我已将我的 repo 配置为使用hooks目录而不是.git/hooks目录,以便可以从 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 文件而不提交其他文件时,是否可以运行预提交脚本?

标签: gitgithooks

解决方案


1) 如果文件pre-commitgit add $FNAME.$FNAMEsed

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

推荐阅读