The Crystal Programming Language Forum

Pre-commit git hook

I don’t claim to know much about shell scripting but I put together a pre-commit githook file to check crystal tool format, ameba (and shards dependencies for ameba), crystal spec
It only runs on staged files (though will run against unstaged changes in those files) and the specs run with --fail-fast to speed execution.

Note: --fail-fast doesn’t give a correct error code on return, but should be fixed for next release so I’m leaving it as is

If you don’t use ameba, you can remove that section and the shards check.

Credits to straight-shooter, j8r and tenebrousedge for the help figuring out how to put this together.

1 Like

In the CONTRIBUTING.md there is a precommit hook for formatting. You could definitely add to that

here is the script.

1 Like

Thanks wontruefree. I actually used that file to help build this one. You can see I linked it in my credits. Since that is geared more towards contributing to the language and has checks to see if there is a compiled version in the bin folder, I reworked it to be more generic and focused on building libs or shards. It can be customised and extended pretty easily but I feel gives a very good starting template for pre-commit checking.

It’s fine to have more specialized git hooks. This one is somewhat opinionated towards using non-standard tooling (ameba) and relatively expensive tests (shards check and crystal spec). Those are things not everyone would want to run on every git commit. I certainly wouldn’t because I wouldn’t want to be forced to wait for specs to compile and run.

As a note regarding your script, instead adding || exit 1 to each sub-command you could just use set -e to make the entire script fail if a sub-command returns a non-zero exit status.

We had that discussion in the gitter regarding -e, and it broke the functionality of returning 0 when there were no .cr files staged.

Also, I agree. It is quite an opinionated git hook aimed at smaller developments. The benefit of such an opinionated hook is that you can remove the parts you don’t want without much knowledge rather than working out how to add the parts you want yourself.

Hopefully, people will get use out of this as a direct file to use, or just as reference for their own hooks.