Finding bundle identifier in XCode project using shell script - ios

A Bundle identifier in Info.plist of an Xcode project could have various forms, for e.g.
com.company.$(PRODUCT_NAME:rfc1034identifier)
$(PRODUCT_BUNDLE_IDENTIFIER)
Someone could design their own product bundle identifier for debug, release etc types of build and write a variable against Bundle identifier, e.g. com.company.$(PRODUCT_NAME:rfc1034identifier).$(someRandomVariable)
I want to write a shell script that just reads the bundle identifier properly.
However, if you only know shell script - I know, how to figure out values of variables in $(), but want a shell script that should give me all such variables in the string and then I will have code to figure out their values, post which I will create string back with the variables replaced with values.
function getBundleIdentifier
{
cfBundleIdentifier=${PRODUCT_BUNDLE_IDENTIFIER}
if [ ${#cfBundleIdentifier} -lt 1 ]; then
SOURCE="rfc1034identifier"
cfBundleIdentifier=$(/usr/libexec/PlistBuddy -c "Print :CFBundleIdentifier" "${PROJECT_DIR}/${INFOPLIST_FILE}")
if echo "$cfBundleIdentifier" | grep -q "$SOURCE"; then
echo `eval echo $cfBundleIdentifier``eval echo ${PRODUCT_NAME:rfc1034identifier}`
else
echo `eval echo $cfBundleIdentifier`
fi
else
echo $cfBundleIdentifier
fi
}
This is what I have written, but it does not cover all the cases.

It's very easy, just run this command:
BUNDLE_ID=`xcodebuild -showBuildSettings | grep PRODUCT_BUNDLE_IDENTIFIER`
echo $BUNDLE_ID

you can use this
xcodebuild -project Myproject.xcodeproj \-showBuildSettings | grep PRODUCT_BUNDLE_IDENTIFIER | awk -F ' = ' '{print $2}'

or just consolidated the non-xcode portion into :
xcodebuild……. |
{m,g}awk '$!NF = $(NF=2*/PRODUCT_BUNDLE_IDENTIFIER/)' FS=' = '

To get get the bundle identifier in a shell script, I found this to be the simplest way:
xcodebuild -showBuildSettings | awk -F ' = ' '/PRODUCT_BUNDLE_IDENTIFIER/ { print $2 }'
If your script works currently in a different path, use -project option:
xcodebuild -project Myproject.xcodeproj -showBuildSettings | awk -F ' = ' '/PRODUCT_BUNDLE_IDENTIFIER/ { print $2 }'

Related

How to read current app version in Xcode 11 with script

Until Xcode 11, I used a script that reads the current app version (for the AppStore) and help me change the LaunchScreen since we can't use swift for that.
sourceFilePath="$PROJECT_DIR/$PROJECT_NAME/App/Base.lproj/LaunchScreen.storyboard"
versionNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "$INFOPLIST_FILE")
buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
sed -i .bak -e "/userLabel=\"APP_VERSION_LABEL\"/s/text=\"[^\"]*\"/text=\"v$versionNumber\"/" "$PROJECT_DIR/$PROJECT_NAME/App/Base.lproj/LaunchScreen.storyboard"
But in Xcode 11 there is a new section inside the project's build settings called Versioning
And CFBundleShortVersionString automatically changed to $(MARKETING_VERSION). Xcode automatically handles that and I don't want to change it manually to an static number and let Xcode do it's work.
So the question is how can I access this new MARKETING_VERSION and set it to my launchScreen label using run script?
Xcode 11/12
In terminal or bash script in your project you can use:
App version
xcodebuild -showBuildSettings | grep MARKETING_VERSION | tr -d 'MARKETING_VERSION =' // will be displayed 1.1.6
Build version
xcodebuild -showBuildSettings | grep CURRENT_PROJECT_VERSION | tr -d 'CURRENT_PROJECT_VERSION =' // will be displayed 7
Or (don't forget to change YouProjectName to your project name):
App version
cat YouProjectName.xcodeproj/project.pbxproj | grep -m1 'MARKETING_VERSION' | cut -d'=' -f2 | tr -d ';' | tr -d ' '
Build version
cat YouProjectName.xcodeproj/project.pbxproj | grep -m1 'CURRENT_PROJECT_VERSION' | cut -d'=' -f2 | tr -d ';' | tr -d ' '
Or slower method (Thx Joshua Kaden):
App version
xcodebuild -project YouProjectName.xcodeproj -showBuildSettings | grep "MARKETING_VERSION" | sed 's/[ ]*MARKETING_VERSION = //'
Build version
xcodebuild -project YouProjectName.xcodeproj -showBuildSettings | grep "CURRENT_PROJECT_VERSION" | sed 's/[ ]*CURRENT_PROJECT_VERSION = //'
Couldn't find right answer on the internet, so I started digging.
Version and build numbers are displayed in ./PROJECTNAME.xcodeproj/project.pbxproj as MARKETING VERSION (MV) and CURRENT PROJECT VERSION (CPV).
I used sed to get the numbers. It finds first occurrence of MV or CPV, removes everything except the number, and returns result. In order for this to work, you need to do 2 things:
navigate to projects root folder
change PROJECTNAME to your project's name
Commands:
version_number=`sed -n '/MARKETING_VERSION/{s/MARKETING_VERSION = //;s/;//;s/^[[:space:]]*//;p;q;}' ./PROJECTNAME.xcodeproj/project.pbxproj`
build_number=`sed -n '/CURRENT_PROJECT_VERSION/{s/CURRENT_PROJECT_VERSION = //;s/;//;s/^[[:space:]]*//;p;q;}' ./PROJECTNAME.xcodeproj/project.pbxproj`
Result:
Note: If you have more targets in your workspace with different version and build numbers, this might or might not work for you, because it stops on first occurrence. In that case, good luck :)
You can use it like any other project variable:
sourceFilePath="$PROJECT_DIR/$PROJECT_NAME/App/Base.lproj/LaunchScreen.storyboard"
versionNumber="$MARKETING_VERSION"
buildNumber="$CURRENT_PROJECT_VERSION"
sed -i .bak -e "/userLabel=\"APP_VERSION_LABEL\"/s/text=\"[^\"]*\"/text=\"v$versionNumber\"/" "$PROJECT_DIR/$PROJECT_NAME/App/Base.lproj/LaunchScreen.storyboard"
I miss here a solution for multiple targets and configurations:
xcodebuild -target <target> -configuration <configuaration> -showBuildSettings | grep -i 'MARKETING_VERSION' | sed 's/[ ]*MARKETING_VERSION = //'
target: the name of the target
configuration: Release, Debug
If you use Bitrise then the following script will save you:
Extracting App Marketing Version
envman add --key=APP_VERSION_NO --value=`sed -n '/MARKETING_VERSION/{s/MARKETING_VERSION = //;s/;//;s/^[[:space:]]*//;p;q;}' ./${PATH_TO_YOUR_PROJECT_XCODEPROJ_FILE}/project.pbxproj`
Extracting App Build Number
Extract the Build Number from xcodeproj file only if you use Apple Generic versioning system otherwise extract the Build Number from the XCode project info.plist file.
Note: The following script extracts the Build Number from the xcodeproj file.
envman add --key=APP_BUILD_NO --value=`sed -n '/CURRENT_PROJECT_VERSION/{s/CURRENT_PROJECT_VERSION = //;s/;//;s/^[[:space:]]*//;p;q;}' ./${PATH_TO_YOUR_PROJECT_XCODEPROJ_FILE}/project.pbxproj`
Printing to console:
envman run bash -c 'echo "App Version: $APP_VERSION_NO"'
envman run bash -c 'echo "App Build No: $APP_BUILD_NO"'
Thanks to the answer by #babac
Most voted answers by now show how to extract the value through sed and further tools in the chain. Thought to provide a (simpler?) solution just through awk.
Just to give a little bit of context, following one-liner shows the culprit row:
xcodebuild -project MyProj/MyProj.xcodeproj -showBuildSettings | awk '/MARKETING_VERSION/ { print }'
# output
MARKETING_VERSION = 0.0.1
Default awk field separator should be the space, and so it's just a matter of extracting the third field (MARKETING_VERSION is first, the equal sign is second):
xcodebuild -project MyProj/MyProj.xcodeproj -showBuildSettings | awk '/MARKETING_VERSION/ { print $3 }'
# output
0.0.1
HTH
How about saving a value to CURRENT_PROJECT_VERSION ? did anyone managed to do this?
I can get the value like
buildNumber=$CURRENT_PROJECT_VERSION
but this doesn't work:
CURRENT_PROJECT_VERSION="" or $CURRENT_PROJECT_VERSION=""
In my case I'm trying to set it to ""
This line doesn't set the CURRENT_PROJECT_VERSION field too
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$appInfoPlist"
If your project is set up to use Apple Generic Versioning then you may use this command:
agvtool what-marketing-version -terse1
More info on how to set up AGV can be found here.
For Node.js: there is xcode package. Example of usage:
const xcode = require('xcode');
const project = xcode.project('ios/PROJECT_NAME.xcodeproj/project.pbxproj').parse(() => {
const config = project.pbxXCBuildConfigurationSection();
const releaseScheme = Object.keys(config).find(key => config[key].name === 'Release');
const version = config[releaseScheme].buildSettings.MARKETING_VERSION;
});
Previously I used the plist package, but with latest xCode changes it became outdated, since I'm not able to extract a version from Info.plist for React Native projects.
I had similar issue and made it work by displaying MARKETING_VERSION itself:
version="$MARKETING_VERSION"
version+=" ("
version+=`/usr/libexec/PlistBuddy -c "Print CFBundleVersion" $SRCROOT/MyApp/Info.plist`
version+=")"
/usr/libexec/PlistBuddy "$SRCROOT/MyApp/Settings.bundle/Root.plist" -c "set PreferenceSpecifiers:1:DefaultValue $version"
I'm developing a framework with this scenario:
A workspace
A framework target
An aggregate target with 2 external scripts:
one for build a fat framework
other for prepare the release framework
The key is that in XCode 11 the aggregate framework script doesn't get run environment variables for other workspace targets so it's impossible to read the $MARKETING_VERSION from my framework target.
So the solution that works for me has been use PlistBuddy specifying the Info.plist result of the framework target build in this way:
FAT_FRAMEWORK="${SRCROOT}/build/${FRAMEWORK_NAME}.framework"
BUILD_NUMBER=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "${FAT_FRAMEWORK}/Info.plist")
VERSION_NUMBER=$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${FAT_FRAMEWORK}/Info.plist")

Xcode 8 add Capabilities from terminal

Have I ability to enable in capabilities Push Notification from bash?
My problem that my builds are using CI.
If I build debug builds with provision, that has app bundle with wildcard *
And I will enable push notification in capabilities debug build will not compile. Because wildcard provision not support Push Notifications
But I need it for release build with normal provision. In this case I need enable push notification in capabilities.
I want to enable it with script if it is real, only for release.
If someone know another approach will be glad to hear.
Will be appreciated for any help.
Thanks
Script I wrote to enable Push Notifications in a Cordova project.
You'll need to modify it to set the DevelopmentTeam to the correct value.
hooks/before_compile/capabilities.sh
#!/bin/sh
# Abort on Error
set -e
APP_NAME=$(sed -e 's/xmlns.*/>/g' config.xml | xmllint --xpath '/widget/name/text()' -)
PROJECT=`find platforms/ios/${APP_NAME} -name project.pbxproj`
# Exit if not required
grep 'TargetAttributes' ${PROJECT} > /dev/null && exit
# Backup
set -x
cp ${PROJECT} ${PROJECT}.orig
# Get ID
ID=`grep -A 1 'Begin PBXNativeTarget section' ${PROJECT} | tail -n 1 | cut -d ' ' -f 1 | tr -d '\t'`
# Inject
sed -i '' -e "/LastUpgradeCheck.*$/a\\
TargetAttributes = {\\
${ID} = {\\
DevelopmentTeam = ABCD1234YZ;\\
SystemCapabilities = {\\
com.apple.Push = {\\
enabled = 1;\\
};\\
};\\
};\\
};" ${PROJECT}
# Compare
diff ${PROJECT}.orig ${PROJECT}

