xcodebug 1.2.1 → 1.2.2

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/changes.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  * Pod membership is derived from the repo's own podspecs (`source_files`
11
11
  * globs), so it follows whatever layout the podspec declares.
12
12
  */
13
- import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
13
+ import { lstat, mkdir, readdir, readFile, realpath, stat, writeFile } from "node:fs/promises";
14
14
  import { dirname, join, relative, resolve } from "node:path";
15
15
  import { runCommand } from "./exec.ts";
16
16
 
@@ -61,17 +61,36 @@ export interface ChangeReport {
61
61
  needsBuild: boolean;
62
62
  }
63
63
 
64
+ /**
65
+ * Is this of a type a project compiles as soon as it sees the file? A new one
66
+ * in a pod then needs `pod install`, which is the only question this answers.
67
+ */
68
+ function isSource(path: string): boolean {
69
+ const lower = path.toLowerCase();
70
+ if (lower.endsWith("podfile") || lower.endsWith("podfile.lock") || lower.endsWith(".podspec")) return true;
71
+ if (lower.includes(".xcodeproj/") || lower.includes(".xcworkspace/")) return true;
72
+ const dot = lower.lastIndexOf(".");
73
+ return dot >= 0 && SOURCE_EXTENSIONS.has(lower.slice(dot));
74
+ }
75
+
76
+ /**
77
+ * Types no build reads, though a working session writes them into a repository:
78
+ * notes, logs, crash reports, patches.
79
+ */
80
+ const NEVER_BUILT = new Set([".md", ".log", ".ips", ".patch", ".diff"]);
81
+
64
82
  function isRelevant(path: string): boolean {
65
83
  const normalized = `/${path.replace(/\\/g, "/")}`;
66
84
  if (IGNORED_SEGMENTS.some((segment) => normalized.includes(segment))) return false;
67
85
  // Agent state is not app source: a session file or skill under a config dir
68
86
  // must not trigger a device build.
69
87
  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));
88
+ // Anything else git reports can feed the build: a Podfile.rb, an .xcconfig,
89
+ // an image dropped into a folder the project takes whole. A build that is
90
+ // reused must not be older than its inputs, so the list is of what is known
91
+ // not to be one, and an unknown type costs a rebuild instead of a stale app.
92
+ const dot = path.lastIndexOf(".");
93
+ return dot < 0 || !NEVER_BUILT.has(path.slice(dot).toLowerCase());
75
94
  }
76
95
 
77
96
  /** Expand one glob (braces, **, *) into a RegExp over repo-relative paths. */
