How to setup hook for "hg branch"? - mercurial

I want to write a hook that performs some actions each time I run hg branch branch_name (e.g. set "In progress" status for a JIRA ticket), but I can't find anything that runs during branching. Is there a way I can do it?

The is a pre-<command> hook (with a hyphen) for each command. Note that is is distinct from any hook that may exist without a hyphen, sush as precommit.
Thus you can do:
[hooks]
pre-bookmark = /usr/bin/notify_jira.sh ${HG_ARGS#bookmark }
to invoke:
/usr/bin/notify_jira.sh PROJ-415
when you run:
hg bookmark PROJ-415
Full details on the generic pre-<command> (and post-<command>) hooks can be found on the hgrc man page.
It also looks like pushkey hook might do what you want, but pre-bookmark (or better, post-bookmark) is probably more straightforward.

Related

Is it possible to pipe output of 'hg log' command to secondary command?

I'm trying to write a small script for my team that automatically updates the feature branche to a case and then creates a branch for review. I've got the commands down manually but I'm having trouble making it a bit more hands off.
For now, I want to use this templated command:
hg log --rev <changeset> --template "{branch}\n"
Which returns the branch name of a changset. Then I would like to remove a portion of the name and prepend a string. For example, a branch would be named case-1234-FeatureDescription and I would want to be creating a branch named review-1234-FeatureDescription
Ideally, I would like to pipe the output of this command to the branch command
hg branch <result-of-previous-command>
Is it possible to do this?
You suggest to create a branch by a name which you just extraced from the logs of the very same repo. That doesn't exactly look like it can succeed as it already exists.
Additionally, it likely is probably not a good idea to create a named branch for each review process as branch names are persistent. You might consider to use bookmarks for that purpose as they can be deleted without trace from the repo after review is completed.
I'd suggest to use - without piping - something like
hg bookmark -r CHANGESET $(hg log --rev CHANGESET -T"{branch}")-review

Prevent mercurial precommit hook from running on histedit

I would like to run clang-format (actually clang-format-diff.py, to format only what's changed) on the code I commit in Mercurial automatically. I know I can do it with a precommit hook. In fact, I've done it in the past but it messed up some histedits, so I removed the hook, and now do it manually, running the command before commiting.
Obviously, the problem is I can, and do, forget to do it sometimes.
Is there any way to run the hook only on "normal" commits, not the ones on histedit or rebase?
There's not a direct way as far as I know. But you can create yourself an alias to use instead of rebase and histedit, let's call them hrebase and hhistedit which disable the hook for their usage.
In order to disable a hook for a single run on the command line you can use --config hook.HOOKNAME=, thus for instance:
hg --config hook.HOOKNAME= rebase -d2 -b5
and you thus define your alias:
[alias]
hrebase = rebase --config hook.HOOKNAME=
hhistedit = histedit --config hook.HOOKNAME=
In order to wrap a single command (in your case, commit) you can either use an alias or an extension. The alias approach is fairly simple, but has some drawbacks. Example for an alias:
commit = !$HG commit --config alias.commit=commit --config hooks.precommit.clang=/tmp/msg "$#"
There are a few subtle issues involved in creating such an alias: first, normal aliases do not accept a --config paramater (all configuration has already been parsed at the point of alias expansion). Therefore, we need to use a shell alias (!$HG) in order to work around this problem; second, in order to avoid getting stuck in a recursion during shell alias expansion (unlike normal aliases, Mercurial cannot do this for shell aliases), we have to realias commit to itself (hence the --config alias.commit=commit part).
This approach has a couple of downsides: First, it doubles startup time (because Mercurial gets invoked twice for a shell alias); while this is relatively little overhead, it can be sufficient to be annoying for a human user. Second, it interacts poorly with scripting; scripts and GUIs may either unintentionally use the alias when they don't intend to or (worse) disable it, thus bypassing the hook.
An alternative is to use an extension to wrap the commit command. For example:
# Simple extension to provide a hook for manual commits only
"""hook for manual commits
This extension allows the selective definition of a hook for
manual commits only (i.e. outside graft, histedit, rebase, etc.).
In order to use it, add the following lines to your ``.hg/hgrc`` or
``~/.hgrc`` file::
[extensions]
manualcommithook=/path/to/extension
[hooks]
premanualcommit=/path/to/hook
The ``hooks.premanualcommit`` hook will then be (temporarily) installed
under ``hooks.precommit.manual``, but only for manual commits.
"""
from mercurial import commands, extensions
def commit_with_hook(original_cmd, ui, repo, *pats, **opts):
hook = ui.config("hooks", "premanualcommit")
if hook:
if ui.config("hooks", "precommit.manual"):
ui.warn("overriding existing precommit.manual hook\n")
ui.setconfig("hooks", "precommit.manual", hook)
return original_cmd(ui, repo, *pats, **opts)
def uisetup(ui):
extensions.wrapcommand(commands.table, "commit", commit_with_hook)
See the doc comment for instructions on how to use the extension.

How to get the working directory of the command from an hg hook?

I'm working on a commit hook for Mercurial and running into problems with relative paths.
Say my hook wants to look at the contents of the files being committed and warn if any contain the phrase "xyzzy". However, the user has decided to call commit from a subfolder and pass in the name of the file as a pattern...
C:\clone\subdir> hg commit file.txt -m 'test'
My hook is called with C:\clone as the working directory, but HG_PATS contains simply file.txt with no subdir\ prefix. How can I get the working directory of the hg command itself? I can't find a way to do this in docs.
The only way I can figure out how to get it is look up the process tree to find the first hg.exe and get its working directory. But that's not exactly portable to other OS's. (And I know I could write an extension, but would really like to avoid that.)
If you use the pretxncommit hook then you are given $HG_NODE which is the commit id, but the commit hasn't been finalized at that point so you can still return 1 to cancel it.
Then you could use
hg log -r $HG_NODE --template '{files}'
to get the list of files in the commit, and it gives you the full path relative to the repo root.
It's not exactly what you were after but it might get you close enough to let you do the content examination you want.
Thanks for the answers and comments, but after some more research I determined there's no clean way to do what I want from an external hook. I did implement the CWD hack I mentioned in my question. Not a ton of code, but quite nasty, and on Windows it requires undocumented access to external process CWD via tlist.exe. It works, but..yuck.
The right way to do this appears to be to write an in-process hook (example library at hghooklib). Usual versioning caveats apply as with writing any extension, though I think for our hooks the interface to hg is simple enough that we'll be ok.
(In my question I mentioned I didn't want to write an extension, but I was thinking of a full extension like hgeol. A hook-only extension with a single function entry point feels more constrained and simple, which is what I want at this point.)

Detect creating of branches or bookmarks in HG

Is it possible to detect if a commit creates a new bookmark or branch via hooks in .hgrc?
I've tried to see if I can find out using hg log, but it just shows on what branch/bookmark the commit has been created: http://hgbook.red-bean.com/read/customizing-the-output-of-mercurial.html
There don't seem to be hooks for it: http://hgbook.red-bean.com/read/handling-repository-events-with-hooks.html
It would make sense I suppose that there isn't a hook for it, because it is also not possible to make a commit which is 'just' the creation of the branch indicating branches/bookmarks only exists when added to a specific commit.
I figured I could check hg branches and hg bookmarks before and after each commit and determine which are removed and added, but is there a cleaner way for detecting branch/bookmark adds/removes?
The pushkey and prepushkey hooks can detect the addition, deletion, and moves of bookmarks.
In hgrc:
[hooks]
prepushkey=echo %HG_NAMESPACE% %HG_KEY% %HG_OLD% %HG_NEW%\n >> out.txt
HG_NAMESPACE will contain "bookmark" and HG_KEY will contain the name of the bookmark.
HG_OLD will contain the hash of the commit the bookmark was before the operation. It won't be set if the bookmark is being created.
HG_NEW will contain the hash of the commit the bookmark will be after the operation. It won't be set if the bookmark is being deleted.
Bookmarks
Bookmarks-handling does not require commit
Bookmark can be created|modified for any changeset in history, not only for current
Bookmark(s) can appear as result of data-exchange (pull|push), not local user's actions
Only part of all possible cases can be covered by hook
Branches
Changing branch always reflected in commit
Branch in changeset may differ from parent's branch not only as result of hg branch (see "merge branches" and "mergesets") - and I haven't nice and easy and ready to use solution for this case
Common notes
You can use standard precommit hook (executed before commit and can enable|disable commit) for testing different conditions in commit or or pretxncommit
Mercurial template-engine has keywords for branch and bookmark for using in hg log -T
In pretxncommit hook commit already exist, but not finalized - it means you can manipulate with commit's data using -r tip and tip's parent in any Mercurial command
Dirty skeleton for hook's body
hg log -T "{KEYWORD}\n" -r "tip + tip^" | ....
where KEYWORD may be branch or bookmarks. Result of log is two-strings output, which can be identical of different (not sure for bookmark, TBT!!), which you have to compare (as you want and can)
PS: Idea inspired by EnsureCommitPolicy Wiki and Mercurial pre commit hook topic here

Mercurial hook to test that username is valid when pushing to repository

I have a "central" repository that I want to ensure that no one pushes changes in to with a wrong user name.
But I can not figure out how to make a hook that tests the user name against a positive list. I have found in the Mercurial API a ctx.user() call that seems to be what I want to test my positive list against.
Also the hook could be a precommit hook that is distributed as part of the repository clone or it could be a hook on the central repository as a pre-incoming or something like that.
Any help or pointers would be greatly appreciated.
I have posted two functional examples on Bitbucket. Both examples are for searching a commit message for some specifically formatted text (like an issue tracked case ID), but could be easily modified to check a user against a list of valid users.
The first example is actually a Mercurial extension that wraps the 'commit' command. If it fails to find the appropriate text (or valid user in your case), it will prevent the commit from occurring at all. You can enable this in your .hgrc file by adding these lines:
[extensions]
someName = path/to/script/commit-msg-check.py
The second example uses a in-process pretxncommit hook, which runs between when the commit has been made, but before it becomes permanent. If this check fails it will automatically roll back the commit. You can enable this in your .hgrc file by adding these lines (assuming you kept the same file/function names):
[hooks]
pretxncommit.example = python:commit-msg-check-hook.CheckForIssueRecord
You can execute any Python code you like inside of these hooks, so user validation could be done in many ways.
Thanks for the examples dls.
In the end I decided to run it as a pretxnchangegroup hook and then use the hg log and grep to test the author field of the commits:
[hooks]
pretxnchangegroup.usercheck = hg log --template '{author}\n' -r \
$HG_NODE: | grep -qe 'user1\|user2\|etc'
It does of course not provide a very good feedback other than usercheck failed. But I think it is good enough for now.