Self-documenting Make files

How to create a help target in the .make file to automatically generate a list of key targets provided by this Makefile?

You can find full example of complete Makefile used in the following examples in my docker-compose repository.

Provide descriptions for each make target in format:

target: ## description

for example:

build: ## Build the environment
    @docker-compose build --build-arg uid=$(UID) --build-arg gid=$(GID)
.PHONY: build

Groups targets into sections using double # sign:

## environment

Define help target, which would scan the whole make file, extract all targets and their desciptions, and build the help screen:

help:
    @awk 'BEGIN {FS = ":.*##"; \
    printf "\033[32mMakefile\033[0m version \033[33m%s\033[0m\n \
    \n\033[33mUsage:\033[0m\n  make <target>\n\n\033[33mAvailable targets:\033[0m\n", $(VERSION) } \
    /^[a-zA-Z_-]+:.*?##/ { printf "  \033[32m%-20s\033[0m %s\n", $$1, $$2 } \
    /^##/ { printf "\033[33m%s\033[0m\n", substr($$0, 3) } ' $(MAKEFILE_LIST)
.PHONY: help

Final result will look something like:

You can also mark help target as default goal, so that executing just make will print help as well:

.DEFAULT_GOAL := help