How to run virtual python script as git pre-commit hook

This is my pre-commit script:

#!/bin/bash for f in .git/hooks/pre-commit.d/*; do if [ -x "$f" ]; then if ! "$f"; then echo "DID NOT COMMIT YOUR CHANGES!"; exit 1 fi fi done 

One of the executables in pre-commit.d is the python script (precomcommit-pylint.py), which starts with:

 #!/usr/bin/env python import pylint 

pylint is installed on my virtual server. My problem is that git runs pre-commit preending /usr/libexec/git-core:/usr/bin up to $PATH , so even if my virtualenv is activated, pre-commit.d/pre-commit-pylint.py The script works with the /usr/bin/python (instead of working with virtual python).

I want to have hooks that are compatible for developers who do not use virtualenv. Is there a way to run a python script using virtualenv transparently (i.e., remain compatible with developers using their system python)?

+6
source share
2 answers

You can check your pre-commit script for the $ VIRTUAL_ENV variable and append it to $ PATH accordingly:

 #!/bin/bash if [ -n $VIRTUAL_ENV ]; then PATH=$VIRTUAL_ENV/bin:$PATH fi for f in .git/hooks/pre-commit.d/*; do if [ -x "$f" ]; then if ! "$f"; then echo "DID NOT COMMIT YOUR CHANGES!"; exit 1 fi fi done 
+2
source

What I ended up with is: .git file structure:

  • .git/hooks/pre-commit
  • .git/hooks/pre-commit-main.py

.git / Hooks / pre-commit:

 #!/usr/bin/env bash export PATH="$THE_GOOD_PATH" python "$GIT_DIR/hooks/pre-commit-main.py" 

.git / Hooks / pre-commit-main.py:

 #!/usr/bin/env python import sys print sys.version_info 

Then, when you call git commit , make sure THE_GOOD_PATH :

 export THE_GOOD_PATH="$PATH" git commit 

You can also export THE_GOOD_PATH="$PATH" from your .profile or top level of your application and symbolize all the bindings to a single file.

This method has the advantage of being a virtual agnostic: it also works with Ruby RVM rbenv.

I wrote to the Git developers at http://permalink.gmane.org/gmane.comp.version-control.git/258454 asking them to leave our PATH alone, but the original answer was WONTFIX.

0
source

Source: https://habr.com/ru/post/907055/


All Articles