git pre-commit hook for code beautification


In this post I will share a git pre-commit hook I created for aiding with code beautification.

In Linux, I work in two different coding styles: User space and Kernel.

The Linux kernel has a very specific coding style and every commit to kernel must adhere to that style.
The Linux kernel provides a very neat script named that can be used to check if your patch adheres to the kernel style. It also works on complete files.

Usually, before I prepare an a patch for pushing upstream, I run the checkpatch script and fix all the errors (well, not all off them, 80 columns ? really ??)

but, can’t we automate this ? well, here’s come git hooks to the rescue.

Git has an option of providing a scripts that can run before or after certain workflow stages.
For instance, if you ever worked with Gerrit, you probably used Gerrit’s commit-msg hook provided to generate a unique Change-Id token embedded in the commit message.

One hook that is particularly interesting in this case is the pre-commit hook. As one might speculate, this scripts runs just before the commit action by Git and has access to Git objects.

The hook I’ve written, basically runs on all the file in the commit and runs astyle (Artistic style) against each of them.

astyle if a very cool command line tool that works on various platforms. It runs against a set rules describing how to do spacing, indentation and various other beautification stuff.
It then rewrites the original file with the fixed style.

You can grab the hook in Github.

Please feel free to fork and enhance it.

Possible improvements:
Currently astyle works on complete objects (files). I would prefer it will only work on the objects diff  in commits.


git pre-commit hook for code beautification