实现Git hook - prePush和preCommit

问题描述 投票:0回答:2

你能告诉我如何实现git hook吗?

在提交之前,钩子应该运行python脚本。像这样的东西:

cd c:\my_framework & run_tests.py --project Proxy-Tests\Aeries \
   --client Aeries --suite <Commit_file_Name> --dryrun

如果干运行失败则应停止提交。

python git githooks
2个回答
1
投票

你需要告诉我们干运行会以什么方式失败。是否会出现输出.txt错误?终端上是否会显示错误?

在任何情况下,您必须将预提交脚本命名为pre-commit并将其保存在.git/hooks/目录中。

由于您的干运行脚本似乎与预提交脚本位于不同的路径,因此这是一个查找并运行脚本的示例。

我假设您在路径中的反斜杠,您在Windows机器上,我还假设您的干运行脚本包含在您安装了git的同一个项目中,并且在一个名为tools的文件夹中(当然您可以将其更改为你的实际文件夹)。

#!/bin/sh

#Path of your python script
FILE_PATH=tools/run_tests.py/

#Get relative path of the root directory of the project
rdir=`git rev-parse --git-dir`
rel_path="$(dirname "$rdir")"

#Cd to that path and run the file. 
cd $rel_path/$FILE_PATH
echo "Running dryrun script..."
python run_tests.py

#From that point on you need to handle the dry run error/s.
#For demonstrating purproses I'll asume that an output.txt file that holds
#the result is produced.

#Extract the result from the output file
final_res="tac output | grep -m 1 . | grep 'error'"

echo -e "--------Dry run result---------\n"${final_res}

#If a warning and/or error exists abort the commit
eval "$final_res" |  while read -r line; do
if [ $line != "0" ]; then
  echo -e "Dry run failed.\nAborting commit..."
  exit 1
fi
done

现在每次启动git commit -m时,预提交脚本将运行干运行文件并在发生任何错误时中止提交,将文件保持在滞留区域。


0
投票

我已经在我的钩子里实现了这一点。这是代码片段。

#!/bin/sh
#Path of your python script

RUN_TESTS="run_tests.py"
FRAMEWORK_DIR="/my-framework/"
CUR_DIR=`echo ${PWD##*/}`

`$`#Get full path of the root directory of the project under RUN_TESTS_PY_FILE

rDIR=`git rev-parse --git-dir --show-toplevel | head -2 | tail -1`
OneStepBack=/../
CD_FRAMEWORK_DIR="$rDIR$OneStepBack$FRAMEWORK_DIR"

#Find list of modified files - to be committed
LIST_OF_FILES=`git status --porcelain | awk -F" " '{print $2}' | grep ".txt" `

for FILE in $LIST_OF_FILES; do
    cd $CD_FRAMEWORK_DIR
        python $RUN_TESTS  --dryrun   --project $CUR_DIR/$FILE
    OUT=$?

    if [ $OUT -eq 0 ];then
        continue
    else
        return 1
    fi
done
© www.soinside.com 2019 - 2024. All rights reserved.