Last active
April 27, 2021 05:15
-
-
Save wookietreiber/3bf8621274caafed543fca6a3feab284 to your computer and use it in GitHub Desktop.
git pre-commit hook to check shell scripts with shellcheck
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -efu -o pipefail | |
# returns staged files | |
function staged.files { | |
if git rev-parse --verify HEAD &> /dev/null | |
then | |
against=HEAD | |
else | |
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 | |
fi | |
git diff-index --cached --name-only $against | | |
grep \ | |
-e '\.bashrc' \ | |
-e '\.zshrc' \ | |
-e '\.bash_profile' \ | |
-e '\.sh$' || true | |
} | |
declare -a paths=() | |
while read -r file | |
do | |
paths[${#paths[@]}+1]=$file | |
done < <(staged.files) | |
if [[ ${#paths[@]} -eq 0 ]] | |
then | |
echo -e '\e[1m\e[32m[info]\e[0m \e[1mshellcheck\e[0m no files in stage' | |
else | |
if ! command -v shellcheck &> /dev/null | |
then | |
echo -e '\e[1m\e[33m[warn]\e[0m \e[1mshellcheck\e[0m is not installed' >&2 | |
exit 0 | |
fi | |
stage=$(mktemp -d) | |
trap 'rm -r $stage' EXIT INT TERM | |
for path in "${paths[@]}" | |
do | |
file="$stage/$path" | |
mkdir -p "$(dirname "$file")" | |
git show ":$path" > "$file" | |
done | |
pushd "$stage" &> /dev/null | |
shellcheck "${paths[@]}" | |
popd &> /dev/null | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment