Documenting Makefile targets

Posted

Inspired by this post (Autodocumenting Makefiles) on Hacker News. This approach only requires sed. That can be a good thing or a bad thing; sed is pretty widely available, but its availability isn't guaranteed, and flags can vary between implementations.

There is a Make-native way to do this, which is more robust. I like this approach because it's concise, but it's not that much more concise. There's a tradeoff to be made for sure.

.DEFAULT_GOAL := help

.PHONY: help
help: ## Display this help message
	@sed -En 's/^([a-zA-Z]+):.*##(.*)$$/\1: \2/p' $(MAKEFILE_LIST) | sort

.PHONY: foo
foo: ## Do the foo
	foo

.PHONY: bar
bar: ## Do the bar
	bar

undocumented_target:
	exit 1
$ make
bar:  Do the bar
foo:  Do the foo
help:  Display this help message

$ make help
bar:  Do the bar
foo:  Do the foo
help:  Display this help message

See this Stack Overflow post on printing capture groups with sed for more info about the sed call.

The regular expression, piece by piece:

Note that sed has slightly different regex syntax.