If you need to run a lot of commands to setup your project environment, or/and to run your project, you’ll love the Makefile.
This post will show you how to change this:
$ rm -rf tmp/install/
$ mkdir -p tmp/install/
$ curl https://s3.amazonaws.com/some-file-bin.zip --output tmp/install/install.zip
$ unzip tmp/install/install.zip -d tmp/install/install
To this
make install
What is the Makefile
Makefile is the file script used by make. We can say that it’s a build system. You can use it to improve your scripting or build applications.
It uses bash code and it’s too easy to script.
Basic Example
Create a new file named Makefile
at the root of your project. After that, create the first code.
hello:
echo "Hello World"
When you run
make hello
We can see the output:
You can say that the output log contains the command instruction, it’s not too beautiful. To solve this, just use the @
in the front of the bash commands.
hello:
@echo "Hello World"
Now the output is better.
Applying to your day-by-day
Now you need to find your default commands and separate this in the Makefile.
For example, if you use Tuist in your iOS project to generate the project, you’ll need to run a lot of commands to install it. Let’s create the install
“function”, in Makefile we call this as target:
install:
@brew install carthage
@curl -Ls https://install.tuist.io | bash
@brew install xcbeautify
@tuist dependencies fetch
You’ll only need to run make install
to install your Tuist environment, all developers will install using the same pattern, and if you need to change something in this pattern, just change the Makefile and tell your team to run the command again.
It’s a great tool to use inside the CI too, keeping patterns and automating the scripting.
Calling other target inside a target
Following our example with Tuist, you’ll need to generate the Xcode project…
generate_xcode:
@tuist dependencies fetch
@tuist generate
… and after the project is created, you’ll want to open it.
xcode:
@open MyProject.xcworkspace
You have two options to generate the project and open the project “using only one command”.
Calling multiple targets in the command line
make generate_xcode xcode
Make allows you to call multiple commands separated by space. It’s a good option if you have independent commands that sometimes need to run one after another.
Calling a target inside a target in the Makefile
generate_xcode:
@tuist dependencies fetch
@tuist generate
xcode: generate_xcode
@open MyProject.xcworkspace
Alter the xcode:
target definition put the targets that you want to call before your target code. Then when you call make xcode
the make will run generate_xcode
before and then the xcode
.
I hope you like this post and you’ll improve your project using Makefile. Comment for suggestions and questions.
If you would like to talk with me or keep updated about new articles: