loading...
Cover image for Autodocumenting Makefiles
Feldroy

Autodocumenting Makefiles

danielfeldroy profile image Daniel Feldroy ・2 min read

Using Code to Write Books (2 Part Series)

1) Adding Metadata to PDFs 2) 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)

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

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

Very useful!

Using Code to Write Books (2 Part Series)

1) Adding Metadata to PDFs 2) Autodocumenting Makefiles

Posted on Apr 24 by:

danielfeldroy profile

Daniel Feldroy

@danielfeldroy

Engineer and writer. Co-author of Django Crash Course & Two Scoops of Django, Husband of @audreyfeldroy 💘, father of Uma 🍼

Feldroy

The little creative company behind Two Scoops Press, Impossible Hero Books, Fuzzy Rainbow, and an upcoming SaaS product.

Discussion

markdown guide
 

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