forked from EvanBacon/xcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXcodeProject.ts
More file actions
513 lines (458 loc) · 18.1 KB
/
Copy pathXcodeProject.ts
File metadata and controls
513 lines (458 loc) · 18.1 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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
import assert from "assert";
import { readFileSync } from "fs";
import path from "path";
import crypto from "crypto";
import { parse, parseOptimized } from "../json";
import * as json from "../json/types";
import { AbstractObject } from "./AbstractObject";
import type { ValueOf } from "./utils/util.types";
import type { PBXGroup } from "./AbstractGroup";
import type { PBXAggregateTarget } from "./PBXAggregateTarget";
import type { PBXBuildFile } from "./PBXBuildFile";
import type { PBXBuildRule } from "./PBXBuildRule";
import type { PBXContainerItemProxy } from "./PBXContainerItemProxy";
import type { PBXFileReference } from "./PBXFileReference";
import type { PBXLegacyTarget } from "./PBXLegacyTarget";
import type { PBXNativeTarget } from "./PBXNativeTarget";
import type { PBXProject } from "./PBXProject";
import type { PBXReferenceProxy } from "./PBXReferenceProxy";
import type {
PBXAppleScriptBuildPhase,
PBXCopyFilesBuildPhase,
PBXFrameworksBuildPhase,
PBXHeadersBuildPhase,
PBXResourcesBuildPhase,
PBXRezBuildPhase,
PBXShellScriptBuildPhase,
PBXSourcesBuildPhase,
} from "./PBXSourcesBuildPhase";
import type { PBXTargetDependency } from "./PBXTargetDependency";
import type { PBXVariantGroup } from "./PBXVariantGroup";
import type { XCBuildConfiguration } from "./XCBuildConfiguration";
import type { XCConfigurationList } from "./XCConfigurationList";
import type { XCVersionGroup } from "./XCVersionGroup";
import type { PBXFileSystemSynchronizedRootGroup } from "./PBXFileSystemSynchronizedRootGroup";
import type { PBXFileSystemSynchronizedBuildFileExceptionSet } from "./PBXFileSystemSynchronizedBuildFileExceptionSet";
import type { PBXFileSystemSynchronizedGroupBuildPhaseMembershipExceptionSet } from "./PBXFileSystemSynchronizedGroupBuildPhaseMembershipExceptionSet";
import {
DEFAULT_OBJECT_VERSION,
LAST_KNOWN_ARCHIVE_VERSION,
} from "./utils/constants";
const debug = require("debug")(
"xcparse:model:XcodeProject"
) as typeof console.log;
function uuidForPath(path: string): string {
return (
// Xcode seems to make the first 7 and last 8 characters the same so we'll inch toward that.
"XX" +
crypto
.createHash("md5")
.update(path)
.digest("hex")
.toUpperCase()
.slice(0, 20) +
"XX"
);
}
type IsaMapping = {
[json.ISA.PBXBuildFile]: PBXBuildFile;
[json.ISA.PBXAppleScriptBuildPhase]: PBXAppleScriptBuildPhase;
[json.ISA.PBXCopyFilesBuildPhase]: PBXCopyFilesBuildPhase;
[json.ISA.PBXFrameworksBuildPhase]: PBXFrameworksBuildPhase;
[json.ISA.PBXHeadersBuildPhase]: PBXHeadersBuildPhase;
[json.ISA.PBXResourcesBuildPhase]: PBXResourcesBuildPhase;
[json.ISA.PBXShellScriptBuildPhase]: PBXShellScriptBuildPhase;
[json.ISA.PBXSourcesBuildPhase]: PBXSourcesBuildPhase;
[json.ISA.PBXContainerItemProxy]: PBXContainerItemProxy;
[json.ISA.PBXFileReference]: PBXFileReference;
[json.ISA.PBXGroup]: PBXGroup;
[json.ISA.PBXVariantGroup]: PBXVariantGroup;
[json.ISA.XCVersionGroup]: XCVersionGroup;
[json.ISA
.PBXFileSystemSynchronizedRootGroup]: PBXFileSystemSynchronizedRootGroup;
[json.ISA
.PBXFileSystemSynchronizedBuildFileExceptionSet]: PBXFileSystemSynchronizedBuildFileExceptionSet;
[json.ISA
.PBXFileSystemSynchronizedGroupBuildPhaseMembershipExceptionSet]: PBXFileSystemSynchronizedGroupBuildPhaseMembershipExceptionSet;
[json.ISA.PBXNativeTarget]: PBXNativeTarget;
[json.ISA.PBXAggregateTarget]: PBXAggregateTarget;
[json.ISA.PBXLegacyTarget]: PBXLegacyTarget;
[json.ISA.PBXProject]: PBXProject;
[json.ISA.PBXTargetDependency]: PBXTargetDependency;
[json.ISA.XCBuildConfiguration]: XCBuildConfiguration;
[json.ISA.XCConfigurationList]: XCConfigurationList;
[json.ISA.PBXBuildRule]: PBXBuildRule;
[json.ISA.PBXReferenceProxy]: PBXReferenceProxy;
[json.ISA.PBXRezBuildPhase]: PBXRezBuildPhase;
};
const KNOWN_ISA = {
[json.ISA.PBXBuildFile]: () =>
require("./PBXBuildFile")
.PBXBuildFile as typeof import("./PBXBuildFile").PBXBuildFile,
[json.ISA.PBXAppleScriptBuildPhase]: () =>
require("./PBXSourcesBuildPhase")
.PBXAppleScriptBuildPhase as typeof import("./PBXSourcesBuildPhase").PBXAppleScriptBuildPhase,
[json.ISA.PBXCopyFilesBuildPhase]: () =>
require("./PBXSourcesBuildPhase")
.PBXCopyFilesBuildPhase as typeof import("./PBXSourcesBuildPhase").PBXCopyFilesBuildPhase,
[json.ISA.PBXFrameworksBuildPhase]: () =>
require("./PBXSourcesBuildPhase")
.PBXFrameworksBuildPhase as typeof import("./PBXSourcesBuildPhase").PBXFrameworksBuildPhase,
[json.ISA.PBXHeadersBuildPhase]: () =>
require("./PBXSourcesBuildPhase")
.PBXHeadersBuildPhase as typeof import("./PBXSourcesBuildPhase").PBXHeadersBuildPhase,
[json.ISA.PBXResourcesBuildPhase]: () =>
require("./PBXSourcesBuildPhase")
.PBXResourcesBuildPhase as typeof import("./PBXSourcesBuildPhase").PBXResourcesBuildPhase,
[json.ISA.PBXShellScriptBuildPhase]: () =>
require("./PBXSourcesBuildPhase")
.PBXShellScriptBuildPhase as typeof import("./PBXSourcesBuildPhase").PBXShellScriptBuildPhase,
[json.ISA.PBXSourcesBuildPhase]: () =>
require("./PBXSourcesBuildPhase")
.PBXSourcesBuildPhase as typeof import("./PBXSourcesBuildPhase").PBXSourcesBuildPhase,
[json.ISA.PBXContainerItemProxy]: () =>
require("./PBXContainerItemProxy")
.PBXContainerItemProxy as typeof import("./PBXContainerItemProxy").PBXContainerItemProxy,
[json.ISA.PBXFileReference]: () =>
require("./PBXFileReference")
.PBXFileReference as typeof import("./PBXFileReference").PBXFileReference,
[json.ISA.PBXGroup]: () =>
require("./AbstractGroup")
.PBXGroup as typeof import("./AbstractGroup").PBXGroup,
[json.ISA.PBXVariantGroup]: () =>
require("./PBXVariantGroup")
.PBXVariantGroup as typeof import("./PBXVariantGroup").PBXVariantGroup,
[json.ISA.XCVersionGroup]: () =>
require("./XCVersionGroup")
.XCVersionGroup as typeof import("./XCVersionGroup").XCVersionGroup,
[json.ISA.PBXFileSystemSynchronizedRootGroup]: () =>
require("./PBXFileSystemSynchronizedRootGroup")
.PBXFileSystemSynchronizedRootGroup as typeof import("./PBXFileSystemSynchronizedRootGroup").PBXFileSystemSynchronizedRootGroup,
[json.ISA.PBXFileSystemSynchronizedBuildFileExceptionSet]: () =>
require("./PBXFileSystemSynchronizedBuildFileExceptionSet")
.PBXFileSystemSynchronizedBuildFileExceptionSet as typeof import("./PBXFileSystemSynchronizedBuildFileExceptionSet").PBXFileSystemSynchronizedBuildFileExceptionSet,
[json.ISA.PBXFileSystemSynchronizedGroupBuildPhaseMembershipExceptionSet]:
() =>
require("./PBXFileSystemSynchronizedGroupBuildPhaseMembershipExceptionSet")
.PBXFileSystemSynchronizedGroupBuildPhaseMembershipExceptionSet as typeof import("./PBXFileSystemSynchronizedGroupBuildPhaseMembershipExceptionSet").PBXFileSystemSynchronizedGroupBuildPhaseMembershipExceptionSet,
[json.ISA.PBXNativeTarget]: () =>
require("./PBXNativeTarget")
.PBXNativeTarget as typeof import("./PBXNativeTarget").PBXNativeTarget,
[json.ISA.PBXAggregateTarget]: () =>
require("./PBXAggregateTarget")
.PBXAggregateTarget as typeof import("./PBXAggregateTarget").PBXAggregateTarget,
[json.ISA.PBXLegacyTarget]: () =>
require("./PBXLegacyTarget")
.PBXLegacyTarget as typeof import("./PBXLegacyTarget").PBXLegacyTarget,
[json.ISA.PBXProject]: () =>
require("./PBXProject")
.PBXProject as typeof import("./PBXProject").PBXProject,
[json.ISA.PBXTargetDependency]: () =>
require("./PBXTargetDependency")
.PBXTargetDependency as typeof import("./PBXTargetDependency").PBXTargetDependency,
[json.ISA.XCBuildConfiguration]: () =>
require("./XCBuildConfiguration")
.XCBuildConfiguration as typeof import("./XCBuildConfiguration").XCBuildConfiguration,
[json.ISA.XCConfigurationList]: () =>
require("./XCConfigurationList")
.XCConfigurationList as typeof import("./XCConfigurationList").XCConfigurationList,
[json.ISA.PBXBuildRule]: () =>
require("./PBXBuildRule")
.PBXBuildRule as typeof import("./PBXBuildRule").PBXBuildRule,
[json.ISA.PBXReferenceProxy]: () =>
require("./PBXReferenceProxy")
.PBXReferenceProxy as typeof import("./PBXReferenceProxy").PBXReferenceProxy,
[json.ISA.PBXRezBuildPhase]: () =>
require("./PBXSourcesBuildPhase")
.PBXRezBuildPhase as typeof import("./PBXSourcesBuildPhase").PBXRezBuildPhase,
[json.ISA.XCSwiftPackageProductDependency]: () =>
require("./XCSwiftPackageProductDependency")
.XCSwiftPackageProductDependency,
[json.ISA.XCRemoteSwiftPackageReference]: () =>
require("./XCRemoteSwiftPackageReference").XCRemoteSwiftPackageReference,
[json.ISA.XCLocalSwiftPackageReference]: () =>
require("./XCLocalSwiftPackageReference").XCLocalSwiftPackageReference,
} as const;
type AnyModel = ValueOf<IsaMapping>;
export class XcodeProject extends Map<json.UUID, AnyModel> {
/**
* Versioning system for the entire archive.
* @example `1`
*/
archiveVersion: number;
/**
* Versioning system for the `objects` dictionary.
* @example `55`
*/
objectVersion: number;
/** UUID for the initial object in the `objects` dictionary. */
rootObject: PBXProject;
/** No idea what this does, I've Googled it a bit. */
classes: Record<json.UUID, unknown>;
/** JSON objects which haven't been inflated yet */
private internalJsonObjects: Record<json.UUID, json.AbstractObject<any>>;
/**
* @param filePath -- path to a `pbxproj` file.
* @returns a new instance of `XcodeProject`
*/
static open(filePath: string) {
const contents = readFileSync(filePath, "utf8");
const json = parse(contents);
return new XcodeProject(filePath, json);
}
/**
* Optimized open method for large projects
* @param filePath -- path to a `pbxproj` file
* @param options -- optimization options
*/
static openLazy(filePath: string, options: {
skipFullInflation?: boolean;
progressCallback?: (message: string) => void;
} = {}) {
const { skipFullInflation = true, progressCallback } = options;
progressCallback?.('Reading file...');
console.time('📁 File read');
const contents = readFileSync(filePath, "utf8");
console.timeEnd('📁 File read');
progressCallback?.('Parsing JSON...');
console.time('🔍 JSON parsing');
const fileSizeMB = contents.length / 1024 / 1024;
let json;
if (fileSizeMB > 5) {
// Use optimized parser for large files
json = parseOptimized(contents, {
progressCallback: (processed, total, stage, memoryMB) => {
progressCallback?.(`${stage}: ${processed}/${total}${memoryMB ? ` (${memoryMB}MB)` : ''}`);
}
});
} else {
json = parse(contents);
}
console.timeEnd('🔍 JSON parsing');
const objectCount = Object.keys(json.objects || {}).length;
console.log(`📊 Found ${objectCount.toLocaleString()} objects`);
progressCallback?.('Creating project...');
console.time('🏗️ Project creation');
const project = new XcodeProject(filePath, json, { skipFullInflation });
console.timeEnd('🏗️ Project creation');
return project;
}
constructor(
public filePath: string,
props: Partial<json.XcodeProject>,
options: { skipFullInflation?: boolean } = {}
) {
super();
const { skipFullInflation = false } = options;
// Optimize: avoid deep clone for large projects
const json = skipFullInflation ? props : JSON.parse(JSON.stringify(props));
assert(json.objects, "objects is required");
assert(json.rootObject, "rootObject is required");
this.internalJsonObjects = json.objects;
this.archiveVersion = json.archiveVersion ?? LAST_KNOWN_ARCHIVE_VERSION;
this.objectVersion = json.objectVersion ?? DEFAULT_OBJECT_VERSION;
this.classes = json.classes ?? {};
// Sanity
assertRootObject(json.rootObject, json.objects?.[json.rootObject]);
// Inflate the root object.
console.time('🌱 Root object inflation');
this.rootObject = this.getObject(json.rootObject);
console.timeEnd('🌱 Root object inflation');
// Skip full inflation for large projects
if (!skipFullInflation) {
console.time('🌳 Full object inflation');
this.ensureAllObjectsInflated();
console.timeEnd('🌳 Full object inflation');
} else {
const remainingCount = Object.keys(this.internalJsonObjects).length;
console.log(`⏭️ Skipping full inflation of ${remainingCount.toLocaleString()} objects (lazy mode)`);
}
}
/** The directory containing the `*.xcodeproj/project.pbxproj` file, e.g. `/ios/` in React Native. */
getProjectRoot() {
// TODO: Not sure if this is right
return path.dirname(path.dirname(this.filePath));
}
getObject(uuid: string) {
const obj = this._getObjectOptional(uuid);
if (obj) {
return obj;
}
throw new Error(`object with uuid '${uuid}' not found.`);
}
private _getObjectOptional(uuid: string) {
if (this.has(uuid)) {
return this.get(uuid);
}
const obj = this.internalJsonObjects[uuid];
if (!obj) {
return null;
}
// Clear out so we known this model has already been inflated.
delete this.internalJsonObjects[uuid];
const model = this.createObject(uuid, obj);
this.set(uuid, model);
// Inflate after the model has been registered.
model.inflate();
return model;
}
createObject<
TKlass extends json.AbstractObject<any>,
TInstance = InstanceType<IsaMapping[TKlass["isa"]]>
>(uuid: string, obj: TKlass): TInstance {
// @ts-expect-error
const Klass = KNOWN_ISA[obj.isa]();
assert(Klass, `unknown object type. (isa: ${obj.isa}, uuid: ${uuid})`);
return new Klass(
this,
uuid,
obj
);
}
private ensureAllObjectsInflated() {
// This method exists for sanity
if (Object.keys(this.internalJsonObjects).length === 0) return;
const remaining = Object.keys(this.internalJsonObjects).length;
debug("inflating unreferenced objects: %o", Object.keys(this.internalJsonObjects));
let processed = 0;
while (Object.keys(this.internalJsonObjects).length > 0) {
const uuid = Object.keys(this.internalJsonObjects)[0];
this.getObject(uuid);
processed++;
// Progress for large batches
if (remaining > 1000 && processed % 500 === 0) {
console.log(` ⚙️ Inflated ${processed}/${remaining} objects...`);
}
}
}
/**
* Manually trigger full inflation of all objects (for lazy-loaded projects)
*/
forceFullInflation(progressCallback?: (processed: number, total: number) => void) {
const remaining = Object.keys(this.internalJsonObjects).length;
if (remaining === 0) {
console.log('✅ All objects already inflated');
return;
}
console.log(`🔄 Force inflating ${remaining.toLocaleString()} remaining objects...`);
console.time('🌳 Full inflation');
let processed = 0;
while (Object.keys(this.internalJsonObjects).length > 0) {
const uuid = Object.keys(this.internalJsonObjects)[0];
this.getObject(uuid);
processed++;
if (progressCallback && processed % 100 === 0) {
progressCallback(processed, remaining);
}
}
console.timeEnd('🌳 Full inflation');
console.log('✅ Full inflation completed');
}
/**
* Get project statistics without full inflation
*/
getQuickStats() {
const totalObjects = this.size + Object.keys(this.internalJsonObjects).length;
const inflatedObjects = this.size;
const uninflatedObjects = Object.keys(this.internalJsonObjects).length;
return {
totalObjects,
inflatedObjects,
uninflatedObjects,
inflationPercentage: ((inflatedObjects / totalObjects) * 100).toFixed(1)
};
}
/**
* Get uninflated objects for analysis (read-only access)
*/
getUninflatedObjects(): Readonly<Record<json.UUID, json.AbstractObject<any>>> {
return this.internalJsonObjects;
}
createModel<TProps extends json.AbstractObject<any>>(opts: TProps) {
const uuid = this.getUniqueId(JSON.stringify(canonicalize(opts)));
const model = this.createObject(uuid, opts);
this.set(uuid, model);
return model;
}
getReferenceForPath(absolutePath: string): PBXFileReference | null {
if (!path.isAbsolute(absolutePath)) {
throw new Error(`Paths must be absolute ${absolutePath}`);
}
for (const child of this.values()) {
if (
child.isa === "PBXFileReference" &&
"getRealPath" in child &&
child.getRealPath() === absolutePath
) {
return child;
}
}
return null;
}
getReferrers(uuid: string): AbstractObject[] {
let referrers = [];
for (const child of this.values()) {
if (child.isReferencing(uuid)) {
referrers.push(child);
}
}
return referrers;
}
private isUniqueId(id: string): boolean {
for (const key of this.keys()) {
if (key === id) {
return false;
}
}
return true;
}
private getUniqueId(seed: string): string {
const id = uuidForPath(seed);
if (this.isUniqueId(id)) {
return id;
}
return this.getUniqueId(
// Add a space to the seed to increase the hash.
seed + " "
);
}
toJSON(): json.XcodeProject {
const json: json.XcodeProject = {
archiveVersion: this.archiveVersion,
objectVersion: this.objectVersion,
classes: this.classes,
objects: {},
rootObject: this.rootObject.uuid,
};
// Inflate all objects.
for (const [uuid, obj] of this.entries()) {
json.objects[uuid] = obj.toJSON();
}
return json;
}
}
function assertRootObject(
id: string,
obj: any
): asserts obj is json.PBXProject {
if (obj?.isa !== "PBXProject") {
throw new Error(`Root object "${id}" is not a PBXProject`);
}
}
function canonicalize(value: any): any {
// Deep sort serialized `value` object to make it deterministic.
if (Array.isArray(value)) {
return value.map(canonicalize);
} else if (typeof value === "object") {
if ("uuid" in value && typeof value.uuid === "string") {
return value.uuid;
}
const sorted: Record<string, any> = {};
for (const key of Object.keys(value).sort()) {
sorted[key] = canonicalize(value[key]);
}
return sorted;
} else {
return value;
}
}