Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Makefile: run the same command with different arguments on different targets

Tags:

makefile

Code

Consider the following makefile snippet:

COMMIT := $(shell git rev-parse HEAD)

build:
    docker build -f Dockerfile --no-cache=false -t $(COMMIT) .
rebuild:
    docker build -f Dockerfile --no-cache=true  -t $(COMMIT) .

The problem

The only difference between build and rebuild is the value of the --no-cache parameter. Obviously, rewriting the same command with a slight change is a bad practice; it breaks the DRY principle, and if I ever need to change something else in the command - for example, the value of -t - I would have to change it across all relevant targets.

I had something like this in mind:

COMMIT := $(shell git rev-parse HEAD)
NO_CACHE := false

build:
    docker build -f Dockerfile --no-cache=$(NO_CACHE) -t $(COMMIT) .
rebuild:
    NO-CACHE = true
    make build

I tried playing with the variables, with no luck.

My question

What would be an elegant way to write the docker build command once, and have each target alter its parameter?

like image 931
Adam Matan Avatar asked Dec 07 '22 18:12

Adam Matan


1 Answers

You can use constructed variable names:

COMMIT := $(shell git rev-parse HEAD)

build_NOCACHE   = false
rebuild_NOCACHE = true

build rebuild:
        docker build -f Dockerfile --no-cache=$($@_NOCACHE) -t $(COMMIT) .

Or you can use target-specific variables:

COMMIT := $(shell git rev-parse HEAD)

build:   NOCACHE = false
rebuild: NOCACHE = true

build rebuild:
        docker build -f Dockerfile --no-cache=$(NOCACHE) -t $(COMMIT) .
like image 56
MadScientist Avatar answered Jan 21 '23 20:01

MadScientist