-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathPBXNativeTarget.ts
More file actions
487 lines (435 loc) · 16.8 KB
/
PBXNativeTarget.ts
File metadata and controls
487 lines (435 loc) · 16.8 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
import * as json from "../json/types";
import { AbstractTarget } from "./AbstractTarget";
import {
PBXCopyFilesBuildPhase,
PBXFrameworksBuildPhase,
PBXHeadersBuildPhase,
PBXResourcesBuildPhase,
PBXSourcesBuildPhase,
type AnyBuildPhase,
} from "./PBXSourcesBuildPhase";
import { PBXFileReference } from "./PBXFileReference";
import { PBXBuildFile } from "./PBXBuildFile";
import { XCSwiftPackageProductDependency } from "./XCSwiftPackageProductDependency";
import type { PickRequired, SansIsa } from "./utils/util.types";
import type { XcodeProject } from "./XcodeProject";
import type { PBXBuildRule } from "./PBXBuildRule";
import { PBXTargetDependency } from "./PBXTargetDependency";
import type { XCConfigurationList } from "./XCConfigurationList";
import type { PBXFileSystemSynchronizedRootGroup } from "./PBXFileSystemSynchronizedRootGroup";
import { PBXContainerItemProxy } from "./PBXContainerItemProxy";
import type { XCRemoteSwiftPackageReference } from "./XCRemoteSwiftPackageReference";
import type { XCLocalSwiftPackageReference } from "./XCLocalSwiftPackageReference";
export type PBXNativeTargetModel = json.PBXNativeTarget<
XCConfigurationList,
PBXTargetDependency,
AnyBuildPhase,
PBXBuildRule,
PBXFileReference,
XCSwiftPackageProductDependency,
PBXFileSystemSynchronizedRootGroup
>;
export class PBXNativeTarget extends AbstractTarget<PBXNativeTargetModel> {
static isa = json.ISA.PBXNativeTarget as const;
static is(object: any): object is PBXNativeTarget {
return object.isa === PBXNativeTarget.isa;
}
static create(
project: XcodeProject,
opts: PickRequired<
SansIsa<PBXNativeTargetModel>,
"name" | "productType" | "buildConfigurationList"
>
) {
return project.createModel<PBXNativeTargetModel>({
isa: json.ISA.PBXNativeTarget,
buildPhases: [],
buildRules: [],
dependencies: [],
// TODO: Should we default the product name to the target name?
...opts,
}) as PBXNativeTarget;
}
/** @returns the `PBXFrameworksBuildPhase` or creates one if there is none. Only one can exist. */
getFrameworksBuildPhase() {
return (
this.getBuildPhase(PBXFrameworksBuildPhase) ??
this.createBuildPhase(PBXFrameworksBuildPhase)
);
}
/** @returns the `PBXHeadersBuildPhase` or creates one if there is none. Only one can exist. */
getHeadersBuildPhase() {
return (
this.getBuildPhase(PBXHeadersBuildPhase) ??
this.createBuildPhase(PBXHeadersBuildPhase)
);
}
/** @returns the `PBXSourcesBuildPhase` or creates one if there is none. Only one can exist. */
getSourcesBuildPhase() {
return (
this.getBuildPhase(PBXSourcesBuildPhase) ??
this.createBuildPhase(PBXSourcesBuildPhase)
);
}
/** @returns the `PBXResourcesBuildPhase` or creates one if there is none. Only one can exist. */
getResourcesBuildPhase() {
return (
this.getBuildPhase(PBXResourcesBuildPhase) ??
this.createBuildPhase(PBXResourcesBuildPhase)
);
}
/** Ensures a list of frameworks are linked to the target, given a list like `['SwiftUI.framework', 'WidgetKit.framework']`. Also ensures the file references are added to the Frameworks display folder. */
ensureFrameworks(frameworks: string[]) {
const frameworksFolder =
this.getXcodeProject().rootObject.getFrameworksGroup();
// TODO: This might need OS-specific checks like https://github.com/CocoaPods/Xcodeproj/blob/ab3dfa504b5a97cae3a653a8924f4616dcaa062e/lib/xcodeproj/project/object/native_target.rb#L322-L328
const getFrameworkFileReference = (name: string): PBXFileReference => {
const frameworkName = name.endsWith(".framework")
? name
: name + ".framework";
for (const [, entry] of this.getXcodeProject().entries()) {
if (
PBXFileReference.is(entry) &&
entry.props.lastKnownFileType === "wrapper.framework" &&
entry.props.sourceTree === "SDKROOT" &&
entry.props.name === frameworkName
) {
// This should never happen but if it does then we can repair the state by adding the framework file reference to the Frameworks display group.
if (
!frameworksFolder.props.children.find(
(child) => child.uuid === entry.uuid
)
) {
frameworksFolder.props.children.push(entry);
}
return entry;
}
}
return frameworksFolder.createFile({
path: "System/Library/Frameworks/" + frameworkName,
});
};
return frameworks.map((framework) => {
return this.getFrameworksBuildPhase().ensureFile({
fileRef: getFrameworkFileReference(framework),
});
});
}
/**
* Adds a dependency on the given target.
*
* @param [AbstractTarget] target
* the target which should be added to the dependencies list of
* the receiver. The target may be a target of this target's
* project or of a subproject of this project. Note that the
* subproject must already be added to this target's project.
*
* @return [void]
*/
addDependency(target: PBXNativeTarget) {
const isSameProject =
target.getXcodeProject().filePath === this.getXcodeProject().filePath;
const existing = this.getDependencyForTarget(target);
if (existing) {
if (!isSameProject) {
// Seems to only be used when the target is a subproject. https://github.com/CocoaPods/Xcodeproj/blob/ab3dfa504b5a97cae3a653a8924f4616dcaa062e/lib/xcodeproj/project/object/target_dependency.rb#L24-L25
// Update existing props with the existing target.
existing.props.name = target.props.name;
}
return;
}
const containerProxy = PBXContainerItemProxy.create(
this.getXcodeProject(),
{
containerPortal: this.getXcodeProject().rootObject,
proxyType: 1,
remoteGlobalIDString: target.uuid,
remoteInfo: target.props.name,
}
);
if (isSameProject) {
containerProxy.props.containerPortal = this.getXcodeProject().rootObject;
} else {
throw new Error(
"adding dependencies to subprojects is not yet supported. Please open an issue if you need this feature."
);
}
const dependency = PBXTargetDependency.create(this.getXcodeProject(), {
target,
targetProxy: containerProxy,
// name: isSameProject ? undefined : target.props.name,
});
this.props.dependencies.push(dependency);
}
getCopyBuildPhaseForTarget(target: PBXNativeTarget): PBXCopyFilesBuildPhase {
const project = this.getXcodeProject();
if (project.rootObject.getMainAppTarget("ios")!.uuid !== this.uuid) {
throw new Error(
`getCopyBuildPhaseForTarget can only be called on the main target`
);
}
const WELL_KNOWN_COPY_EXTENSIONS_NAME = (() => {
if (
target.props.productType ===
"com.apple.product-type.application.on-demand-install-capable"
) {
return "Embed App Clips";
} else if (target.isWatchOSTarget()) {
return "Embed Watch Content";
} else if (
target.props.productType ===
"com.apple.product-type.extensionkit-extension"
) {
return "Embed ExtensionKit Extensions";
}
return "Embed Foundation Extensions";
})();
const existing = this.props.buildPhases.find((phase) => {
// TODO: maybe there's a safer way to do this? The name is not a good identifier.
return (
PBXCopyFilesBuildPhase.is(phase) &&
phase.props.name === WELL_KNOWN_COPY_EXTENSIONS_NAME
);
});
if (existing) {
const phase = existing as PBXCopyFilesBuildPhase;
// Ensure correct settings even for existing phases.
// This handles cases where an existing phase has incorrect dstPath/dstSubfolderSpec,
// which can cause App Store validation failures (e.g., watch apps must be in Watch/ subdirectory).
phase.ensureDefaultsForTarget(target);
return phase;
}
const phase = this.createBuildPhase(PBXCopyFilesBuildPhase, {
name: WELL_KNOWN_COPY_EXTENSIONS_NAME,
files: [],
});
phase.ensureDefaultsForTarget(target);
return phase;
}
/**
* Returns true if this target is a watchOS application.
* This includes both legacy watchOS app types (watchapp, watchapp2) and
* modern watchOS apps which use the standard application product type
* with SDKROOT = watchos in build settings.
*/
isWatchOSTarget(): boolean {
// Legacy watchOS app product types
if (
this.props.productType === "com.apple.product-type.application.watchapp" ||
this.props.productType === "com.apple.product-type.application.watchapp2" ||
this.props.productType ===
"com.apple.product-type.application.watchapp2-container"
) {
return true;
}
// Modern watchOS apps use com.apple.product-type.application with
// SDKROOT = watchos in build settings
if (this.props.productType === "com.apple.product-type.application") {
const buildSettings =
this.props.buildConfigurationList?.props.buildConfigurations?.[0]?.props
.buildSettings;
if (buildSettings && buildSettings.SDKROOT === "watchos") {
return true;
}
}
return false;
}
isWatchExtension(): boolean {
return (
this.props.productType === "com.apple.product-type.watchkit-extension" ||
this.props.productType === "com.apple.product-type.watchkit2-extension"
);
}
protected getObjectProps(): Partial<{
buildRules: any;
productType: any;
productReference?: any;
productInstallPath?: any;
packageProductDependencies?: any;
productName?: any;
buildConfigurationList: any;
dependencies: any;
buildPhases: any;
}> {
return {
...super.getObjectProps(),
buildRules: [String],
productReference: [String],
packageProductDependencies: [String],
fileSystemSynchronizedGroups: [String],
};
}
/**
* Removes this target from the project along with all of its exclusively-owned children.
* Children that are shared with other targets (e.g., shared build phases) are preserved.
*/
removeFromProject() {
const project = this.getXcodeProject();
// Helper to check if an object is only referenced by this target
const isExclusivelyOwnedByThisTarget = (obj: { getReferrers(): { uuid: string }[] }) => {
const referrers = obj.getReferrers();
return referrers.length === 1 && referrers[0].uuid === this.uuid;
};
// Remove build phases that are only referenced by this target
for (const phase of [...this.props.buildPhases]) {
if (isExclusivelyOwnedByThisTarget(phase)) {
phase.removeFromProject();
}
}
// Remove build rules that are only referenced by this target
for (const rule of [...this.props.buildRules]) {
if (isExclusivelyOwnedByThisTarget(rule)) {
rule.removeFromProject();
}
}
// Remove the build configuration list (it will cascade to configurations)
if (isExclusivelyOwnedByThisTarget(this.props.buildConfigurationList)) {
this.props.buildConfigurationList.removeFromProject();
}
// Remove dependencies (PBXTargetDependency objects that this target depends on)
for (const dep of [...this.props.dependencies]) {
if (isExclusivelyOwnedByThisTarget(dep)) {
dep.removeFromProject();
}
}
// Remove file system synchronized groups
// Check if any OTHER target uses this group (not just any referrer, since groups can be in PBXGroups too)
if (this.props.fileSystemSynchronizedGroups) {
for (const group of [...this.props.fileSystemSynchronizedGroups]) {
const groupUsedByOtherTarget = [...project.values()].some(
(obj) =>
PBXNativeTarget.is(obj) &&
obj.uuid !== this.uuid &&
obj.props.fileSystemSynchronizedGroups?.some(
(g) => g.uuid === group.uuid
)
);
if (!groupUsedByOtherTarget) {
group.removeFromProject();
}
}
}
// Remove package product dependencies
if (this.props.packageProductDependencies) {
for (const dep of [...this.props.packageProductDependencies]) {
if (isExclusivelyOwnedByThisTarget(dep)) {
dep.removeFromProject();
}
}
}
// Remove the product reference (the .app, .framework, etc. file reference)
// Check if any OTHER target uses this as their productReference
if (this.props.productReference) {
const productRefUsedByOtherTarget = [...project.values()].some(
(obj) =>
PBXNativeTarget.is(obj) &&
obj.uuid !== this.uuid &&
obj.props.productReference?.uuid === this.props.productReference?.uuid
);
if (!productRefUsedByOtherTarget) {
this.props.productReference.removeFromProject();
}
}
// Find and remove any PBXTargetDependency objects from OTHER targets that depend on THIS target
for (const [, obj] of project.entries()) {
if (
PBXTargetDependency.is(obj) &&
(obj.props.target?.uuid === this.uuid ||
obj.props.targetProxy?.props.remoteGlobalIDString === this.uuid)
) {
obj.removeFromProject();
}
}
// Call parent which handles removing from PBXProject.targets array
return super.removeFromProject();
}
/**
* Adds a Swift package product dependency to this target.
* This handles the full wiring:
* 1. Creates the XCSwiftPackageProductDependency
* 2. Adds it to target's packageProductDependencies
* 3. Creates a PBXBuildFile with productRef
* 4. Adds the build file to the frameworks build phase
*
* Note: The package reference must already be added to the project via
* `project.addPackageReference()`, `project.addRemoteSwiftPackage()`, or
* `project.addLocalSwiftPackage()`.
*
* @param opts.productName Name of the product from the Swift package
* @param opts.package The package reference (XCRemoteSwiftPackageReference or XCLocalSwiftPackageReference)
* @returns The created XCSwiftPackageProductDependency
*/
addSwiftPackageProduct(opts: {
productName: string;
package?: XCRemoteSwiftPackageReference | XCLocalSwiftPackageReference;
}): XCSwiftPackageProductDependency {
const xcproj = this.getXcodeProject();
// Initialize packageProductDependencies if needed
if (!this.props.packageProductDependencies) {
this.props.packageProductDependencies = [];
}
// Check if this product dependency already exists for this target
const existing = this.props.packageProductDependencies.find(
(dep) =>
dep.props.productName === opts.productName &&
dep.props.package?.uuid === opts.package?.uuid
);
if (existing) {
return existing;
}
// Create the product dependency
const productDep = XCSwiftPackageProductDependency.create(xcproj, {
productName: opts.productName,
package: opts.package,
});
// Add to target's packageProductDependencies
this.props.packageProductDependencies.push(productDep);
// Create a build file with productRef pointing to the dependency
const buildFile = PBXBuildFile.createFromProductRef(xcproj, {
productRef: productDep,
});
// Add the build file to the frameworks build phase
this.getFrameworksBuildPhase().props.files.push(buildFile);
return productDep;
}
/**
* Gets all Swift package product dependencies for this target.
*
* @returns Array of XCSwiftPackageProductDependency objects
*/
getSwiftPackageProductDependencies(): XCSwiftPackageProductDependency[] {
return this.props.packageProductDependencies ?? [];
}
/**
* Removes a Swift package product dependency from this target.
* This handles removing from packageProductDependencies and the build file from the frameworks phase.
*
* @param productDep The product dependency to remove
*/
removeSwiftPackageProduct(productDep: XCSwiftPackageProductDependency): void {
// Remove from packageProductDependencies
if (this.props.packageProductDependencies) {
const index = this.props.packageProductDependencies.findIndex(
(dep) => dep.uuid === productDep.uuid
);
if (index !== -1) {
this.props.packageProductDependencies.splice(index, 1);
}
}
// Find and remove the build file that references this product dependency
const frameworksPhase = this.getBuildPhase(PBXFrameworksBuildPhase);
if (frameworksPhase) {
const buildFileIndex = frameworksPhase.props.files.findIndex(
(file) => file.props.productRef?.uuid === productDep.uuid
);
if (buildFileIndex !== -1) {
const buildFile = frameworksPhase.props.files[buildFileIndex];
frameworksPhase.props.files.splice(buildFileIndex, 1);
// Remove the build file from the project
buildFile.removeFromProject();
}
}
// Remove the product dependency from the project
productDep.removeFromProject();
}
}