Mercurial Pre-Commit Hook: How to hook to python program in current directory?

戏子无情 提交于 2019-12-09 15:32:31

问题


I'm trying to create a Mercurial hook that runs when the commits are being pushed to the main repository. I created a python script as given below:

# commit.py

from mercurial import ui, hg
from mercurial.i18n import gettext as _

def getV1ID(ui, repo, **kwargs):
    ui.write("The hook works!!!")
    v1id = ui.prompt('Enter the VersionOne ID')
    ui.write('VersionOne ID: '+v1id)

For each branch, this commit.py is duplicated as it contains mechanisms that needs to run before code gets pushed onto the main respository. The push should only be successful if those pre-push mechanisms pass. Users can modify their local commit.py so that they only run a subset of those pre-push operations depending on the project their working on and each person could be working on more than one project at a time. And so, commit.py cannot be a global python script that can reside in .hg folder.

To make mercurial run the local commit.py, in my mercurial.ini file (in C:\Users\UserName\mercurial.ini), I added the following statement:

[hooks]
prechangegroup = python:./commit.py:getV1ID

The python script runs if I place it inside .hg folder, but not when I do this. Can anyone help me shed light on this issue? Many thanks.


回答1:


I got this solution over IRC for Mercurial. As stated in one of my comments, the script for the hook should be specified as an absolute path or it should a python module in PYTHONPATH. Hence, I was suggested by pmezard over IRC that I should have a fixed script that invokes the local commit.py. This can be done as shown below:

In mercurial.ini, hook to a 'global' python-script that resides in .hg directory of the user's home as shown below:

[hooks]
preoutgoing = python:%USERPROFILE%\.hg\commit.py:run

The 'global' python-script, commit.py looks something like this:

from mercurial import ui, hg
import os

class Chdir:
    def __init__(self, newPath):
        self.savedPath = os.getcwd()
        os.chdir(newPath)

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        os.chdir(self.savedPath)

def run(ui, repo, **kwargs):
    if kwargs['source'] == 'push':
        with Chdir(repo.root) as dirchanged:
            import localcommit
            sys.exit(localcommit.main(ui, repo, **kwargs))

The localcommit.py in the repository's directory then gets run by the global commit-script and thus every repository can maintain its own customized commit-script.



来源:https://stackoverflow.com/questions/6829112/mercurial-pre-commit-hook-how-to-hook-to-python-program-in-current-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!