Nix and Pre-commit Git Hooks

reproducible nix git hooks

Nix
Git

When working on a local repo, I find it nice to have some common pre-commits set up with git. Here's how I use nix-shell to add some pre-commit hooks to my workflow.

# Within the scope of a repo, do the following
vim .git/hook/pre-commit

I then add the following shebangs for my nix shell and packages needed for the hook (in my case, cargo and a rust project):

#!/usr/bin/env nix-shell
#!nix-shell -i bash -p bash cargo
cargo fmt -- --check

If i want to make them more reproducible, i can pin nixpkgs to a specific sha and always pull the dependencies from a fixed point.

#!/usr/bin/env nix-shell
#!nix-shell -i bash -p bash cargo
#!nix-shell -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/ee084c02040e864eeeb4cf4f8538d92f7c675671.tar.gz
cargo fmt -- --check

This checks for any formatting errors, and kicks me out of a commit til clean. Enjoy and adapt to your needs and programs! I used the following gist to get inspired