Makefile:在不同的目标上运行带有不同参数的同一命令 [英] Makefile: run the same command with different arguments on different targets

查看:107
本文介绍了Makefile:在不同的目标上运行带有不同参数的同一命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下makefile代码段:

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) .

问题

buildrebuild之间的唯一区别是--no-cache参数的值.显然,只需稍作更改就可以重写同一命令,这是一种不好的做法.它违反了DRY原理,如果我需要在命令中进行其他更改(例如-t的值),则必须在所有相关目标之间进行更改.

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.

我有这样的想法:

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.

一次编写docker build命令并让每个目标更改其参数的优美方法是什么?

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

推荐答案

您可以使用构造的变量名称:

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

build_NOCACHE   = false
rebuild_NOCACHE = true

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

或者您可以使用目标特定的变量:

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

build:   NOCACHE = false
rebuild: NOCACHE = true

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

这篇关于Makefile:在不同的目标上运行带有不同参数的同一命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