Coding with style (mercurial kwstyle hook)
October 14th, 2009 by Melaneum Google+
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:
[hooks]
commit.kwstyle = python:/path/to/this/file.py:kwstyle
changegroup.kwstyle = python:/path/to/this/file.py:kwstyle
'''
if kwargs.get('parent2'):
return
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')
f.write(fctx.data())
f.close()
cmd = "/home/kwstyle/KWStyle -v -xml /home/kwstyle/OTB.kws.xml " \
+tempFile
out = commands.getoutput(cmd)
message = '*** Checking '+filename \
+'\n'+'\n'.join(out.split('\n')[1:])
ui.write(message)
os.remove(tempFile)
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.
This entry was posted on Wednesday, October 14th, 2009 at 08:56 UTC and is filed under Python. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.