实现Git钩子prePush和preCommi

2024-04-20 12:41:18 发布

您现在位置:Python中文网/ 问答频道 /正文

你能告诉我如何实现git钩子吗?在

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

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

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


Tags: runpygitproject脚本clientmycd
2条回答

你需要告诉我们干运行会以什么方式失败。是否会有带错误的output.txt?终端上会显示错误吗?在

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

由于您的干运行脚本似乎与预提交脚本处于不同的路径中,下面是一个查找并运行脚本的示例。在

根据路径中的反斜杠,我假设您在一台windows机器上,并且我还假设您的dry run脚本包含在安装了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时,预提交脚本都会运行干运行文件,如果发生任何错误,则会中止提交,并将文件保留在stagin区域中。在

我已经在我的钩子里实现了这个。下面是代码片段。在

#!/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

相关问题 更多 >