我如何运行一个virtualenv python脚本作为git pre-commit钩子 [英] How can I run a virtualenv python script as a git pre-commit hook

查看:319
本文介绍了我如何运行一个virtualenv python脚本作为git pre-commit钩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的pre-commit脚本:

 #!/ bin / bash 
for f in .git /hooks/pre-commit.d/*;如果[-x$ f]执行
;那么
if! $ F;那么
会回显不会改变你的改变!;
出口1
fi
fi
完成

pre-commit.d中的一个可执行文件是一个以脚本开头的python脚本(precommit-pylint.py)。

 #!/ usr / bin / env python 
import pylint

pylint安装在我的virtualenv中。我的问题是git运行预先提交pre prepending / usr / libexec / git-core:/ usr / bin $ PATH ,所以即使我的virtualenv被激活, pre-commit.d / precommit-pylint.py 脚本也会与系统 / usr一起运行/ bin / python (而不是使用virtualenv python运行)。



我想要具有与不使用开发者兼容的钩子virtualenv中。有没有办法透明地使用virtualenv来运行我的python脚本(即,与使用他们的系统python的开发人员保持兼容)? 解决方案

p>您可以在您的预提交脚本中检查$ VIRTUAL_ENV变量,并相应地将其前置到$ PATH中:

 #! / bin / bash 

if [-n $ VIRTUAL_ENV];那么
PATH = $ VIRTUAL_ENV / bin:$ PATH
fi

for .git / hooks / pre-commit.d / *;如果[-x$ f]执行
;那么
if! $ F;那么
会回显不会改变你的改变!;
出口1
fi
fi
完成


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)?

解决方案

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

这篇关于我如何运行一个virtualenv python脚本作为git pre-commit钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