@@ -157,16 +176,78 @@ function podsForPath(path: string, pods: PodEntry[]): string[] {
157
176
  *
158
177
  * `git status` keeps reporting the same path after a second edit, so hashing
159
178
  * paths alone would silently skip a rebuild. mtime + size changes on every
160
- * write and costs one stat per changed file.
179
+ * write and costs one stat per changed file. Whether the change is staged is
180
+ * left out: `git add` does not alter what gets built.
161
181
  */
162
182
  async function fileSignature(repoRoot: string, file: ChangedFile): Promise<string> {
163
- if (file.deleted) return `${file.status}:${file.path}:deleted`;
183
+ if (file.deleted) return `${file.path}:deleted`;
184
+ try {
185
+ const path = join(repoRoot, file.path);
186
+ const info = await stat(path);
187
+ // A directory here is a submodule: one entry however much changed inside
188
+ // it, and nothing on the entry itself tells two of its states apart.
189
+ if (info.isDirectory()) return `${file.path}:${(await directorySignature(path, "source")) ?? "unreadable"}`;
190
+ return `${file.path}:${info.mtimeMs}:${info.size}`;
191
+ } catch {
192
+ return `${file.path}:missing`;
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Fingerprint every file's path, time and size in a built product or source tree.
198
+ *
199
+ * Products include all directories: even a resource called `build` is installed
200
+ * app content. Source trees omit generated/build directories and git metadata
201
+ * so a local pod's build output does not invalidate its own inputs.
202
+ * Undefined when the directory is missing or changes under the walk, which is
203
+ * never "the same as before".
204
+ */
205
+ export async function directorySignature(root: string, kind: "product" | "source" = "product"): Promise<string | undefined> {
206
+ const files: string[] = [];
207
+ const pending = [root];
208
+ for (let dir = pending.pop(); dir !== undefined; dir = pending.pop()) {
209
+ try {
210
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
211
+ const path = join(dir, entry.name);
212
+ if (entry.isDirectory()) {
213
+ if (kind === "product" || !IGNORED_SEGMENTS.includes(`/${entry.name}/`)) pending.push(path);
214
+ continue;
215
+ }
216
+ // Not followed: a link is recorded as itself, so one that points at a
217
+ // directory, or at nothing, does not make the whole tree unreadable.
218
+ const info = await lstat(path);
219
+ files.push(`${path}:${info.mtimeMs}:${info.size}`);
220
+ }
221
+ } catch {
222
+ return undefined;
223
+ }
224
+ }
225
+ return hashString(files.sort().join("\n"));
226
+ }
227
+
228
+ /**
229
+ * The directories outside the repository that a container's Podfile.lock
230
+ * installs pods from (`:path` entries). An edit there changes what gets built
231
+ * and leaves `git status` exactly as it was.
232
+ */
233
+ async function outsidePodDirs(containerPath: string, repoRoot: string, cwd: string): Promise<string[]> {
234
+ const dir = dirname(resolve(cwd, containerPath));
235
+ let lock: string;
164
236
  try {
165
- const info = await stat(join(repoRoot, file.path));
166
- return `${file.status}:${file.path}:${info.mtimeMs}:${info.size}`;
237
+ lock = await readFile(join(dir, "Podfile.lock"), "utf8");
167
238
  } catch {
168
- return `${file.status}:${file.path}:missing`;
239
+ return [];
169
240
  }
241
+ // Compared as real paths: git reports the repository's, and a path reached
242
+ // through a link (/tmp, /var) would otherwise always look like another place.
243
+ const root = await realpath(repoRoot).catch(() => repoRoot);
244
+ const dirs = new Set<string>();
245
+ for (const match of lock.matchAll(/^\s+:path:\s*"?([^"\n]+?)"?\s*$/gm)) {
246
+ const path = resolve(dir, match[1]);
247
+ const real = await realpath(path).catch(() => path);
248
+ if (real !== root && !real.startsWith(`${root}/`)) dirs.add(real);
249
+ }
250
+ return [...dirs].sort();
170
251
  }
171
252
 
172
253
  export function hashString(value: string): string {
@@ -242,7 +323,12 @@ export async function checkPodLockSync(
242
323
  return { synced: false, podfileDir: dir, reason: "Podfile.lock differs from Pods/Manifest.lock" };
243
324
  }
244
325
 
245
- export async function detectChanges(cwd: string): Promise<ChangeReport> {
326
+ /**
327
+ * `containerPath` is the .xcworkspace/.xcodeproj the run targets, resolved from
328
+ * `cwd` when relative. With it, the fingerprint also covers pods that container
329
+ * installs from outside the repository; without it, only what git can see.
330
+ */
331
+ export async function detectChanges(cwd: string, containerPath?: string): Promise<ChangeReport> {
246
332
  const root = await runCommand("git", ["rev-parse", "--show-toplevel"], { cwd, timeoutMs: 30_000 });
247
333
  if (root.code !== 0) {
248
334
  return {
@@ -294,15 +380,27 @@ export async function detectChanges(cwd: string): Promise<ChangeReport> {
294
380
  for (const file of changed) {
295
381
  if (file.deleted) continue;
296
382
  const isNew = file.untracked || file.status.includes("A");
297
- if (!isNew) continue;
383
+ // Only a file the generated Pods project would compile needs it regenerated.
384
+ if (!isNew || !isSource(file.path)) continue;
298
385
  const matched = podsForPath(file.path, pods);
299
386
  if (matched.length === 0) continue;
300
387
  newComponentFiles.push({ ...file, pods: matched });
301
388
  for (const pod of matched) podsNeedingInstall.add(pod);
302
389
  }
303
390
 
391
+ // The committed tree is part of the identity: after a commit, a pull or a
392
+ // checkout the working tree can be clean again while holding other code than
393
+ // was last built. The tree rather than the commit, so that rewording a commit
394
+ // or switching to a branch with the same content costs no rebuild.
395
+ const head = await runCommand("git", ["rev-parse", "HEAD^{tree}"], { cwd: repoRoot, timeoutMs: 30_000 });
304
396
  const signatures = await Promise.all(changed.map((file) => fileSignature(repoRoot, file)));
305
- const fingerprint = hashString(signatures.sort().join("\n"));
397
+ const outside = containerPath ? await outsidePodDirs(containerPath, repoRoot, cwd) : [];
398
+ const outsideSignatures = await Promise.all(
399
+ outside.map(async (dir) => `${dir}:${(await directorySignature(dir, "source")) ?? "unreadable"}`),
400
+ );
401
+ const fingerprint = hashString(
402
+ [head.code === 0 ? head.stdout.trim() : "no commit", ...signatures.sort(), ...outsideSignatures].join("\n"),
403
+ );
306
404
 
307
405
  return {
308
406
  repoRoot,
@@ -358,7 +456,7 @@ export function describeChanges(report: ChangeReport): string {
358
456
  if (report.unavailable) {
359
457
  return `change detection unavailable (${report.reason ?? "unknown"}); assuming a rebuild is needed`;
360
458
  }
361
- if (report.changed.length === 0) return "no build-relevant changes";
459
+ if (report.changed.length === 0) return "no uncommitted build-relevant changes";
362
460
  const lines = [`${report.changed.length} build-relevant change(s)`];
363
461
  for (const file of report.changed.slice(0, 15)) {
364
462
  lines.push(` ${file.status} ${file.path}`);
package/devices.ts CHANGED
@@ -4,6 +4,8 @@
4
4
  * devicectl accepts a uuid, ecid, serial number, udid, name or DNS name, so
5
5
  * every identifier we keep is accepted verbatim by later commands.
6
6
  */
7
+ import { mkdtemp, readFile, rename, rm } from "node:fs/promises";
8
+ import { basename, join } from "node:path";
7
9
  import { asRecord, asString, runCommand } from "./exec.ts";
8
10
 
9
11
  export interface DeviceInfo {
@@ -265,14 +267,83 @@ async function findProcessPidOnce(
265
267
  }
266
268
  const processes = asRecord(asRecord(parsed).result).runningProcesses;
267
269
  if (!Array.isArray(processes)) return { queryFailed: true };
270
+ // The app's own executable sits directly in its bundle. An extension runs from
271
+ // `<App>.app/PlugIns/…` as a process of its own, and taking it for the app
272
+ // would report a pid that is not the app's and an app that is not there.
268
273
  const needle = `/${executableName}.app/`;
269
274
  for (const raw of processes) {
270
275
  const entry = asRecord(raw);
271
276
  const executable = asString(entry.executable) ?? "";
272
- if (executable.includes(needle) && typeof entry.processIdentifier === "number") {
273
- return { pid: entry.processIdentifier, queryFailed: false };
274
- }
277
+ const at = executable.lastIndexOf(needle);
278
+ if (at < 0 || executable.indexOf("/", at + needle.length) >= 0) continue;
279
+ if (typeof entry.processIdentifier === "number") return { pid: entry.processIdentifier, queryFailed: false };
275
280
  }
276
281
  // The table was read successfully and the app is not in it: a real exit.
277
282
  return { queryFailed: false };
278
283
  }
284
+
285
+ /**
286
+ * Copy the crash report the device wrote for one instance of an app into
287
+ * `directory`, and return where it landed.
288
+ *
289
+ * Crash reports are named `<executable>-<date>.ips`. The resource diagnostics
290
+ * beside them (`<executable>.cpu_resource-…`) share the prefix up to the dot and
291
+ * are not crashes. A report names the process it is about, so with `pid` only
292
+ * that instance's report is returned: the next launch of the same app, crashing
293
+ * in turn, writes one that is not this instance's. Without `pid` the newest
294
+ * report since `since` is taken.
295
+ */
296
+ export async function pullCrashReport(
297
+ device: DeviceInfo,
298
+ executableName: string,
299
+ options: { since: number; directory: string; pid?: number },
300
+ ): Promise<string | undefined> {
301
+ const listed = await runCommand(
302
+ "xcrun",
303
+ [
304
+ "devicectl", "device", "info", "files", "--device", device.id,
305
+ "--domain-type", "systemCrashLogs", "--search", executableName, "--json-output", "-",
306
+ ],
307
+ { timeoutMs: 45_000 },
308
+ );
309
+ if (listed.code !== 0) return undefined;
310
+ let files: unknown;
311
+ try {
312
+ files = asRecord(asRecord(JSON.parse(listed.stdout)).result).files;
313
+ } catch {
314
+ return undefined;
315
+ }
316
+ if (!Array.isArray(files)) return undefined;
317
+ const candidates: Array<{ name: string; at: number }> = [];
318
+ for (const raw of files) {
319
+ const entry = asRecord(raw);
320
+ const name = asString(entry.name);
321
+ const at = Date.parse(asString(asRecord(entry.metadata).lastModDate) ?? "");
322
+ if (name?.startsWith(`${executableName}-`) && name.endsWith(".ips") && basename(name) === name && at >= options.since) candidates.push({ name, at });
323
+ }
324
+ for (const { name } of candidates.sort((a, b) => b.at - a.at)) {
325
+ const directory = await mkdtemp(join(options.directory, "crash-")).catch(() => undefined);
326
+ if (!directory) return undefined;
327
+ const destination = join(directory, `crash-${name}`);
328
+ try {
329
+ const copied = await runCommand(
330
+ "xcrun",
331
+ [
332
+ "devicectl", "device", "copy", "from", "--device", device.id,
333
+ "--domain-type", "systemCrashLogs", "--source", name, "--destination", destination,
334
+ ],
335
+ { timeoutMs: 60_000 },
336
+ );
337
+ if (copied.code !== 0) continue;
338
+ const report = await readFile(destination, "utf8").catch(() => undefined);
339
+ if (report === undefined) continue;
340
+ const reported = /"pid"\s*:\s*(\d+)/.exec(report)?.[1];
341
+ if (options.pid !== undefined && Number(reported) !== options.pid) continue;
342
+ const retained = join(options.directory, `${basename(directory)}-${name}`);
343
+ if (await rename(destination, retained).then(() => true, () => false)) return retained;
344
+ } finally {
345
+ await rm(directory, { recursive: true, force: true }).catch(() => {});
346
+ }
347
+ }
348
+ return undefined;
349
+ }