#!/usr/bin/env bash
set -e

root_dir=$(git rev-parse --show-toplevel)

this_dir=${BASH_SOURCE[0]%/*}
. "${this_dir}"/lib/eslintignore.sh


## CLI PARSING

usage() {
    cat >&2 <<EOF
usage: tools/fmt [--all]

Options:
  --all       Run on all files (default: only files changed in this
              branch, as found by \`tools/info changed-files\`.)
EOF
    exit 2
}

all=
while (( $# )); do
    case "$1" in
        --all) all=1; shift;;
        *) usage;;
    esac
done


## EXECUTION

cd "$(git rev-parse --show-toplevel)"

PATH=node_modules/.bin:"$PATH"

if [ -z "$all" ]; then
    files=( $(apply_eslintignore $(tools/info changed-files | grep '^src/.*\.js$') ) ) \
        || exit 0
else
    files=( $(apply_eslintignore 'src/**/*.js' ) )
fi

prettier-eslint \
    --write \
    --eslint-config-path "${root_dir}"/tools/formatting.eslintrc.yaml \
    --log-level=warn \
    "${files[@]}"
eslint --no-eslintrc -c tools/formatting.eslintrc.yaml --fix "${files[@]}"
