Mercurial Commit Hook with Python main function

584 Views Asked by At

I'm trying to create a complex mercurial commit hook in python. I want to also be allowed to pass parameters using OptionParser. Here is the gist of what I have so far:

.hg/hgrc config:

[hooks]
commit = python:/mydir/pythonFile.py:main
# using python:/mydir/pythonFile.py doesn't work for some reason either

pythonFile.py:

def main(ui, repo, **kwargs):
    from optparse import OptionParser

    parser = OptionParser()
    parser.add_option('--test-dir', action='store', type="string",
                  dest='test_dir', default='otherdir/',
                  help='help info')
    (options, args) = parser.parse_args()

    # do some stuff here
    someFunc(options.test_dir)

if __name__ == '__main__':
    import sys
    main(sys.argv[0], sys.argv[1], sys.argv[2:])

When I run hg commit -m 'message' I get an error: "Usage: hg [options] hg: error: no such option: -m". When I try hg commit --test-dir '/somedir' I get an error: "hg commit: option --test-dir not recognized".

Lastly I tried specifying commit = python:/mydir/pythonFile.py:main --test-dir '/somedir' in the hgrc config and I got this error: "AttributeError: 'module' object has no attribute 'main --test-dir '/somedir''"

Thank you for your help.

1

There are 1 best solutions below

0
On

I think your problem may be in trying to import something that isn't part of the python packaged with mercurial. If what you need is to pass additional information to the hook such that you can configure it differently for different repos/branches etc, you could use

param_value= ui.config('ini_section', 'param_key', default='', untrusted=False)

where ini_section is the bit in [] in the mercurial.ini / .hgrc file and param_key is the name of the entry so something like

[my_hook_params]
test-dir=/somedir

then use

test_dir = ui.config('my_hook_params', 'test-dir', default='otherdir/', untrusted=False)