Skip to content

Instantly share code, notes, and snippets.

@Pierstoval
Last active March 7, 2024 09:34
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Pierstoval/b2539c387c467c017bf2b0ace5a2e79b to your computer and use it in GitHub Desktop.
Save Pierstoval/b2539c387c467c017bf2b0ace5a2e79b to your computer and use it in GitHub Desktop.
"confirm" action for your Makefile
# To use the "confirm" target inside another target,
# use the " if $(MAKE) -s confirm ; " syntax.
mycommand:
@if $(MAKE) -s confirm ; then \
execute_your_command_here ; \
fi
.PHONY: mycommand
# The CI environment variable can be set to a non-empty string,
# it'll bypass this command that will "return true", as a "yes" answer.
confirm:
@if [[ -z "$(CI)" ]]; then \
REPLY="" ; \
read -p "⚠ Are you sure? [y/n] > " -r ; \
if [[ ! $$REPLY =~ ^[Yy]$$ ]]; then \
printf $(_ERROR) "KO" "Stopping" ; \
exit 1 ; \
else \
printf $(_TITLE) "OK" "Continuing" ; \
exit 0; \
fi \
fi
.PHONY: confirm
_WARN := "\033[33m[%s]\033[0m %s\n" # Yellow text for "printf"
_TITLE := "\033[32m[%s]\033[0m %s\n" # Green text for "printf"
_ERROR := "\033[31m[%s]\033[0m %s\n" # Red text for "printf"
# Notes:
#
# As we're using an "if" statement,
# we need to use ";" and "\" at the end of lines,
# else make would consider each line to be a separate command to call,
# which doesn't work.
# Using ";" and "\" at the end of lines helps make
# interpret this "if" as one single statement/command.
#
# You can replace ";" with "&&" if you need to stop the
# execution process before running next commands.
#
#
@urmichm
Copy link

urmichm commented Jul 17, 2022

Hi,

If anyone is interested, yellow WARNINGS are below:

_WARN := "\033[33m[%s]\033[0m %s\n" # Yellow text for "printf"

_TITLE := "\033[32m[%s]\033[0m %s\n" # Green text for "printf"
_ERROR := "\033[31m[%s]\033[0m %s\n" # Red text for "printf"

@Pierstoval
Copy link
Author

Thanks @urmichm for your suggestion, I added it to the gist! 👍

@AntonioCS
Copy link

You can also do this entirely in make.
Here is what I have:

define util_confirm_code
$(eval confirm := $(shell read -p "⚠ Are you sure? [y/n] > " -r; echo $$REPLY))
$(if $(filter y Y,$(confirm)),1)
endef
#NOTE: We must call this one to remove \n or any other spaces
util_confirm_ask = $(strip $(util_confirm_code))

mycommand:
	$(if $(util_confirm_ask),
		echo "User said yes",
		echo "User said no"
	)

We can remove the middle variable util_confirm_ask by condencing the code in util_confirm_code but it will make it less readable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment