Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

virtualenv

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 a python script (pre-commit-pylint.py) that starts with:

#!/usr/bin/env python
import pylint

pylint is installed on my virtualenv. My problem is that git runs pre-commit prepending /usr/libexec/git-core:/usr/bin to $PATH, so even if my virtualenv is activated the pre-commit.d/pre-commit-pylint.py script runs with the system /usr/bin/python (instead of running with the virtualenv python).

I want to have hooks that are compatible for developers that are not using virtualenv. Is there any way to run my python script with virtualenv transparently (ie, staying compatible with developers that are using their system python)?

like image 676
Joaquin Cuenca Abela Avatar asked Jan 27 '12 17:01

Joaquin Cuenca Abela


People also ask

Can I write a git hook in Python?

Git hooks are language agnostic. I wrote this small hook as a shell script, but you can use other languages liek Perl, Ruby or Python. Here is an example of a pre-commit hook in written in Python.

How do I enable pre-commit hook?

Open a terminal window by using option + T in GitKraken Client. Once the terminal windows is open, change directory to . git/hooks . Then use the command chmod +x pre-commit to make the pre-commit file executable.

Can you commit pre-commit hooks?

pre-commit hooks are a mechanism of the version control system git. They let you execute code right before the commit. Confusingly, there is also a Python package called pre-commit which allows you to create and use pre-commit hooks with a way simpler interface.

How do you use pre-commit hooks in Python?

If you want to manually run all pre-commit hooks on a repository, run pre-commit run --all-files . To run individual hooks use pre-commit run <hook_id> . The first time pre-commit runs on a file it will automatically download, install, and run the hook. Note that running a hook for the first time may be slow.


1 Answers

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
like image 191
Rob Wouters Avatar answered Sep 19 '22 14:09

Rob Wouters