#!/bin/bash
#
# Checks changed javascript files in stage area by running npm test for each commit.
#

PATCH_FILE="working-tree.patch"
NPM_BIN="node_modules/.bin"

function cleanup {
    exit_code=$?
    if [ -f "$PATCH_FILE" ]; then
        git apply "$PATCH_FILE" 2> /dev/null
        rm "$PATCH_FILE"
    fi
    exit $exit_code
}

trap cleanup EXIT SIGINT SIGHUP

# Cancel any changes to the working tree that are not going to be committed
git diff > "$PATCH_FILE"
git checkout -- .

js_cached_files=$(git diff --cached --name-only --diff-filter=ACMR | grep "^.\+\.js[x]\{0,1\}$")
css_cached_files=$(git diff --cached --name-only --diff-filter=ACMR | grep "^.\+\.css$")

if [ "$js_cached_files" ]; then
    $NPM_BIN/eslint $js_cached_files --ignore-path ".eslintignore" --quiet || exit 1
fi

if [ "$css_cached_files" ]; then
    $NPM_BIN/stylelint $css_cached_files || exit 1
fi