Reputation: 1013
The following works as intended:
branch := $(shell git rev-parse --abbrev-ref HEAD)
ifeq ($(branch), master)
ami_regions = us-west-2
endif
show_regions:
echo $(ami_regions)
How could this ifeq
statement be written as a one-liner, where the variable is set if the condition passes, otherwise sets the variable as another value or simply leaves it unset?
Upvotes: 8
Views: 6897
Reputation: 137
A general one-liner if
$(if $(strip $(subst $(a),,$(b))),false-command,true-command)
For your case you can do this:
$(if $(strip $(subst $(branch),,master)),,$(eval ami_regions = us-west-2))
Upvotes: 0
Reputation: 1431
That should be possible. Try from chapter 8.4 one conditional in combination with string search from chapter 8.2 of the manual:
branch := $(shell git rev-parse --abbrev-ref HEAD)
ami_regions = $(if $(findstring master,$(branch)),us-west-2,)
show_regions:
echo $(ami_regions)
The function $if
will return the value from the then branch if $findstring
returns anything. $findstring
will return master
if $(branch)
contains the string master
. The downside is that this will also match something like master-tests
.
To make this match exactly master you will have to rely on bash: $(shell if [ master = $(branch) ]; then echo "true"; fi )
. But then you also have to take care that $(branch)
does not contain shell code with side effects (usually not).
Renaud Pacalet and MadScientist in the comments have given improvements to the use of $findstring
: Use $filter
or $patsubst
. As the string you are searching isn't a pattern, using simple $subst
instead of $patsubst
is also possible.
$(if $(patsubst master,,$(branch)),,us-west-2)
Notice that us-west-2
moved to the else branch, as $patsubst/subst
replace the found string with the empty string leading to a false condition if the substitution is successful.
$(if $(filter master,$(branch)),us-west-2,)
$filter
returns words from the input that match the supplied patter. Because the pattern is a single word, in this case it only returns exact matches.
So basically both alternatives give similar results. Differences arise if $branch
contains spaces: Spaces between removed words will be returned by $patsubst
, while $filter
only returns matches. Git doesn't allow branches with spaces, this case should not occur.
Upvotes: 9
Reputation: 311606
You could do it all in your $(shell ...)
expression:
region := $(shell test `git rev-parse --abbrev-ref HEAD` = master && echo us-west-2)
all:
echo $(region)
Upvotes: 2