commit e11ff092a380b8335a99425bb4c1d0282abc8f2a Author: The Magician Date: Thu Dec 7 15:17:02 2023 +0000 Add pre-commit.shellcheck hook diff --git a/README.md b/README.md new file mode 100644 index 0000000..f70b441 --- /dev/null +++ b/README.md @@ -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] for the original. diff --git a/pre-commit.shellcheck b/pre-commit.shellcheck new file mode 100755 index 0000000..78b0924 --- /dev/null +++ b/pre-commit.shellcheck @@ -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