Lakshmi narayana
Lakshmi narayana

Reputation: 184

Implement Git hook - prePush and preCommit

Could you please show me how to implement git hook?

Before committing, the hook should run a python script. Something like this:

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

If the dry run fails then commit should be stopped.

Upvotes: 0

Views: 978

Answers (2)

Lakshmi narayana
Lakshmi narayana

Reputation: 184

I have implemented this in my hook. Here is the code snippet.

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

Upvotes: 0

kingJulian
kingJulian

Reputation: 6190

You need to tell us in what way the dry run will fail. Will there be an output .txt with errors? Will there be an error displayed on terminal?

In any case you must name the pre-commit script as pre-commit and save it in .git/hooks/ directory.

Since your dry run script seems to be in a different path than the pre-commit script, here's an example that finds and runs your script.

I assume from the backslash in your path that you are on a windows machine and I also assume that your dry-run script is contained in the same project where you have git installed and in a folder called tools (of course you can change this to your actual folder).

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

Now every time you fire git commit -m the pre-commit script will run the dry run file and abort the commit if any errors have occured, keeping your files in the stagin area.

Upvotes: 1

Related Questions