Skip to content

Instantly share code, notes, and snippets.

@maxchuquimia
Created April 28, 2018 07:51
Show Gist options
  • Save maxchuquimia/df2892e8732da00d9d97913e900a4d56 to your computer and use it in GitHub Desktop.
Save maxchuquimia/df2892e8732da00d9d97913e900a4d56 to your computer and use it in GitHub Desktop.
Demo of using Swift in a Run Script phase in Xcode
#!/bin/bash
CONFIG_PASSWORD="BE5D2905-0625-4EBF-BCA2-7F6F5D138425"
REQUIRED_CONFIG_FILE_PATH="${SRCROOT}/YourProject/App/Config/Configurations/Config-${CONFIGURATION}.plist"
CONFIG_OUTPUT_PATH="${SRCROOT}/YourProject/App/Config/Configurations/Config.json"
CONFIG_EXTENSION_OUTPUT_PATH="${SRCROOT}/YourProject/App/Config/Configurations/Config+Extension.swift"
set -e
if [ -z "${CONFIGURATION}" ]
then
echo "CONFIGURATION environment variable is unset"
exit 1 # Never happens
fi
if [ ! -f "${REQUIRED_CONFIG_FILE_PATH}" ]
then
# Safety - otherwise a build may be made with the wrong config file
echo "Missing config file ${REQUIRED_CONFIG_FILE_PATH}"
exit 2
fi
# Use RNCryptor to encrypt the config file, seeing as we'll be using it for decryption later
swift_code() {
cat <<EOF
import Foundation
import RNCryptor
// Get the contents of Config-(SCHEME).plist
let requiredConfigParameters = NSDictionary(contentsOfFile: "$REQUIRED_CONFIG_FILE_PATH")!
let configData = try! JSONSerialization.data(withJSONObject: requiredConfigParameters, options: [])
// Encrypt it
let encrypted = RNCryptor.encrypt(data: configData, withPassword: "$CONFIG_PASSWORD")
let base64String = encrypted.base64EncodedString()
// Base64 it and save it to a file
try! base64String.write(toFile: "$CONFIG_OUTPUT_PATH", atomically: true, encoding: .utf8)
// Generate an extension on Config containing the password
let byteArray = "$CONFIG_PASSWORD".data(using: .utf8)!.map { x in return String(format:"0x%02x, ", x) }.joined()
let configExtension = """
//! This file was generated by a RunScript Build Phase
//! ⚠️ Do not modify or commit ⚠️
extension Config {
static func password() -> String {
let bytes: [UInt8] = [\(byteArray)0x0] // End in 0x0 to avoid reading into random memory
let data = Data(bytes: bytes)
return String(data: data, encoding: .utf8)!
}
}
"""
try! configExtension.write(toFile: "$CONFIG_EXTENSION_OUTPUT_PATH", atomically: true, encoding: .utf8)
EOF
}
# Run the Swift code in swift_code()
echo "$(swift_code)" \
| DEVELOPER_DIR="$DEVELOPER_DIR" \
xcrun --sdk macosx \
"$TOOLCHAIN_DIR/usr/bin/"swift -F "$SRCROOT/Carthage/Build/Mac/" -
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment