2021-07-08 00:31:12 +00:00
|
|
|
#!/usr/bin/env bash
|
|
|
|
|
2022-11-20 22:10:39 +00:00
|
|
|
if git rev-parse --verify HEAD >/dev/null 2>&1; then
|
2021-07-08 00:31:12 +00:00
|
|
|
against=HEAD
|
|
|
|
else
|
|
|
|
# Initial commit: diff against an empty tree object
|
|
|
|
against=$(${git}/bin/git hash-object -t tree /dev/null)
|
|
|
|
fi
|
|
|
|
|
2023-04-26 10:49:44 +00:00
|
|
|
# Stash only unstaged changes, keeping staged changes
|
2023-07-02 12:49:47 +00:00
|
|
|
# We have to stash two times, because:
|
|
|
|
# --keep-index also stashes the staged changes.
|
|
|
|
# The staged changes end up in both the stage AND the stash.
|
|
|
|
# https://overflow.hostux.net/questions/7650797/how-to-stash-only-unstaged-changes-in-git#60875082
|
2023-04-26 10:49:44 +00:00
|
|
|
old_stash=$(git rev-parse --quiet --verify refs/stash)
|
2023-07-02 12:49:47 +00:00
|
|
|
git stash push --quiet --staged --message "Staged changes before pre-commit hook"
|
|
|
|
git stash push --quiet --message "Unstaged changes before pre-commit hook"
|
|
|
|
if git stash show "stash@{1}" 2>/dev/null; then
|
|
|
|
git stash pop --quiet --index "stash@{1}"
|
|
|
|
else
|
|
|
|
git stash pop --quiet --index "stash@{0}"
|
|
|
|
fi
|
2023-04-26 10:49:44 +00:00
|
|
|
new_stash=$(git rev-parse --quiet --verify refs/stash)
|
|
|
|
|
2023-05-05 16:32:40 +00:00
|
|
|
diff="git diff-index --name-only --cached $against --diff-filter d"
|
|
|
|
|
|
|
|
mapfile -t all_files < <($diff)
|
|
|
|
|
2023-04-26 10:49:44 +00:00
|
|
|
# Format staged files
|
2022-11-20 22:10:39 +00:00
|
|
|
if ((${#all_files[@]} != 0)); then
|
|
|
|
treefmt "${all_files[@]}" &&
|
|
|
|
git add "${all_files[@]}"
|
2021-07-08 00:31:12 +00:00
|
|
|
fi
|
|
|
|
|
2023-04-26 10:49:44 +00:00
|
|
|
# If unstaged changes were stashed re-apply to working tree
|
|
|
|
if [ "$old_stash" != "$new_stash" ]; then
|
|
|
|
git stash pop --quiet
|
|
|
|
fi
|
|
|
|
|
|
|
|
# Check editorconfig
|
2022-11-20 22:10:39 +00:00
|
|
|
if ((${#all_files[@]} != 0)); then
|
|
|
|
if ! editorconfig-checker -- "${all_files[@]}"; then
|
|
|
|
printf "%b\n" \
|
|
|
|
"\nCode is not aligned with .editorconfig" \
|
|
|
|
"Review the output and commit your fixes" >&2
|
|
|
|
exit 1
|
|
|
|
fi
|
2021-07-08 00:31:12 +00:00
|
|
|
fi
|