【问题标题】:Git pre-commit hook not working as expectedGit 预提交挂钩未按预期工作
【发布时间】:2019-12-25 18:47:52
【问题描述】:

我已将我的存储库配置为使用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 文件而不提交其他文件时运行预提交脚本?

【问题讨论】:

  • 从附加的pre-commit 钩子上看,您好像忘记在更新后的文件上运行git add
  • @Alderath:它已经被添加并先前提交。我只需要在提交之前在文件上运行sed
  • 即使git addgit commit 之前执行,你也需要git add sedpre-commit 钩子中所做的更新。

标签: git githooks


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-09-10
    • 2014-01-03
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 2016-10-16
    相关资源
    最近更新 更多