nixf-tidy (introduction, docs) is a simple Nix linter CLI tool which takes Nix code on standard input and emits a JSON array of issues. This mode of operation makes it non-trivial to use as a pre-commit hook, so I’ve written a small wrapper:

nixf-tidy.bash
#!/usr/bin/env bash

set -o errexit -o noclobber -o nounset -o pipefail
shopt -s failglob inherit_errexit

for file; do
    result="$(nixf-tidy --pretty-print --variable-lookup < "${file}")"
    if [[ "${result}" != '[]' ]]; then
        printf '%s: %s\n' "${file}" "${result}" >&2
        exit_code=3
    fi
done

exit "${exit_code-0}"

Use

Save nixf-tidy.bash above somewhere in your repository and use the following snippet:

.pre-commit-config.yaml
repos:
  - repo: local
    hooks:
      - id: nixf-tidy
        name: nixf-tidy
        entry: ./path/to/nixf-tidy.bash
        files: \.nix$
        language: system
        stages: [pre-commit]