开发者

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

开发者 https://www.devze.com 2023-03-23 03:17 出处:网络
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:

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 开发者_如何学Goonly 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号