Last active
April 27, 2023 09:46
-
-
Save raohmaru/8b7f3b215b47f1e53b65f44de1f3ab84 to your computer and use it in GitHub Desktop.
Git pre-comit hook to lint files using npm
This file contains 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 sh | |
# This loads nvm | |
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")" | |
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" | |
# Bypass if a merge is happening | |
function skipIfMerging() { | |
local isMerge="$(git rev-parse -q --verify MERGE_HEAD)" | |
# If isMerge is a hash, a merge is ongoing | |
if [[ ! -z "$isMerge" ]]; then | |
exit 0 | |
fi | |
} | |
function stagedFiles() { | |
# Get staged files by extension | |
local files=$(git diff-index --cached --name-only HEAD | grep ".*\.$1$") | |
# Join lines by whitespace | |
files=$(echo $files | tr '\n' ' ') | |
# Trim last whitespace character | |
files=$(echo $files | xargs) | |
echo "$files" | |
} | |
function lintFiles() { | |
local type=$1 | |
# Command to run from a local or remote npm package | |
local bin="npx $2" | |
local args=$3 | |
# Shifts all the positional arguments down by three | |
shift; shift; shift | |
# $@ is all the arguments | |
if [[ ! -z "$@" ]]; then | |
echo -e "\033[33mLinting $type files...\033[0m" | |
# Invoke npm bin+binary with the staged files | |
echo "$@" | xargs $bin $args | |
# $? is the output of the last command | |
if [[ ! "$?" == 0 ]]; then | |
PASS=false | |
fi | |
fi | |
} | |
skipIfMerging | |
PASS=true | |
STAGED_CSS=$(stagedFiles "scss") | |
if [[ ! -z "$STAGED_CSS" ]]; then | |
lintFiles CSS stylelint "--allow-empty-input" $STAGED_CSS | |
fi | |
STAGED_JS=$(stagedFiles "jsx\?") | |
if [[ ! -z "$STAGED_JS" ]]; then | |
lintFiles JS eslint "--no-error-on-unmatched-pattern --color" $STAGED_JS | |
fi | |
if ! $PASS; then | |
echo -e "\033[41m\033[1mCOMMIT FAILED:\033[0m \033[1mYour commit contains files that did not pass the linter check. Please fix the errors and try again.\033[0m\n" | |
exit 1 | |
fi | |
exit $? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment