The XCode Run Script Phase
“run script” phase i.e. the phase that runs scripts
Run Script Phase scripts are a useful little feature of Xcode that allow us to write bash scripts (actually, you can run any kind of scripts, e.g. other shells, python, ruby, etc.) to be executed in the build phase. To create a new Run Script, click on your project, then select the Build Phases tab and then add a New Run Script Phase. Xcode lets you specify the path to the shell which should interpret your script. By default, this is the default system shell, which on my system is /bin/sh
.
What makes those Run Script Phase scripts really useful is that they have access to Xcode’s Build Settings and other environmental variables.
One useful Build Setting variable, for instance, is the SRCROOT
variable, the value of which is the directory which contains the source files. Using this Build Setting as a variable in a Run Script Phase script, you could access and manipulate your project files.
A list of available Build Settings can be found here
Example
One application of Run Scripts Build Phase is making //TODO
and //FIXME
comments stand out, which is not supported by Xcode by default.
As Xcode doesn’t offer a way to list all //TODO
or //FIXME
mentions by default we can create a Run Script to be run in the Run Script Phase, displaying the //TODOs
and //FIXMEs
and any other comments we want to stand out as warnings during builds, with the following script:
KEYWORDS="TODO|FIXME|\?\?\?|\!\!\!" find ${SRCROOT} -name "*.swift" -print0 | \ xargs -0 egrep --with-filename --line-number --only-matching "($KEYWORDS).*\$" | \ perl -p -e "s/($KEYWORDS)/ warning: \$1/“
What this script does
- Declare the keywords which we want to be presented as warnings when found in a .swift source file.
- Search the directory containing the source files, denoted by
SRCROOT
, for .swift files. - For each found .swift source file, search for the keywords declared in step 1 and output the line numbers where they were found.
- With perl, format the found lines as warnings.