eyeezzi
eyeezzi

Reputation: 635

How do you skip a Make target if a variable is empty?

Consider the following makefile

# If current commit is not part of a PR, the PULL_REQUEST_ID variable will be empty.
PULL_REQUEST_ID := $(shell git ls-remote origin 'pull/*/head' | grep -F -f <(git rev-parse HEAD) | awk -F'/' '{print $3}')

# if PULL_REQUEST_ID is empty, I want 'make deploy-to-staging' to be no-op
.PHONY deploy-to-staging
deploy-to-staging: update-some-files apply-those-files-to-k8s

Upvotes: 0

Views: 791

Answers (2)

raspy
raspy

Reputation: 4261

If all of your actions to deploy are prerequisites of a target, you can conditionally define those prerequisites, i.e.:

$ cat Makefile
ifneq ($(PULL_REQUEST_ID),)
  deploy-to-staging:  update-some-files apply-those-files-to-k8s
endif

.PHONY: deploy-to-staging
deploy-to-staging:

.PHONY: update-some-files
update-some-files:
        echo Updating...

.PHONY: apply-those-files-to-k8s
apply-those-files-to-k8s:
        echo Applying...

Output:

$ make deploy-to-staging
make: Nothing to be done for 'deploy-to-staging'.

$ make deploy-to-staging PULL_REQUEST_ID=foo
echo Updating...
Updating...
echo Applying...
Applying...

Upvotes: 1

chepner
chepner

Reputation: 531055

Use the conditional directive ifneq.

deploy-to-staging: update-some-files apply-those-files-to-k8s
ifneq ($(PULL_REQUEST_ID),'')
        git push ...  # or whatever
else
        echo "Refusing to deploy non-pull-request to staging"
endif

Upvotes: 2

Related Questions