xcode4: reliably detect the DerivedData directory of a project/workspace - xcode

Xcode 4 builds everything into $HOME/Library/Developer/Xcode/DerivedData/$PROJECT-$UUID, where $UUID is a seemingly random string (it's not really random, it just looks random).
How can I reliably detect the $PROJECT-$UUID part of the above? I've seen a script (https://gist.github.com/949831) that guesses by assuming it is the last modified directory in DerivedData -- but that's not true if my CI machine is building a few projects in parallel.

Nobody answered, so I kept looking for ideas until I found the one below, which satisfies my needs. It can be further modified to be even safer.
In Xcode, add a run-script build phase to the target (the main target, if building a few for the same project).
In the script, put this line:
ln -sf "$BUILD_DIR" BuildDir
Now, when the target is built a symlink to the project's DerivedData directory will be created in the project directory.
If desirable, you can also/instead create BuildDir as a file who's content is the $BUILD_DIR:
echo "$BUILD_DIR" > BuildDir
Then in a script use $(cat BuildDir) to retrieve it.

Related

Xcode 10 fails to copy file generated by target dependency

I have one target A that just runs a script and generates a bunch of files (localization files via twine). Other targets that copy these localization files have a target dependency on A so that they don't run before the files are generated.
Somehow, this doesn't work. Even though the files are all generated successfully, and I see that the copy files phases are running later, the files aren't found.
Also this only fails when I do a clean build. On the second build, the generated files already exist and the copies complete successfully.
For example, my script runs this:
bundle exec twine generate-all-localization-files Strings/ExtensionStrings.txt MyExtension/Resources --format apple --create-folders --tags ios
find /Users/me/proj/myapp -name Localizable.strings
I see it output /Users/me/proj/myapp/MyExtension/Resources/zh-Hans.lproj/Localizable.strings early on in the build process, then later on I see this:
builtin-copyStrings --validate --outputencoding binary --outdir /Users/me/Library/Developer/Xcode/DerivedData/myapp-adfoisdfnasdao/Build/Products/Debug-iphonesimulator/MyExtension.appex/zh-Hans.lproj -- /Users/me/proj/myapp/MyExtension/Resources/zh-Hans.lproj/Localizable.strings
error: Build input file cannot be found: '/Users/me/proj/myapp/MyExtension/Resources/zh-Hans.lproj/Localizable.strings'
And again, if I build a second time it works. What the heck is going on? I'm guessing this has something to do with Xcode 10's parallel builds but I thought that putting the generation/copy in separate targets with a dependency between them would solve that problem.

How can I dynamically set my app's build number without dirtying my source tree?

I'm using git-svn and I'm trying to embed my revision number into my iOS app. At the moment, I have a build phase which runs the following script:
SVN_REVISION=$(git svn find-rev HEAD)
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $SVN_REVISION" "$INFOPLIST_FILE"
The problem with this is that, since the repo always contains the previous revision, the script always makes my Info.plist dirty.
Is it possible for me to dynamically set my app's build number without dirtying my source tree?
1) Add a new target to your project of type "Aggregate", e.g. you may name it "Update Info.plist Prefix Header"; just use that as "Product Name" in the dialog.
2) Add a Run Script build phase to this new target with the following source code:
#!/bin/sh
SVN_REVISION=$(git svn find-rev HEAD)
echo "#define SVN_REVISION $SVN_REVISION" > "$SCRIPT_OUTPUT_FILE_0"
3) Add an output file to your script, name it
$(CONFIGURATION_TEMP_DIR)/InfoPlist.pch
4) Open the Build Phases of your iOS app.
5) Add the aggregate target you created before as dependent target (add it to "Target Dependencies"). This means Xcode will always first build this target before it will build your iOS target.
6) Open the Build Settings of your iOS app.
7) Search for the setting "Info.plist Preprocessor Prefix File" and change it to exactly the same value you used for the output file in step (3).
8) Search for the setting "Preprocess Info.plist File" and make sure it is enabled.
9) Open your current Info.plist file and change the value of CFBundleVersion to SVN_REVISION. Do not use $(SVN_REVISION) or ${SVN_REVISION}; this is no build setting or environment variable replacement, this is a preprocessor replacement, so just use SVN_REVISION.
That's it. Each time you build your iOS app, Xcode first builds the aggregate target, which updates the PCH file, and when it builds your iOS app, it will run the Info.plist file through the C pre-processor (using the PCH file as prefix header) before copying it to your application. The pre-processor will replace SVN_REVISION since it is defined as a macro in your PCH file.
Important Notes
Some people may think it is a better idea to use $(DERIVED_FILE_DIR) instead of $(CONFIGURATION_TEMP_DIR). Well, in theory they are right, yet there is just one problem in practice: The derived file dir is different for every target, while the configuration temp dir is the same (it is only different for every build configuration). When using derived file dir, the PCH file is written to the derived file dir of the aggregate target, yet when building the iOS app, Xcode will search for this file in the derived file dir of the iOS app and thus it won't find the file.
Some people may also think it is a better idea to just add the Run Script phase that updates the prefix header as the first build phase of you iOS app instead of creating a separated target for it (this would also resolve the derived file dir issue mentioned above). Again, nice idea in theory but cannot work in practice: If preprocessing is requested, the Info.plist is preprocessed before the first script phase is even executed, so if the PCH file does not exist already or has not been updated already, either the build terminates with an error or an outdated SVN revision is written to the plist file. That's why you need a separate target for this task that is guaranteed to be build before your actual target is.
Mecki thank you for the excellent answer! I applied the same concept to set a version timestamp and the current git SHA for the build.
FYI I just ran into a small issue. It seems that, at least in Xcode 5, if you specify an output file the script step uses it as a cache, so no matter the changes I made to my actual app code the script reported that it had ran but the values were not the current ones...
I had to move the output file declaration to the script itself to solve the issue, i.e. added
SCRIPT_OUTPUT_FILE_0="$CONFIGURATION_TEMP_DIR/InfoPlist.pch"
to the top of my script.
Additionally the original plist should also be touched in order for the build step to copy the new values in, so I also added
`touch $SCRIPT_INPUT_FILE_0`
after the previous output file declaration. This touch operation does not make git detect the change as commit-able.
Cheers

