简体   繁体   English

Git pre-commit hook用于在文件中查找文本

[英]Git pre-commit hook to find text in files

I'm writing a git pre-commit hook to check if any of the staged files are containing disallowed text and abort if that's the case. 我正在编写一个git pre-commit钩子来检查是否有任何暂存文件包含不允许的文本,如果是这种情况则中止。

Not an expert at this. 不是这方面的专家。 So far I've got this 到目前为止我已经有了这个

git diff --cached --name-status | while read x file; do
        if [ "$x" == 'D' ]; then continue; fi
        if [[ egrep "DISALLOWED_TEXT" ${file}]]; then
                echo "ERROR: Disallowed text in file: ${file}"
                exit 1
        fi
done

Doesn't seem to work. 似乎没有用。 I'm getting these errors while commiting: 我在提交时遇到这些错误:

.git/hooks/pre-commit: line 16: conditional binary operator expected
.git/hooks/pre-commit: line 16: syntax error near `"DISALLOWED_TEXT"'
.git/hooks/pre-commit: line 16: `        if [[ egrep "DISALLOWED_TEXT" ${file}]]; then'

Any suggestions, ideas and help appreciated. 任何建议,想法和帮助表示赞赏。 Thanks! 谢谢!

SOLVED: (syntax errors and dysfunctional exit call) 解决:(语法错误和退出调用功能不正常)

disallowed="word1 word2"

git diff --cached --name-status | while read x file; do
        if [ "$x" == 'D' ]; then continue; fi
        for word in $disallowed
        do
            if egrep $word $file ; then
                echo "ERROR: Disallowed expression \"${word}\" in file: ${file}"
                exit 1
            fi
        done
done || exit $?

Answer to mark this question as having an answer: 回答将此问题标记为有答案:

OP ended up with: OP结束了:

disallowed="word1 word2"

git diff --cached --name-status | while read x file; do
        if [ "$x" == 'D' ]; then continue; fi
        for word in $disallowed
        do
            if egrep $word $file ; then
                echo "ERROR: Disallowed expression \"${word}\" in file: ${file}"
                exit 1
            fi
        done
done || exit $?

I am using the same logic as above and even though the stagged file contains the disallowed word, it commits the changes to the branch. 我使用与上面相同的逻辑,即使交错的文件包含不允许的单词,它也会将更改提交给分支。 Any lead would be greatly appreciated. 任何领导都将非常感激。

#!/bin/bash
import os
echo "Running pre-commit hook" 
checks=os.environ["APPSETTING_DEVPASSWORD"],os.environ["APPSETTING_DEVUSER"],os.environ["APPSETTING_DEVPASS_ELMAH"]


git diff --cached --name-status | while read x file; do

          if [ "$x" == 'D' ]; then continue; fi
        for word in $checks
        do
            if egrep $word $file ; then
                echo "ERROR: Disallowed expression \"${word}\" in file: ${file}"
                exit 1
            fi
        done
done || exit $?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM