xcodebug 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/GUIDE.md +213 -0
- package/LICENSE +21 -0
- package/README.md +449 -2
- package/archive.ts +164 -0
- package/capture.ts +327 -0
- package/changes.ts +368 -0
- package/devices.ts +278 -0
- package/exec.ts +122 -0
- package/index.ts +2274 -0
- package/package.json +52 -4
- package/progress.ts +171 -0
- package/xcode.ts +220 -0
package/changes.ts
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local-change detection for a CocoaPods iOS project.
|
|
3
|
+
*
|
|
4
|
+
* Two decisions matter before a device run:
|
|
5
|
+
* 1. Did any build-relevant source change since the last run? -> rebuild.
|
|
6
|
+
* 2. Did a *new* file land inside a pod? -> `pod install` first, because the
|
|
7
|
+
* generated Pods project enumerates pod sources and will not compile a
|
|
8
|
+
* file it has never seen.
|
|
9
|
+
*
|
|
10
|
+
* Pod membership is derived from the repo's own podspecs (`source_files`
|
|
11
|
+
* globs), so it follows whatever layout the podspec declares.
|
|
12
|
+
*/
|
|
13
|
+
import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
14
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
15
|
+
import { runCommand } from "./exec";
|
|
16
|
+
|
|
17
|
+
const SOURCE_EXTENSIONS = new Set([
|
|
18
|
+
".swift", ".h", ".m", ".mm", ".c", ".cc", ".cpp", ".metal",
|
|
19
|
+
".storyboard", ".xib", ".strings", ".stringsdict", ".plist", ".json",
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
/** Paths that never imply a rebuild of app or pod code. */
|
|
23
|
+
const IGNORED_SEGMENTS = ["/Pods/", "/build/", "/.build/", "/DerivedData/", "/Carthage/", "/.git/"];
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Config directories the engine ships under, i.e. agent state that may live
|
|
27
|
+
* inside a repo and must never look like app code.
|
|
28
|
+
*
|
|
29
|
+
* The engine's own resolver keeps this same set (`KNOWN_BRAND_CONFIG_DIRS`) for
|
|
30
|
+
* the same reason; xcodebug is a generic pi extension, so it cannot assume the
|
|
31
|
+
* one brand it happens to run under.
|
|
32
|
+
*/
|
|
33
|
+
const AGENT_STATE_DIRS = [".pi", ".omp", ".omo", ".senpi"];
|
|
34
|
+
|
|
35
|
+
export interface ChangedFile {
|
|
36
|
+
/** Two-letter porcelain status: " M", "M ", "??", "A ", "D ". */
|
|
37
|
+
status: string;
|
|
38
|
+
path: string;
|
|
39
|
+
untracked: boolean;
|
|
40
|
+
deleted: boolean;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface PodEntry {
|
|
44
|
+
pod: string;
|
|
45
|
+
podspec: string;
|
|
46
|
+
globs: RegExp[];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface ChangeReport {
|
|
50
|
+
repoRoot: string;
|
|
51
|
+
/** True when git could not report (no repo, no git binary). */
|
|
52
|
+
unavailable: boolean;
|
|
53
|
+
reason?: string;
|
|
54
|
+
changed: ChangedFile[];
|
|
55
|
+
/** New (untracked or added) files that belong to a pod. */
|
|
56
|
+
newComponentFiles: Array<ChangedFile & { pods: string[] }>;
|
|
57
|
+
/** Pods whose file list changed and therefore need `pod install`. */
|
|
58
|
+
podsNeedingInstall: string[];
|
|
59
|
+
/** Stable hash of the relevant change set; equal hashes mean "no change since". */
|
|
60
|
+
fingerprint: string;
|
|
61
|
+
needsBuild: boolean;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function isRelevant(path: string): boolean {
|
|
65
|
+
const normalized = `/${path.replace(/\\/g, "/")}`;
|
|
66
|
+
if (IGNORED_SEGMENTS.some((segment) => normalized.includes(segment))) return false;
|
|
67
|
+
// Agent state is not app source: a session file or skill under a config dir
|
|
68
|
+
// must not trigger a device build.
|
|
69
|
+
if (AGENT_STATE_DIRS.some((dir) => normalized.includes(`/${dir}/`))) return false;
|
|
70
|
+
const lower = path.toLowerCase();
|
|
71
|
+
if (lower.endsWith("podfile") || lower.endsWith("podfile.lock") || lower.endsWith(".podspec")) return true;
|
|
72
|
+
if (lower.includes(".xcodeproj/") || lower.includes(".xcworkspace/")) return true;
|
|
73
|
+
const dot = lower.lastIndexOf(".");
|
|
74
|
+
return dot >= 0 && SOURCE_EXTENSIONS.has(lower.slice(dot));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Expand one glob (braces, **, *) into a RegExp over repo-relative paths. */
|
|
78
|
+
export function globToRegExp(glob: string): RegExp {
|
|
79
|
+
const alternatives: string[] = [];
|
|
80
|
+
const brace = /\{([^{}]*)\}/.exec(glob);
|
|
81
|
+
if (brace) {
|
|
82
|
+
for (const option of brace[1].split(",")) {
|
|
83
|
+
alternatives.push(glob.slice(0, brace.index) + option.trim() + glob.slice(brace.index + brace[0].length));
|
|
84
|
+
}
|
|
85
|
+
} else {
|
|
86
|
+
alternatives.push(glob);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const source = alternatives
|
|
90
|
+
.map((pattern) => {
|
|
91
|
+
let out = "";
|
|
92
|
+
for (let i = 0; i < pattern.length; i += 1) {
|
|
93
|
+
const char = pattern[i];
|
|
94
|
+
if (char === "*") {
|
|
95
|
+
if (pattern[i + 1] === "*") {
|
|
96
|
+
i += 1;
|
|
97
|
+
if (pattern[i + 1] === "/") i += 1;
|
|
98
|
+
out += "(?:.*/)?";
|
|
99
|
+
} else {
|
|
100
|
+
out += "[^/]*";
|
|
101
|
+
}
|
|
102
|
+
} else if (char === "?") {
|
|
103
|
+
out += "[^/]";
|
|
104
|
+
} else {
|
|
105
|
+
out += char.replace(/[.+^$`{}()|[\]\\]/g, "\\$&");
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
})
|
|
110
|
+
.join("|");
|
|
111
|
+
|
|
112
|
+
return new RegExp(`^(?:${source})$`);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function readPodspec(podspecPath: string): Promise<{ name?: string; globs: string[] }> {
|
|
116
|
+
let content = "";
|
|
117
|
+
try {
|
|
118
|
+
content = await readFile(podspecPath, "utf8");
|
|
119
|
+
} catch {
|
|
120
|
+
return { globs: [] };
|
|
121
|
+
}
|
|
122
|
+
const nameMatch = /(?:spec|s)\.name\s*=\s*["']([^"']+)["']/.exec(content);
|
|
123
|
+
const globs: string[] = [];
|
|
124
|
+
// source_files may be assigned per subspec; collect every occurrence.
|
|
125
|
+
for (const match of content.matchAll(/source_files\s*=\s*\[?\s*([^\n\]]+)/g)) {
|
|
126
|
+
for (const literal of match[1].matchAll(/["']([^"']+)["']/g)) {
|
|
127
|
+
globs.push(literal[1]);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return { name: nameMatch?.[1], globs };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function loadPods(repoRoot: string): Promise<PodEntry[]> {
|
|
134
|
+
let entries: import("node:fs").Dirent[];
|
|
135
|
+
try {
|
|
136
|
+
entries = await readdir(repoRoot, { withFileTypes: true });
|
|
137
|
+
} catch {
|
|
138
|
+
return [];
|
|
139
|
+
}
|
|
140
|
+
const pods: PodEntry[] = [];
|
|
141
|
+
for (const entry of entries) {
|
|
142
|
+
if (!entry.isFile() || !entry.name.endsWith(".podspec")) continue;
|
|
143
|
+
const podspecPath = join(repoRoot, entry.name);
|
|
144
|
+
const { name, globs } = await readPodspec(podspecPath);
|
|
145
|
+
if (!name || globs.length === 0) continue;
|
|
146
|
+
pods.push({ pod: name, podspec: relative(repoRoot, podspecPath), globs: globs.map(globToRegExp) });
|
|
147
|
+
}
|
|
148
|
+
return pods;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function podsForPath(path: string, pods: PodEntry[]): string[] {
|
|
152
|
+
return pods.filter((pod) => pod.globs.some((pattern) => pattern.test(path))).map((pod) => pod.pod);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Fingerprint one changed file by content identity, not just by path.
|
|
157
|
+
*
|
|
158
|
+
* `git status` keeps reporting the same path after a second edit, so hashing
|
|
159
|
+
* paths alone would silently skip a rebuild. mtime + size changes on every
|
|
160
|
+
* write and costs one stat per changed file.
|
|
161
|
+
*/
|
|
162
|
+
async function fileSignature(repoRoot: string, file: ChangedFile): Promise<string> {
|
|
163
|
+
if (file.deleted) return `${file.status}:${file.path}:deleted`;
|
|
164
|
+
try {
|
|
165
|
+
const info = await stat(join(repoRoot, file.path));
|
|
166
|
+
return `${file.status}:${file.path}:${info.mtimeMs}:${info.size}`;
|
|
167
|
+
} catch {
|
|
168
|
+
return `${file.status}:${file.path}:missing`;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function hashString(value: string): string {
|
|
173
|
+
let hash = 0x811c9dc5;
|
|
174
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
175
|
+
hash ^= value.charCodeAt(i);
|
|
176
|
+
hash = Math.imul(hash, 0x01000193) >>> 0;
|
|
177
|
+
}
|
|
178
|
+
return hash.toString(16).padStart(8, "0");
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function readGitStatus(repoRoot: string): Promise<{ ok: boolean; lines: string[]; reason?: string }> {
|
|
182
|
+
const result = await runCommand(
|
|
183
|
+
"git",
|
|
184
|
+
[
|
|
185
|
+
"status", "--porcelain", "-uall", "--", ".",
|
|
186
|
+
// Same brand set as isRelevant: keeping one list means the pathspec and the
|
|
187
|
+
// filter cannot disagree about which directories are agent state.
|
|
188
|
+
...AGENT_STATE_DIRS.flatMap((dir) => [`:!${dir}`, `:!*/${dir}`]),
|
|
189
|
+
],
|
|
190
|
+
{ cwd: repoRoot, timeoutMs: 60_000, maxBytes: 8_000_000 },
|
|
191
|
+
);
|
|
192
|
+
if (result.code !== 0) {
|
|
193
|
+
return { ok: false, lines: [], reason: (result.stderr || result.stdout).trim().slice(0, 300) };
|
|
194
|
+
}
|
|
195
|
+
return { ok: true, lines: result.stdout.split("\n").filter((line) => line.trim().length > 0) };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Is `Pods/Manifest.lock` out of step with `Podfile.lock`?
|
|
200
|
+
*
|
|
201
|
+
* CocoaPods writes a copy of the resolved lock into the Pods directory during
|
|
202
|
+
* `pod install`. When the two differ, the Pods project was generated from a
|
|
203
|
+
* different dependency set and every target's "[CP] Check Pods Manifest.lock"
|
|
204
|
+
* phase fails the build with "The sandbox is not in sync with the Podfile.lock".
|
|
205
|
+
* The user cannot act on that from a build log, so the gate runs `pod install`
|
|
206
|
+
* before building.
|
|
207
|
+
*
|
|
208
|
+
* The check is anchored to the Xcode container, not to the caller's cwd: the
|
|
209
|
+
* Podfile that governs a workspace lives beside it. Walking up from a nested
|
|
210
|
+
* cwd could land on an unrelated project's Podfile and run `pod install` in the
|
|
211
|
+
* wrong place.
|
|
212
|
+
*
|
|
213
|
+
* Returns undefined when the container's directory has no Podfile - the caller
|
|
214
|
+
* then skips `pod install` instead of guessing.
|
|
215
|
+
*/
|
|
216
|
+
export async function checkPodLockSync(
|
|
217
|
+
containerPath: string,
|
|
218
|
+
): Promise<{ synced: boolean; podfileDir: string; reason: string } | undefined> {
|
|
219
|
+
const dir = dirname(resolve(containerPath));
|
|
220
|
+
try {
|
|
221
|
+
await stat(join(dir, "Podfile"));
|
|
222
|
+
} catch {
|
|
223
|
+
return undefined;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const lockPath = join(dir, "Podfile.lock");
|
|
227
|
+
const manifestPath = join(dir, "Pods", "Manifest.lock");
|
|
228
|
+
let lock: string;
|
|
229
|
+
try {
|
|
230
|
+
lock = await readFile(lockPath, "utf8");
|
|
231
|
+
} catch {
|
|
232
|
+
// No resolved lock yet: pod install has never run here.
|
|
233
|
+
return { synced: false, podfileDir: dir, reason: "Podfile.lock is missing" };
|
|
234
|
+
}
|
|
235
|
+
let manifest: string;
|
|
236
|
+
try {
|
|
237
|
+
manifest = await readFile(manifestPath, "utf8");
|
|
238
|
+
} catch {
|
|
239
|
+
return { synced: false, podfileDir: dir, reason: "Pods/Manifest.lock is missing (pod install has not run)" };
|
|
240
|
+
}
|
|
241
|
+
if (lock === manifest) return { synced: true, podfileDir: dir, reason: "Podfile.lock matches Pods/Manifest.lock" };
|
|
242
|
+
return { synced: false, podfileDir: dir, reason: "Podfile.lock differs from Pods/Manifest.lock" };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export async function detectChanges(cwd: string): Promise<ChangeReport> {
|
|
246
|
+
const root = await runCommand("git", ["rev-parse", "--show-toplevel"], { cwd, timeoutMs: 30_000 });
|
|
247
|
+
if (root.code !== 0) {
|
|
248
|
+
return {
|
|
249
|
+
repoRoot: cwd,
|
|
250
|
+
unavailable: true,
|
|
251
|
+
reason: "not a git repository",
|
|
252
|
+
changed: [],
|
|
253
|
+
newComponentFiles: [],
|
|
254
|
+
podsNeedingInstall: [],
|
|
255
|
+
fingerprint: "no-git",
|
|
256
|
+
needsBuild: true,
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
const repoRoot = root.stdout.trim();
|
|
260
|
+
const status = await readGitStatus(repoRoot);
|
|
261
|
+
if (!status.ok) {
|
|
262
|
+
return {
|
|
263
|
+
repoRoot,
|
|
264
|
+
unavailable: true,
|
|
265
|
+
reason: status.reason ?? "git status failed",
|
|
266
|
+
changed: [],
|
|
267
|
+
newComponentFiles: [],
|
|
268
|
+
podsNeedingInstall: [],
|
|
269
|
+
fingerprint: "no-git-status",
|
|
270
|
+
needsBuild: true,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const changed: ChangedFile[] = [];
|
|
275
|
+
for (const line of status.lines) {
|
|
276
|
+
const statusCode = line.slice(0, 2);
|
|
277
|
+
let path = line.slice(3).trim();
|
|
278
|
+
// Renames are reported as "old -> new"; the new path is what matters.
|
|
279
|
+
const arrow = path.indexOf(" -> ");
|
|
280
|
+
if (arrow >= 0) path = path.slice(arrow + 4);
|
|
281
|
+
path = path.replace(/^"|"$/g, "");
|
|
282
|
+
if (!isRelevant(path)) continue;
|
|
283
|
+
changed.push({
|
|
284
|
+
status: statusCode,
|
|
285
|
+
path,
|
|
286
|
+
untracked: statusCode === "??",
|
|
287
|
+
deleted: statusCode.includes("D"),
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const pods = await loadPods(repoRoot);
|
|
292
|
+
const newComponentFiles: Array<ChangedFile & { pods: string[] }> = [];
|
|
293
|
+
const podsNeedingInstall = new Set<string>();
|
|
294
|
+
for (const file of changed) {
|
|
295
|
+
if (file.deleted) continue;
|
|
296
|
+
const isNew = file.untracked || file.status.includes("A");
|
|
297
|
+
if (!isNew) continue;
|
|
298
|
+
const matched = podsForPath(file.path, pods);
|
|
299
|
+
if (matched.length === 0) continue;
|
|
300
|
+
newComponentFiles.push({ ...file, pods: matched });
|
|
301
|
+
for (const pod of matched) podsNeedingInstall.add(pod);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const signatures = await Promise.all(changed.map((file) => fileSignature(repoRoot, file)));
|
|
305
|
+
const fingerprint = hashString(signatures.sort().join("\n"));
|
|
306
|
+
|
|
307
|
+
return {
|
|
308
|
+
repoRoot,
|
|
309
|
+
unavailable: false,
|
|
310
|
+
changed,
|
|
311
|
+
newComponentFiles,
|
|
312
|
+
podsNeedingInstall: [...podsNeedingInstall].sort(),
|
|
313
|
+
fingerprint,
|
|
314
|
+
needsBuild: changed.length > 0,
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export interface PodInstallOutcome {
|
|
319
|
+
ok: boolean;
|
|
320
|
+
message: string;
|
|
321
|
+
logFile: string;
|
|
322
|
+
durationMs: number;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export async function runPodInstall(
|
|
326
|
+
podfileDir: string,
|
|
327
|
+
options: { timeoutMs: number; signal?: AbortSignal; logFile: string },
|
|
328
|
+
): Promise<PodInstallOutcome> {
|
|
329
|
+
const started = Date.now();
|
|
330
|
+
const result = await runCommand("pod", ["install", "--no-repo-update"], {
|
|
331
|
+
cwd: podfileDir,
|
|
332
|
+
timeoutMs: options.timeoutMs,
|
|
333
|
+
maxBytes: 12_000_000,
|
|
334
|
+
signal: options.signal,
|
|
335
|
+
});
|
|
336
|
+
const durationMs = Date.now() - started;
|
|
337
|
+
const output = `$ pod install --no-repo-update (cwd ${podfileDir})\n\n${result.stdout}\n${result.stderr}`;
|
|
338
|
+
// The log directory is created lazily by whatever wrote a log first; pod
|
|
339
|
+
// install can be the very first thing a run does, so ensure it here.
|
|
340
|
+
await mkdir(dirname(options.logFile), { recursive: true });
|
|
341
|
+
await writeFile(options.logFile, output);
|
|
342
|
+
const ok = result.code === 0;
|
|
343
|
+
return {
|
|
344
|
+
ok,
|
|
345
|
+
durationMs,
|
|
346
|
+
logFile: options.logFile,
|
|
347
|
+
message: ok
|
|
348
|
+
? `pod install succeeded in ${(durationMs / 1000).toFixed(1)}s`
|
|
349
|
+
: `pod install failed (exit ${result.code})\n${output.trim().split("\n").slice(-25).join("\n")}`,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** A short human summary of a change report for tool output. */
|
|
354
|
+
export function describeChanges(report: ChangeReport): string {
|
|
355
|
+
if (report.unavailable) {
|
|
356
|
+
return `change detection unavailable (${report.reason ?? "unknown"}); assuming a rebuild is needed`;
|
|
357
|
+
}
|
|
358
|
+
if (report.changed.length === 0) return "no build-relevant changes";
|
|
359
|
+
const lines = [`${report.changed.length} build-relevant change(s)`];
|
|
360
|
+
for (const file of report.changed.slice(0, 15)) {
|
|
361
|
+
lines.push(` ${file.status} ${file.path}`);
|
|
362
|
+
}
|
|
363
|
+
if (report.changed.length > 15) lines.push(` … and ${report.changed.length - 15} more`);
|
|
364
|
+
if (report.podsNeedingInstall.length > 0) {
|
|
365
|
+
lines.push(`new component files -> pod install required: ${report.podsNeedingInstall.join(", ")}`);
|
|
366
|
+
}
|
|
367
|
+
return lines.join("\n");
|
|
368
|
+
}
|
package/devices.ts
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Device discovery and process lookup through `xcrun devicectl`.
|
|
3
|
+
*
|
|
4
|
+
* devicectl accepts a uuid, ecid, serial number, udid, name or DNS name, so
|
|
5
|
+
* every identifier we keep is accepted verbatim by later commands.
|
|
6
|
+
*/
|
|
7
|
+
import { asRecord, asString, runCommand } from "./exec";
|
|
8
|
+
|
|
9
|
+
export interface DeviceInfo {
|
|
10
|
+
/** CoreDevice identifier (uuid) — accepted by devicectl. */
|
|
11
|
+
id: string;
|
|
12
|
+
/** Hardware UDID — required by xcodebuild destinations and idevicesyslog. */
|
|
13
|
+
udid?: string;
|
|
14
|
+
name: string;
|
|
15
|
+
model?: string;
|
|
16
|
+
os?: string;
|
|
17
|
+
state: string;
|
|
18
|
+
physical: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* How the device is attached: `wired` for USB, `network` for Wi-Fi.
|
|
21
|
+
*
|
|
22
|
+
* This tool's console bridge is a USB-speed firehose, and a Wi-Fi drop shows
|
|
23
|
+
* up mid-run as `WebSocket connection closed`, which reads exactly like an app
|
|
24
|
+
* crash. Surfacing the transport lets that be diagnosed instead of guessed at.
|
|
25
|
+
*/
|
|
26
|
+
transport?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function describeDevices(devices: DeviceInfo[]): string {
|
|
30
|
+
if (devices.length === 0) return "(no devices reported by devicectl)";
|
|
31
|
+
return devices
|
|
32
|
+
.map((device) => {
|
|
33
|
+
const kind = device.physical ? "physical" : "simulated";
|
|
34
|
+
const os = device.os ? ` · iOS ${device.os}` : "";
|
|
35
|
+
// Name the transport: a Wi-Fi-only device produces mid-run disconnects
|
|
36
|
+
// that look like app crashes, and the fix (plug in USB) is invisible
|
|
37
|
+
// unless the attachment is reported.
|
|
38
|
+
const link = device.transport ? ` · ${device.transport}` : "";
|
|
39
|
+
return `- ${device.name} [${device.state}] ${kind}${os}${link} · udid=${device.udid ?? "?"}`;
|
|
40
|
+
})
|
|
41
|
+
.join("\n");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function toDevice(raw: unknown): DeviceInfo | undefined {
|
|
45
|
+
const entry = asRecord(raw);
|
|
46
|
+
const properties = asRecord(entry.properties);
|
|
47
|
+
const hardware = asRecord(properties.hardware ?? entry.hardwareProperties);
|
|
48
|
+
const connection = asRecord(properties.connection ?? entry.connectionProperties);
|
|
49
|
+
const state = asRecord(properties.state ?? entry.deviceProperties);
|
|
50
|
+
const software = asRecord(properties.software);
|
|
51
|
+
const id = asString(entry.identifier);
|
|
52
|
+
if (!id) return undefined;
|
|
53
|
+
return {
|
|
54
|
+
id,
|
|
55
|
+
udid: asString(hardware.udid),
|
|
56
|
+
name: asString(state.name) ?? asString(hardware.marketingName) ?? id,
|
|
57
|
+
model: asString(hardware.marketingName),
|
|
58
|
+
os: asString(asRecord(software.osVersionNumber).stringValue) ?? asString(state.osVersionNumber),
|
|
59
|
+
state: asString(connection.state) ?? asString(connection.tunnelState) ?? "unknown",
|
|
60
|
+
physical: asString(hardware.reality) === "physical",
|
|
61
|
+
transport: asString(connection.transportType),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function listDevices(): Promise<DeviceInfo[]> {
|
|
66
|
+
const result = await runCommand("xcrun", ["devicectl", "list", "devices", "--json-output", "-"], {
|
|
67
|
+
timeoutMs: 45_000,
|
|
68
|
+
});
|
|
69
|
+
if (result.code !== 0) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
`devicectl list devices failed (exit ${result.code}): ${(result.stderr || result.stdout).trim().slice(0, 600)}`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
let parsed: unknown;
|
|
75
|
+
try {
|
|
76
|
+
parsed = JSON.parse(result.stdout);
|
|
77
|
+
} catch {
|
|
78
|
+
throw new Error("devicectl returned invalid JSON for the device list");
|
|
79
|
+
}
|
|
80
|
+
const devices = asRecord(asRecord(parsed).result).devices;
|
|
81
|
+
if (!Array.isArray(devices)) return [];
|
|
82
|
+
return devices
|
|
83
|
+
.map(toDevice)
|
|
84
|
+
.filter((device): device is DeviceInfo => device !== undefined);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface DeviceResolution {
|
|
88
|
+
device: DeviceInfo;
|
|
89
|
+
devices: DeviceInfo[];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function resolveDevice(selector?: string): Promise<DeviceResolution> {
|
|
93
|
+
const devices = await listDevices();
|
|
94
|
+
/**
|
|
95
|
+
* USB only, by policy.
|
|
96
|
+
*
|
|
97
|
+
* `devicectl list` reports the CoreDevice tunnel, which is lazy: a wired
|
|
98
|
+
* device that has not been spoken to yet reads `disconnected` even though it
|
|
99
|
+
* is plugged in and healthy, while a Wi-Fi device can read `connected` and
|
|
100
|
+
* then drop mid-run. Neither state is trustworthy on its own, so the
|
|
101
|
+
* transport decides: only `wired` is accepted, and an ambiguous device is
|
|
102
|
+
* probed once to bring its tunnel up before giving up.
|
|
103
|
+
*/
|
|
104
|
+
const isUsb = (device: DeviceInfo): boolean => device.transport === "wired";
|
|
105
|
+
const wifi = (device: DeviceInfo): boolean => device.transport === "network";
|
|
106
|
+
|
|
107
|
+
if (selector && selector.trim().length > 0) {
|
|
108
|
+
const wanted = selector.trim().toLowerCase();
|
|
109
|
+
const identifiers = (device: DeviceInfo): string[] =>
|
|
110
|
+
[device.id, device.udid, device.name]
|
|
111
|
+
.filter((value): value is string => Boolean(value))
|
|
112
|
+
.map((value) => value.toLowerCase());
|
|
113
|
+
const exact = devices.find((device) => identifiers(device).includes(wanted));
|
|
114
|
+
const partial = devices.find((device) => identifiers(device).some((value) => value.includes(wanted)));
|
|
115
|
+
const match = exact ?? partial;
|
|
116
|
+
if (!match) {
|
|
117
|
+
throw new Error(`No device matches "${selector}".\n${describeDevices(devices)}`);
|
|
118
|
+
}
|
|
119
|
+
if (!match.physical) {
|
|
120
|
+
throw new Error(
|
|
121
|
+
`${match.name} is a simulator. xcodebug only targets physical hardware: the build destination is ` +
|
|
122
|
+
`platform=iOS,id=<udid> and the console bridge is devicectl, neither of which a simulator can provide.\n` +
|
|
123
|
+
describeDevices(devices),
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
if (wifi(match)) {
|
|
127
|
+
throw new Error(
|
|
128
|
+
`${match.name} is attached over Wi-Fi (transport=network). xcodebug needs USB: a wireless link drops ` +
|
|
129
|
+
`mid-run and the console bridge reports it as "WebSocket connection closed", which looks like a crash. ` +
|
|
130
|
+
`Connect the cable and retry.\n${describeDevices(devices)}`,
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
return { device: match, devices };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Only USB-attached hardware, in either tunnel state: a wired device whose
|
|
137
|
+
// tunnel is idle is still the right target and will come up when used.
|
|
138
|
+
const candidates = devices.filter((device) => device.physical && !wifi(device));
|
|
139
|
+
const ready = candidates.filter((device) => device.state === "connected");
|
|
140
|
+
if (ready.length === 1) return { device: ready[0], devices };
|
|
141
|
+
if (ready.length > 1) {
|
|
142
|
+
throw new Error(
|
|
143
|
+
`Multiple physical devices are connected; pass device: <name|udid>.\n${describeDevices(ready)}`,
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Nothing reports `connected`. A wired device is almost always just asleep
|
|
148
|
+
// from CoreDevice's point of view - one direct query opens the tunnel - so
|
|
149
|
+
// probe before declaring the device absent.
|
|
150
|
+
const wired = candidates.find(isUsb) ?? candidates[0];
|
|
151
|
+
if (wired) {
|
|
152
|
+
const probed = await probeDevice(wired);
|
|
153
|
+
const refreshed = await listDevices();
|
|
154
|
+
const nowReady = refreshed.filter((device) => device.physical && !wifi(device) && device.state === "connected");
|
|
155
|
+
if (nowReady.length >= 1) {
|
|
156
|
+
const picked = nowReady.find((device) => device.udid === wired.udid) ?? nowReady[0]!;
|
|
157
|
+
return { device: picked, devices: refreshed };
|
|
158
|
+
}
|
|
159
|
+
// The probe answered, so devicectl can still address this device even
|
|
160
|
+
// though `list` keeps calling the tunnel idle. Using it is better than
|
|
161
|
+
// failing a run that would have worked. A probe that failed says nothing
|
|
162
|
+
// about the device, so it must not be read as "present".
|
|
163
|
+
if (probed) return { device: wired, devices: refreshed };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// xcodebug only ever targets real hardware: the build destination is
|
|
167
|
+
// platform=iOS,id=<udid> and the console bridge is devicectl. Saying so
|
|
168
|
+
// explicitly stops the user waiting for a simulator that will never open.
|
|
169
|
+
const simulators = devices.filter((device) => !device.physical).length;
|
|
170
|
+
const hint = simulators > 0
|
|
171
|
+
? `\n${simulators} simulator(s) were reported and ignored - a simulator cannot provide device logs.`
|
|
172
|
+
: "";
|
|
173
|
+
throw new Error(
|
|
174
|
+
`No USB-connected physical iOS device. Plug in the cable, trust the device, then retry.` +
|
|
175
|
+
`\n(xcodebug never falls back to Wi-Fi or the simulator.)${hint}\n${describeDevices(devices)}`,
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Bring a device's CoreDevice tunnel up by asking it one question.
|
|
181
|
+
*
|
|
182
|
+
* `devicectl list` only reports the tunnel that already exists; a freshly
|
|
183
|
+
* plugged-in phone often reads `disconnected` until something addresses it by
|
|
184
|
+
* identifier. `device info details` does exactly that and is read-only, so the
|
|
185
|
+
* probe cannot disturb a run.
|
|
186
|
+
*/
|
|
187
|
+
async function probeDevice(device: DeviceInfo): Promise<boolean> {
|
|
188
|
+
const target = device.udid ?? device.id;
|
|
189
|
+
const result = await runCommand(
|
|
190
|
+
"xcrun",
|
|
191
|
+
["devicectl", "device", "info", "details", "--device", target],
|
|
192
|
+
{ timeoutMs: 45_000 },
|
|
193
|
+
);
|
|
194
|
+
return result.code === 0;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Best-effort pid lookup so `status` can name the running process.
|
|
199
|
+
*
|
|
200
|
+
* devicectl's process listing occasionally answers without the app (it can be
|
|
201
|
+
* queried while the launch is still settling), so retry briefly before
|
|
202
|
+
* concluding the process is absent.
|
|
203
|
+
*/
|
|
204
|
+
/**
|
|
205
|
+
* Look up a running app's pid on the device.
|
|
206
|
+
*
|
|
207
|
+
* "The app is gone" and "I could not ask" must not be conflated: a verification
|
|
208
|
+
* capture only ends when the app really exited, and a flaky USB/`devicectl`
|
|
209
|
+
* probe would otherwise be mistaken for an exit and stop the capture for good.
|
|
210
|
+
* `pid` is set only on a successful lookup; `queryFailed` marks the inconclusive
|
|
211
|
+
* case where the process table could not be read at all.
|
|
212
|
+
*/
|
|
213
|
+
export interface ProcessLookup {
|
|
214
|
+
pid?: number;
|
|
215
|
+
/** True when the process table could not be read (command/JSON failure). */
|
|
216
|
+
queryFailed: boolean;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export async function findProcessPid(
|
|
220
|
+
device: DeviceInfo,
|
|
221
|
+
executableName: string,
|
|
222
|
+
options: { attempts?: number; delayMs?: number } = {},
|
|
223
|
+
): Promise<number | undefined> {
|
|
224
|
+
const lookup = await lookupProcess(device, executableName, options);
|
|
225
|
+
return lookup.pid;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export async function lookupProcess(
|
|
229
|
+
device: DeviceInfo,
|
|
230
|
+
executableName: string,
|
|
231
|
+
options: { attempts?: number; delayMs?: number; signal?: AbortSignal } = {},
|
|
232
|
+
): Promise<ProcessLookup> {
|
|
233
|
+
const attempts = Math.max(1, options.attempts ?? 3);
|
|
234
|
+
const delayMs = options.delayMs ?? 800;
|
|
235
|
+
let queryFailed = false;
|
|
236
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
237
|
+
// The probe can take up to 45s; aborting it is what makes a user stop take
|
|
238
|
+
// effect immediately instead of after the device finally answers.
|
|
239
|
+
if (options.signal?.aborted) return { queryFailed: true };
|
|
240
|
+
const result = await findProcessPidOnce(device, executableName, options.signal);
|
|
241
|
+
if (result.pid !== undefined) return { pid: result.pid, queryFailed: false };
|
|
242
|
+
if (result.queryFailed) queryFailed = true;
|
|
243
|
+
if (attempt < attempts - 1) await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
244
|
+
}
|
|
245
|
+
return { queryFailed };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function findProcessPidOnce(
|
|
249
|
+
device: DeviceInfo,
|
|
250
|
+
executableName: string,
|
|
251
|
+
signal?: AbortSignal,
|
|
252
|
+
): Promise<ProcessLookup> {
|
|
253
|
+
const result = await runCommand(
|
|
254
|
+
"xcrun",
|
|
255
|
+
["devicectl", "device", "info", "processes", "--device", device.id, "--json-output", "-"],
|
|
256
|
+
{ timeoutMs: 45_000, signal },
|
|
257
|
+
);
|
|
258
|
+
// A failed command says nothing about the app; report it as inconclusive.
|
|
259
|
+
if (result.code !== 0) return { queryFailed: true };
|
|
260
|
+
let parsed: unknown;
|
|
261
|
+
try {
|
|
262
|
+
parsed = JSON.parse(result.stdout);
|
|
263
|
+
} catch {
|
|
264
|
+
return { queryFailed: true };
|
|
265
|
+
}
|
|
266
|
+
const processes = asRecord(asRecord(parsed).result).runningProcesses;
|
|
267
|
+
if (!Array.isArray(processes)) return { queryFailed: true };
|
|
268
|
+
const needle = `/${executableName}.app/`;
|
|
269
|
+
for (const raw of processes) {
|
|
270
|
+
const entry = asRecord(raw);
|
|
271
|
+
const executable = asString(entry.executable) ?? "";
|
|
272
|
+
if (executable.includes(needle) && typeof entry.processIdentifier === "number") {
|
|
273
|
+
return { pid: entry.processIdentifier, queryFailed: false };
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
// The table was read successfully and the app is not in it: a real exit.
|
|
277
|
+
return { queryFailed: false };
|
|
278
|
+
}
|