Skip to main content

NixOS: Ensuring Correctness with Git Hooks

NixOS - This article is part of a series.
Part 11: This Article

Adding Nix checks
#

Using the pre-commit-hooks flake module we can define the set of checks to be run by the nix check command:

{
  inputs,
  ...
}:
{
  perSystem =
    {
      self',
      system,
      pkgs,
      ...
    }:
    {
      checks = {
        pre-commit-check = inputs.pre-commit-hooks.lib.${system}.run {
          src = ../../.;
          hooks = {
            nixfmt-rfc-style.enable = true;
            flake-checker.enable = true;
            statix.enable = true;
            nil.enable = true;
          };
        };
      };
    };
}

Adding git hooks to run checks before committing
#

With the checks defined, we can create a nix dev-shell to install git hooks to run each check before commits:

{
  inputs,
  ...
}:
{
  perSystem =
    {
      self',
      system,
      pkgs,
      ...
    }:
    {
      devShells = {
        default = pkgs.mkShell {
          buildInputs = self'.checks.pre-commit-check.enabledPackages;
          shellHook = ''
            ${self'.checks.pre-commit-check.shellHook}
            exit
          '';
        };
      };
    };
}

NixOS - This article is part of a series.
Part 11: This Article