ROS how to find all executables of a package?

I want to ask how to find all the executable names of a package in ROS (Robot Operating System)? For example, find spawn_model in gazebo_ros package. When I inspect the package in my system, it just shows some .xml, .cmake files, without any executables. But I can run it, such as: rosrun gazebo_ros spawn_model.
Thank you!
An easy way to do this is to type: "rosrun name_of_package " and then press tab two times, it should show you all the executables built.
After looking in the bash autocompletion script for rosrun, it looks like the command catkin_find is used to find the location of the executables for a package, and the executables are filtered with a find command.
If you want to create a script to give you a list of the executables follow the instructions below:
Save the following script in a file called rospack-list-executables:
#!/bin/bash
if [[ $# -lt 1 ]]; then
echo "usage: $(basename $0) <pkg_name>"
echo ""
echo " To get a list of all package names use the command"
echo " 'rospack list-names'"
exit
fi
pkgname=${1}
pkgdir="$(catkin_find --first-only --without-underlays --libexec ${pkgname})"
if [[ -n "${pkgdir}" ]]; then
find -L "${pkgdir}" -executable -type f ! -regex ".*/[.].*" ! -regex ".*${pkgdir}\/build\/.*" -print0 | tr '\000' '\n' | sed -e "s/.*\/\(.*\)/\1/g" | sort
else
echo "Cannot find executables for package '${pkgname}'." >&2
exit 1
fi
Then make the rospack-list-executables script executable (chmod +x rospack-list-executables) and place it in a directory that can be found in your $PATH environment variable.
Run the script:
$ rospack-list-executables gazebo_ros
debug
gazebo
gdbrun
gzclient
gzserver
libcommon.sh
perf
spawn_model
You should get the same result that you get when you type the rosrun <pkgname> command and press Tab:
$ rosrun gazebo_ros
debug gazebo gdbrun gzclient gzserver libcommon.sh perf spawn_model
You can check the executables for all packages with the following bash code:
rospack list-names | while read pkgname; do
echo "Executables for package '${pkgname}':";
rospack-list-executables $pkgname; echo "";
done
To enable package autocompletion for your newly created command, type the following:
complete -F _roscomplete rospack-list-executables
If you do not want to have to type the complete command every time you login, you can append it to your .bashrc file:
echo "complete -F _roscomplete rospack-list-executables" >> ~/.bashrc
Now when you type the command rospack-list-executables and press the Tab key, you should get a list of all the available packages to choose from.
catkin_find --first-only --without-underlays --libexec <your package name>)
should give you the folder where the executables are

Using xcodebuild to install application on iPhone

I am working on a shell script that builds and install our xcodeproj directly to the first found and connected iDevice. This is the script
#!/bin/bash
cd ../../cordova/platforms/ios
deviceName=$(ideviceinfo | grep -i DeviceName)
deviceName=${deviceName//DeviceName: /} #This is the device name you set in Settings->General->Info->Name on your iDevice
deviceUdid=$(system_profiler SPUSBDataType | sed -n -e '/iPad/,/Serial/p' -e '/iPhone/,/Serial/p' | grep "Serial Number:" | awk -F ": " '{print $2}')
if [ -n "deviceUdid" ]; then
echo 'Found device "'${deviceName}'" with UUID "'${deviceUdid}'", process...'
xcodeProject=$(ls | grep -i *.xcodeproj)
if [ -n "$xcodeProject" ]; then
echo "Is xCode project dir, start building..."
################### Not working command ###################
eval "xcodebuild -scheme AppScheme -destination 'platform=iOS,id=$deviceUdid' install" #This line is not really working
################### Not working command ################
else
echo "Directory is not an xCode project directory!"
fi
else
echo 'It looks like there is no iDevice connected!'
fi
Everything works, except installing it on my iPhone. I get the correct device name, it looks like as if it finds the device, but I don't see the app on my iPhone. The strange thing is, that everything works well if I install it from xCode.
Does anyone know how to fix this issue?
I use this following commands to build and run my Application in Simulator:
xcodebuild -sdk iphonesimulator8.4 -arch i386 -workspace MyApp.xcworkspace -scheme MyApp install DSTROOT=~/MyApp
xcrun instruments -w "iPhone 5s (8.4 Simulator)"
xcrun simctl install booted ~/MyApp/Applications/MyApp.app
if you want to run in another Simulator try see available simulators with:
xcrun instruments -s

Running iOS UIAutomation as a post-action build script is return as a posix spawn error

I'm entirely new to using bash and Xcode build scripts and so my code is probably a jungle full of errors.
The idea here is to trigger the script below which will scrape the directory that it is saved in for any .js automation scripts. It will then send these scripts to instruments to be run one at a time. I found some nifty code that created time stamped files and so I used that to create a more meaningful storage system.
#!/bin/bash
# This script should run all (currently only one) tests, independently from
# where it is called from (terminal, or Xcode Run Script).
# REQUIREMENTS: This script has to be located in the same folder as all the
# UIAutomation tests. Additionally, a *.tracetemplate file has to be present
# in the same folder. This can be created with Instruments (Save as template...)
# The following variables have to be configured:
#EXECUTABLE="Plans.app"
# Find the test folder (this script has to be located in the same folder).
ROOT="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# Prepare all the required args for instruments.
TEMPLATE=`find $ROOT -name '*.tracetemplate'`
#EXECUTABLE=`find ~/Library/Application\ Support/iPhone\ Simulator | grep "${EXECUTABLE}$"`
echo "$BUILT_PRODUCTS_DIR"
echo "$PRODUCT_NAME"
EXECUTABLE="${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/"
SCRIPTS=`find $ROOT -name '*.js'`
# Prepare traces folder
TRACES="${ROOT}/Traces/`date +%Y-%m-%d_%H-%M-%S`"
mkdir -p "$TRACES"
printf "\n" >> "$ROOT/results.log"
echo `date +%Y-%m-%d_%H-%M-%S` >> "$ROOT/results.log"
# Get the name of the user we should use to run Instruments.
# Currently this is done, by getting the owner of the folder containing this script.
USERNAME=`ls -l "${ROOT}/.." | grep \`basename "$ROOT"\` | awk '{print $3}'`
# Bring simulator window to front. Depending on the localization, the name is different.
osascript -e 'try
tell application "iPhone Simulator" to activate
on error
tell application "iOS Simulator" to activate
end try'
# Prepare an Apple Script that promts for the password.
PASS_SCRIPT="tell application \"System Events\"
activate
display dialog \"Password for user $USER:\" default answer \"\" with hidden answer
text returned of the result
end tell"
# Run all the tests.
for SCRIPT in $SCRIPTS; do
echo -e "\nRunning test script $SCRIPT"
TESTC="sudo -u ${USER} xcrun instruments -l -c -t ${TEMPLATE} ${EXECUTABLE} -e UIARESULTSPATH ${TRACES}/${TRACENAME} -e UIASCRIPT ${SCRIPT} >> ${ROOT}/results.log"
#echo "$COMMAND"
echo "Executing command $TESTC" >> "$ROOT/results.log"
echo "here $TESTC" >> "$ROOT/results.log"
OUTPUT=$(TESTC)
echo $OUTPUT >> "$ROOT/results.log"
echo "Finished logging" >> "$ROOT/results.log"
SCRIPTNAME=`basename "$SCRIPT"`
TRACENAME=`echo "$SCRIPTNAME" | sed 's_\.js$_.trace_g'`
for i in $(ls -A1t $PWD | grep -m 1 '.trace')
do
TRACEFILE="$PWD/$i"
done
if [ -e $TRACEFILE ]; then
mv "$TRACEFILE" "${TRACES}/${TRACENAME}"
fi
if [ `grep " Fail: " results.log | wc -l` -gt 0 ]; then
echo "Test ${SCRIPTNAME} failed. See trace for details."
open "${TRACES}/${TRACENAME}"
exit 1
break
fi
done
rm results.log
A good portion of this was taken from another Stack Overflow answer but because of the repository setup that I'm working with I needed to keep the paths abstract and separate from the root folder of the script. Everything seems to work (although probably not incredibly efficiently) except for the actual xcrun command to launch instruments.
TESTC="sudo -u ${USER} xcrun instruments -l -c -t ${TEMPLATE} ${EXECUTABLE} -e UIARESULTSPATH ${TRACES}/${TRACENAME} -e UIASCRIPT ${SCRIPT} >> ${ROOT}/results.log"
echo "Executing command $TESTC" >> "$ROOT/results.log"
OUTPUT=$(TESTC)
This is turned into the following by whatever black magic Bash runs on:
sudo -u Braains xcrun instruments -l -c -t
/Users/Braains/Documents/Automation/AppName/TestCases/UIAutomationTemplate.tracetemplate
/Users/Braains/Library/Developer/Xcode/DerivedData/AppName-
ekqevowxyipndychtscxwgqkaxdk/Build/Products/Debug-iphoneos/AppName.app/ -e UIARESULTSPATH
/Users/Braains/Documents/Automation/AppName/TestCases/Traces/2014-07-17_16-31-49/ -e
UIASCRIPT /Users/Braains/Documents/Automation/AppName/TestCases/Test-Case_1js
(^ Has inserted line breaks for clarity of the question ^)
The resulting error that I am seeing is:
posix spawn failure; aborting launch (binary ==
/Users/Braains/Library/Developer/Xcode/DerivedData/AppName-
ekqevowxyipndychtscxwgqkaxdk/Build/Products/Debug-iphoneos/AppName.app/AppName).
I have looked all over for a solution to this but I can't find anything because Appium has a similar issue. Unfortunately I don't understand the systems well enough to know how to translate the fixes to Appium to my own code but I imagine it's a similar issue.
I do know that the posix spawn failure is related to threading, but I don't know enough about xcrun to say what's causing the threading issue.
Related info:
- I'm building for the simulator but it'd be great to work on real devices too
- I'm using xCode 5.1.1 and iOS Simulator 7.1
- This script is meant to be run as a build post action script in xCode
- I did get it briefly working once before I broke it and couldn't get it back to the working state. So I think that means all of my permissions are set correctly.
UPDATE: So I've gotten to the root of this problem although I have not found a fix yet. First of all I have no idea what xcrun is for and so I dropped it. Then after playing around I found that my Xcode environment variables are returning the wrong path, probably because of some project setting somewhere. If you copy the Bash command from above but replace Debug-iphoneos with Debug-iphonesimulator the script can be run from the command line and will work as expected.
So for anyone who happens across this the only solution I could find was to hardcode the script for the simulator.
I changed EXECUTABLE="${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/" to be EXECUTABLE="${SYMROOT}/Debug-iphonesimulator/${EXECUTABLE_PATH}". This is obviously not a great solution but it works for now.

Resources