Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
71 views
in Technique[技术] by (71.8m points)

How to get Python Exit code in a Git Hook on Windows with git for Windows

I added a call of a Python script into my pre-push git hook, which executes my Unit Tests.

This works fine, if I do not use Git LFS. However, if I use Git LFS this does not work as I have to distinguish, if my tests fail or not. If they fail I do not want to push the actual code otherwise I push them with the Git LFS command.

Following hook is my starting point. From this point I want to use an IF-statement to decide if I execute the Git LFS command or not.

#!/bin/sh
python .git/hooks/pre-push.py
command -v git-lfs >/dev/null 2>&1 || { echo >&2 "
This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting .git/hooks/pre-push.
"; exit 2; }
git lfs pre-push "$@"

Following snippet shows how I exit from Python when the test fails.

errno = pytest.main(["-v", "-m", "not device_test"])
if(errno == ExitCode.TESTS_FAILED):
    print("Pytests failed!")
    sys.exit(1)

The problem is that I can't get the exit code with $? (like suggested on several places).

Any idea how I can get the exit code?

Of course a workaround would be to use a git hook which is not used by Git LFS e.g., pre-commit. However, I want to execute the Unit Tests before a push.

question from:https://stackoverflow.com/questions/65952188/how-to-get-python-exit-code-in-a-git-hook-on-windows-with-git-for-windows

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add a line to the top of your script, right after the shebang (#!) that says this:

set -e

This makes the shell check the exit status of each command and exit if it is nonzero. Therefore, if your tests fail, the remaining commands will not be executed, and your data won't be pushed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...