-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathmigrate-controller.ts
1398 lines (1268 loc) · 37.6 KB
/
migrate-controller.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 semver from "semver";
import * as constants from "../constants";
import * as glob from "glob";
import * as _ from "lodash";
import simpleGit, { SimpleGit } from "simple-git";
import { UpdateControllerBase } from "./update-controller-base";
import { fromWindowsRelativePathToUnix, getHash } from "../common/helpers";
import {
IBackup,
INsConfig,
IProjectBackupService,
IProjectCleanupService,
IProjectConfigService,
IProjectData,
IProjectDataService,
} from "../definitions/project";
import {
IMigrateController,
IMigrationData,
IMigrationDependency,
} from "../definitions/migrate";
import {
IOptions,
IPackageInstallationManager,
IPackageManager,
IPlatformCommandHelper,
IPlatformValidationService,
} from "../declarations";
import {
IAddPlatformService,
IPlatformsDataService,
} from "../definitions/platform";
import { IPluginsService } from "../definitions/plugins";
import {
IDictionary,
IErrors,
IFileSystem,
IResourceLoader,
ISettingsService,
} from "../common/declarations";
import { IInjector } from "../common/definitions/yok";
import { injector } from "../common/yok";
import { IJsonFileSettingsService } from "../common/definitions/json-file-settings-service";
import { SupportedConfigValues } from "../tools/config-manipulation/config-transformer";
// const wait: (ms: number) => Promise<void> = (ms: number = 1000) =>
// new Promise((resolve) => setTimeout(resolve, ms));
export class MigrateController
extends UpdateControllerBase
implements IMigrateController {
// private static COMMON_MIGRATE_MESSAGE =
// "not affect the codebase of the application and you might need to do additional changes manually – for more information, refer to the instructions in the following blog post: https://www.nativescript.org/blog/nativescript-6.0-application-migration";
// private static UNABLE_TO_MIGRATE_APP_ERROR = `The current application is not compatible with NativeScript CLI 7.0.
// Use the \`ns migrate\` command to migrate the app dependencies to a form compatible with NativeScript 7.0.
// Running this command will ${MigrateController.COMMON_MIGRATE_MESSAGE}`;
// private static MIGRATE_FINISH_MESSAGE = `The \`tns migrate\` command does ${MigrateController.COMMON_MIGRATE_MESSAGE}`;
constructor(
protected $fs: IFileSystem,
protected $platformCommandHelper: IPlatformCommandHelper,
protected $platformsDataService: IPlatformsDataService,
protected $packageInstallationManager: IPackageInstallationManager,
protected $packageManager: IPackageManager,
protected $pacoteService: IPacoteService,
// private $androidResourcesMigrationService: IAndroidResourcesMigrationService,
private $devicePlatformsConstants: Mobile.IDevicePlatformsConstants,
private $logger: ILogger,
private $errors: IErrors,
private $addPlatformService: IAddPlatformService,
private $pluginsService: IPluginsService,
private $projectDataService: IProjectDataService,
private $projectConfigService: IProjectConfigService,
private $options: IOptions,
private $platformValidationService: IPlatformValidationService,
private $resources: IResourceLoader,
private $injector: IInjector,
private $settingsService: ISettingsService,
private $staticConfig: Config.IStaticConfig,
private $terminalSpinnerService: ITerminalSpinnerService,
private $projectCleanupService: IProjectCleanupService,
private $projectBackupService: IProjectBackupService
) {
super(
$fs,
$platformCommandHelper,
$platformsDataService,
$packageInstallationManager,
$packageManager,
$pacoteService
);
}
// static readonly typescriptPackageName: string = "typescript";
static readonly backupFolderName: string = ".migration_backup";
static readonly pathsToBackup: string[] = [
constants.LIB_DIR_NAME,
constants.HOOKS_DIR_NAME,
constants.WEBPACK_CONFIG_NAME,
constants.PACKAGE_JSON_FILE_NAME,
constants.PACKAGE_LOCK_JSON_FILE_NAME,
constants.TSCCONFIG_TNS_JSON_NAME,
constants.KARMA_CONFIG_NAME,
constants.CONFIG_NS_FILE_NAME,
];
private spinner: ITerminalSpinner;
private get $jsonFileSettingsService(): IJsonFileSettingsService {
const cliVersion = semver.coerce(this.$staticConfig.version);
const shouldMigrateCacheFilePath = path.join(
this.$settingsService.getProfileDir(),
`should-migrate-cache-${cliVersion}.json`
);
return this.$injector.resolve("jsonFileSettingsService", {
jsonFileSettingsPath: shouldMigrateCacheFilePath,
});
}
private migrationDependencies: IMigrationDependency[] = [
{
packageName: constants.SCOPED_TNS_CORE_MODULES,
verifiedVersion: "7.0.0",
shouldAddIfMissing: true,
},
{
packageName: constants.TNS_CORE_MODULES_NAME,
shouldRemove: true,
},
{
packageName: "@nativescript/types",
verifiedVersion: "7.0.0",
isDev: true,
},
{
packageName: "tns-platform-declarations",
replaceWith: "@nativescript/types",
verifiedVersion: "7.0.0",
isDev: true,
},
{
packageName: constants.TNS_CORE_MODULES_WIDGETS_NAME,
shouldRemove: true,
},
{
packageName: "nativescript-dev-webpack",
replaceWith: constants.WEBPACK_PLUGIN_NAME,
shouldRemove: true,
isDev: true,
shouldMigrateAction: async () => {
return true;
},
migrateAction: this.migrateWebpack.bind(this),
},
{
packageName: constants.WEBPACK_PLUGIN_NAME,
verifiedVersion: "3.0.0",
shouldAddIfMissing: true,
},
{
packageName: "nativescript-vue",
verifiedVersion: "2.8.0",
shouldMigrateAction: async (
projectData: IProjectData,
allowInvalidVersions: boolean
) => {
const dependency = {
packageName: "nativescript-vue",
verifiedVersion: "2.8.0",
isDev: false,
};
const result =
this.hasDependency(dependency, projectData) &&
(await this.shouldMigrateDependencyVersion(
dependency,
projectData,
allowInvalidVersions
));
return result;
},
migrateAction: this.migrateNativeScriptVue.bind(this),
},
{
packageName: "nativescript-angular",
replaceWith: "@nativescript/angular",
verifiedVersion: "10.0.0",
},
{
packageName: "@nativescript/angular",
verifiedVersion: "10.0.0",
shouldMigrateAction: async (
projectData: IProjectData,
allowInvalidVersions: boolean
) => {
const dependency = {
packageName: "@nativescript/angular",
verifiedVersion: "10.0.0",
isDev: false,
};
const result =
this.hasDependency(dependency, projectData) &&
(await this.shouldMigrateDependencyVersion(
dependency,
projectData,
allowInvalidVersions
));
return result;
},
migrateAction: this.migrateNativeScriptAngular.bind(this),
},
{
packageName: "svelte-native",
verifiedVersion: "0.9.4",
shouldMigrateAction: async (
projectData: IProjectData,
allowInvalidVersions: boolean
) => {
const dependency = {
packageName: "svelte-native",
verifiedVersion: "0.9.0", // minimum version required - anything less will need a migration
isDev: false,
};
const result =
this.hasDependency(dependency, projectData) &&
(await this.shouldMigrateDependencyVersion(
dependency,
projectData,
allowInvalidVersions
));
return result;
},
migrateAction: this.migrateNativeScriptSvelte.bind(this),
},
{
packageName: "@nativescript/unit-test-runner",
verifiedVersion: "1.0.0",
shouldMigrateAction: async (
projectData: IProjectData,
allowInvalidVersions: boolean
) => {
const dependency = {
packageName: "@nativescript/unit-test-runner",
verifiedVersion: "1.0.0",
isDev: false,
};
const result =
this.hasDependency(dependency, projectData) &&
(await this.shouldMigrateDependencyVersion(
dependency,
projectData,
allowInvalidVersions
));
return result;
},
migrateAction: this.migrateUnitTestRunner.bind(this),
},
{
packageName: "typescript",
isDev: true,
verifiedVersion: "3.9.7",
},
];
get verifiedPlatformVersions(): IDictionary<string> {
return {
[this.$devicePlatformsConstants.Android.toLowerCase()]: "6.5.3",
[this.$devicePlatformsConstants.iOS.toLowerCase()]: "6.5.2",
};
}
public async shouldMigrate({
projectDir,
platforms,
allowInvalidVersions = false,
}: IMigrationData): Promise<boolean> {
const remainingPlatforms = [];
let shouldMigrate = false;
for (const platform of platforms) {
const cachedResult = await this.getCachedShouldMigrate(
projectDir,
platform
);
if (cachedResult !== false) {
remainingPlatforms.push(platform);
} else {
this.$logger.trace(
`Got cached result for shouldMigrate for platform: ${platform}`
);
}
}
if (remainingPlatforms.length > 0) {
shouldMigrate = await this._shouldMigrate({
projectDir,
platforms: remainingPlatforms,
allowInvalidVersions,
});
this.$logger.trace(
`Executed shouldMigrate for platforms: ${remainingPlatforms}. Result is: ${shouldMigrate}`
);
if (!shouldMigrate) {
for (const remainingPlatform of remainingPlatforms) {
await this.setCachedShouldMigrate(projectDir, remainingPlatform);
}
}
}
return shouldMigrate;
}
public async validate({
projectDir,
platforms,
allowInvalidVersions = true,
}: IMigrationData): Promise<void> {
const shouldMigrate = await this.shouldMigrate({
projectDir,
platforms,
allowInvalidVersions,
});
if (shouldMigrate) {
this.$errors.fail(
`The current application is not compatible with NativeScript CLI 7.0.\n\nRun 'ns migrate' to migrate your project to NativeScript 7.\n\nAlternatively you may try running it with '--force' to skip this check.`
);
}
}
public async migrate({
projectDir,
platforms,
allowInvalidVersions = false,
}: IMigrationData): Promise<void> {
this.spinner = this.$terminalSpinnerService.createSpinner();
const projectData = this.$projectDataService.getProjectData(projectDir);
this.$logger.trace("MigrationController.migrate called with", {
projectDir,
platforms,
allowInvalidVersions,
});
// ensure in git repo and require --force if not (for safety)
// ensure git branch is clean
const canMigrate = await this.ensureGitCleanOrForce(projectDir);
if (!canMigrate) {
this.spinner.fail("Pre-Migration verification failed");
return;
}
this.spinner.succeed("Pre-Migration verification complete");
// back up project files and folders
this.spinner.start("Backing up project files before migration");
const backup = await this.backupProject(projectDir);
this.spinner.text = "Project files have been backed up";
this.spinner.succeed();
// clean up project files
this.spinner.start("Cleaning up project files before migration");
await this.cleanUpProject(projectData);
this.spinner.text = "Project files have been cleaned up";
this.spinner.succeed();
// clean up artifacts
this.spinner.start("Cleaning up old artifacts");
await this.handleAutoGeneratedFiles(backup, projectData);
this.spinner.text = "Cleaned old artifacts";
this.spinner.succeed();
// migrate configs
this.spinner.start(
`Migrating project to use ${"nativescript.config.ts".green}`
);
await this.migrateConfigs(projectDir);
this.spinner.text = `Project has been migrated to use ${
"nativescript.config.ts".green
}`;
this.spinner.succeed();
// update dependencies
this.spinner.start("Updating project dependencies");
await this.migrateDependencies(
projectData,
platforms,
allowInvalidVersions
);
this.spinner.text = "Project dependencies have been updated";
this.spinner.succeed();
// add latest runtimes (if they were specified in the nativescript key)
// this.spinner.start("Updating runtimes");
//
// await wait(2000);
// this.spinner.clear();
// this.$logger.info(
// ` - ${"@nativescript/android".yellow} ${"v7.0.0".green} has been added`
// );
// this.spinner.render();
//
// this.spinner.text = "Runtimes have been updated";
// this.spinner.succeed();
this.spinner.succeed("Migration complete.");
this.$logger.info("");
this.$logger.printMarkdown(
"Project has been successfully migrated. The next step is to run `ns run <platform>` to ensure everything is working properly." +
"\n\nPlease note that `ns migrate` does not make changes to your source code, you may need additional changes to complete the migration."
// + "\n\nYou may restore your project with `ns migrate restore`"
);
// print markdown for next steps:
// if no runtime has been added, print a message that it will be added when they run ns run <platform>
// if all is good, run ns migrate clean to clean up backup folders
// in case of failure, print diagnostic data: what failed and why
// restore all files - or perhaps let the user sort it out
// or ns migrate restore - to restore from pre-migration backup
// for some known cases, print suggestions perhaps
//
// return;
//
// this.spinner = this.$terminalSpinnerService.createSpinner();
//
// this.spinner.start("Migrating project...");
// // const projectData = this.$projectDataService.getProjectData(projectDir);
// const backupDir = path.join(projectDir, MigrateController.backupFolderName);
//
// try {
// this.spinner.start("Backup project configuration.");
// this.backup(
// [
// ...MigrateController.pathsToBackup,
// path.join(projectData.getAppDirectoryRelativePath(), "package.json"),
// ],
// backupDir,
// projectData.projectDir
// );
// this.spinner.text = "Backup project configuration complete.";
// this.spinner.succeed();
// } catch (error) {
// // this.spinner.text = MigrateController.backupFailMessage;
// this.spinner.fail();
// // this.$logger.error(MigrateController.backupFailMessage);
// await this.$projectCleanupService.cleanPath(backupDir);
// // this.$fs.deleteDirectory(backupDir);
// return;
// }
//
// try {
// this.spinner.start("Clean auto-generated files.");
// this.handleAutoGeneratedFiles(backupDir, projectData);
// this.spinner.text = "Clean auto-generated files complete.";
// this.spinner.succeed();
// } catch (error) {
// this.$logger.trace(
// `Error during auto-generated files handling. ${
// (error && error.message) || error
// }`
// );
// }
//
// // await this.migrateOldAndroidAppResources(projectData, backupDir);
//
// try {
// await this.cleanUpProject(projectData);
// // await this.migrateConfigs(projectData);
// await this.migrateDependencies(
// projectData,
// platforms,
// allowInvalidVersions
// );
// } catch (error) {
// const backupFolders = MigrateController.pathsToBackup;
// const embeddedPackagePath = path.join(
// projectData.getAppDirectoryRelativePath(),
// "package.json"
// );
// backupFolders.push(embeddedPackagePath);
// this.restoreBackup(backupFolders, backupDir, projectData.projectDir);
// this.spinner.fail();
// // this.$errors.fail(
// // `${MigrateController.migrateFailMessage} The error is: ${error}`
// // );
// }
//
// this.spinner.stop();
// // this.spinner.info(MigrateController.MIGRATE_FINISH_MESSAGE);
}
private async ensureGitCleanOrForce(projectDir: string): Promise<boolean> {
const git: SimpleGit = simpleGit(projectDir);
const isGit = await git.checkIsRepo();
const isForce = this.$options.force;
if (!isGit) {
// not a git repo and no --force
if (!isForce) {
this.$logger.printMarkdown(
`Running \`ns migrate\` in a non-git project is not recommended. If you want to skip this check run \`ns migrate --force\`.`
);
this.$errors.fail("Not in Git repo.");
return false;
}
this.spinner.warn(`Not in Git repo, but using ${"--force".red}`);
return true;
}
const isClean = (await git.status()).isClean();
if (!isClean) {
if (!isForce) {
this.$logger.printMarkdown(
`Current git branch has uncommitted changes. Please commit the changes and try again. Alternatively run \`ns migrate --force\` to skip this check.`
);
this.$errors.fail("Git branch not clean.");
return false;
}
this.spinner.warn(`Git branch not clean, but using ${"--force".red}`);
return true;
}
return true;
}
private async backupProject(projectDir: string): Promise<IBackup> {
const projectData = this.$projectDataService.getProjectData(projectDir);
const backup = this.$projectBackupService.getBackup("migration");
backup.addPaths([
...MigrateController.pathsToBackup,
path.join(projectData.getAppDirectoryRelativePath(), "package.json"),
]);
try {
return backup.create();
} catch (error) {
this.spinner.fail(`Project backup failed.`);
backup.remove();
this.$errors.fail(`Project backup failed. Error is: ${error.message}`);
}
}
private async migrateConfigs(projectDir: string): Promise<boolean> {
const projectData = this.$projectDataService.getProjectData(projectDir);
// package.json
const rootPackageJsonPath: any = path.resolve(
projectDir,
constants.PACKAGE_JSON_FILE_NAME
);
// nested package.json
const embeddedPackageJsonPath = path.resolve(
projectData.projectDir,
projectData.getAppDirectoryRelativePath(),
constants.PACKAGE_JSON_FILE_NAME
);
// nsconfig.json
const legacyNsConfigPath = path.resolve(
projectData.projectDir,
constants.CONFIG_NS_FILE_NAME
);
let rootPackageJsonData: any = {};
if (this.$fs.exists(rootPackageJsonPath)) {
rootPackageJsonData = this.$fs.readJson(rootPackageJsonPath);
}
// write the default config unless it already exists
const newConfigPath = this.$projectConfigService.writeDefaultConfig(
projectData.projectDir
);
// force legacy config mode
this.$projectConfigService.setForceUsingLegacyConfig(true);
// all different sources are combined into configData (nested package.json, nsconfig and root package.json[nativescript])
const configData = this.$projectConfigService.readConfig(
projectData.projectDir
);
// we no longer want to force legacy config mode
this.$projectConfigService.setForceUsingLegacyConfig(false);
// move main key into root package.json
if (configData.main) {
rootPackageJsonData.main = configData.main;
delete configData.main;
}
// detect appPath and App_Resources path
configData.appPath = this.detectAppPath(projectDir, configData);
configData.appResourcesPath = this.detectAppResourcesPath(
projectDir,
configData
);
// delete nativescript key from root package.json
if (rootPackageJsonData.nativescript) {
delete rootPackageJsonData.nativescript;
}
// force the config service to use nativescript.config.ts
this.$projectConfigService.setForceUsingNewConfig(true);
// migrate data into nativescript.config.ts
const hasUpdatedConfigSuccessfully = await this.$projectConfigService.setValue(
"", // root
configData as { [key: string]: SupportedConfigValues }
);
if (!hasUpdatedConfigSuccessfully) {
if (typeof newConfigPath === "string") {
// only clean the config if it was created by the migration script
await this.$projectCleanupService.cleanPath(newConfigPath);
}
this.$errors.fail(
`Failed to migrate project to use ${constants.CONFIG_FILE_NAME_TS}. One or more values could not be updated.`
);
}
// save root package.json
this.$fs.writeJson(rootPackageJsonPath, rootPackageJsonData);
// delete migrated files
await this.$projectCleanupService.cleanPath(embeddedPackageJsonPath);
await this.$projectCleanupService.cleanPath(legacyNsConfigPath);
return true;
}
private async _shouldMigrate({
projectDir,
platforms,
allowInvalidVersions,
}: IMigrationData): Promise<boolean> {
const isMigrate = _.get(this.$options, "argv._[0]") === "migrate";
const projectData = this.$projectDataService.getProjectData(projectDir);
const projectInfo = this.$projectConfigService.detectProjectConfigs(
projectData.projectDir
);
if (!isMigrate && projectInfo.hasNSConfig) {
return;
}
const shouldMigrateCommonMessage =
"The app is not compatible with this CLI version and it should be migrated. Reason: ";
for (let i = 0; i < this.migrationDependencies.length; i++) {
const dependency = this.migrationDependencies[i];
const hasDependency = this.hasDependency(dependency, projectData);
if (
hasDependency &&
dependency.shouldMigrateAction &&
(await dependency.shouldMigrateAction(
projectData,
allowInvalidVersions
))
) {
this.$logger.trace(
`${shouldMigrateCommonMessage}'${dependency.packageName}' requires an update.`
);
return true;
}
if (
hasDependency &&
(dependency.replaceWith || dependency.shouldRemove)
) {
this.$logger.trace(
`${shouldMigrateCommonMessage}'${dependency.packageName}' is deprecated.`
);
return true;
}
if (
hasDependency &&
(await this.shouldMigrateDependencyVersion(
dependency,
projectData,
allowInvalidVersions
))
) {
this.$logger.trace(
`${shouldMigrateCommonMessage}'${dependency.packageName}' should be updated.`
);
return true;
}
if (!hasDependency && dependency.shouldAddIfMissing) {
this.$logger.trace(
`${shouldMigrateCommonMessage}'${dependency.packageName}' is missing.`
);
return true;
}
}
for (let platform of platforms) {
platform = platform && platform.toLowerCase();
if (
!this.$platformValidationService.isValidPlatform(platform, projectData)
) {
continue;
}
const hasRuntimeDependency = this.hasRuntimeDependency({
platform,
projectData,
});
if (
hasRuntimeDependency &&
(await this.shouldUpdateRuntimeVersion(
this.verifiedPlatformVersions[platform.toLowerCase()],
platform,
projectData,
allowInvalidVersions
))
) {
this.$logger.trace(
`${shouldMigrateCommonMessage}Platform '${platform}' should be updated.`
);
return true;
}
}
}
private async getCachedShouldMigrate(
projectDir: string,
platform: string
): Promise<boolean> {
let cachedShouldMigrateValue = null;
const cachedHash = await this.$jsonFileSettingsService.getSettingValue(
getHash(`${projectDir}${platform.toLowerCase()}`)
);
const packageJsonHash = await this.getPackageJsonHash(projectDir);
if (cachedHash === packageJsonHash) {
cachedShouldMigrateValue = false;
}
return cachedShouldMigrateValue;
}
private async setCachedShouldMigrate(
projectDir: string,
platform: string
): Promise<void> {
const packageJsonHash = await this.getPackageJsonHash(projectDir);
await this.$jsonFileSettingsService.saveSetting(
getHash(`${projectDir}${platform.toLowerCase()}`),
packageJsonHash
);
}
private async getPackageJsonHash(projectDir: string) {
const projectPackageJsonFilePath = path.join(
projectDir,
constants.PACKAGE_JSON_FILE_NAME
);
return await this.$fs.getFileShasum(projectPackageJsonFilePath);
}
// private async migrateOldAndroidAppResources(
// projectData: IProjectData,
// backupDir: string
// ) {
// const appResourcesPath = projectData.getAppResourcesDirectoryPath();
// if (!this.$androidResourcesMigrationService.hasMigrated(appResourcesPath)) {
// this.spinner.info("Migrate old Android App_Resources structure.");
// try {
// await this.$androidResourcesMigrationService.migrate(
// appResourcesPath,
// backupDir
// );
// } catch (error) {
// this.$logger.warn(
// "Migrate old Android App_Resources structure failed: ",
// error.message
// );
// }
// }
// }
private async cleanUpProject(projectData: IProjectData): Promise<void> {
await this.$projectCleanupService.clean([
constants.HOOKS_DIR_NAME,
constants.PLATFORMS_DIR_NAME,
constants.NODE_MODULES_FOLDER_NAME,
constants.WEBPACK_CONFIG_NAME,
constants.PACKAGE_LOCK_JSON_FILE_NAME,
constants.TSCCONFIG_TNS_JSON_NAME,
]);
}
private async handleAutoGeneratedFiles(
backup: IBackup,
projectData: IProjectData
): Promise<void> {
const globOptions: glob.IOptions = {
silent: true,
nocase: true,
matchBase: true,
nodir: true,
absolute: false,
cwd: projectData.appDirectoryPath,
};
const jsFiles = glob.sync("*.@(js|ts|js.map)", globOptions);
const autoGeneratedJsFiles = this.getGeneratedFiles(
jsFiles,
[".js"],
[".ts"]
);
const autoGeneratedJsMapFiles = this.getGeneratedFiles(
jsFiles,
[".map"],
[""]
);
const cssFiles = glob.sync("*.@(le|sa|sc|c)ss", globOptions);
const autoGeneratedCssFiles = this.getGeneratedFiles(
cssFiles,
[".css"],
[".scss", ".sass", ".less"]
);
const allGeneratedFiles = autoGeneratedJsFiles
.concat(autoGeneratedJsMapFiles)
.concat(autoGeneratedCssFiles);
const pathsToBackup = allGeneratedFiles.map((generatedFile) =>
path.join(projectData.appDirectoryPath, generatedFile)
);
backup.addPaths(pathsToBackup);
backup.create();
if (backup.isUpToDate()) {
await this.$projectCleanupService.clean(pathsToBackup);
}
}
private getGeneratedFiles(
allFiles: string[],
generatedFileExts: string[],
sourceFileExts: string[]
): string[] {
const autoGeneratedFiles = allFiles.filter((file) => {
let isGenerated = false;
const { dir, name, ext } = path.parse(file);
if (generatedFileExts.indexOf(ext) > -1) {
for (const sourceExt of sourceFileExts) {
const possibleSourceFile = path.format({ dir, name, ext: sourceExt });
isGenerated = allFiles.indexOf(possibleSourceFile) > -1;
if (isGenerated) {
break;
}
}
}
return isGenerated;
});
return autoGeneratedFiles;
}
private async migrateDependencies(
projectData: IProjectData,
platforms: string[],
allowInvalidVersions: boolean
): Promise<void> {
for (let i = 0; i < this.migrationDependencies.length; i++) {
const dependency = this.migrationDependencies[i];
const hasDependency = this.hasDependency(dependency, projectData);
if (
hasDependency &&
dependency.migrateAction &&
(await dependency.shouldMigrateAction(
projectData,
allowInvalidVersions
))
) {
const newDependencies = await dependency.migrateAction(
projectData,
path.join(projectData.projectDir, MigrateController.backupFolderName)
);
for (const newDependency of newDependencies) {
await this.migrateDependency(
newDependency,
projectData,
allowInvalidVersions
);
}
}
await this.migrateDependency(
dependency,
projectData,
allowInvalidVersions
);
}
for (const platform of platforms) {
const lowercasePlatform = platform.toLowerCase();
const hasRuntimeDependency = this.hasRuntimeDependency({
platform,
projectData,
});
if (
hasRuntimeDependency &&
(await this.shouldUpdateRuntimeVersion(
this.verifiedPlatformVersions[lowercasePlatform],
platform,
projectData,
allowInvalidVersions
))
) {
const verifiedPlatformVersion = this.verifiedPlatformVersions[
lowercasePlatform
];
const platformData = this.$platformsDataService.getPlatformData(
lowercasePlatform,
projectData
);
this.spinner.info(
`Updating ${platform} platform to version '${verifiedPlatformVersion}'.`
);
await this.$addPlatformService.setPlatformVersion(
platformData,
projectData,
verifiedPlatformVersion
);
this.spinner.succeed();
}
}
// this.spinner.info("Installing packages.");
// await this.$packageManager.install(
// projectData.projectDir,
// projectData.projectDir,
// {
// disableNpmInstall: false,
// frameworkPath: null,
// ignoreScripts: false,
// path: projectData.projectDir,
// }
// );
// this.spinner.text = "Installing packages... Complete";
// this.spinner.succeed();
//
// this.spinner.succeed("Migration complete.");
}
private async migrateDependency(
dependency: IMigrationDependency,
projectData: IProjectData,
allowInvalidVersions: boolean
): Promise<void> {
const hasDependency = this.hasDependency(dependency, projectData);
if (hasDependency && dependency.warning) {
this.$logger.warn(dependency.warning);
}
if (hasDependency && (dependency.replaceWith || dependency.shouldRemove)) {
this.$pluginsService.removeFromPackageJson(
dependency.packageName,
projectData.projectDir
);
if (dependency.replaceWith) {
const replacementDep = _.find(
this.migrationDependencies,
(migrationPackage) =>
migrationPackage.packageName === dependency.replaceWith
);
if (!replacementDep) {
this.$errors.fail("Failed to find replacement dependency.");
}
this.$pluginsService.addToPackageJson(
replacementDep.packageName,
replacementDep.verifiedVersion,
replacementDep.isDev,
projectData.projectDir
);
this.spinner.clear();