xcodebashunit-testingbuild-settingssensitive-data

How to change Xcode Build Settings environment vars from a Build Phase script?


Is it possible to change Xcode BuildSettings environment variable on a build phase in a script?

The whole idea is the following: I want to publish an open source project with unit tests. My tests require sensitive data like "login" and "password", so I can't hardcode them. I want to pass login through process environment to be able to do something like this:

let login = ProcessInfo().environment["login"]!

I've found the way how to pass a variable from a build settings environment to a tests process: select "Tests" scheme, go to environment variables and add a new value with name "login" and value "$(login)". If I set value for "login" right in the build settings tab – it will be accessible from the ProcessInfo just like I expected.

But what I want is to set "login" from a project's root folder script file "SetupCreds.sh" which is in .gitignore, so it's safe to keep login and password in it. So the idea is:

  1. Add Build Phase script
  2. This script runs "SetupCreds.sh"
  3. "SetupCreds.sh" consist of export lines like export login="MyLogin

If I add echo ${login} in a Build Phase script it tells me that the "login" really has value "MyLogin". But this export does not affect Build Settings environment, only the Build Phase script environment.

How to do exports that override Build Settings environment variables? Or maybe there is another way to do what I want?


Solution

  • I've copied the answer @Vladex mentioned in the comments here so it's more easily readable.

    1. Add the following script phase right after the "Copy Resources" script.
        $file then
        copy_target="${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.xctest/Tests.cfg"
        cp -r $file $copy_target echo "Tests.cfg file copied to
        ${copy_target}" else echo "warning: No Tests.cfg file found. Some
        tests will be ignored." fi 
    
    1. Put "Tests.cfg" to gitignore.
    2. Create "Tests.cfg" file and fill it with sensitive or config-specific values.
    3. In tests use Bundle.for(type(of: self).self) to get "Tests.cfg" url.