Add pre-commit.shellcheck hook

This commit is contained in:
The Magician 2023-12-07 15:17:02 +00:00
commit e11ff092a3
2 changed files with 61 additions and 0 deletions

14
README.md Normal file
View File

@ -0,0 +1,14 @@
# githooks
A collection of various Git hook scripts for different purposes.
This file contains a description of what each one is used for.
## pre-commit.shellcheck
This is used in repositories containing Shell code to ensure that commits which would include code that causes `shellcheck` errors can't be committed.
The files which are `shellchecked` are:
- Any files for which the `file` command returns output containing 'shell script'
- Any files which end in the `.sh` file extension
- Any hidden files which begin with either `.bash` or `.zsh`
My version of this hook is based heavily on this Gist: https://gist.github.com/wookietreiber/3bf8621274caafed543fca6a3feab284
Credit to [wookietreiber]<https://gist.github.com/wookietreiber> for the original.

47
pre-commit.shellcheck Executable file
View File

@ -0,0 +1,47 @@
#!/bin/bash
set -e
function check_dependencies_installed() {
for dependency in xargs shellcheck; do
if ! command -v "$dependency" &>/dev/null; then
printf '\e[1;31m[error]\e[0m \e[1mdependency\[0m is not installed.\n'
exit 1
fi
done
}
function get_staged_files {
if ! git rev-parse --verify HEAD &> /dev/null; then
printf '\e[1;31m[error]\e[0m \e[1mHEAD\e[0m does not point to a commit.\n'
exit 1
fi
git diff-index --cached --name-only HEAD
}
function get_shell_files {
get_staged_files | xargs 'file' | grep 'shell script' | cut -d ':' -f 1
get_staged_files | grep --regexp=".*\.sh$" --regexp="\.bash.*$" --regexp="\.zsh.*$"
}
#function blah {
#
#while read -r file; do
#files[${files[@]}+1]="$file"
#done < <()
#}
function main {
check_dependencies_installed
declare -a files=()
while read -r file; do
files[${files[@]}+1]="$file"
done < <(get_shell_files)
shellcheck "${files[@]}"
}
main