DEV Community

Cover image for Autodocumenting Makefiles
Daniel Feldroy for Feldroy

Posted on

Autodocumenting Makefiles

Today was my 6th day of 100 days of code. I was working on the forthcoming Two Scoops of Django 3.x and thanks to my co-worker Fabio I learned something new about Makefiles. This is an expansion on what he provided (I added the output list and sort feature).

Using PYSCRIPT to Print Documentation

I've seen variations of this trick but this is the best version ever. At the top of your Makefile, put in this code:

.DEFAULT_GOAL := help # Sets default action to be help

define PRINT_HELP_PYSCRIPT # start of Python section
import re, sys

output = []
# Loop through the lines in this file
for line in sys.stdin:
    # if the line has a command and a comment start with
    #   two pound signs, add it to the output
    match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line)
    if match:
        target, help = match.groups()
        output.append("%-20s %s" % (target, help))
# Sort the output in alphanumeric order
output.sort()
# Print the help result
print('\n'.join(output))
endef
export PRINT_HELP_PYSCRIPT # End of python section

help:
    @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST)
Enter fullscreen mode Exit fullscreen mode

Next, we added concise docstrings for every Makefile command. Here's what we did for two of the commands:

code:  ## Extracts code for uploading to GitHub
    python extractor.py

rmcode: ## Removes sample code 
    rm -rf code
Enter fullscreen mode Exit fullscreen mode

Notice how each command's docstring starts with two pound signs? The "##"? That's what the auto documenter code needs to find the docstring.

Trying it out!

When I type just make without any arguments, by default that triggers the help function, which runs the Python script at the top of the makefile. What I get is this:

$ make
clean                Cleans up the environment
cleandocker          Cleans up the docker environment
code                 Extracts code for uploading to GitHub
dpdf                 Render PDF in docker
mdeps                Discovers missing LaTeX deps
mint                 Production ebook rendering
print                Renders print version
rmcode               Removes sample code 
short                faster rendering with minimal index check
tiny                 even faster rendering with no index check
Enter fullscreen mode Exit fullscreen mode

Very useful!

Top comments (1)

Collapse
 
autoferrit profile image
Shawn McElroy

I was looking for a good solution last week for this and gave up. This is the best! thanks.