How can I run a virtualenv python script as a git pre-commit hook

后端 未结 2 787
说谎
说谎 2021-01-11 14:47

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          


        
相关标签:
2条回答
  • 2021-01-11 15:09

    What I ended up doing is: the .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 that THE_GOOD_PATH, is defined:

    export THE_GOOD_PATH="$PATH"
    git commit
    

    You could also export THE_GOOD_PATH="$PATH" from your .profile or the toplevel of your application and symlink all hooks to a single file.

    This method has the advantage of being virtualenv 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 initial reply was WONTFIX.

    0 讨论(0)
  • 2021-01-11 15:16

    You can check in your pre-commit script for the $VIRTUAL_ENV variable and prepend 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
    
    0 讨论(0)
提交回复
热议问题