-
-
Notifications
You must be signed in to change notification settings - Fork 195
/
platform-service.ts
807 lines (660 loc) · 35.2 KB
/
platform-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
import * as path from "path";
import * as shell from "shelljs";
import * as constants from "../constants";
import { Configurations } from "../common/constants";
import * as helpers from "../common/helpers";
import * as semver from "semver";
import { EventEmitter } from "events";
import { AppFilesUpdater } from "./app-files-updater";
import { attachAwaitDetach } from "../common/helpers";
import * as temp from "temp";
temp.track();
const buildInfoFileName = ".nsbuildinfo";
export class PlatformService extends EventEmitter implements IPlatformService {
// Type with hooks needs to have either $hooksService or $injector injected.
// In order to stop TypeScript from failing for not used $hooksService, use it here.
private get _hooksService(): IHooksService {
return this.$hooksService;
}
private _trackedProjectFilePath: string = null;
constructor(private $devicesService: Mobile.IDevicesService,
private $preparePlatformNativeService: IPreparePlatformService,
private $preparePlatformJSService: IPreparePlatformService,
private $progressIndicator: IProgressIndicator,
private $errors: IErrors,
private $fs: IFileSystem,
private $logger: ILogger,
private $npmInstallationManager: INpmInstallationManager,
private $platformsData: IPlatformsData,
private $projectDataService: IProjectDataService,
private $hooksService: IHooksService,
private $pluginsService: IPluginsService,
private $projectFilesManager: IProjectFilesManager,
private $mobileHelper: Mobile.IMobileHelper,
private $hostInfo: IHostInfo,
private $devicePathProvider: IDevicePathProvider,
private $npm: INodePackageManager,
private $devicePlatformsConstants: Mobile.IDevicePlatformsConstants,
private $projectChangesService: IProjectChangesService,
private $analyticsService: IAnalyticsService) {
super();
}
public async cleanPlatforms(platforms: string[], platformTemplate: string, projectData: IProjectData, config: IPlatformOptions, framworkPath?: string): Promise<void> {
for (const platform of platforms) {
const version: string = this.getCurrentPlatformVersion(platform, projectData);
let platformWithVersion: string = platform;
if (version !== undefined) {
platformWithVersion += "@" + version;
}
await this.removePlatforms([platform], projectData);
await this.addPlatforms([platformWithVersion], platformTemplate, projectData, config);
}
}
public async addPlatforms(platforms: string[], platformTemplate: string, projectData: IProjectData, config: IPlatformOptions, frameworkPath?: string): Promise<void> {
const platformsDir = projectData.platformsDir;
this.$fs.ensureDirectoryExists(platformsDir);
for (const platform of platforms) {
this.validatePlatform(platform, projectData);
const platformPath = path.join(projectData.platformsDir, platform);
if (this.$fs.exists(platformPath)) {
this.$errors.failWithoutHelp(`Platform ${platform} already added`);
}
await this.addPlatform(platform.toLowerCase(), platformTemplate, projectData, config, frameworkPath);
}
}
private getCurrentPlatformVersion(platform: string, projectData: IProjectData): string {
const platformData = this.$platformsData.getPlatformData(platform, projectData);
const currentPlatformData: any = this.$projectDataService.getNSValue(projectData.projectDir, platformData.frameworkPackageName);
let version: string;
if (currentPlatformData && currentPlatformData[constants.VERSION_STRING]) {
version = currentPlatformData[constants.VERSION_STRING];
}
return version;
}
private async addPlatform(platformParam: string, platformTemplate: string, projectData: IProjectData, config: IPlatformOptions, frameworkPath?: string, nativePrepare?: INativePrepare): Promise<void> {
const data = platformParam.split("@");
const platform = data[0].toLowerCase();
let version = data[1];
const platformData = this.$platformsData.getPlatformData(platform, projectData);
if (version === undefined) {
version = this.getCurrentPlatformVersion(platform, projectData);
}
// Log the values for project
this.$logger.trace("Creating NativeScript project for the %s platform", platform);
this.$logger.trace("Path: %s", platformData.projectRoot);
this.$logger.trace("Package: %s", projectData.projectId);
this.$logger.trace("Name: %s", projectData.projectName);
this.$logger.out("Copying template files...");
let packageToInstall = "";
const npmOptions: IStringDictionary = {
pathToSave: path.join(projectData.platformsDir, platform),
dependencyType: "save"
};
if (!frameworkPath) {
packageToInstall = platformData.frameworkPackageName;
npmOptions["version"] = version;
}
const spinner = this.$progressIndicator.getSpinner("Installing " + packageToInstall);
const projectDir = projectData.projectDir;
const platformPath = path.join(projectData.platformsDir, platform);
try {
spinner.start();
const downloadedPackagePath = await this.$npmInstallationManager.install(packageToInstall, projectDir, npmOptions);
let frameworkDir = path.join(downloadedPackagePath, constants.PROJECT_FRAMEWORK_FOLDER_NAME);
frameworkDir = path.resolve(frameworkDir);
const coreModuleName = await this.addPlatformCore(platformData, frameworkDir, platformTemplate, projectData, config, nativePrepare);
await this.$npm.uninstall(coreModuleName, { save: true }, projectData.projectDir);
} catch (err) {
this.$fs.deleteDirectory(platformPath);
throw err;
} finally {
spinner.stop();
}
this.$fs.ensureDirectoryExists(platformPath);
this.$logger.out("Project successfully created.");
}
private async addPlatformCore(platformData: IPlatformData, frameworkDir: string, platformTemplate: string, projectData: IProjectData, config: IPlatformOptions, nativePrepare?: INativePrepare): Promise<string> {
const coreModuleData = this.$fs.readJson(path.join(frameworkDir, "..", "package.json"));
const installedVersion = coreModuleData.version;
await this.$preparePlatformJSService.addPlatform({
platformData,
frameworkDir,
installedVersion,
projectData,
config,
platformTemplate
});
if (!nativePrepare || !nativePrepare.skipNativePrepare) {
const platformDir = path.join(projectData.platformsDir, platformData.normalizedPlatformName.toLowerCase());
this.$fs.deleteDirectory(platformDir);
await this.$preparePlatformNativeService.addPlatform({
platformData,
frameworkDir,
installedVersion,
projectData,
config
});
}
const coreModuleName = coreModuleData.name;
return coreModuleName;
}
public getInstalledPlatforms(projectData: IProjectData): string[] {
if (!this.$fs.exists(projectData.platformsDir)) {
return [];
}
const subDirs = this.$fs.readDirectory(projectData.platformsDir);
return _.filter(subDirs, p => this.$platformsData.platformsNames.indexOf(p) > -1);
}
public getAvailablePlatforms(projectData: IProjectData): string[] {
const installedPlatforms = this.getInstalledPlatforms(projectData);
return _.filter(this.$platformsData.platformsNames, p => {
return installedPlatforms.indexOf(p) < 0 && this.isPlatformSupportedForOS(p, projectData); // Only those not already installed
});
}
public getPreparedPlatforms(projectData: IProjectData): string[] {
return _.filter(this.$platformsData.platformsNames, p => { return this.isPlatformPrepared(p, projectData); });
}
public async preparePlatform(platformInfo: IPreparePlatformInfo): Promise<boolean> {
const platformData = this.$platformsData.getPlatformData(platformInfo.platform, platformInfo.projectData);
const changesInfo = await this.initialPrepare(platformInfo.platform, platformData, platformInfo.appFilesUpdaterOptions, platformInfo.platformTemplate, platformInfo.projectData, platformInfo.config, platformInfo.nativePrepare);
const requiresNativePrepare = (!platformInfo.nativePrepare || !platformInfo.nativePrepare.skipNativePrepare) && changesInfo.nativePlatformStatus === constants.NativePlatformStatus.requiresPrepare;
if (changesInfo.hasChanges || platformInfo.appFilesUpdaterOptions.bundle || requiresNativePrepare) {
// Always clear up the app directory in platforms if `--bundle` value has changed in between builds or is passed in general
// this is done as user has full control over what goes in platforms when `--bundle` is passed
// and we may end up with duplicate symbols which would fail the build
if (changesInfo.bundleChanged || platformInfo.appFilesUpdaterOptions.bundle) {
await this.cleanDestinationApp(platformInfo);
}
await this.preparePlatformCore(
platformInfo.platform,
platformInfo.appFilesUpdaterOptions,
platformInfo.projectData,
platformInfo.config,
platformInfo.env,
changesInfo,
platformInfo.filesToSync,
platformInfo.nativePrepare,
);
this.$projectChangesService.savePrepareInfo(platformInfo.platform, platformInfo.projectData);
} else {
this.$logger.out("Skipping prepare.");
}
return true;
}
public async validateOptions(provision: true | string, teamId: true | string, projectData: IProjectData, platform?: string): Promise<boolean> {
if (platform) {
platform = this.$mobileHelper.normalizePlatformName(platform);
this.$logger.trace("Validate options for platform: " + platform);
const platformData = this.$platformsData.getPlatformData(platform, projectData);
return await platformData.platformProjectService.validateOptions(projectData.projectId, provision, teamId);
} else {
let valid = true;
for (const availablePlatform in this.$platformsData.availablePlatforms) {
this.$logger.trace("Validate options for platform: " + availablePlatform);
const platformData = this.$platformsData.getPlatformData(availablePlatform, projectData);
valid = valid && await platformData.platformProjectService.validateOptions(projectData.projectId, provision, teamId);
}
return valid;
}
}
private async initialPrepare(platform: string, platformData: IPlatformData, appFilesUpdaterOptions: IAppFilesUpdaterOptions, platformTemplate: string, projectData: IProjectData, config: IPlatformOptions, nativePrepare?: INativePrepare): Promise<IProjectChangesInfo> {
this.validatePlatform(platform, projectData);
await this.trackProjectType(projectData);
//We need dev-dependencies here, so before-prepare hooks will be executed correctly.
try {
await this.$pluginsService.ensureAllDependenciesAreInstalled(projectData);
} catch (err) {
this.$logger.trace(err);
this.$errors.failWithoutHelp(`Unable to install dependencies. Make sure your package.json is valid and all dependencies are correct. Error is: ${err.message}`);
}
await this.ensurePlatformInstalled(platform, platformTemplate, projectData, config, nativePrepare);
const bundle = appFilesUpdaterOptions.bundle;
const nativePlatformStatus = (nativePrepare && nativePrepare.skipNativePrepare) ? constants.NativePlatformStatus.requiresPlatformAdd : constants.NativePlatformStatus.requiresPrepare;
const changesInfo = await this.$projectChangesService.checkForChanges(platform, projectData, { bundle, release: appFilesUpdaterOptions.release, provision: config.provision, teamId: config.teamId, nativePlatformStatus });
this.$logger.trace("Changes info in prepare platform:", changesInfo);
return changesInfo;
}
/* Hooks are expected to use "filesToSync" parameter, as to give plugin authors additional information about the sync process.*/
@helpers.hook('prepare')
private async preparePlatformCore(platform: string, appFilesUpdaterOptions: IAppFilesUpdaterOptions, projectData: IProjectData, platformSpecificData: IPlatformSpecificData, env: Object, changesInfo?: IProjectChangesInfo, filesToSync?: string[], nativePrepare?: INativePrepare): Promise<void> {
this.$logger.out("Preparing project...");
const platformData = this.$platformsData.getPlatformData(platform, projectData);
const projectFilesConfig = helpers.getProjectFilesConfig({ isReleaseBuild: appFilesUpdaterOptions.release });
await this.$preparePlatformJSService.preparePlatform({
platform,
platformData,
projectFilesConfig,
appFilesUpdaterOptions,
projectData,
platformSpecificData,
changesInfo,
filesToSync,
env
});
if (!nativePrepare || !nativePrepare.skipNativePrepare) {
await this.$preparePlatformNativeService.preparePlatform({
platform,
platformData,
appFilesUpdaterOptions,
projectData,
platformSpecificData,
changesInfo,
filesToSync,
projectFilesConfig,
env
});
}
const directoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME);
const excludedDirs = [constants.APP_RESOURCES_FOLDER_NAME];
if (!changesInfo || !changesInfo.modulesChanged) {
excludedDirs.push(constants.TNS_MODULES_FOLDER_NAME);
}
this.$projectFilesManager.processPlatformSpecificFiles(directoryPath, platform, projectFilesConfig, excludedDirs);
this.$logger.out(`Project successfully prepared (${platform})`);
}
public async shouldBuild(platform: string, projectData: IProjectData, buildConfig: IBuildConfig, outputPath?: string): Promise<boolean> {
if (this.$projectChangesService.currentChanges.changesRequireBuild) {
return true;
}
const platformData = this.$platformsData.getPlatformData(platform, projectData);
const forDevice = !buildConfig || buildConfig.buildForDevice;
outputPath = outputPath || (forDevice ? platformData.deviceBuildOutputPath : platformData.emulatorBuildOutputPath || platformData.deviceBuildOutputPath);
if (!this.$fs.exists(outputPath)) {
return true;
}
const packageNames = platformData.getValidPackageNames({ isForDevice: forDevice });
const packages = this.getApplicationPackages(outputPath, packageNames);
if (packages.length === 0) {
return true;
}
const prepareInfo = this.$projectChangesService.getPrepareInfo(platform, projectData);
const buildInfo = this.getBuildInfo(platform, platformData, buildConfig, outputPath);
if (!prepareInfo || !buildInfo) {
return true;
}
if (buildConfig.clean) {
return true;
}
if (prepareInfo.time === buildInfo.prepareTime) {
return false;
}
return prepareInfo.changesRequireBuildTime !== buildInfo.prepareTime;
}
public async trackProjectType(projectData: IProjectData): Promise<void> {
// Track each project once per process.
// In long living process, where we may work with multiple projects, we would like to track the information for each of them.
if (projectData && (projectData.projectFilePath !== this._trackedProjectFilePath)) {
this._trackedProjectFilePath = projectData.projectFilePath;
await this.$analyticsService.track("Working with project type", projectData.projectType);
}
}
public async trackActionForPlatform(actionData: ITrackPlatformAction): Promise<void> {
const normalizePlatformName = this.$mobileHelper.normalizePlatformName(actionData.platform);
let featureValue = normalizePlatformName;
if (actionData.isForDevice !== null) {
const deviceType = actionData.isForDevice ? "device" : "emulator";
featureValue += `.${deviceType}`;
}
await this.$analyticsService.track(actionData.action, featureValue);
if (actionData.deviceOsVersion) {
await this.$analyticsService.track(`Device OS version`, `${normalizePlatformName}_${actionData.deviceOsVersion}`);
}
}
public async buildPlatform(platform: string, buildConfig: IBuildConfig, projectData: IProjectData): Promise<void> {
this.$logger.out("Building project...");
const action = constants.TrackActionNames.Build;
await this.trackProjectType(projectData);
const isForDevice = this.$mobileHelper.isAndroidPlatform(platform) ? null : buildConfig && buildConfig.buildForDevice;
await this.trackActionForPlatform({ action, platform, isForDevice });
await this.$analyticsService.trackEventActionInGoogleAnalytics({
action,
isForDevice,
platform,
projectDir: projectData.projectDir,
additionalData: `${buildConfig.release ? Configurations.Release : Configurations.Debug}_${buildConfig.clean ? constants.BuildStates.Clean : constants.BuildStates.Incremental}`
});
const platformData = this.$platformsData.getPlatformData(platform, projectData);
const handler = (data: any) => {
this.emit(constants.BUILD_OUTPUT_EVENT_NAME, data);
this.$logger.printInfoMessageOnSameLine(data.data.toString());
};
await attachAwaitDetach(constants.BUILD_OUTPUT_EVENT_NAME, platformData.platformProjectService, handler, platformData.platformProjectService.buildProject(platformData.projectRoot, projectData, buildConfig));
const buildInfoFilePath = this.getBuildOutputPath(platform, platformData, buildConfig);
this.saveBuildInfoFile(platform, projectData.projectDir, buildInfoFilePath);
this.$logger.out("Project successfully built.");
}
public saveBuildInfoFile(platform: string, projectDir: string, buildInfoFileDirname: string): void {
const buildInfoFile = path.join(buildInfoFileDirname, buildInfoFileName);
const prepareInfo = this.$projectChangesService.getPrepareInfo(platform, this.$projectDataService.getProjectData(projectDir));
const buildInfo = {
prepareTime: prepareInfo.changesRequireBuildTime,
buildTime: new Date().toString()
};
this.$fs.writeJson(buildInfoFile, buildInfo);
}
public async shouldInstall(device: Mobile.IDevice, projectData: IProjectData, outputPath?: string): Promise<boolean> {
const platform = device.deviceInfo.platform;
if (!(await device.applicationManager.isApplicationInstalled(projectData.projectId))) {
return true;
}
const platformData = this.$platformsData.getPlatformData(platform, projectData);
const deviceBuildInfo: IBuildInfo = await this.getDeviceBuildInfo(device, projectData);
const localBuildInfo = this.getBuildInfo(platform, platformData, { buildForDevice: !device.isEmulator }, outputPath);
return !localBuildInfo || !deviceBuildInfo || deviceBuildInfo.buildTime !== localBuildInfo.buildTime;
}
public async installApplication(device: Mobile.IDevice, buildConfig: IBuildConfig, projectData: IProjectData, packageFile?: string, outputFilePath?: string): Promise<void> {
this.$logger.out("Installing...");
await this.$analyticsService.trackEventActionInGoogleAnalytics({
action: constants.TrackActionNames.Deploy,
device,
projectDir: projectData.projectDir
});
const platformData = this.$platformsData.getPlatformData(device.deviceInfo.platform, projectData);
if (!packageFile) {
if (this.$devicesService.isiOSSimulator(device)) {
packageFile = this.getLatestApplicationPackageForEmulator(platformData, buildConfig, outputFilePath).packageName;
} else {
packageFile = this.getLatestApplicationPackageForDevice(platformData, buildConfig, outputFilePath).packageName;
}
}
await platformData.platformProjectService.cleanDeviceTempFolder(device.deviceInfo.identifier, projectData);
await device.applicationManager.reinstallApplication(projectData.projectId, packageFile);
if (!buildConfig.release) {
const deviceFilePath = await this.getDeviceBuildInfoFilePath(device, projectData);
const buildInfoFilePath = outputFilePath || this.getBuildOutputPath(device.deviceInfo.platform, platformData, { buildForDevice: !device.isEmulator });
const appIdentifier = projectData.projectId;
await device.fileSystem.putFile(path.join(buildInfoFilePath, buildInfoFileName), deviceFilePath, appIdentifier);
}
this.$logger.out(`Successfully installed on device with identifier '${device.deviceInfo.identifier}'.`);
}
public async deployPlatform(deployInfo: IDeployPlatformInfo): Promise<void> {
await this.preparePlatform({
platform: deployInfo.platform,
appFilesUpdaterOptions: deployInfo.appFilesUpdaterOptions,
platformTemplate: deployInfo.deployOptions.platformTemplate,
projectData: deployInfo.projectData,
config: deployInfo.config,
env: deployInfo.env
});
const options: Mobile.IDevicesServicesInitializationOptions = {
platform: deployInfo.platform, deviceId: deployInfo.deployOptions.device, emulator: deployInfo.deployOptions.emulator
};
await this.$devicesService.initialize(options);
const action = async (device: Mobile.IDevice): Promise<void> => {
const buildConfig: IBuildConfig = {
buildForDevice: !this.$devicesService.isiOSSimulator(device),
projectDir: deployInfo.deployOptions.projectDir,
release: deployInfo.deployOptions.release,
device: deployInfo.deployOptions.device,
provision: deployInfo.deployOptions.provision,
teamId: deployInfo.deployOptions.teamId,
keyStoreAlias: deployInfo.deployOptions.keyStoreAlias,
keyStoreAliasPassword: deployInfo.deployOptions.keyStoreAliasPassword,
keyStorePassword: deployInfo.deployOptions.keyStorePassword,
keyStorePath: deployInfo.deployOptions.keyStorePath,
clean: deployInfo.deployOptions.clean
};
const shouldBuild = await this.shouldBuild(deployInfo.platform, deployInfo.projectData, buildConfig);
if (shouldBuild) {
await this.buildPlatform(deployInfo.platform, buildConfig, deployInfo.projectData);
} else {
this.$logger.out("Skipping package build. No changes detected on the native side. This will be fast!");
}
if (deployInfo.deployOptions.forceInstall || shouldBuild || (await this.shouldInstall(device, deployInfo.projectData))) {
await this.installApplication(device, buildConfig, deployInfo.projectData);
} else {
this.$logger.out("Skipping install.");
}
await this.trackActionForPlatform({ action: constants.TrackActionNames.Deploy, platform: device.deviceInfo.platform, isForDevice: !device.isEmulator, deviceOsVersion: device.deviceInfo.version });
};
if (deployInfo.deployOptions.device) {
const device = await this.$devicesService.getDevice(deployInfo.deployOptions.device);
deployInfo.deployOptions.device = device.deviceInfo.identifier;
}
await this.$devicesService.execute(action, this.getCanExecuteAction(deployInfo.platform, deployInfo.deployOptions));
}
public async startApplication(platform: string, runOptions: IRunPlatformOptions, projectId: string): Promise<void> {
this.$logger.out("Starting...");
const action = async (device: Mobile.IDevice) => {
await device.applicationManager.startApplication(projectId);
this.$logger.out(`Successfully started on device with identifier '${device.deviceInfo.identifier}'.`);
};
await this.$devicesService.initialize({ platform: platform, deviceId: runOptions.device });
if (runOptions.device) {
const device = await this.$devicesService.getDevice(runOptions.device);
runOptions.device = device.deviceInfo.identifier;
}
await this.$devicesService.execute(action, this.getCanExecuteAction(platform, runOptions));
}
private getBuildOutputPath(platform: string, platformData: IPlatformData, options: IBuildForDevice): string {
if (platform.toLowerCase() === this.$devicePlatformsConstants.iOS.toLowerCase()) {
return options.buildForDevice ? platformData.deviceBuildOutputPath : platformData.emulatorBuildOutputPath;
}
return platformData.deviceBuildOutputPath;
}
private async getDeviceBuildInfoFilePath(device: Mobile.IDevice, projectData: IProjectData): Promise<string> {
const deviceRootPath = await this.$devicePathProvider.getDeviceProjectRootPath(device, {
appIdentifier: projectData.projectId,
getDirname: true
});
return helpers.fromWindowsRelativePathToUnix(path.join(deviceRootPath, buildInfoFileName));
}
private async getDeviceBuildInfo(device: Mobile.IDevice, projectData: IProjectData): Promise<IBuildInfo> {
const deviceFilePath = await this.getDeviceBuildInfoFilePath(device, projectData);
try {
return JSON.parse(await this.readFile(device, deviceFilePath, projectData));
} catch (e) {
return null;
}
}
private getBuildInfo(platform: string, platformData: IPlatformData, options: IBuildForDevice, buildOutputPath?: string): IBuildInfo {
buildOutputPath = buildOutputPath || this.getBuildOutputPath(platform, platformData, options);
const buildInfoFile = path.join(buildOutputPath, buildInfoFileName);
if (this.$fs.exists(buildInfoFile)) {
try {
const buildInfoTime = this.$fs.readJson(buildInfoFile);
return buildInfoTime;
} catch (e) {
return null;
}
}
return null;
}
@helpers.hook('cleanApp')
public async cleanDestinationApp(platformInfo: IPreparePlatformInfo): Promise<void> {
await this.ensurePlatformInstalled(platformInfo.platform, platformInfo.platformTemplate, platformInfo.projectData, platformInfo.config);
const appSourceDirectoryPath = path.join(platformInfo.projectData.projectDir, constants.APP_FOLDER_NAME);
const platformData = this.$platformsData.getPlatformData(platformInfo.platform, platformInfo.projectData);
const appDestinationDirectoryPath = path.join(platformData.appDestinationDirectoryPath, constants.APP_FOLDER_NAME);
const appUpdater = new AppFilesUpdater(appSourceDirectoryPath, appDestinationDirectoryPath, platformInfo.appFilesUpdaterOptions, this.$fs);
appUpdater.cleanDestinationApp();
}
public lastOutputPath(platform: string, buildConfig: IBuildConfig, projectData: IProjectData, outputPath?: string): string {
let packageFile: string;
const platformData = this.$platformsData.getPlatformData(platform, projectData);
if (buildConfig.buildForDevice) {
packageFile = this.getLatestApplicationPackageForDevice(platformData, buildConfig, outputPath).packageName;
} else {
packageFile = this.getLatestApplicationPackageForEmulator(platformData, buildConfig, outputPath).packageName;
}
if (!packageFile || !this.$fs.exists(packageFile)) {
this.$errors.failWithoutHelp("Unable to find built application. Try 'tns build %s'.", platform);
}
return packageFile;
}
public copyLastOutput(platform: string, targetPath: string, buildConfig: IBuildConfig, projectData: IProjectData): void {
platform = platform.toLowerCase();
targetPath = path.resolve(targetPath);
const packageFile = this.lastOutputPath(platform, buildConfig, projectData);
this.$fs.ensureDirectoryExists(path.dirname(targetPath));
if (this.$fs.exists(targetPath) && this.$fs.getFsStats(targetPath).isDirectory()) {
const sourceFileName = path.basename(packageFile);
this.$logger.trace(`Specified target path: '${targetPath}' is directory. Same filename will be used: '${sourceFileName}'.`);
targetPath = path.join(targetPath, sourceFileName);
}
this.$fs.copyFile(packageFile, targetPath);
this.$logger.info(`Copied file '${packageFile}' to '${targetPath}'.`);
}
public async removePlatforms(platforms: string[], projectData: IProjectData): Promise<void> {
for (const platform of platforms) {
this.validatePlatformInstalled(platform, projectData);
const platformData = this.$platformsData.getPlatformData(platform, projectData);
await platformData.platformProjectService.stopServices(platformData.projectRoot);
const platformDir = path.join(projectData.platformsDir, platform);
this.$fs.deleteDirectory(platformDir);
this.$projectDataService.removeNSProperty(projectData.projectDir, platformData.frameworkPackageName);
this.$logger.out(`Platform ${platform} successfully removed.`);
}
}
public async updatePlatforms(platforms: string[], platformTemplate: string, projectData: IProjectData, config: IPlatformOptions): Promise<void> {
for (const platformParam of platforms) {
const data = platformParam.split("@"),
platform = data[0],
version = data[1];
if (this.isPlatformInstalled(platform, projectData)) {
await this.updatePlatform(platform, version, platformTemplate, projectData, config);
} else {
await this.addPlatform(platformParam, platformTemplate, projectData, config);
}
}
}
private getCanExecuteAction(platform: string, options: IDeviceEmulator): any {
const canExecute = (currentDevice: Mobile.IDevice): boolean => {
if (options.device && currentDevice && currentDevice.deviceInfo) {
return currentDevice.deviceInfo.identifier === options.device;
}
if (this.$mobileHelper.isiOSPlatform(platform) && this.$hostInfo.isDarwin) {
if (this.$devicesService.isOnlyiOSSimultorRunning() || options.emulator || this.$devicesService.isiOSSimulator(currentDevice)) {
return true;
}
return this.$devicesService.isiOSDevice(currentDevice);
}
return true;
};
return canExecute;
}
public validatePlatform(platform: string, projectData: IProjectData): void {
if (!platform) {
this.$errors.fail("No platform specified.");
}
platform = platform.split("@")[0].toLowerCase();
if (!this.isValidPlatform(platform, projectData)) {
this.$errors.fail("Invalid platform %s. Valid platforms are %s.", platform, helpers.formatListOfNames(this.$platformsData.platformsNames));
}
}
public validatePlatformInstalled(platform: string, projectData: IProjectData): void {
this.validatePlatform(platform, projectData);
if (!this.isPlatformInstalled(platform, projectData)) {
this.$errors.fail("The platform %s is not added to this project. Please use 'tns platform add <platform>'", platform);
}
}
public async ensurePlatformInstalled(platform: string, platformTemplate: string, projectData: IProjectData, config: IPlatformOptions, nativePrepare?: INativePrepare): Promise<void> {
let requiresNativePlatformAdd = false;
if (!this.isPlatformInstalled(platform, projectData)) {
await this.addPlatform(platform, platformTemplate, projectData, config, "", nativePrepare);
} else {
const shouldAddNativePlatform = !nativePrepare || !nativePrepare.skipNativePrepare;
const prepareInfo = this.$projectChangesService.getPrepareInfo(platform, projectData);
// In case there's no prepare info, it means only platform add had been executed. So we've come from CLI and we do not need to prepare natively.
requiresNativePlatformAdd = prepareInfo && prepareInfo.nativePlatformStatus === constants.NativePlatformStatus.requiresPlatformAdd;
if (requiresNativePlatformAdd && shouldAddNativePlatform) {
await this.addPlatform(platform, platformTemplate, projectData, config, "", nativePrepare);
}
}
}
private isPlatformInstalled(platform: string, projectData: IProjectData): boolean {
return this.$fs.exists(path.join(projectData.platformsDir, platform.toLowerCase()));
}
private isValidPlatform(platform: string, projectData: IProjectData) {
return this.$platformsData.getPlatformData(platform, projectData);
}
public isPlatformSupportedForOS(platform: string, projectData: IProjectData): boolean {
const targetedOS = this.$platformsData.getPlatformData(platform, projectData).targetedOS;
const res = !targetedOS || targetedOS.indexOf("*") >= 0 || targetedOS.indexOf(process.platform) >= 0;
return res;
}
private isPlatformPrepared(platform: string, projectData: IProjectData): boolean {
const platformData = this.$platformsData.getPlatformData(platform, projectData);
return platformData.platformProjectService.isPlatformPrepared(platformData.projectRoot, projectData);
}
private getApplicationPackages(buildOutputPath: string, validPackageNames: string[]): IApplicationPackage[] {
// Get latest package` that is produced from build
const candidates = this.$fs.readDirectory(buildOutputPath);
const packages = _.filter(candidates, candidate => {
return _.includes(validPackageNames, candidate);
}).map(currentPackage => {
currentPackage = path.join(buildOutputPath, currentPackage);
return {
packageName: currentPackage,
time: this.$fs.getFsStats(currentPackage).mtime
};
});
return packages;
}
private getLatestApplicationPackage(buildOutputPath: string, validPackageNames: string[]): IApplicationPackage {
let packages = this.getApplicationPackages(buildOutputPath, validPackageNames);
if (packages.length === 0) {
const packageExtName = path.extname(validPackageNames[0]);
this.$errors.fail("No %s found in %s directory", packageExtName, buildOutputPath);
}
packages = _.sortBy(packages, pkg => pkg.time).reverse(); // We need to reverse because sortBy always sorts in ascending order
return packages[0];
}
public getLatestApplicationPackageForDevice(platformData: IPlatformData, buildConfig: IBuildConfig, outputPath?: string): IApplicationPackage {
return this.getLatestApplicationPackage(outputPath || platformData.deviceBuildOutputPath, platformData.getValidPackageNames({ isForDevice: true, isReleaseBuild: buildConfig.release }));
}
public getLatestApplicationPackageForEmulator(platformData: IPlatformData, buildConfig: IBuildConfig, outputPath?: string): IApplicationPackage {
return this.getLatestApplicationPackage(outputPath || platformData.emulatorBuildOutputPath || platformData.deviceBuildOutputPath, platformData.getValidPackageNames({ isForDevice: false, isReleaseBuild: buildConfig.release }));
}
private async updatePlatform(platform: string, version: string, platformTemplate: string, projectData: IProjectData, config: IPlatformOptions): Promise<void> {
const platformData = this.$platformsData.getPlatformData(platform, projectData);
const data = this.$projectDataService.getNSValue(projectData.projectDir, platformData.frameworkPackageName);
const currentVersion = data && data.version ? data.version : "0.2.0";
let newVersion = version === constants.PackageVersion.NEXT ?
await this.$npmInstallationManager.getNextVersion(platformData.frameworkPackageName) :
version || await this.$npmInstallationManager.getLatestCompatibleVersion(platformData.frameworkPackageName);
const installedModuleDir = await this.$npmInstallationManager.install(platformData.frameworkPackageName, projectData.projectDir, { version: newVersion, dependencyType: "save" });
const cachedPackageData = this.$fs.readJson(path.join(installedModuleDir, "package.json"));
newVersion = (cachedPackageData && cachedPackageData.version) || newVersion;
const canUpdate = platformData.platformProjectService.canUpdatePlatform(installedModuleDir, projectData);
await this.$npm.uninstall(platformData.frameworkPackageName, { save: true }, projectData.projectDir);
if (canUpdate) {
if (!semver.valid(newVersion)) {
this.$errors.fail("The version %s is not valid. The version should consists from 3 parts separated by dot.", newVersion);
}
if (!semver.gt(currentVersion, newVersion)) {
await this.updatePlatformCore(platformData, { currentVersion, newVersion, canUpdate, platformTemplate }, projectData, config);
} else if (semver.eq(currentVersion, newVersion)) {
this.$errors.fail("Current and new version are the same.");
} else {
this.$errors.fail(`Your current version: ${currentVersion} is higher than the one you're trying to install ${newVersion}.`);
}
} else {
this.$errors.failWithoutHelp("Native Platform cannot be updated.");
}
}
private async updatePlatformCore(platformData: IPlatformData, updateOptions: IUpdatePlatformOptions, projectData: IProjectData, config: IPlatformOptions): Promise<void> {
let packageName = platformData.normalizedPlatformName.toLowerCase();
await this.removePlatforms([packageName], projectData);
packageName = updateOptions.newVersion ? `${packageName}@${updateOptions.newVersion}` : packageName;
await this.addPlatform(packageName, updateOptions.platformTemplate, projectData, config);
this.$logger.out("Successfully updated to version ", updateOptions.newVersion);
}
// TODO: Remove this method from here. It has nothing to do with platform
public async readFile(device: Mobile.IDevice, deviceFilePath: string, projectData: IProjectData): Promise<string> {
temp.track();
const uniqueFilePath = temp.path({ suffix: ".tmp" });
try {
await device.fileSystem.getFile(deviceFilePath, projectData.projectId, uniqueFilePath);
} catch (e) {
return null;
}
if (this.$fs.exists(uniqueFilePath)) {
const text = this.$fs.readText(uniqueFilePath);
shell.rm(uniqueFilePath);
return text;
}
return null;
}
}
$injector.register("platformService", PlatformService);