# Makefile snippet for some standard Python stuff

PACKAGE ?= $(notdir $(shell pwd))

PATH := /usr/share/sphinx/scripts/python3:${PATH}
export PYTHONPATH := $(PYTHONPATH)$(if $(PYTHONPATH),:)$(shell pwd)

PYTHON ?= python3
PYTEST ?= pytest
PYTEST_OPTIONS ?= -x
TESTS ?= tests/
CODE ?= $(PACKAGE)
MAXLEN ?= 99

BUILD_DIR ?= build
INPUT_DIR ?= docs/source

# Sphinx options (are passed to build_docs, which passes them to sphinx-build)
#   -W       : turn warning into errors
#   -a       : write all files
#   -b html  : use html builder
#   -i [pat] : ignore pattern

SPHINXOPTS ?= -a -W -b html
AUTOSPHINXOPTS := -i *~ -i *.sw* -i Makefile*

SPHINXBUILDDIR ?= $(BUILD_DIR)/sphinx/html
ALLSPHINXOPTS ?= -d $(BUILD_DIR)/sphinx/doctrees $(SPHINXOPTS) docs

it: untagged test push tag format deb pypi
itt: untagged test push ttag format deb pypi

deb: tagged
	merge-to-deb

tag:
	test $$(git ls-files -m | wc -l) = 0
	git nt
ttag:
	test $$(git ls-files -m | wc -l) = 0
	git ntt

doc:
	sphinx-build -a $(INPUT_DIR) $(BUILD_DIR)

livehtml: docs
	sphinx-autobuild $(AUTOSPHINXOPTS) $(ALLSPHINXOPTS) $(SPHINXBUILDDIR)

update:
	pip install -r ci/test-requirements.txt

cov:
	$(PYTEST) $(TESTS) --cov=$(CODE) --cov-report=term-missing

test: statictest pytest
statictest:
	black -l $(MAXLEN) --check $(CODE) $(TESTS) setup.py
	flake8 $(CODE) $(TESTS) setup.py
	pylint $(CODE) $(TESTS) setup.py
pytest:
	$(PYTEST) $(PYTEST_OPTIONS) $(TESTS)

format:
	black -l $(MAXLEN) $(CODE) $(TESTS) setup.py

precommit: format test

tagged:
	git describe --tags --exact-match
	test $$(git ls-files -m | wc -l) = 0

untagged:
	if git describe --tags --exact-match ; then exit 1; else exit 0; fi

pypi:	tagged
	python3 setup.py sdist upload
	## version depends on tag, so re-tagging doesn't make sense

upload: pypi
	git push --tags

push:
	git push-all

.PHONY: all tagged pypi upload precommit format test cov update doc livehtml statictest pytest it deb tag untagged push ttag itt
