-
-
Notifications
You must be signed in to change notification settings - Fork 195
/
ios-project-service.ts
1317 lines (1100 loc) · 59.3 KB
/
ios-project-service.ts
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as path from "path";
import * as shell from "shelljs";
import * as os from "os";
import * as semver from "semver";
import * as constants from "../constants";
import * as helpers from "../common/helpers";
import { attachAwaitDetach } from "../common/helpers";
import * as projectServiceBaseLib from "./platform-project-service-base";
import { PlistSession, Reporter } from "plist-merge-patch";
import { EOL } from "os";
import * as temp from "temp";
import * as plist from "plist";
import { IOSProvisionService } from "./ios-provision-service";
import { IOSEntitlementsService } from "./ios-entitlements-service";
import { XCConfigService } from "./xcconfig-service";
import * as simplePlist from "simple-plist";
import * as mobileprovision from "ios-mobileprovision-finder";
export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServiceBase implements IPlatformProjectService {
private static XCODE_PROJECT_EXT_NAME = ".xcodeproj";
private static XCODE_SCHEME_EXT_NAME = ".xcscheme";
private static XCODEBUILD_MIN_VERSION = "6.0";
private static IOS_PROJECT_NAME_PLACEHOLDER = "__PROJECT_NAME__";
private static IOS_PLATFORM_NAME = "ios";
private static PODFILE_POST_INSTALL_SECTION_NAME = "post_install";
private get $npmInstallationManager(): INpmInstallationManager {
return this.$injector.resolve("npmInstallationManager");
}
constructor($fs: IFileSystem,
private $childProcess: IChildProcess,
private $cocoapodsService: ICocoaPodsService,
private $errors: IErrors,
private $logger: ILogger,
private $iOSEmulatorServices: Mobile.IEmulatorPlatformServices,
private $injector: IInjector,
$projectDataService: IProjectDataService,
private $prompter: IPrompter,
private $config: IConfiguration,
private $devicePlatformsConstants: Mobile.IDevicePlatformsConstants,
private $devicesService: Mobile.IDevicesService,
private $mobileHelper: Mobile.IMobileHelper,
private $hostInfo: IHostInfo,
private $pluginVariablesService: IPluginVariablesService,
private $xcprojService: IXcprojService,
private $iOSProvisionService: IOSProvisionService,
private $pbxprojDomXcode: IPbxprojDomXcode,
private $xcode: IXcode,
private $iOSEntitlementsService: IOSEntitlementsService,
private $sysInfo: ISysInfo,
private $xCConfigService: XCConfigService) {
super($fs, $projectDataService);
}
private _platformsDirCache: string = null;
private _platformData: IPlatformData = null;
public getPlatformData(projectData: IProjectData): IPlatformData {
if (!projectData && !this._platformData) {
throw new Error("First call of getPlatformData without providing projectData.");
}
if (projectData && projectData.platformsDir && this._platformsDirCache !== projectData.platformsDir) {
let projectRoot = path.join(projectData.platformsDir, "ios");
this._platformData = {
frameworkPackageName: "tns-ios",
normalizedPlatformName: "iOS",
appDestinationDirectoryPath: path.join(projectRoot, projectData.projectName),
platformProjectService: this,
emulatorServices: this.$iOSEmulatorServices,
projectRoot: projectRoot,
deviceBuildOutputPath: path.join(projectRoot, "build", "device"),
emulatorBuildOutputPath: path.join(projectRoot, "build", "emulator"),
getValidPackageNames: (buildOptions: { isReleaseBuild?: boolean, isForDevice?: boolean }): string[] => {
if (buildOptions.isForDevice) {
return [`${projectData.projectName}.ipa`];
}
return [`${projectData.projectName}.app`, `${projectData.projectName}.zip`];
},
frameworkFilesExtensions: [".a", ".framework", ".bin"],
frameworkDirectoriesExtensions: [".framework"],
frameworkDirectoriesNames: ["Metadata", "metadataGenerator", "NativeScript", "internal"],
targetedOS: ['darwin'],
configurationFileName: "Info.plist",
configurationFilePath: path.join(projectRoot, projectData.projectName, projectData.projectName + "-Info.plist"),
relativeToFrameworkConfigurationFilePath: path.join("__PROJECT_NAME__", "__PROJECT_NAME__-Info.plist"),
fastLivesyncFileExtensions: [".tiff", ".tif", ".jpg", "jpeg", "gif", ".png", ".bmp", ".BMPf", ".ico", ".cur", ".xbm"] // https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/
};
}
return this._platformData;
}
public async validateOptions(projectId: string, provision: true | string): Promise<boolean> {
if (provision === true) {
await this.$iOSProvisionService.list(projectId);
this.$errors.failWithoutHelp("Please provide provisioning profile uuid or name with the --provision option.");
return false;
}
return true;
}
public getAppResourcesDestinationDirectoryPath(projectData: IProjectData): string {
let frameworkVersion = this.getFrameworkVersion(this.getPlatformData(projectData).frameworkPackageName, projectData.projectDir);
if (semver.lt(frameworkVersion, "1.3.0")) {
return path.join(this.getPlatformData(projectData).projectRoot, projectData.projectName, "Resources", "icons");
}
return path.join(this.getPlatformData(projectData).projectRoot, projectData.projectName, "Resources");
}
public async validate(): Promise<void> {
if (!this.$hostInfo.isDarwin) {
return;
}
try {
await this.$childProcess.exec("which xcodebuild");
} catch (error) {
this.$errors.fail("Xcode is not installed. Make sure you have Xcode installed and added to your PATH");
}
let xcodeBuildVersion = await this.getXcodeVersion();
if (helpers.versionCompare(xcodeBuildVersion, IOSProjectService.XCODEBUILD_MIN_VERSION) < 0) {
this.$errors.fail("NativeScript can only run in Xcode version %s or greater", IOSProjectService.XCODEBUILD_MIN_VERSION);
}
}
// TODO: Remove Promise, reason: readDirectory - unable until androidProjectService has async operations.
public async createProject(frameworkDir: string, frameworkVersion: string, projectData: IProjectData, config: ICreateProjectOptions): Promise<void> {
this.$fs.ensureDirectoryExists(path.join(this.getPlatformData(projectData).projectRoot, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER));
if (config.pathToTemplate) {
// Copy everything except the template from the runtime
this.$fs.readDirectory(frameworkDir)
.filter(dirName => dirName.indexOf(IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER) === -1)
.forEach(dirName => shell.cp("-R", path.join(frameworkDir, dirName), this.getPlatformData(projectData).projectRoot));
shell.cp("-rf", path.join(config.pathToTemplate, "*"), this.getPlatformData(projectData).projectRoot);
} else {
shell.cp("-R", path.join(frameworkDir, "*"), this.getPlatformData(projectData).projectRoot);
}
}
//TODO: plamen5kov: revisit this method, might have unnecessary/obsolete logic
public async interpolateData(projectData: IProjectData, platformSpecificData: IPlatformSpecificData): Promise<void> {
let projectRootFilePath = path.join(this.getPlatformData(projectData).projectRoot, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER);
// Starting with NativeScript for iOS 1.6.0, the project Info.plist file resides not in the platform project,
// but in the hello-world app template as a platform specific resource.
if (this.$fs.exists(path.join(projectRootFilePath, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER + "-Info.plist"))) {
this.replaceFileName("-Info.plist", projectRootFilePath, projectData);
}
this.replaceFileName("-Prefix.pch", projectRootFilePath, projectData);
let xcschemeDirPath = path.join(this.getPlatformData(projectData).projectRoot, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER + IOSProjectService.XCODE_PROJECT_EXT_NAME, "xcshareddata/xcschemes");
let xcschemeFilePath = path.join(xcschemeDirPath, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER + IOSProjectService.XCODE_SCHEME_EXT_NAME);
if (this.$fs.exists(xcschemeFilePath)) {
this.$logger.debug("Found shared scheme at xcschemeFilePath, renaming to match project name.");
this.$logger.debug("Checkpoint 0");
this.replaceFileContent(xcschemeFilePath, projectData);
this.$logger.debug("Checkpoint 1");
this.replaceFileName(IOSProjectService.XCODE_SCHEME_EXT_NAME, xcschemeDirPath, projectData);
this.$logger.debug("Checkpoint 2");
} else {
this.$logger.debug("Copying xcscheme from template not found at " + xcschemeFilePath);
}
this.replaceFileName(IOSProjectService.XCODE_PROJECT_EXT_NAME, this.getPlatformData(projectData).projectRoot, projectData);
let pbxprojFilePath = this.getPbxProjPath(projectData);
this.replaceFileContent(pbxprojFilePath, projectData);
}
public interpolateConfigurationFile(projectData: IProjectData, platformSpecificData: IPlatformSpecificData): void {
return undefined;
}
public afterCreateProject(projectRoot: string, projectData: IProjectData): void {
this.$fs.rename(path.join(projectRoot, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER),
path.join(projectRoot, projectData.projectName));
}
/**
* Archive the Xcode project to .xcarchive.
* Returns the path to the .xcarchive.
*/
public async archive(projectData: IProjectData, buildConfig?: IBuildConfig, options?: { archivePath?: string }): Promise<string> {
let projectRoot = this.getPlatformData(projectData).projectRoot;
let archivePath = options && options.archivePath ? path.resolve(options.archivePath) : path.join(projectRoot, "/build/archive/", projectData.projectName + ".xcarchive");
let args = ["archive", "-archivePath", archivePath, "-configuration",
(!buildConfig || buildConfig.release) ? "Release" : "Debug"]
.concat(this.xcbuildProjectArgs(projectRoot, projectData, "scheme"));
await this.$childProcess.spawnFromEvent("xcodebuild", args, "exit", { stdio: 'inherit' });
return archivePath;
}
/**
* Exports .xcarchive for AppStore distribution.
*/
public async exportArchive(projectData: IProjectData, options: { archivePath: string, exportDir?: string, teamID?: string }): Promise<string> {
let projectRoot = this.getPlatformData(projectData).projectRoot;
let archivePath = options.archivePath;
// The xcodebuild exportPath expects directory and writes the <project-name>.ipa at that directory.
let exportPath = path.resolve(options.exportDir || path.join(projectRoot, "/build/archive"));
let exportFile = path.join(exportPath, projectData.projectName + ".ipa");
// These are the options that you can set in the Xcode UI when exporting for AppStore deployment.
let plistTemplate = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
`;
if (options && options.teamID) {
plistTemplate += ` <key>teamID</key>
<string>${options.teamID}</string>
`;
}
plistTemplate += ` <key>method</key>
<string>app-store</string>
<key>uploadBitcode</key>
<false/>
<key>uploadSymbols</key>
<false/>
</dict>
</plist>`;
// Save the options...
temp.track();
let exportOptionsPlist = temp.path({ prefix: "export-", suffix: ".plist" });
this.$fs.writeFile(exportOptionsPlist, plistTemplate);
let args = ["-exportArchive",
"-archivePath", archivePath,
"-exportPath", exportPath,
"-exportOptionsPlist", exportOptionsPlist
];
await this.$childProcess.spawnFromEvent("xcodebuild", args, "exit", { stdio: 'inherit' });
return exportFile;
}
/**
* Exports .xcarchive for a development device.
*/
private async exportDevelopmentArchive(projectData: IProjectData, buildConfig: IBuildConfig, options: { archivePath: string, exportDir?: string, teamID?: string }): Promise<string> {
let platformData = this.getPlatformData(projectData);
let projectRoot = platformData.projectRoot;
let archivePath = options.archivePath;
let buildOutputPath = path.join(projectRoot, "build", "device");
// The xcodebuild exportPath expects directory and writes the <project-name>.ipa at that directory.
let exportPath = path.resolve(options.exportDir || buildOutputPath);
let exportFile = path.join(exportPath, projectData.projectName + ".ipa");
let args = ["-exportArchive",
"-archivePath", archivePath,
"-exportPath", exportPath,
"-exportOptionsPlist", platformData.configurationFilePath
];
await this.$childProcess.spawnFromEvent("xcodebuild", args, "exit",
{ stdio: buildConfig.buildOutputStdio || 'inherit', cwd: this.getPlatformData(projectData).projectRoot },
{ emitOptions: { eventName: constants.BUILD_OUTPUT_EVENT_NAME }, throwError: true });
return exportFile;
}
private xcbuildProjectArgs(projectRoot: string, projectData: IProjectData, product?: "scheme" | "target"): string[] {
let xcworkspacePath = path.join(projectRoot, projectData.projectName + ".xcworkspace");
if (this.$fs.exists(xcworkspacePath)) {
return ["-workspace", xcworkspacePath, product ? "-" + product : "-scheme", projectData.projectName];
} else {
let xcodeprojPath = path.join(projectRoot, projectData.projectName + ".xcodeproj");
return ["-project", xcodeprojPath, product ? "-" + product : "-target", projectData.projectName];
}
}
public async buildProject(projectRoot: string, projectData: IProjectData, buildConfig: IBuildConfig): Promise<void> {
let basicArgs = [
"-configuration", buildConfig.release ? "Release" : "Debug",
"build",
'SHARED_PRECOMPS_DIR=' + path.join(projectRoot, 'build', 'sharedpch')
];
basicArgs = basicArgs.concat(this.xcbuildProjectArgs(projectRoot, projectData));
// Starting from tns-ios 1.4 the xcconfig file is referenced in the project template
let frameworkVersion = this.getFrameworkVersion(this.getPlatformData(projectData).frameworkPackageName, projectData.projectDir);
if (semver.lt(frameworkVersion, "1.4.0")) {
basicArgs.push("-xcconfig", path.join(projectRoot, projectData.projectName, "build.xcconfig"));
}
// if (this.$logger.getLevel() === "INFO") {
// let xcodeBuildVersion = this.getXcodeVersion();
// if (helpers.versionCompare(xcodeBuildVersion, "8.0") >= 0) {
// basicArgs.push("-quiet");
// }
// }
const handler = (data: any) => {
this.emit(constants.BUILD_OUTPUT_EVENT_NAME, data);
};
if (buildConfig.buildForDevice) {
await attachAwaitDetach(constants.BUILD_OUTPUT_EVENT_NAME,
this.$childProcess,
handler,
this.buildForDevice(projectRoot, basicArgs, buildConfig, projectData));
} else {
await attachAwaitDetach(constants.BUILD_OUTPUT_EVENT_NAME,
this.$childProcess,
handler,
this.buildForSimulator(projectRoot, basicArgs, projectData, buildConfig.buildOutputStdio));
}
}
public async validatePlugins(projectData: IProjectData): Promise<void> {
let installedPlugins = await (<IPluginsService>this.$injector.resolve("pluginsService")).getAllInstalledPlugins(projectData);
for (let pluginData of installedPlugins) {
let pluginsFolderExists = this.$fs.exists(path.join(pluginData.pluginPlatformsFolderPath(this.$devicePlatformsConstants.iOS.toLowerCase()), "Podfile"));
let cocoaPodVersion = await this.$sysInfo.getCocoapodVersion();
if (pluginsFolderExists && !cocoaPodVersion) {
this.$errors.failWithoutHelp(`${pluginData.name} has Podfile and you don't have Cocoapods installed or it is not configured correctly. Please verify Cocoapods can work on your machine.`);
}
}
Promise.resolve();
}
private async buildForDevice(projectRoot: string, args: string[], buildConfig: IBuildConfig, projectData: IProjectData): Promise<void> {
let defaultArchitectures = [
'ARCHS=armv7 arm64',
'VALID_ARCHS=armv7 arm64'
];
// build only for device specific architecture
if (!buildConfig.release && !buildConfig.architectures) {
await this.$devicesService.initialize({
platform: this.$devicePlatformsConstants.iOS.toLowerCase(), deviceId: buildConfig.device,
skipEmulatorStart: true
});
let instances = this.$devicesService.getDeviceInstances();
let devicesArchitectures = _(instances)
.filter(d => this.$mobileHelper.isiOSPlatform(d.deviceInfo.platform) && d.deviceInfo.activeArchitecture)
.map(d => d.deviceInfo.activeArchitecture)
.uniq()
.value();
if (devicesArchitectures.length > 0) {
let architectures = [
`ARCHS=${devicesArchitectures.join(" ")}`,
`VALID_ARCHS=${devicesArchitectures.join(" ")}`
];
if (devicesArchitectures.length > 1) {
architectures.push('ONLY_ACTIVE_ARCH=NO');
}
buildConfig.architectures = architectures;
}
}
args = args.concat((buildConfig && buildConfig.architectures) || defaultArchitectures);
args = args.concat([
"-sdk", "iphoneos",
"CONFIGURATION_BUILD_DIR=" + path.join(projectRoot, "build", "device")
]);
let xcodeBuildVersion = await this.getXcodeVersion();
if (helpers.versionCompare(xcodeBuildVersion, "8.0") >= 0) {
await this.setupSigningForDevice(projectRoot, buildConfig, projectData);
}
if (buildConfig && buildConfig.codeSignIdentity) {
args.push(`CODE_SIGN_IDENTITY=${buildConfig.codeSignIdentity}`);
}
if (buildConfig && buildConfig.mobileProvisionIdentifier) {
args.push(`PROVISIONING_PROFILE=${buildConfig.mobileProvisionIdentifier}`);
}
if (buildConfig && buildConfig.teamIdentifier) {
args.push(`DEVELOPMENT_TEAM=${buildConfig.teamIdentifier}`);
}
// this.$logger.out("xcodebuild...");
await this.$childProcess.spawnFromEvent("xcodebuild",
args,
"exit",
{ stdio: buildConfig.buildOutputStdio || "inherit", cwd: this.getPlatformData(projectData).projectRoot },
{ emitOptions: { eventName: constants.BUILD_OUTPUT_EVENT_NAME }, throwError: true });
// this.$logger.out("xcodebuild build succeded.");
await this.createIpa(projectRoot, projectData, buildConfig);
}
private async setupSigningFromProvision(projectRoot: string, projectData: IProjectData, provision?: string, mobileProvisionData?: mobileprovision.provision.MobileProvision): Promise<void> {
if (provision) {
const xcode = this.$pbxprojDomXcode.Xcode.open(this.getPbxProjPath(projectData));
const signing = xcode.getSigning(projectData.projectName);
let shouldUpdateXcode = false;
if (signing && signing.style === "Manual") {
for (let config in signing.configurations) {
let options = signing.configurations[config];
if (options.name !== provision && options.uuid !== provision) {
shouldUpdateXcode = true;
break;
}
}
} else {
shouldUpdateXcode = true;
}
if (shouldUpdateXcode) {
const pickStart = Date.now();
const mobileprovision = mobileProvisionData || await this.$iOSProvisionService.pick(provision, projectData.projectId);
const pickEnd = Date.now();
this.$logger.trace("Searched and " + (mobileprovision ? "found" : "failed to find ") + " matching provisioning profile. (" + (pickEnd - pickStart) + "ms.)");
if (!mobileprovision) {
this.$errors.failWithoutHelp("Failed to find mobile provision with UUID or Name: " + provision);
}
xcode.setManualSigningStyle(projectData.projectName, {
team: mobileprovision.TeamIdentifier && mobileprovision.TeamIdentifier.length > 0 ? mobileprovision.TeamIdentifier[0] : undefined,
uuid: mobileprovision.UUID,
name: mobileprovision.Name,
identity: mobileprovision.Type === "Development" ? "iPhone Developer" : "iPhone Distribution"
});
xcode.save();
// this.cache(uuid);
this.$logger.trace("Set Manual signing style and provisioning profile.");
} else {
this.$logger.trace("The specified provisioning profile allready set in the Xcode.");
}
} else {
// read uuid from Xcode and cache...
}
}
private async setupSigningForDevice(projectRoot: string, buildConfig: IiOSBuildConfig, projectData: IProjectData): Promise<void> {
const xcode = this.$pbxprojDomXcode.Xcode.open(this.getPbxProjPath(projectData));
const signing = xcode.getSigning(projectData.projectName);
const hasProvisioningProfileInXCConfig =
this.readXCConfigProvisioningProfileSpecifierForIPhoneOs(projectData) ||
this.readXCConfigProvisioningProfileSpecifier(projectData) ||
this.readXCConfigProvisioningProfileForIPhoneOs(projectData) ||
this.readXCConfigProvisioningProfile(projectData);
if (hasProvisioningProfileInXCConfig && (!signing || signing.style !== "Manual")) {
xcode.setManualSigningStyle(projectData.projectName);
xcode.save();
} else if (!buildConfig.provision && !(signing && signing.style === "Manual" && !buildConfig.teamId)) {
if (buildConfig) {
delete buildConfig.teamIdentifier;
}
const teamId = await this.getDevelopmentTeam(projectData, buildConfig.teamId);
xcode.setAutomaticSigningStyle(projectData.projectName, teamId);
xcode.save();
this.$logger.trace("Set Automatic signing style and team.");
}
}
private async buildForSimulator(projectRoot: string, args: string[], projectData: IProjectData, buildOutputStdio?: string): Promise<void> {
args = args.concat([
"-sdk", "iphonesimulator",
"ARCHS=i386 x86_64",
"VALID_ARCHS=i386 x86_64",
"ONLY_ACTIVE_ARCH=NO",
"CONFIGURATION_BUILD_DIR=" + path.join(projectRoot, "build", "emulator"),
"CODE_SIGN_IDENTITY="
]);
await this.$childProcess.spawnFromEvent("xcodebuild", args, "exit",
{ stdio: buildOutputStdio || "inherit", cwd: this.getPlatformData(projectData).projectRoot },
{ emitOptions: { eventName: constants.BUILD_OUTPUT_EVENT_NAME }, throwError: true });
}
private async createIpa(projectRoot: string, projectData: IProjectData, buildConfig: IBuildConfig): Promise<string> {
let xarchivePath = await this.archive(projectData, buildConfig);
let exportFileIpa = await this.exportDevelopmentArchive(projectData,
buildConfig,
{
archivePath: xarchivePath,
});
return exportFileIpa;
}
public isPlatformPrepared(projectRoot: string, projectData: IProjectData): boolean {
return this.$fs.exists(path.join(projectRoot, projectData.projectName, constants.APP_FOLDER_NAME));
}
public cleanDeviceTempFolder(deviceIdentifier: string): Promise<void> {
return Promise.resolve();
}
private async addFramework(frameworkPath: string, projectData: IProjectData): Promise<void> {
if (!this.$hostInfo.isWindows) {
this.validateFramework(frameworkPath);
let project = this.createPbxProj(projectData);
let frameworkName = path.basename(frameworkPath, path.extname(frameworkPath));
let frameworkBinaryPath = path.join(frameworkPath, frameworkName);
let isDynamic = _.includes((await this.$childProcess.spawnFromEvent("file", [frameworkBinaryPath], "close")).stdout, "dynamically linked");
let frameworkAddOptions: IXcode.Options = { customFramework: true };
if (isDynamic) {
frameworkAddOptions["embed"] = true;
}
let frameworkRelativePath = '$(SRCROOT)/' + this.getLibSubpathRelativeToProjectPath(frameworkPath, projectData);
project.addFramework(frameworkRelativePath, frameworkAddOptions);
this.savePbxProj(project, projectData);
}
}
private async addStaticLibrary(staticLibPath: string, projectData: IProjectData): Promise<void> {
await this.validateStaticLibrary(staticLibPath);
// Copy files to lib folder.
let libraryName = path.basename(staticLibPath, ".a");
let headersSubpath = path.join(path.dirname(staticLibPath), "include", libraryName);
// Add static library to project file and setup header search paths
let project = this.createPbxProj(projectData);
let relativeStaticLibPath = this.getLibSubpathRelativeToProjectPath(staticLibPath, projectData);
project.addFramework(relativeStaticLibPath);
let relativeHeaderSearchPath = path.join(this.getLibSubpathRelativeToProjectPath(headersSubpath, projectData));
project.addToHeaderSearchPaths({ relativePath: relativeHeaderSearchPath });
this.generateModulemap(headersSubpath, libraryName);
this.savePbxProj(project, projectData);
}
public canUpdatePlatform(installedModuleDir: string, projectData: IProjectData): boolean {
let currentXcodeProjectFile = this.buildPathToCurrentXcodeProjectFile(projectData);
let currentXcodeProjectFileContent = this.$fs.readFile(currentXcodeProjectFile);
let newXcodeProjectFile = this.buildPathToNewXcodeProjectFile(installedModuleDir);
this.replaceFileContent(newXcodeProjectFile, projectData);
let newXcodeProjectFileContent = this.$fs.readFile(newXcodeProjectFile);
let contentIsTheSame = currentXcodeProjectFileContent.toString() === newXcodeProjectFileContent.toString();
if (!contentIsTheSame) {
this.$logger.warn(`The content of the current project file: ${currentXcodeProjectFile} and the new project file: ${newXcodeProjectFile} is different.`);
}
return contentIsTheSame;
}
/**
* Patch **LaunchScreen.xib** so we can be backward compatible for eternity.
* The **xcodeproj** template proior v**2.1.0** had blank white screen launch screen.
* We extended that by adding **app/AppResources/iOS/LaunchScreen.storyboard**
* However for projects created prior **2.1.0** to keep working without the obsolete **LaunchScreen.xib**
* we must still provide it on prepare.
* Here we check if **UILaunchStoryboardName** is set to **LaunchScreen** in the **platform/ios/<proj>/<proj>-Info.plist**.
* If it is, and no **LaunchScreen.storyboard** nor **.xib** is found in the project, we will create one.
*/
private provideLaunchScreenIfMissing(projectData: IProjectData): void {
try {
this.$logger.trace("Checking if we need to provide compatability LaunchScreen.xib");
let platformData = this.getPlatformData(projectData);
let projectPath = path.join(platformData.projectRoot, projectData.projectName);
let projectPlist = this.getInfoPlistPath(projectData);
let plistContent = plist.parse(this.$fs.readText(projectPlist));
let storyName = plistContent["UILaunchStoryboardName"];
this.$logger.trace(`Examining ${projectPlist} UILaunchStoryboardName: "${storyName}".`);
if (storyName !== "LaunchScreen") {
this.$logger.trace("The project has its UILaunchStoryboardName set to " + storyName + " which is not the pre v2.1.0 default LaunchScreen, probably the project is migrated so we are good to go.");
return;
}
let expectedStoryPath = path.join(projectPath, "Resources", "LaunchScreen.storyboard");
if (this.$fs.exists(expectedStoryPath)) {
// Found a LaunchScreen on expected path
this.$logger.trace("LaunchScreen.storyboard was found. Project is up to date.");
return;
}
this.$logger.trace("LaunchScreen file not found at: " + expectedStoryPath);
let expectedXibPath = path.join(projectPath, "en.lproj", "LaunchScreen.xib");
if (this.$fs.exists(expectedXibPath)) {
this.$logger.trace("Obsolete LaunchScreen.xib was found. It'k OK, we are probably running with iOS runtime from pre v2.1.0.");
return;
}
this.$logger.trace("LaunchScreen file not found at: " + expectedXibPath);
let isTheLaunchScreenFile = (fileName: string) => fileName === "LaunchScreen.xib" || fileName === "LaunchScreen.storyboard";
let matches = this.$fs.enumerateFilesInDirectorySync(projectPath, isTheLaunchScreenFile, { enumerateDirectories: false });
if (matches.length > 0) {
this.$logger.trace("Found LaunchScreen by slowly traversing all files here: " + matches + "\nConsider moving the LaunchScreen so it could be found at: " + expectedStoryPath);
return;
}
let compatabilityXibPath = path.join(projectPath, "Resources", "LaunchScreen.xib");
this.$logger.warn(`Failed to find LaunchScreen.storyboard but it was specified in the Info.plist.
Consider updating the resources in app/App_Resources/iOS/.
A good starting point would be to create a new project and diff the changes with your current one.
Also the following repo may be helpful: https://github.com/NativeScript/template-hello-world/tree/master/App_Resources/iOS
We will now place an empty obsolete compatability white screen LauncScreen.xib for you in ${path.relative(projectData.projectDir, compatabilityXibPath)} so your app may appear as it did in pre v2.1.0 versions of the ios runtime.`);
let content = `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="6751" systemVersion="14A389" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6736"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="iN0-l3-epB">
<rect key="frame" x="0.0" y="0.0" width="480" height="480"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<nil key="simulatedStatusBarMetrics"/>
<freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
<point key="canvasLocation" x="548" y="455"/>
</view>
</objects>
</document>`;
try {
this.$fs.createDirectory(path.dirname(compatabilityXibPath));
this.$fs.writeFile(compatabilityXibPath, content);
} catch (e) {
this.$logger.warn("We have failed to add compatability LaunchScreen.xib due to: " + e);
}
} catch (e) {
this.$logger.warn("We have failed to check if we need to add a compatability LaunchScreen.xib due to: " + e);
}
}
public async prepareProject(projectData: IProjectData, platformSpecificData: IPlatformSpecificData): Promise<void> {
let provision = platformSpecificData && platformSpecificData.provision;
if (provision) {
let projectRoot = path.join(projectData.platformsDir, "ios");
await this.setupSigningFromProvision(projectRoot, projectData, provision, platformSpecificData.mobileProvisionData);
}
let project = this.createPbxProj(projectData);
this.provideLaunchScreenIfMissing(projectData);
let resources = project.pbxGroupByName("Resources");
if (resources) {
let references = project.pbxFileReferenceSection();
let xcodeProjectImages = _.map(<any[]>resources.children, resource => this.replace(references[resource.value].name));
this.$logger.trace("Images from Xcode project");
this.$logger.trace(xcodeProjectImages);
let appResourcesImages = this.$fs.readDirectory(this.getAppResourcesDestinationDirectoryPath(projectData));
this.$logger.trace("Current images from App_Resources");
this.$logger.trace(appResourcesImages);
let imagesToAdd = _.difference(appResourcesImages, xcodeProjectImages);
this.$logger.trace(`New images to add into xcode project: ${imagesToAdd.join(", ")}`);
_.each(imagesToAdd, image => project.addResourceFile(path.relative(this.getPlatformData(projectData).projectRoot, path.join(this.getAppResourcesDestinationDirectoryPath(projectData), image))));
let imagesToRemove = _.difference(xcodeProjectImages, appResourcesImages);
this.$logger.trace(`Images to remove from xcode project: ${imagesToRemove.join(", ")}`);
_.each(imagesToRemove, image => project.removeResourceFile(path.join(this.getAppResourcesDestinationDirectoryPath(projectData), image)));
this.savePbxProj(project, projectData);
}
}
public prepareAppResources(appResourcesDirectoryPath: string, projectData: IProjectData): void {
let platformFolder = path.join(appResourcesDirectoryPath, this.getPlatformData(projectData).normalizedPlatformName);
let filterFile = (filename: string) => this.$fs.deleteFile(path.join(platformFolder, filename));
filterFile(this.getPlatformData(projectData).configurationFileName);
this.$fs.deleteDirectory(this.getAppResourcesDestinationDirectoryPath(projectData));
}
public async processConfigurationFilesFromAppResources(release: boolean, projectData: IProjectData): Promise<void> {
await this.mergeInfoPlists({ release }, projectData);
await this.$iOSEntitlementsService.merge(projectData);
await this.mergeProjectXcconfigFiles(release, projectData);
for (let pluginData of await this.getAllInstalledPlugins(projectData)) {
await this.$pluginVariablesService.interpolatePluginVariables(pluginData, this.getPlatformData(projectData).configurationFilePath, projectData);
}
this.$pluginVariablesService.interpolateAppIdentifier(this.getPlatformData(projectData).configurationFilePath, projectData);
}
private getInfoPlistPath(projectData: IProjectData): string {
return path.join(
projectData.projectDir,
constants.APP_FOLDER_NAME,
constants.APP_RESOURCES_FOLDER_NAME,
this.getPlatformData(projectData).normalizedPlatformName,
this.getPlatformData(projectData).configurationFileName
);
}
public ensureConfigurationFileInAppResources(): void {
return null;
}
public async stopServices(): Promise<ISpawnResult> {
return { stderr: "", stdout: "", exitCode: 0 };
}
public async cleanProject(projectRoot: string): Promise<void> {
return Promise.resolve();
}
private async mergeInfoPlists(buildOptions: IRelease, projectData: IProjectData): Promise<void> {
let projectDir = projectData.projectDir;
let infoPlistPath = path.join(projectDir, constants.APP_FOLDER_NAME, constants.APP_RESOURCES_FOLDER_NAME, this.getPlatformData(projectData).normalizedPlatformName, this.getPlatformData(projectData).configurationFileName);
this.ensureConfigurationFileInAppResources();
if (!this.$fs.exists(infoPlistPath)) {
this.$logger.trace("Info.plist: No app/App_Resources/iOS/Info.plist found, falling back to pre-1.6.0 Info.plist behavior.");
return;
}
const reporterTraceMessage = "Info.plist:";
const reporter: Reporter = {
log: (txt: string) => this.$logger.trace(`${reporterTraceMessage} ${txt}`),
warn: (txt: string) => this.$logger.warn(`${reporterTraceMessage} ${txt}`)
};
let session = new PlistSession(reporter);
let makePatch = (plistPath: string) => {
if (!this.$fs.exists(plistPath)) {
this.$logger.trace("No plist found at: " + plistPath);
return;
}
this.$logger.trace("Schedule merge plist at: " + plistPath);
session.patch({
name: path.relative(projectDir, plistPath),
read: () => this.$fs.readText(plistPath)
});
};
let allPlugins = await this.getAllInstalledPlugins(projectData);
for (let plugin of allPlugins) {
let pluginInfoPlistPath = path.join(plugin.pluginPlatformsFolderPath(IOSProjectService.IOS_PLATFORM_NAME), this.getPlatformData(projectData).configurationFileName);
makePatch(pluginInfoPlistPath);
}
makePatch(infoPlistPath);
if (projectData.projectId) {
session.patch({
name: "CFBundleIdentifier from package.json nativescript.id",
read: () =>
`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>${projectData.projectId}</string>
</dict>
</plist>`
});
}
if (!buildOptions.release && projectData.projectId) {
session.patch({
name: "CFBundleURLTypes from package.json nativescript.id",
read: () =>
`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>${projectData.projectId.replace(/[^A-Za-z0-9]/g, "")}</string>
</array>
</dict>
</array>
</dict>
</plist>`
});
}
let plistContent = session.build();
this.$logger.trace("Info.plist: Write to: " + this.getPlatformData(projectData).configurationFilePath);
this.$fs.writeFile(this.getPlatformData(projectData).configurationFilePath, plistContent);
}
private getAllInstalledPlugins(projectData: IProjectData): Promise<IPluginData[]> {
return (<IPluginsService>this.$injector.resolve("pluginsService")).getAllInstalledPlugins(projectData);
}
private getXcodeprojPath(projectData: IProjectData): string {
return path.join(this.getPlatformData(projectData).projectRoot, projectData.projectName + IOSProjectService.XCODE_PROJECT_EXT_NAME);
}
private getProjectPodFilePath(projectData: IProjectData): string {
return path.join(this.getPlatformData(projectData).projectRoot, "Podfile");
}
private getPluginsDebugXcconfigFilePath(projectData: IProjectData): string {
return path.join(this.getPlatformData(projectData).projectRoot, "plugins-debug.xcconfig");
}
private getPluginsReleaseXcconfigFilePath(projectData: IProjectData): string {
return path.join(this.getPlatformData(projectData).projectRoot, "plugins-release.xcconfig");
}
private replace(name: string): string {
if (_.startsWith(name, '"')) {
name = name.substr(1, name.length - 2);
}
return name.replace(/\\\"/g, "\"");
}
private getLibSubpathRelativeToProjectPath(targetPath: string, projectData: IProjectData): string {
let frameworkPath = path.relative(this.getPlatformData(projectData).projectRoot, targetPath);
return frameworkPath;
}
private getPbxProjPath(projectData: IProjectData): string {
return path.join(this.getXcodeprojPath(projectData), "project.pbxproj");
}
private createPbxProj(projectData: IProjectData): any {
let project = new this.$xcode.project(this.getPbxProjPath(projectData));
project.parseSync();
return project;
}
private savePbxProj(project: any, projectData: IProjectData): void {
return this.$fs.writeFile(this.getPbxProjPath(projectData), project.writeSync());
}
public async preparePluginNativeCode(pluginData: IPluginData, projectData: IProjectData, opts?: any): Promise<void> {
let pluginPlatformsFolderPath = pluginData.pluginPlatformsFolderPath(IOSProjectService.IOS_PLATFORM_NAME);
await this.prepareFrameworks(pluginPlatformsFolderPath, pluginData, projectData);
await this.prepareStaticLibs(pluginPlatformsFolderPath, pluginData, projectData);
await this.prepareCocoapods(pluginPlatformsFolderPath, projectData);
}
public async removePluginNativeCode(pluginData: IPluginData, projectData: IProjectData): Promise<void> {
let pluginPlatformsFolderPath = pluginData.pluginPlatformsFolderPath(IOSProjectService.IOS_PLATFORM_NAME);
this.removeFrameworks(pluginPlatformsFolderPath, pluginData, projectData);
this.removeStaticLibs(pluginPlatformsFolderPath, pluginData, projectData);
this.removeCocoapods(pluginPlatformsFolderPath, projectData);
}
public async afterPrepareAllPlugins(projectData: IProjectData): Promise<void> {
if (this.$fs.exists(this.getProjectPodFilePath(projectData))) {
let projectPodfileContent = this.$fs.readText(this.getProjectPodFilePath(projectData));
this.$logger.trace("Project Podfile content");
this.$logger.trace(projectPodfileContent);
let firstPostInstallIndex = projectPodfileContent.indexOf(IOSProjectService.PODFILE_POST_INSTALL_SECTION_NAME);
if (firstPostInstallIndex !== -1 && firstPostInstallIndex !== projectPodfileContent.lastIndexOf(IOSProjectService.PODFILE_POST_INSTALL_SECTION_NAME)) {
this.$cocoapodsService.mergePodfileHookContent(IOSProjectService.PODFILE_POST_INSTALL_SECTION_NAME, this.getProjectPodFilePath(projectData));
}
let xcuserDataPath = path.join(this.getXcodeprojPath(projectData), "xcuserdata");
let sharedDataPath = path.join(this.getXcodeprojPath(projectData), "xcshareddata");
if (!this.$fs.exists(xcuserDataPath) && !this.$fs.exists(sharedDataPath)) {
this.$logger.info("Creating project scheme...");
await this.checkIfXcodeprojIsRequired();
let createSchemeRubyScript = `ruby -e "require 'xcodeproj'; xcproj = Xcodeproj::Project.open('${projectData.projectName}.xcodeproj'); xcproj.recreate_user_schemes; xcproj.save"`;
await this.$childProcess.exec(createSchemeRubyScript, { cwd: this.getPlatformData(projectData).projectRoot });
}
await this.executePodInstall(projectData);
}
}
public beforePrepareAllPlugins(): Promise<void> {
return Promise.resolve();
}
public checkForChanges(changesInfo: IProjectChangesInfo, options: IProjectChangesOptions, projectData: IProjectData): void {
const provision = options.provision;
if (provision !== undefined) {
// Check if the native project's signing is set to the provided provision...
const pbxprojPath = this.getPbxProjPath(projectData);
if (this.$fs.exists(pbxprojPath)) {
const xcode = this.$pbxprojDomXcode.Xcode.open(pbxprojPath);
const signing = xcode.getSigning(projectData.projectName);
if (signing && signing.style === "Manual") {
for (let name in signing.configurations) {
let config = signing.configurations[name];
if (config.uuid !== provision && config.name !== provision) {
changesInfo.signingChanged = true;
break;
}
}
} else {
// Specifying provisioning profile requires "Manual" signing style.
// If the current signing style was not "Manual" it was probably "Automatic" or,
// it was not uniform for the debug and release build configurations.
changesInfo.signingChanged = true;
}
} else {
changesInfo.signingChanged = true;
}
}
}
private getAllLibsForPluginWithFileExtension(pluginData: IPluginData, fileExtension: string): string[] {
let filterCallback = (fileName: string, pluginPlatformsFolderPath: string) => path.extname(fileName) === fileExtension;
return this.getAllNativeLibrariesForPlugin(pluginData, IOSProjectService.IOS_PLATFORM_NAME, filterCallback);
}
private buildPathToCurrentXcodeProjectFile(projectData: IProjectData): string {
return path.join(projectData.platformsDir, "ios", `${projectData.projectName}.xcodeproj`, "project.pbxproj");
}
private buildPathToNewXcodeProjectFile(newModulesDir: string): string {
return path.join(newModulesDir, constants.PROJECT_FRAMEWORK_FOLDER_NAME, `${IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER}.xcodeproj`, "project.pbxproj");
}
private validateFramework(libraryPath: string): void {
const infoPlistPath = path.join(libraryPath, "Info.plist");
if (!this.$fs.exists(infoPlistPath)) {
this.$errors.failWithoutHelp("The bundle at %s does not contain an Info.plist file.", libraryPath);
}
const plistJson = simplePlist.readFileSync(infoPlistPath);
const packageType = plistJson["CFBundlePackageType"];
if (packageType !== "FMWK") {
this.$errors.failWithoutHelp("The bundle at %s does not appear to be a dynamic framework.", libraryPath);
}
}
private async validateStaticLibrary(libraryPath: string): Promise<void> {
if (path.extname(libraryPath) !== ".a") {
this.$errors.failWithoutHelp(`The bundle at ${libraryPath} does not contain a valid static library in the '.a' file format.`);
}
let expectedArchs = ["armv7", "arm64", "i386"];
let archsInTheFatFile = await this.$childProcess.exec("lipo -i " + libraryPath);
expectedArchs.forEach(expectedArch => {
if (archsInTheFatFile.indexOf(expectedArch) < 0) {
this.$errors.failWithoutHelp(`The static library at ${libraryPath} is not built for one or more of the following required architectures: ${expectedArchs.join(", ")}. The static library must be built for all required architectures.`);
}
});
}
private replaceFileContent(file: string, projectData: IProjectData): void {
let fileContent = this.$fs.readText(file);
let replacedContent = helpers.stringReplaceAll(fileContent, IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER, projectData.projectName);
this.$fs.writeFile(file, replacedContent);
}
private replaceFileName(fileNamePart: string, fileRootLocation: string, projectData: IProjectData): void {
let oldFileName = IOSProjectService.IOS_PROJECT_NAME_PLACEHOLDER + fileNamePart;
let newFileName = projectData.projectName + fileNamePart;
this.$fs.rename(path.join(fileRootLocation, oldFileName), path.join(fileRootLocation, newFileName));
}
private async executePodInstall(projectData: IProjectData): Promise<any> {
// Check availability
try {
await this.$childProcess.exec("gem which cocoapods");
await this.$childProcess.exec("gem which xcodeproj");
} catch (e) {
this.$errors.failWithoutHelp("CocoaPods or ruby gem 'xcodeproj' is not installed. Run `sudo gem install cocoapods` and try again.");
}
await this.$xcprojService.verifyXcproj(true);
this.$logger.info("Installing pods...");
let podTool = this.$config.USE_POD_SANDBOX ? "sandbox-pod" : "pod";
let childProcess = await this.$childProcess.spawnFromEvent(podTool, ["install"], "close", { cwd: this.getPlatformData(projectData).projectRoot, stdio: ['pipe', process.stdout, 'pipe'] });
if (childProcess.stderr) {
let warnings = childProcess.stderr.match(/(\u001b\[(?:\d*;){0,5}\d*m[\s\S]+?\u001b\[(?:\d*;){0,5}\d*m)|(\[!\].*?\n)|(.*?warning.*)/gi);
_.each(warnings, (warning: string) => {
this.$logger.warnWithLabel(warning.replace("\n", ""));
});
let errors = childProcess.stderr;
_.each(warnings, warning => {
errors = errors.replace(warning, "");
});