#!/usr/bin/env bash

# Cause the script to exit if a single command fails
set -e  # o pipefail -v

usage()
{
  cat << USAGE >&2
usage: $(basename "$0") [-h] [--config CONFIG] [files [files ...]]

Python code style checker

positional arguments:
files                   files that need to be checked, all files\
 with \`.py\` extension will be checked if no files are specified

optional arguments:
  -h, --help            show this help message and exit
  -l, --line-length INT maximum length that any line may be
  --ignore ERRORS       specify a list of codes to ignore
USAGE
  exit 1
}


# ---- environment variables

LINE_LENGTH=79
IGNORE="C812,C813,C814,C815,C816,D100,D104,D200,D204,D205,D301,D400,D401,D402,D412,D413,DAR103,DAR203,E203,E731,E1101,S101,S311,W0221,W503,W504,WPS0,WPS110,WPS111,WPS2,WPS305,WPS420,WPS421,WPS430,WPS431,WPS433,WPS5,WPS6"
FILES=""

while (( "$#" )); do
  case "$1" in
    -l|--line-length)
      LINE_LENGTH=$2
      shift 2
      ;;
    --ignore)
      IGNORE=$2
      shift 2
      ;;
    -h|--help)
      usage
      ;;
    -*|--*=) # unsupported flags
      echo "Error: Unsupported flag $1" >&2
      exit 1
      ;;
    *) # preserve positional arguments
      FILES="${FILES} $1"
      shift
      ;;
  esac
done

# if `FILES` unspecified check all python files in git repo
if [[ -z "${FILES}" ]]; then
  ROOT="$(git rev-parse --show-toplevel)"
  builtin cd "${ROOT}" || exit 1

  shopt -s globstar  # allow ** for recursive matches
  FILES=**/*.py
fi


# ---- code checking

# test to make sure the code is isort compliant
catalyst-codestyle-isort --check-only --diff \
  --line-width "${LINE_LENGTH}" \
  -- ${FILES}

# test to make sure the code is black compliant
black --diff --check --line-length "${LINE_LENGTH}" -- ${FILES}

# stop the build if there are any unexpected flake8 issues
catalyst-codestyle-flake8 --ignore "${IGNORE}" \
  --line-length "${LINE_LENGTH}" \
  --quotes double \
  --show-source \
  --statistics \
  --count \
  -- ${FILES}
