Open Xcode project and set active file from terminal
Opening an Xcode project from the terminal is easy:
open Foo.xcodeproj/
But that just opens the project and resumes its previous state with UserInterfaceState.xcuserstate
- so it just opens to the last active file you edited.
Is there a way to open an Xcode project and specify which file it should open?
What I have tried:
- Editing
.xcuserstate
is a nightmare, don't do it. - Startup
open Foo/Foo.xcodeproj/
, thenopen Foo/Sources/main.swift
, which works for a while, but not always. (If you just generated the project and do so, it will open the project and then open the file in a separate window.)
Any other ideas?
source to share
An Xcode engineer named Mike pointed me to a property on the loaded
Xcode scripting class workspace document
. Having questioned this, we can wait for Xcode to finish loading the project (including loading the editor area) before asking it to open the file. This allows the file to be opened securely in the project window.
Here's the xopen
script I wrote:
#!/bin/bash
shopt -s nullglob
sourceFile="$1"
case "$sourceFile" in
/*) ;;
*) sourceFile="$PWD"/"$sourceFile" ;;
esac
projectDir="$sourceFile"
while [[ $projectDir = */* ]]; do
projectDir="${projectDir%/*}"
candidates=("$projectDir"/*.xcodeproj)
candidate="${candidates[0]}"
if [[ "$candidate" != "" ]]; then
jPath="$candidate"
fi
done
if [[ "$jPath" = "" ]]; then
echo 1>&2 "error: couldn't find .xcodeproj in any parent directory"
exit 1
fi
exec osascript - "$jPath" "$sourceFile" <<EOF
on run argv
set jPath to item 1 of argv
set sourceFile to item 2 of argv
tell app "Xcode"
set wsDoc to (open jPath)
set waitCount to 0
repeat until wsDoc loaded or waitCount ≥ 20
set waitCount to waitCount + 1
delay 1
end repeat
if wsDoc loaded then
open sourceFile
end if
end tell
end run
EOF
This script uses the shell to traverse the directory tree from the source file (given as a command line argument) until it finds the directory containing the Xcode project package. It then passes the project path and source file path to AppleScript. AppleScript asks Xcode to open the project. If Xcode already has a project open, it will just bring the existing project window to the top.
Next, the script will poll Xcode until it says the workspace document is loaded, or until 20 seconds have elapsed.
Finally, if the workspace document is loaded, it asks Xcode to open the source file. Xcode will open the source file in the existing project window editor.
source to share