Xcode build script: Change value in non-compiled file between Debug and Release.

I have a file that contains lines of text. One of those lines should to have a different value between Debug and Release. The file is not handled by the C preprocessor.

I am accomplishing this with an Xcode build script. If you know of something better, please tell me.

Here is the file and its contents.

I want the string "Production" for thing1 to be replaced with "Debug" during development. In my particular situation, if the script fails, it is better that the release value is used during development instead of the debug value escaping into the app store. Therefore, I use the "Production" string as the default value.

Look at Project | Target | Build Phases | Copy Bundle Sources.

I create a new build phase after this one. Select + button (tooltip: Add New Build Phase tool) | New Run Script Phase.

Put the Run Script after Copy Bundle Resources.

The next step unfortunately involves intimate knowledge of shell syntax. To create your own scripts to do different things, you will also be digging around in the Build Setting Reference doc.

Here is the script that does my task relatively safely.

I doubt anyone wants to cut and paste that, but just in case:

if [ "$CONFIGURATION" == "Debug" ]; then
    if [ -f $f2 ]; then
        sed -i "" -e '/thing1:/s/Production/Debug/' "$f2"
        echo "File not found: $f2"
    echo "CONFIGURATION is not Debug. Not updating $f1."

I like the echoes in that script because they help to debug it by looking at the build logs.

Here is my Terminal output to test that my changes worked.

$ pwd
$ ls -l
total 72
drwxr-xr-x  6 jeff  staff    204 Feb  8 10:11 Base.lproj
-rw-r--r--  1 jeff  staff    920 Feb  8 10:11 Info.plist
-rwxr-xr-x  1 jeff  staff  21240 Feb  8 10:11 Pen1
-rw-r--r--  1 jeff  staff      8 Feb  8 10:11 PkgInfo
-rw-r--r--  1 jeff  staff     67 Feb  8 10:11 Statham.notJson
$ cat Statham.notJson 
# Whatever file.
    thing0: 76
    thing1: "Debug"
oddItem: tulip

Of course, my build settings were Debug at the time. Here is my scheme to prove it.

Let's make sure the changes do not happen if we are building for Release. I update my scheme and build again. The first thing I notice is a difference in the build logs.

That looks good, but let's check for real, but be sure I'm in the right directory when I look.

$ pwd
$ ls -l
total 0
drwxr-xr-x  4 jeff  staff  136 Feb  7 16:16 Debug-iphoneos
drwxr-xr-x  7 jeff  staff  238 Feb  8 10:11 Debug-iphonesimulator
drwxr-xr-x  6 jeff  staff  204 Feb  8 10:26 Release-iphonesimulator
$ cat Release-iphonesimulator/Pen1.app/Statham.notJson 
# Whatever file.
    thing0: 76
    thing1: "Production"
oddItem: tulip

It worked!

Now, who can spot the (fairly harmless) defect in my shell script?

No comments:

Post a Comment