Learn About MakeFiles
What are Makefiles
Makefiles are a way for developers to easily build, run and deploy projects without having to remember commands and intricacies that are required to run a program.
Makefiles are made of rules. These rules are run to produce some file or action. A target is usually the name of the output of a rule. However, rules do not always have an output file. In the case where a rule does not have an output file, the target can be thought as the name for what the rule does when run.
Anatomy of a Makefile
# this is the target
run/cmd/api:
# this is the rule
go run cmd/api
Env variables
psql:
psql ${DB_DSN}
up:
@echo 'Running up migrations'
migrate -path ./migrations -database ${DB_DSN} up
@
rule: prevents a command from being echoed itself
Passing Arguments
arguments are referred to the same way as environment variables.
migration:
@echo 'Creating migration files for ${name}...'
migrate create -seq -ext=.sql -dir=./migrations ${name}
Run it with:
make migration name=create_example_table
Namespace
Use namespaces to make intentions clearer.
Example: migration
-> db/migration/new
Prerequisite Targets
You can write targets, called a prerequisite target, that can be run with another target.
confirm:
@echo -n 'Are you sure? [y/N] ' && read ans && [ $${ans:-N} = y ]
db/migrations/up: confirm
@echo 'Running up migrations...'
migrate -path ./migrations -database ${DB_DSN} up
Running make db/migrations/up
will run the confirm
target first before
continueing with db/migrations/up
Phony Target
In general, the target name is supposed to be the filename that is to be generated by the rule. If a target will not be generating a file or if you have filename conflicts, you instead need to delcare it as a phony target. A phony target is is just a name for a rule to be executed.
Example:
.PHONY: confirm
confirm:
@echo -n 'Are you sure? [y/N] ' && read ans && [ $${ans:-N} = y ]
.PHONY: db/migrations/up
db/migrations/up: confirm
@echo 'Running up migrations...'
migrate -path ./migrations -database ${DB_DSN} up
This is important because if someone accidentally creates a file with the same name as one of the targets and then tries to run the rule. That rule would never be executed which could lead to dangerous or destructive rules to be run without confirmation.