Coding with style (mercurial kwstyle hook)

I like the source code to look good, have uniform presentation, etc. Maybe I’m a bit particular, but I’m definitely not alone here: KWStyle is a great tool to check a number of files and signal the imperfections. This is especially valuable for project where several people are involved and all using different editors.

You can produce a very nice matrix like this one. The only problem is that you have to go and actively look for it. As all stuffs that require a conscious effort and are not on the high priority list, this slip away and end up forgotten.

Few weeks ago, I discovered the capabilities of mercurial hooks. So here is the idea: check the style with KWStyle each time the code is pushed to the reference hg repository. We can also check when the code is committed, but that requires each developer to set up the hook.

I just came out with a quick solution using the KWStyle program. It would be much better with some python bindings, but in one hour, I had no time to start building that. Here is the hook:

def kwstyle(ui, repo, **kwargs):
  '''Use it like:

  commit.kwstyle = python:/path/to/this/
  changegroup.kwstyle = python:/path/to/this/

  if kwargs.get('parent2'):
  node = kwargs['node']
  ctx = repo[node]
  tempDir = '/tmp/'
  for filename in ctx.files():
    if (fnmatch.fnmatch(filename, '*.cxx')
        or fnmatch.fnmatch(filename, '*.h')
        or fnmatch.fnmatch(filename, '*.txx')):

      fctx = ctx[filename]
      #This would be better handled with python binding for kwstyle
      tempFile = tempDir+filename.split('/')[-1]
      f = open(tempFile,'w')
      cmd = "/home/kwstyle/KWStyle -v -xml /home/kwstyle/OTB.kws.xml " \
      out = commands.getoutput(cmd)
      message = '*** Checking '+filename \

When a new changeset is pushed to the repository, modified files are checked and the result is displayed to the use such as:

*** Checking modifiedFile.cxx
Error #13 (1) The header is incomplete
Error #9 (10) Number of empty lines at the end of files: 2

This is just a quick draft, if it works well, it will be good to have a look at KWStyle python bindings.

Leave a Reply

Your email address will not be published. Required fields are marked *