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.
Related
We are using pretxncommit hook for HG to run a quick static analysis check on code commited. However the hook is triggered on applying any changes to commit tree - which includes rebasing and using MQ to edit and squash commits.
Is it possible to somehow check what type of change is happening in hook itself? Like
def analyze_hook(ui, repo, node=None, **kwargs):
if repo.state.is_commit_added and not (repo.state.is_rebase or repo.state.is_patch):
return 0
you'd want to check the HG_SOURCE to see what operation is bringing you those commits
https://book.mercurial-scm.org/read/hook.html#sources-of-changesets
e.g. https://github.com/vmg/hg-stable/blob/master/tests/test-hook.t
e.g. https://stackoverflow.com/a/11105493/1681985
We are looking for a way to add / update a custom tag at the beginning of each file being committed during a commit. Its some kind of local timestamp we need.
I was thinking of hooks.
Unfortunately I cannot find a useful hook for that:
precommit: unsuitable as it fires before hg knows any metadata of the commit
pretxncommit: unsuitable, as the documentation clearly states that we should not change the working dir at this point
commit: unsuitable, as it fires when the commit has already happened.
EDIT:
I can not use hg's inline changeset-hash and / or datetime. For the following reason:
Our files get later imported into an external system (we do not have control over) which does not support any kind of versioning.
To simplify stuff: let's say tag is an ever-incrementing no. (everytime we commit). This tag is then used to help getting an idea of the version / status of the file on the system in respect to the file in the repo - like "no. of changes we're missing" and such.
Any ideas?
I would suggest a two-stage solution. First, create an alias along the following lines:
[alias]
tcommit = !tag-changed-files && $HG commit "$#"
Here, tag-changed-files would retrieve a list of modified and added/moved files via $HG status -ma -n or $HG status -ma -n -0 and tag them. I am assuming that re-tagging files that have been modified but aren't being committed yet is a harmless operation; more on that below. Note that you can even redefine commit if you absolutely want to via:
[alias]
commit = !tag-changed-files && $HG --config alias.commit=commit commit "$#"
However, this is potentially problematic, because it may confuse scripts.
You could also integrate the commit step in the program if you wanted to, and even try and parse the command line arguments to only tag those files that you are committing. For this approach, using hglib might be appropriate to avoid the overhead of invoking Mercurial multiple times. (Note that hglib and other tools that use the command server ignore aliases and command defaults, so this works even if you alias commit).
Second, you'd install a pretxncommit hook that verifies that files that are being committed have indeed been tagged appropriately (to ensure that the tag-changed-files program hasn't been bypassed by accident).
This should work without a problem on full commits; for partial commits, any files that were changed but have not been committed would also have been retagged, but since they will be either committed later (and get tagged properly at that point) or reverted, that should be harmless.
an idea of the version / status of the file on the system in respect to the file in the repo
Just one idea
Stop reinvent the wheel
Incremental counter is just shit, if you task is "to know, which version is on LIVE and which - in Mercurial's tip" (and this is your real business-task, yes?!)
Keyword Extension give you last changes per file.
If you want to inject changeset of repository into files (it's reasonable good way), re-read this part of wiki-page
If you just want to version your entire repo, do not use this
extension but let your build system take care of it. Something along
the lines of
hg -q id > version
before distribution might be well enough if file-wise keyword
expansion in the source is not absolutely required
You can insert hg id output into files at export stage (in planetmaker's sed-style), bu you can also have this additional metadata in files permanently in VCS with special encode|decode filters
There is - to my knowledge - no intrinsic system in mercurial which supports what you describe. However I can recommend an approach which somewhat is adopted from building a software release package from the repository: Make a small export script which replaces a certain KEYWORD in your files with the version information you need. A Makefile target could look like which creates a zip export for revision XXX with version information in all files which support it (thus contain the verbatim KEYWORD - use something truely unique here):
VERSION=$(hg log -rXXX --template="Version: {node|short} from {date|isodate}")
export:
hg archive -rXXX -t files export
for i in $(hg ma -rXXX); do sed -i "s/KEYWORD/$VERSION/g" $i; done
zip -9rq export.zip export
I use a similar approach in my Makefiles where I create versioned export for the source of a particular revision of my software.
EDIT: if your purpose (as stated by the comment) is only to implant the number of commits made to that file: then you can use indeed a pre-commit hook and modify the file. You can count the number of modifications made to a file with hg log FILENAME --template="{node}\n" | wc -l. Do that for every file and do the sed replacement in the header of each file in the pre-commit 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.)
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.
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.