From b911badb8a319ed2bb58c1abe25591509a2a83d8 Mon Sep 17 00:00:00 2001 From: teutat3s Date: Sat, 9 Apr 2022 15:46:51 +0200 Subject: [PATCH] pre-commit hook: only format modified lines instead of entire files --- shell/hooks/pre-commit.sh | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/shell/hooks/pre-commit.sh b/shell/hooks/pre-commit.sh index 2a370734..329ae3f4 100755 --- a/shell/hooks/pre-commit.sh +++ b/shell/hooks/pre-commit.sh @@ -5,7 +5,7 @@ then against=HEAD else # Initial commit: diff against an empty tree object - against=$(${git}/bin/git hash-object -t tree /dev/null) + against=$(git hash-object -t tree /dev/null) fi diff="git diff-index --name-only --cached $against --diff-filter d" @@ -15,8 +15,19 @@ mapfile -t all_files < <($diff) # Format staged nix files. if [[ -n "${nix_files[@]}" ]]; then + # stash only unstaged changes, keeping staged changes + old_stash=$(git rev-parse --quiet --verify refs/stash) + git stash push --quiet --keep-index -m 'Unstaged changes before pre-commit hook' + new_stash=$(git rev-parse --quiet --verify refs/stash) + + # format staged changes nixpkgs-fmt "${nix_files[@]}" \ && git add "${nix_files[@]}" + + # if unstaged changes were stashed reapply to working tree + if [ "$old_stash" != "$new_stash" ]; then + git stash pop --quiet + fi fi # check editorconfig