DEV Community

Xun Zhou
Xun Zhou

Posted on

Best Practice: Makefile

Output by using "make"
Download My Makefile on GitHub Gist

I use Makefile for most of every my project, both at work and in side-projects.
It let you just create very easily task group in a Makefile, which you can execute them via make command.

My best practices are the following:

Minimal config

I remove all unnecessary definition which might make noise in the Makefile. Now it has just 6 lines to configure and define the templating of my favorite Makefile.

SHELL := /bin/bash

    @grep -E '^[0-9a-zA-Z_-]+:.*?## .*$$|(^#--)' $(MAKEFILE_LIST) \
    | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[32m %-43s\033[0m %s\n", $$1, $$2}' \
    | sed -e 's/\[32m #-- /[33m/'
Enter fullscreen mode Exit fullscreen mode

Help: this code block defines the templating for the task group and its tasks and I used it in every my makefile.

Group your task

With Prefix #--, you are able to define the title of task group. We can organise the relevant tasks in the same task group.

#-- Docker  
Enter fullscreen mode Exit fullscreen mode

this will define a task group with title name Docker

Add task always the a task description

by using prefix ## description of this task, we can add the description to each task.
The following code defines a task group Docker with a single task clean, which triggers four commands to clean up the docker resources.

clean: ## clean up all docker resources
  docker-compose stop
  docker container prune -f
  docker volume prune -f
  docker network prune -f
Enter fullscreen mode Exit fullscreen mode

each command should begin with a Tab, for example, there is always a Tab before the command docker-compose stop.

Simple start

By using make, you can show the list of all defined task groups in Makefile
By using make clean, you can execute the task clean under the task group docker

See the final result in the terminal:
Output by using "make"

Download My Makefile on GitHub Gist

Top comments (1)