#!/bin/bash
#
# * Check changed js files using eslint.
#

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 -- .

git_cached_files=$(git diff --cached --name-only --diff-filter=ACMR | grep "\.js$")
if [ "$git_cached_files" ]; then
    echo "Start linting..."

    $NPM_BIN/eslint $git_cached_files --quiet || exit 1

    echo "There are no errors in codestyle."
fi
