VENV_NAME=venv
VENV_BIN=$(VENV_NAME)/bin
PYTHON=$(VENV_BIN)/python3
PIP=$(VENV_BIN)/pip3
BLACK=$(VENV_BIN)/black
ISORT=$(VENV_BIN)/isort

.PHONY: install-dev venv lint mypy test
.DEFAULT_GOAL := help

define PRINT_HELP_PYSCRIPT
import re, sys

for line in sys.stdin:
	match = re.match(r'^(?P<target>[a-zA-Z0-9_//-]+):(.*?## (?P<help>.*))?', line)
	if match:
		target = match.group('target')
		help = match.group('help')
		if not help:
			help = ''
		print(f"{target:20s} {help}")
endef
export PRINT_HELP_PYSCRIPT

help: ## list all commands
	@python3 -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST)

install-dev: ## prepare virtual environment and install all dependencies
	python3 -m venv $(VENV_NAME) --upgrade-deps
	$(PIP) install -r requirements-dev.txt

uninstall-dev:
	rm -rf $(VENV_NAME)
	find -iname "*.pyc" -delete

lint: venv lint/flake8 lint/black lint/isort mypy ## lint source codes

lint/flake8: venv
	$(VENV_BIN)/flake8 battery/ tests/

lint/black: venv
	$(BLACK) --check .

lint/isort:
	$(ISORT) --check .

format-diff: venv  ## show invalid source code formatting
	$(BLACK) --diff .
	$(ISORT) --diff .

format-fix: venv ## fix source code formatting
	$(BLACK) .
	$(ISORT) .

mypy: venv ## run mypy
	$(PYTHON) -m mypy battery/ tests/

test: venv ## run tests
	$(PYTHON) -m unittest discover -v -s tests/

pytest: venv ## run pytests
	$(VENV_BIN)/pytest -v

venv:
	. $(VENV_NAME)/bin/activate
