External build scripts in iOS

Alfredo Luco G
3 min readJun 16, 2021
Photo by 贝莉儿 DANIST on Unsplash

After seeing WWDC21, apple introduce a talk of going dive in build settings. In that talk they talk about how to make some build rules for ci, archive, build and tests. In this paper I will show you how to make a custom build script within a bash script.

Generally, a bash script is a sh script that follows some instruction in your macOS system such as commit some changes, upgrade your build number or simply set some warnings. This script can be easily run in your build phases as a run script, but it would be some uncomfortable to write a very big script inside a little box.

The build script

The build script must be written in bash/shell script because this is the language that your compiler follows, so take a look with the following script:

#!/bin/bash# Define GITGIT="$(which git)"# Check if git is availableif [ ! -x "${GIT}" -o -z "${GIT}" ]thenexitfi# Last commit dateCOMMIT=$(${GIT} show --pretty=format:%ai | head -n 1)# Split the dateDATECOMMITS=(${COMMIT// / })# get the last dateLAST=$(date -j -f '%F' "${DATECOMMITS[0]}" "+%s")# Now dateNOW="$(date +%s)"
# DifferenceDIFF=`expr $NOW - $LAST`# check if there's changesif [[ -n $(${GIT} status -s) ]];then# check if the last commit happen more than a dayif [ $DIFF -gt 86400 -o $DIFF -eq 86400 ];thenecho "error: You must commit your changes!"exit 1fiecho "hay cambios"fi

This script simply follows these instructions; (i) check your last commit date, (ii) compare this date with your current date (iii) if there’s changes and the time’s difference is greater than or equal to a day (86400 seconds) it will be an error.

To write that script in XCode you must put an empty new file with sh extension.

Implement the script in your build

Photo by Wes Hicks on Unsplash

First of all we must create a new target called external build system. That target just make some adjustment in order to run this script. So go to file>new target>External Build System:

When you create that target you must specify the script path that you want to run, so go to that target and in the info tab you must set the build tool with:

${PROJECT_DIR}/script.sh

Now you forget something, the script shouldn’t work if you don’t give some permissions so go ahead with your terminal and run:

sudo chmod +x script.sh

Manage your scheme with your script

Photo by Sam Moqadam on Unsplash

You’re almost ready to implement your custom git checker script, but you must implement in your scheme system as a part of your compiler, so go ahead to manage your scheme (press your app on the left side of your simulator name and press edit scheme). Now you must add your git checker in every build status (analyze, test, run, profile and of course archive):

Now when you build your app you will see your custom error message:

And that it! Happy Coding

Written by: Alfredo Luco

Github: https://github.com/aluco100

--

--