koaning / calmcode-feedback

A repo to collect issues with calmcode.io
12 stars 0 forks source link

Automatic help in Makefiles #203

Closed rsmith-nl closed 6 months ago

rsmith-nl commented 7 months ago

By adding special comments to the targets in the Makefile, it is possible to automatically generate help. Below is my standard Makefile for python programs.

The important bits are:

1) The comments starting with ## on the same line as the targets 2) the sed command in the all target.

The sed command reads the Makefile, and extracts the lines that contain ##. It then replaces the colon up to and including ## with a tab and prints the line. This gives a target followed by a tab followed by the help text.

Tested with both BSD make and GNU make.

.POSIX
.PHONY: clean check format test doc zip
.SUFFIXES:

PROJECT:=foobar

TAGCOMMIT!=git rev-list --tags --max-count=1
TAG!=git describe --tags ${TAGCOMMIT}

# For a Python program, help is the default target.
help::
    @echo "Command  Meaning"
    @echo "-------  -------"
    @sed -n -e '/##/s/:.*\#\#/\t/p' -e '/@sed/d' Makefile

clean:: ## remove all generated files.
    rm -f backup-*.tar* ${PROJECT}-*.zip
    find . -type f -name '*.pyc' -delete
    find . -type d -name __pycache__ -delete
    cd doc && make clean

check:: .IGNORE ## check all python files. (requires pylama)
    pylama lp/*.py test/*.py *.py tools/*.py

tags:: ## regenerate tags file. (requires uctags)
    uctags -R --languages=Python

format:: ## format the source. (requires black)
    black lp/*.py test/*.py *.py tools/*.py

test:: ## run the built-in tests. (requires py.test)
    py.test -v

doc:: ## build the documentation using LaTeX.
    cd doc/; make

zip:: clean ## create a zip-file from the most recent tagged state of the repository.
    cd doc && make clean
    git checkout ${TAG}
    cd .. && zip -r ${PROJECT}-${TAG}.zip ${PROJECT} \
        -x '*/.git/*' '*/.pytest_cache/*' '*/__pycache__/*' '*/.cache/*'
    git checkout main
    mv ../${PROJECT}-${TAG}.zip .

Calling make with no arguments gives:

Command Meaning


clean remove all generated files. check check all python files. (requires pylama) tags regenerate tags file. (requires uctags) format format the source. (requires black) test run the built-in tests. (requires py.test) doc build the documentation using LaTeX. zip create a zip-file from the most recent tagged state of the repository.

koaning commented 6 months ago

Thanks for the suggestion.

I'll keep the Makefile course around for a bit, but I have started suggesting taskfile.dev as an alternative to folks now. It just seems more flexible for the day-to-day devwork. It also has better support for documentation features like this.