From b6ddceff3a82fea3d6be52739af81025e9fe9da7 Mon Sep 17 00:00:00 2001 From: David Arnold Date: Tue, 20 Apr 2021 14:21:30 -0500 Subject: [PATCH] devshell: add (tiny) but useful pre-commit hook --- devshell.toml | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/devshell.toml b/devshell.toml index a39b209bc13df..f1c762278fc02 100644 --- a/devshell.toml +++ b/devshell.toml @@ -1,10 +1,17 @@ +imports = [ "git.hooks" ] + [devshell] name = "nixpkgs" packages = [ "fd", "nixpkgs-fmt", + "editorconfig-checker", ] +[[commands]] +package = "editorconfig-checker" +category = "linters" + [[commands]] name = "fmt" help = "Check Nix formatting" @@ -17,3 +24,34 @@ help = "Check Nix parsing" category = "folder tree checks" command = "fd --extension nix --exec nix-instantiate --parse --quiet {} >/dev/null" +[git.hooks] +enable = true +pre-commit.text = """ +#!/usr/bin/env bash +set -eou pipefail +if git rev-parse --verify HEAD >/dev/null 2>&1 +then + against=HEAD +else + # Initial commit: diff against an empty tree object + against=$(${git}/bin/git hash-object -t tree /dev/null) +fi + +diff="git diff-index --name-only --cached $against --diff-filter d" + +nix_files=($($diff -- '*.nix')) +all_files=($($diff)) + +# Format staged nix files. +if [[ -n "${nix_files[@]}" ]]; then + nixpkgs-fmt "${nix_files[@]}" + git add "${nix_files[@]}" +fi + +# check editorconfig +if ! editorconfig-checker -- "${all_files[@]}"; then + echo -e "\nCode is not aligned with .editorconfig +Review the output and commit your fixes" >&2 + exit 1 +fi +"""