Skip to content

Instantly share code, notes, and snippets.

@erancihan
Last active April 12, 2021 23:33
Show Gist options
  • Save erancihan/8b332cbcb281ceda577066d38700d4b9 to your computer and use it in GitHub Desktop.
Save erancihan/8b332cbcb281ceda577066d38700d4b9 to your computer and use it in GitHub Desktop.
Simple GIT pre-commit hook for linting
#!/usr/bin/env bash
echo "> Running pre-commit script"
PWD=$(pwd)
BIN_PRETTIER="$PWD/node_modules/prettier/bin-prettier.js"
mapfile files < <(git diff-index --diff-filter=d --cached --name-only HEAD)
files_c=${#files[@]}
for (( i=0; i<files_c; i++ ));
do
file=${files[$i]}
file=${file%$'\n'}
out=$file
# lint JavaScript & TypeScript files with Prettier
if [[ "$PWD/$file" =~ \.(js|jsx|ts|tsx)$ ]];
then
if [[ ! $(node -v) ]]; then
echo "Node does not exist"
continue
fi
if [[ ! -f "$BIN_PRETTIER" ]];
then
echo "Prettier does not exist"
continue
fi
out="$(node "$BIN_PRETTIER" "$PWD/$file" --write)"
out="${out//\\//}"
fi
printf "\r> %d/%d %s \033[K" "$((i + 1))" "$files_c" "$out"
git add "$PWD/$file"
done
printf "\r\u221A Done \033[K"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment