A simple snippet that allows you to quickly add a 'help' command to a Makefile to show command documentation. Based on the cool snippet at github.com/FalcoSuessgott/golang-cli-template.
To add a help recipe to your makefile, just use the snippet below:
default: help
.PHONY: help
help: # Show help for each of the Makefile recipes.
@grep -E '^[a-zA-Z0-9 -]+:.*#' Makefile | sort | while read -r l; do printf "\033[1;32m$$(echo $$l | cut -f 1 -d':')\033[00m:$$(echo $$l | cut -f 2- -d'#')\n"; done
.PHONY: test
test: # Lint and test the code.
@./test.sh
.PHONY: build
build: # Build the code.
npm installNow just run make or make help to show a list of the makefile commands and the documentation that is in the comment after each recipe line.
To add documentation to your recipes, just add a comment after the name of the recipe, like so:
build: # This comment will be used as the documentation for the 'build' recipe.Run the ./test.sh command to asset that the help recipes render the expected output.
This snippet was inspired by the makefile I saw at github.com/FalcoSuessgott/golang-cli-template, the direct link to the Makefile is here.
The help recipe I have built is a bit less efficient thank the one in the repo above, but I think is a little easier to reason about. Essentially the code does this:
grep -E '^[a-zA-Z0-9 -]+:.*#' $(MAKEFILE_LIST)- find all lines that look like recipes with commentssort- sort the recipe lines alphabeticallywhile read -r l- read each lineprintf "\033[1;32m$$(echo $$l | cut -f 1 -d':')\033[00m:$$(echo $$l | cut -f 2- -d'#')\n"- extract the recipe name then comment usingcutand print the results with colour
The original version of the code uses awk, which leads to a slightly shorter command - I have included both in the ./Makefile file, you can choose the one you prefer.
Thanks to FalcoSuessgott for the original source and inspiration!
This is quick and dirty list of potential improvements that could be added.
- A better comparison for tests could show where the differences are.
- A regex bash version (using
BASH_REMATCH)