forked from getsentry/XcodeBuildMCP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxcode-state-reader.ts
More file actions
331 lines (287 loc) · 9.88 KB
/
Copy pathxcode-state-reader.ts
File metadata and controls
331 lines (287 loc) · 9.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/**
* Xcode IDE State Reader
*
* Reads Xcode's UserInterfaceState.xcuserstate file to extract the currently
* selected scheme and run destination (simulator/device).
*
* This enables XcodeBuildMCP to auto-sync with Xcode's IDE selection when
* running under Xcode's coding agent.
*/
import { dirname, resolve, sep } from 'node:path';
import { log } from './logger.ts';
import { parseXcuserstate } from './nskeyedarchiver-parser.ts';
import type { CommandExecutor } from './execution/index.ts';
export interface XcodeStateResult {
scheme?: string;
simulatorId?: string;
simulatorName?: string;
error?: string;
}
export interface XcodeStateReaderContext {
executor: CommandExecutor;
cwd: string;
/** Optional boundary for parent-directory fallback search (typically workspace root) */
searchRoot?: string;
/** Optional pre-configured workspace path to use directly */
workspacePath?: string;
/** Optional pre-configured project path to use directly */
projectPath?: string;
}
/**
* Finds the UserInterfaceState.xcuserstate file for the workspace/project.
*
* Search order:
* 1. Use configured workspacePath/projectPath if provided
* 2. Search for .xcworkspace/.xcodeproj under cwd
* 3. If none (or to broaden candidates), search direct children of parent directories
* up to searchRoot (workspace boundary)
*
* For each found project:
* - .xcworkspace: <workspace>/xcuserdata/<user>.xcuserdatad/UserInterfaceState.xcuserstate
* - .xcodeproj: <project>/project.xcworkspace/xcuserdata/<user>.xcuserdatad/UserInterfaceState.xcuserstate
*/
function buildFindProjectsCommand(root: string, maxDepth: number): string[] {
return [
'find',
root,
'-maxdepth',
String(maxDepth),
'(',
'-name',
'*.xcworkspace',
'-o',
'-name',
'*.xcodeproj',
')',
'-type',
'd',
];
}
function isPathWithinBoundary(path: string, boundary: string): boolean {
return path === boundary || path.startsWith(`${boundary}${sep}`);
}
function listParentDirectories(startPath: string, boundaryPath: string): string[] {
const parents: string[] = [];
const start = resolve(startPath);
const boundary = resolve(boundaryPath);
if (!isPathWithinBoundary(start, boundary)) {
return parents;
}
let current = start;
while (true) {
const parent = dirname(current);
if (parent === current) {
break;
}
if (!isPathWithinBoundary(parent, boundary)) {
break;
}
parents.push(parent);
if (parent === boundary) {
break;
}
current = parent;
}
return parents;
}
function collectFindPaths(output: string): string[] {
return output
.trim()
.split('\n')
.map((path) => path.trim())
.filter(Boolean);
}
export async function findXcodeStateFile(
ctx: XcodeStateReaderContext,
): Promise<string | undefined> {
const { executor, cwd, searchRoot, workspacePath, projectPath } = ctx;
// Get current username
const userResult = await executor(['whoami'], 'Get username', false);
if (!userResult.success) {
log('warn', `[xcode-state] Failed to get username: ${userResult.error}`);
return undefined;
}
const username = userResult.output.trim();
// If workspacePath or projectPath is configured, use it directly
if (workspacePath || projectPath) {
const basePath = workspacePath ?? projectPath;
const xcuserstatePath = buildXcuserstatePath(basePath!, username);
const testResult = await executor(
['test', '-f', xcuserstatePath],
'Check xcuserstate exists',
false,
);
if (testResult.success) {
log('debug', `[xcode-state] Found xcuserstate from config: ${xcuserstatePath}`);
return xcuserstatePath;
}
log('debug', `[xcode-state] Configured path xcuserstate not found: ${xcuserstatePath}`);
}
const discoveredPaths = new Set<string>();
// Search descendants from cwd with increased depth (projects can be nested deeper).
const descendantsResult = await executor(
buildFindProjectsCommand(cwd, 6),
'Find Xcode project/workspace in cwd descendants',
false,
);
if (descendantsResult.success && descendantsResult.output.trim()) {
for (const path of collectFindPaths(descendantsResult.output)) {
discoveredPaths.add(path);
}
}
// Also search direct children of parent directories to support nested cwd usage.
// Example: cwd=/repo/feature/subdir, project=/repo/App.xcodeproj
// Parent traversal stops at searchRoot (workspace boundary).
const parentSearchBoundary = searchRoot ?? cwd;
for (const parentDir of listParentDirectories(cwd, parentSearchBoundary)) {
const parentResult = await executor(
buildFindProjectsCommand(parentDir, 1),
'Find Xcode project/workspace in parent directory',
false,
);
if (!parentResult.success || !parentResult.output.trim()) {
continue;
}
for (const path of collectFindPaths(parentResult.output)) {
discoveredPaths.add(path);
}
}
if (discoveredPaths.size === 0) {
log(
'debug',
`[xcode-state] No Xcode project/workspace found in ${cwd} (boundary: ${parentSearchBoundary})`,
);
return undefined;
}
const paths = [...discoveredPaths];
// Filter out nested workspaces inside xcodeproj and sort
const filteredPaths = paths
.filter((p) => !p.includes('.xcodeproj/project.xcworkspace'))
.sort((a, b) => {
// Prefer .xcworkspace over .xcodeproj
const aIsWorkspace = a.endsWith('.xcworkspace');
const bIsWorkspace = b.endsWith('.xcworkspace');
if (aIsWorkspace && !bIsWorkspace) return -1;
if (!aIsWorkspace && bIsWorkspace) return 1;
return 0;
});
// Collect all candidate xcuserstate files with their mtimes
const candidates: Array<{ path: string; mtime: number }> = [];
for (const projectPath of filteredPaths) {
const xcuserstatePath = buildXcuserstatePath(projectPath, username);
// Check if file exists and get mtime
const statResult = await executor(
['stat', '-f', '%m', xcuserstatePath],
'Get xcuserstate mtime',
false,
);
if (statResult.success) {
const mtime = parseInt(statResult.output.trim(), 10);
candidates.push({ path: xcuserstatePath, mtime });
}
}
if (candidates.length === 0) {
log('debug', `[xcode-state] No xcuserstate file found for user ${username}`);
return undefined;
}
// If multiple candidates, pick the one with the newest mtime (most recently active)
if (candidates.length > 1) {
candidates.sort((a, b) => b.mtime - a.mtime);
log(
'debug',
`[xcode-state] Found ${candidates.length} xcuserstate files, using newest: ${candidates[0].path}`,
);
}
log('debug', `[xcode-state] Found xcuserstate: ${candidates[0].path}`);
return candidates[0].path;
}
/**
* Builds the path to the xcuserstate file for a given project/workspace path.
*/
function buildXcuserstatePath(projectPath: string, username: string): string {
if (projectPath.endsWith('.xcworkspace')) {
return `${projectPath}/xcuserdata/${username}.xcuserdatad/UserInterfaceState.xcuserstate`;
} else {
// .xcodeproj - look in embedded workspace
return `${projectPath}/project.xcworkspace/xcuserdata/${username}.xcuserdatad/UserInterfaceState.xcuserstate`;
}
}
/**
* Looks up a simulator name by its UUID.
*/
export async function lookupSimulatorName(
ctx: XcodeStateReaderContext,
simulatorId: string,
): Promise<string | undefined> {
const { executor } = ctx;
const result = await executor(
['xcrun', 'simctl', 'list', 'devices', 'available', '--json'],
'List simulators',
false,
);
if (!result.success) {
log('warn', `[xcode-state] Failed to list simulators: ${result.error}`);
return undefined;
}
try {
const data = JSON.parse(result.output) as {
devices: Record<string, Array<{ udid: string; name: string }>>;
};
for (const runtime of Object.values(data.devices)) {
for (const device of runtime) {
if (device.udid === simulatorId) {
return device.name;
}
}
}
} catch (e) {
log('warn', `[xcode-state] Failed to parse simulator list: ${e}`);
}
return undefined;
}
/**
* Reads Xcode's IDE state and extracts the active scheme and simulator.
*
* Uses bplist-parser for robust binary plist parsing of the xcuserstate file,
* navigating the NSKeyedArchiver object graph to extract:
* - ActiveScheme -> IDENameString (scheme name)
* - ActiveRunDestination -> targetDeviceLocation (simulator/device UUID)
*
* @param ctx Context with command executor and working directory
* @returns The extracted Xcode state or an error
*/
export async function readXcodeIdeState(ctx: XcodeStateReaderContext): Promise<XcodeStateResult> {
try {
// Find the xcuserstate file
const xcuserstatePath = await findXcodeStateFile(ctx);
if (!xcuserstatePath) {
return { error: 'No Xcode project/workspace found in working directory' };
}
// Parse the state file using bplist-parser
const state = parseXcuserstate(xcuserstatePath);
const result: XcodeStateResult = {};
if (state.scheme) {
result.scheme = state.scheme;
log('info', `[xcode-state] Detected active scheme: ${state.scheme}`);
}
if (state.simulatorId) {
result.simulatorId = state.simulatorId;
// Look up the simulator name
const name = await lookupSimulatorName(ctx, state.simulatorId);
if (name) {
result.simulatorName = name;
log('info', `[xcode-state] Detected active simulator: ${name} (${state.simulatorId})`);
} else {
log('info', `[xcode-state] Detected active destination: ${state.simulatorId}`);
}
}
if (!result.scheme && !result.simulatorId) {
return { error: 'Could not extract active scheme or destination from Xcode state' };
}
return result;
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
log('warn', `[xcode-state] Failed to read Xcode IDE state: ${message}`);
return { error: message };
}
}