How can I conditionally include a file based on build configuration in Xcode?

I have an Xcode project with a large number of targets where I would like to include a settings bundle for apps built under the Ad-hoc and Debug configurations, but not under the Release configuration.
Build Phases don't seem to allow for making themselves conditional on configuration (they can obviously be conditional on target, but doubling the number of targets in the project would make it completely unusable).
That leaves writing a custom Build Rule. My plan is to exclude the Settings.bundle from all targets, and create a build rule that conditionally copies it into the product package, but applicable examples are really hard to find.
The build rule I've started has the Process setting set to "Source files with names matching:" and Settings.bundle as the name. The Using setting is "Custom script:".
My custom script is as follows (with the caveat that my bash scripting is on a cargo cult level):
if [${CONFIGURATION} = 'Debug'] then
cp -r ${INPUT_FILE_PATH} ${DERIVED_FILES_DIR}/.
fi
Finally, I have ${DERIVED_FILES_DIR}/Settings.bundle listed as an output file.
Since I'm here, it should be obvious that it's not working. My first question is whether there is somewhere I can view the output of the build rules as the execute to make sure that 1) it's actually being executed and that 2) I don't have a stupid syntax error somewhere.
Also, what's the proper location (in the form of an environment variable) to copy the output to?
I finally figured it out.
For each target for which you want to conditionally include the settings bundle, choose its Project from the source list, choose the target, and switch to the "Build Phases" tab.
Click the "Add Build Phase" button and choose "Add Run Script".
Then enter the following for the script:
if [ "${CONFIGURATION}" == "Debug" ]; then
cp -r "${PROJECT_DIR}/Settings.bundle" "${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app"
fi
I know this question has been answered already, and the answer was very helpful to me, but I wanted to throw my own modified solution out there as well.
My requirement was to have different settings bundles for different build configurations, rather than just not including it at release. Assuming a simplistic approach of only Debug and Release configurations, here's how to do it:
Start by adding 2 settings bundles to the project, named Settings-debug.bundle and Settings-release.bundle and then remove these files from the Copy Bundle Resources build phase. Next add a user defined build setting called SETTINGS_BUNDLE, which has different values for each configuration:
Debug ${PROJECT_DIR}/relative/path/to/Settings-debug.bundle
Release ${PROJECT_DIR}/relative/path/to/Settings-release.bundle
Next add a run-script build phase (after Copy Bundle Resources) named Copy Settings Bundle with a modified version of the script in Frank's solution.
cp -r "${SETTINGS_BUNDLE}/" "${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/Settings.bundle"
The difference here is that the copied bundle is always named Settings.bundle regardless of the source name.
You then need to add another build phase script to prevent code signing errors when the only changes are in the settings bundles. It forces the code signing step to occur on every build. This should run before the Compile Source Files build phase. I called mine Force Codesign.
touch "${PROJECT_DIR}/relative/path/to/main.m"
For complied sources, there is a poorly documented user defined build setting that can be added. Files can be both excluded and included from compilation
Go to your target's Build Settings > Tap the + button > Add User-Defined Setting
The key is either INCLUDED_SOURCE_FILE_NAMES or EXCLUDED_SOURCE_FILE_NAMES
The value is a space separated list of file paths
See reference:
http://lists.apple.com/archives/xcode-users/2009/Jun/msg00153.html
(Tested with Xcode 9.3)
I can't find when Xcode included this feature but EXCLUDED_SOURCE_FILE_NAMES is now directly available in Build Settings > Build Options > Excluded Source File Names.
So you no longer need to create a User-Defined Setting.
See below:
It will automatically add this line in your .pbxproj.
Settings.bundle is always copied into destination area no matter whether Release or Debug configuration. So, maybe you need the following code:
if [ ${CONFIGURATION} == "Release" ]; then
rm -rf ${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/Settings.bundle
fi
I am no shell script expert but I think you need space between the square brackets and the condition. Also, quoting the variables may help:
if [ "${CONFIGURATION}" = "Debug" ] then
cp -r "${INPUT_FILE_PATH}" "${DERIVED_FILES_DIR}"/.
fi
As for the location, I use "$BUILT_PRODUCTS_DIR"/"$FULL_PRODUCT_NAME" for the root of my OS X app bundle.

Xcode - build phase or script for copying only modified files to App Bundle

Mac OS X 10.5 compatibility required. Xcode 3.2.5.
My app looks in the bundle's Resources folder, for a "data" folder.
"data" contains a hierarchy of subfolders and data. The contents are constantly being modified.
I don't need to navigate or modify this data within Xcode.
Q. When building, how can I copy "data" (say, from the Xcode project's folder) to the Resources folder, but only copying those files within "data" that have been modified since the last build?
(Simply copying all files every time I build is not feasible; the file sizes are too large, slowing build times.)
Thanks for any help.
Shouldn't be a problem to use rsync in a shell script build phase. Something like this:
rsync -a "${SRCROOT}/data" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
That does a bit more than date comparison but it should still be quite a bit faster than what you're doing now.
The above doesn't delete any files you removed from the source directory; to do so, you can add --delete but I'd only suggest doing that after you're sure it's working properly.

Xcode: Running a script before every build that modifies source code directly

What I did:
I have a script that
Read some configuration files to generate source code snippets
Find relevant Objective-C source files and
Replace some portions of the source code with the generated code in step 1.
and a Makefile that has a special timestamp file as a make target and the configuration files as target sources:
SRC = $(shell find ../config -iname "*.txt")
STAMP = $(PROJECT_TEMP_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME).stamp
$(STAMP): $(SRC)
python inject.py
touch $(STAMP)
I added this Makefile as a "Run Script Build Phase" on top of the stack of build phases for the project target.
What happened:
The script build phase was run before compiling the source.
However, since the script modifies source code during its execution, I needed to build twice to get the most recent version of the build product. Here is what I imagine to be happening:
1st run: Xcode collects dependency information ---> no changes
1st run: Xcode runs "Run Script Build Phase" ---> source is changed behind Xcode's back
1st run: Xcode finishes build, thinking nothing needs to be updated
2nd run: Xcode collects dependency information ---> source has changed, needs rebuild!
2nd run: Xcode runs Run Script Build Phase" ---> everything is up-to-date
2nd run: Xcode proceeds to compilation
After reading Xcode documentation on Build Phases, I tried adding a source file which is known to be updated every time the script is run as the output of "Run Script Build Phases", but nothing changed. Since the number of configuration files may vary in my project, I don't want to specify every input and output file.
Question:
How do I make Xcode aware of source file changes made during "Run Script Build Phase"?
Edit:
Added that I placed the script build phase before the other build phases
Every technique mentioned so far is an overkill. Reproducing steve kim's comment for visibility:
In the build phases tab, simply drag the "Run Script" step to a higher location (e.g. before "Compile Sources").
Tested on Xcode 6
This solution is probably outdated. See the higher voted answer instead; I no longer actively use Xcode and am not qualified to vet a solution.
Use "External Target":
Select "Project" > "New Target..." from the menu
Select "Mac OS X" > "Other" > "External Target" and add it to your project
Open its settings and fill in your script setup
Open the "General" tab of the main target's settings and add the new target as it's direct dependency
Now the new "External Target" runs before the main target even starts gathering dependency information, so that any changes made during the script execution should be included in the build.
There is another, slightly simpler option that doesn't require a separate target, but it's only viable if your script tends to modify the same source files every time.
First, here's a brief explanation for anyone who's confused about why Xcode sometimes requires you to build twice (or do a clean build) to see certain changes reflected in your target app. Xcode compiles a source file if the object file it produces is missing, or if the object file's last-modified date is earlier than the source file's last-modified date was at the beginning of the first build phase. If your project runs a script that modifies a source file in a pre-compilation build phase, Xcode won't notice that the source file's last-modified date has changed, so it won't bother to recompile it. It's only when you build the project a second time that Xcode will notice the date change and recompile the file.
Here's a simple solution if your script happens to modify the same source files every time. Just add a Run Script build phase at the end of your build process like this:
touch Classes/FirstModifiedFile.m Classes/SecondModifiedFile.m
exit $?
Running touch on these source files at the end of your build process guarantees that they will always have a later last-modified date than their object files, so Xcode will recompile them every time.
As of Xcode 4, it looks like if you add the generated files to the output section of the build phase, it will respect that setting, and not generate the ... has been modified since the precompiled header was built error messages.
This is a good option if your script is only generating a handful of files each time.
I as well struggled with this for a long time. The answer is to use ento's "External Target" solution. He is WHY this problem occurs and how we use it in practice...
Xcode 4 build steps do not execute until AFTER the plist has been compiled. This is silly, of course, because it means that any pre-build steps that modify the plist won't take effect. But if you think about it, they actually DO take effect...on the NEXT build. That's why some people have talked about "caching" of plist values or "I have to do 2 builds to make it work." What happens is the plist is built, then your script runs. Next time you build, the plist builds using your modified files, hence the second build.
ento's solution is the one way I've found to actually do a true pre-build step. Unfortunately I also found that it does not cause the plist to update without a clean build and I fixed that. Here is how we have data-driven user values in the plist:
Add an External Build System project that points to a python script and passes some arguments
Add user-defined build settings to the build. These are the arguments that you pass to python (more on why we do this later)
The python script reads some input JSON files and builds a plist preprocessor header file AND touches the main app plist
The main project has "preprocess plist files" turned on and points to this preprocessor file
Using touch on the main app plist file causes the main target to generate the plist every time. The reason we pass in build settings as parameters is so our command-line build can override settings:
Add a user-defined variable "foo" to the prebuild project.
In your prebuild you can use $(foo) to pass the value into the python script.
On the command-line you can add foo=test to pass in a new value.
The python script uses base settings files and allows for user-defined settings files to override the defaults. You make a change and immediately it ends up in the plist. We only use this for settings that MUST be in the plist. For anything else it's a waste of effort....generate a json file or something similar instead and load it at run-time :)
I hope this helps...it's been a couple rough days figuring this out.
The External Target solution from #ento no longer works as of Xcode 11.5. The solution is to add all files that will be changed under Output Files in the Run Script.
Another option is to create a subproject framework with your scripts and just add it as a dependency to all targets. The phase scripts of this subproject should now be executed before all targets.

Resources