-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathmigrate-controller.ts
1668 lines (1478 loc) · 41.9 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 { globSync, GlobOptions } 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 {
IDependencyVersion,
IMigrateController,
IMigrationData,
IMigrationDependency,
} from "../definitions/migrate";
import {
IOptions,
IPackageInstallationManager,
IPackageManager,
IPlatformCommandHelper,
} from "../declarations";
import { IPlatformsDataService } from "../definitions/platform";
import { IPluginsService } from "../definitions/plugins";
import {
IChildProcess,
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";
import * as temp from "temp";
import { color } from "../color";
import {
ITerminalSpinner,
ITerminalSpinnerService,
} from "../definitions/terminal-spinner-service";
// const wait: (ms: number) => Promise<void> = (ms: number = 1000) =>
// new Promise((resolve) => setTimeout(resolve, ms));
export class MigrateController
extends UpdateControllerBase
implements IMigrateController
{
constructor(
protected $fs: IFileSystem,
protected $platformCommandHelper: IPlatformCommandHelper,
protected $platformsDataService: IPlatformsDataService,
protected $packageInstallationManager: IPackageInstallationManager,
protected $packageManager: IPackageManager,
protected $pacoteService: IPacoteService,
// private $androidResourcesMigrationService: IAndroidResourcesMigrationService,
private $logger: ILogger,
private $errors: IErrors,
private $pluginsService: IPluginsService,
private $projectDataService: IProjectDataService,
private $projectConfigService: IProjectConfigService,
private $projectData: IProjectData,
private $options: IOptions,
private $resources: IResourceLoader,
private $injector: IInjector,
private $settingsService: ISettingsService,
private $staticConfig: Config.IStaticConfig,
private $terminalSpinnerService: ITerminalSpinnerService,
private $projectCleanupService: IProjectCleanupService,
private $projectBackupService: IProjectBackupService,
private $childProcess: IChildProcess
) {
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`
);
this.$logger.trace(
`Migration cache path is: ${shouldMigrateCacheFilePath}`
);
return this.$injector.resolve("jsonFileSettingsService", {
jsonFileSettingsPath: shouldMigrateCacheFilePath,
});
}
private migrationDependencies: IMigrationDependency[] = [
{
packageName: "@nativescript/core",
minVersion: "6.5.0",
desiredVersion: "~8.5.0",
shouldAddIfMissing: true,
},
{
packageName: "tns-core-modules",
shouldRemove: true,
},
{
packageName: "@nativescript/types",
minVersion: "7.0.0",
desiredVersion: "~8.5.0",
isDev: true,
},
{
packageName: "tns-platform-declarations",
replaceWith: "@nativescript/types",
minVersion: "6.5.0",
isDev: true,
},
{
packageName: "tns-core-modules-widgets",
shouldRemove: true,
},
{
packageName: "nativescript-dev-webpack",
replaceWith: "@nativescript/webpack",
shouldRemove: true,
isDev: true,
async shouldMigrateAction() {
return true;
},
migrateAction: this.migrateWebpack.bind(this),
},
{
packageName: "@nativescript/webpack",
minVersion: "3.0.0",
desiredVersion: "~5.0.0",
shouldAddIfMissing: true,
isDev: true,
},
{
packageName: "nativescript-vue",
minVersion: "2.7.0",
desiredVersion: "~2.9.3",
async shouldMigrateAction(
dependency: IMigrationDependency,
projectData: IProjectData,
loose: boolean
) {
if (!this.hasDependency(dependency, projectData)) {
return false;
}
return await this.shouldMigrateDependencyVersion(
dependency,
projectData,
loose
);
},
migrateAction: this.migrateNativeScriptVue.bind(this),
},
{
packageName: "nativescript-angular",
replaceWith: "@nativescript/angular",
minVersion: "10.0.0",
},
{
packageName: "@nativescript/angular",
minVersion: "10.0.0",
desiredVersion: "^16.0.0",
async shouldMigrateAction(
dependency: IMigrationDependency,
projectData: IProjectData,
loose: boolean
) {
if (!this.hasDependency(dependency, projectData)) {
return false;
}
return await this.shouldMigrateDependencyVersion(
dependency,
projectData,
loose
);
},
migrateAction: this.migrateNativeScriptAngular.bind(this),
},
{
packageName: "svelte-native",
minVersion: "0.9.0",
desiredVersion: "~0.9.4",
async shouldMigrateAction(
dependency: IMigrationDependency,
projectData: IProjectData,
loose: boolean
) {
if (!this.hasDependency(dependency, projectData)) {
return false;
}
return await this.shouldMigrateDependencyVersion(
dependency,
projectData,
loose
);
},
migrateAction: this.migrateNativeScriptSvelte.bind(this),
},
{
packageName: "nativescript-unit-test-runner",
replaceWith: "@nativescript/unit-test-runner",
shouldRemove: true,
isDev: true,
async shouldMigrateAction() {
return true;
},
migrateAction: this.migrateUnitTestRunner.bind(this),
},
{
packageName: "@nativescript/unit-test-runner",
minVersion: "1.0.0",
desiredVersion: "~3.0.0",
async shouldMigrateAction(
dependency: IMigrationDependency,
projectData: IProjectData,
loose: boolean
) {
if (!this.hasDependency(dependency, projectData)) {
return false;
}
return await this.shouldMigrateDependencyVersion(
dependency,
projectData,
loose
);
},
migrateAction: this.migrateUnitTestRunner.bind(this),
},
{
packageName: "typescript",
isDev: true,
minVersion: "3.7.0",
desiredVersion: "~4.8.4",
},
{
packageName: "node-sass",
replaceWith: "sass",
minVersion: "0.0.0", // ignore
isDev: true,
// shouldRemove: true,
},
{
packageName: "sass",
minVersion: "0.0.0", // ignore
desiredVersion: "~1.49.9",
isDev: true,
// shouldRemove: true,
},
// runtimes
{
packageName: "tns-ios",
minVersion: "6.5.3",
replaceWith: "@nativescript/ios",
isDev: true,
},
{
packageName: "tns-android",
minVersion: "6.5.4",
replaceWith: "@nativescript/android",
isDev: true,
},
{
packageName: "@nativescript/ios",
minVersion: "6.5.3",
desiredVersion: "~8.5.0",
isDev: true,
},
{
packageName: "@nativescript/android",
minVersion: "7.0.0",
desiredVersion: "~8.5.0",
isDev: true,
},
];
public async shouldMigrate({
projectDir,
platforms,
loose = false,
}: IMigrationData): Promise<boolean> {
const remainingPlatforms = [];
let shouldMigrate = false;
for (const platform of platforms) {
if (!loose) {
remainingPlatforms.push(platform);
continue;
}
// should only run in loose mode...
const cachedResult = await this.getCachedShouldMigrate(
projectDir,
platform
);
this.$logger.trace(
`Got cached result for shouldMigrate for platform: ${platform}: ${cachedResult}`
);
// the cached result is only used if it's false, otherwise we need to check again
if (cachedResult !== false) {
remainingPlatforms.push(platform);
}
}
if (remainingPlatforms.length > 0) {
shouldMigrate = await this._shouldMigrate({
projectDir,
platforms: remainingPlatforms,
loose,
});
this.$logger.trace(
`Executed shouldMigrate for platforms: ${remainingPlatforms}. Result is: ${shouldMigrate}`
);
// only cache results if running in loose mode
if (!shouldMigrate && loose) {
for (const remainingPlatform of remainingPlatforms) {
await this.setCachedShouldMigrate(projectDir, remainingPlatform);
}
}
}
return shouldMigrate;
}
public async validate({
projectDir,
platforms,
loose = true,
}: IMigrationData): Promise<void> {
const shouldMigrate = await this.shouldMigrate({
projectDir,
platforms,
loose,
});
if (shouldMigrate) {
this.$errors.fail(
`The current application is not compatible with NativeScript CLI ${this.$staticConfig.version}.\n\nRun 'ns migrate' to migrate your project to the latest NativeScript version.\n\nAlternatively you may try running it with '--force' to skip this check.`
);
}
}
public async migrate({
projectDir,
platforms,
loose = false,
}: IMigrationData): Promise<void> {
this.spinner = this.$terminalSpinnerService.createSpinner();
const projectData = this.$projectDataService.getProjectData(projectDir);
this.$logger.trace("MigrationController.migrate called with", {
projectDir,
platforms,
loose: loose,
});
// 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.info("Backing up project files before migration");
const backup = await this.backupProject(projectDir);
this.spinner.succeed("Project files have been backed up");
// clean up project files
this.spinner.info("Cleaning up project files before migration");
await this.cleanUpProject(projectData);
this.spinner.succeed("Project files have been cleaned up");
// clean up artifacts
this.spinner.info("Cleaning up old artifacts");
await this.handleAutoGeneratedFiles(backup, projectData);
this.spinner.succeed("Cleaned old artifacts");
const newConfigPath = path.resolve(projectDir, "nativescript.config.ts");
if (!this.$fs.exists(newConfigPath)) {
// migrate configs
this.spinner.info(
`Migrating project to use ${color.green("nativescript.config.ts")}`
);
await this.migrateConfigs(projectDir);
this.spinner.succeed(
`Project has been migrated to use ${color.green(
"nativescript.config.ts"
)}`
);
}
// update dependencies
this.spinner.info("Updating project dependencies");
await this.migrateDependencies(projectData, platforms, loose);
this.spinner.succeed("Project dependencies have been updated");
const isAngular = this.hasDependency(
{
packageName: "@nativescript/angular",
},
projectData
);
// ensure polyfills.ts exists in angular projects
let polyfillsPath;
if (isAngular) {
polyfillsPath = await this.checkOrCreatePolyfillsTS(projectData);
}
// update tsconfig
const tsConfigPath = path.resolve(projectDir, "tsconfig.json");
if (this.$fs.exists(tsConfigPath)) {
this.spinner.info(`Updating ${color.yellow("tsconfig.json")}`);
await this.migrateTSConfig({
tsConfigPath,
isAngular,
polyfillsPath,
});
this.spinner.succeed(`Updated ${color.yellow("tsconfig.json")}`);
}
await this.migrateWebpack5(projectDir, projectData);
// run @nativescript/eslint over codebase
await this.runESLint(projectDir);
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 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
}
private async _shouldMigrate({
projectDir,
platforms,
loose,
}: 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) {
if (dependency.shouldAddIfMissing) {
this.$logger.trace(
`${shouldMigrateCommonMessage}'${dependency.packageName}' is missing.`
);
if (loose) {
// in loose mode we ignore missing dependencies
continue;
}
return true;
}
continue;
}
if (dependency.shouldMigrateAction) {
const shouldMigrate = await dependency.shouldMigrateAction.bind(this)(
dependency,
projectData,
loose
);
if (shouldMigrate) {
this.$logger.trace(
`${shouldMigrateCommonMessage}'${dependency.packageName}' requires an update.`
);
return true;
}
}
if (dependency.replaceWith || dependency.shouldRemove) {
this.$logger.trace(
`${shouldMigrateCommonMessage}'${dependency.packageName}' is deprecated.`
);
// in loose mode we ignore deprecated dependencies
if (loose) {
continue;
}
return true;
}
const shouldUpdate = await this.shouldMigrateDependencyVersion(
dependency,
projectData,
loose
);
if (shouldUpdate) {
this.$logger.trace(
`${shouldMigrateCommonMessage}'${dependency.packageName}' should be updated.`
);
return true;
}
}
return false;
}
private async shouldMigrateDependencyVersion(
dependency: IMigrationDependency,
projectData: IProjectData,
loose: boolean
): Promise<boolean> {
const installedVersion =
await this.$packageInstallationManager.getInstalledDependencyVersion(
dependency.packageName,
projectData.projectDir
);
const desiredVersion = dependency.desiredVersion ?? dependency.minVersion;
const minVersion = dependency.minVersion ?? dependency.desiredVersion;
if (
dependency.shouldUseExactVersion &&
installedVersion !== desiredVersion
) {
return true;
}
return this.isOutdatedVersion(
installedVersion,
{ minVersion, desiredVersion },
loose
);
}
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> {
this.$logger.trace(
`Caching shouldMigrate result for platform ${platform}.`
);
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 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 ${color.red("--force")}`);
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 ${color.red("--force")}`
);
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 cleanUpProject(projectData: IProjectData): Promise<void> {
await this.$projectCleanupService.clean([
constants.HOOKS_DIR_NAME,
this.$projectData.getBuildRelativeDirectoryPath(),
constants.NODE_MODULES_FOLDER_NAME,
constants.PACKAGE_LOCK_JSON_FILE_NAME,
]);
const { dependencies, devDependencies } =
await this.$pluginsService.getDependenciesFromPackageJson(
projectData.projectDir
);
const hasSchematics = [...dependencies, ...devDependencies].find(
(p) => p.name === "@nativescript/schematics"
);
if (!hasSchematics) {
// clean tsconfig.tns.json if not in a shared project
await this.$projectCleanupService.clean([
constants.TSCCONFIG_TNS_JSON_NAME,
]);
}
}
private async handleAutoGeneratedFiles(
backup: IBackup,
projectData: IProjectData
): Promise<void> {
const globOptions: GlobOptions = {
nocase: true,
matchBase: true,
nodir: true,
absolute: false,
cwd: projectData.appDirectoryPath,
withFileTypes: false,
};
const jsFiles = globSync("*.@(js|ts|js.map)", globOptions) as string[];
const autoGeneratedJsFiles = this.getGeneratedFiles(
jsFiles,
[".js"],
[".ts"]
);
const autoGeneratedJsMapFiles = this.getGeneratedFiles(
jsFiles,
[".map"],
[""]
);
const cssFiles = globSync(
"*.@(less|sass|scss|css)",
globOptions
) as string[];
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[] {
return 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;
});
}
private isOutdatedVersion(
current: string,
target: IDependencyVersion,
loose: boolean
): boolean {
// in loose mode, a falsy version is not considered outdated
if (!current && loose) {
return false;
}
const installed = semver.coerce(current);
const min = semver.coerce(target.minVersion);
const desired = semver.coerce(target.desiredVersion);
// in loose mode we check if we satisfy the min version
if (loose) {
if (!installed || !min) {
return false;
}
return semver.lt(installed, min);
}
if (!installed || !desired) {
return true;
}
// otherwise we compare with the desired version
return semver.lt(installed, desired);
}
private detectAppPath(projectDir: string, configData: INsConfig) {
if (configData.appPath) {
return configData.appPath;
}
const possibleAppPaths = [
path.resolve(projectDir, constants.SRC_DIR),
path.resolve(projectDir, constants.APP_FOLDER_NAME),
];
const appPath = possibleAppPaths.find((possiblePath) =>
this.$fs.exists(possiblePath)
);
if (appPath) {
const relativeAppPath = path
.relative(projectDir, appPath)
.replace(path.sep, "/");
this.$logger.trace(`Found app source at '${appPath}'.`);
return relativeAppPath.toString();
}
}
private detectAppResourcesPath(projectDir: string, configData: INsConfig) {
if (configData.appResourcesPath) {
return configData.appResourcesPath;
}
const possibleAppResourcesPaths = [
path.resolve(
projectDir,
configData.appPath,
constants.APP_RESOURCES_FOLDER_NAME
),
path.resolve(projectDir, constants.APP_RESOURCES_FOLDER_NAME),
];
const appResourcesPath = possibleAppResourcesPaths.find((possiblePath) =>
this.$fs.exists(possiblePath)
);
if (appResourcesPath) {
const relativeAppResourcesPath = path
.relative(projectDir, appResourcesPath)
.replace(path.sep, "/");
this.$logger.trace(`Found App_Resources at '${appResourcesPath}'.`);
return relativeAppResourcesPath.toString();
}
}
private async runMigrateActionIfAny(
dependency: IMigrationDependency,
projectData: IProjectData,
loose: boolean,
force: boolean = false
): Promise<void> {
if (dependency.migrateAction) {
const shouldMigrate =
force ||
(await dependency.shouldMigrateAction.bind(this)(
dependency,
projectData,
loose
));
if (shouldMigrate) {
const newDependencies = await dependency.migrateAction(
projectData,
path.join(projectData.projectDir, MigrateController.backupFolderName)
);
for (const newDependency of newDependencies) {
await this.migrateDependency(newDependency, projectData, loose);
}
}
}
}
private async migrateDependencies(
projectData: IProjectData,
platforms: string[],
loose: 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.shouldAddIfMissing) {
continue;
}
await this.runMigrateActionIfAny(dependency, projectData, loose);
await this.migrateDependency(dependency, projectData, loose);
}
}
private async migrateDependency(
dependency: IMigrationDependency,
projectData: IProjectData,
loose: boolean
): Promise<void> {
const hasDependency = this.hasDependency(dependency, projectData);
// show warning if needed
if (hasDependency && dependency.warning) {
this.$logger.warn(dependency.warning);
}
if (!hasDependency) {
if (!dependency.shouldAddIfMissing) {
return;
}
const version = dependency.desiredVersion ?? dependency.minVersion;
this.$pluginsService.addToPackageJson(
dependency.packageName,
version,
dependency.isDev,
projectData.projectDir
);
this.spinner.clear();
this.$logger.info(
` - ${color.yellow(dependency.packageName)} ${color.green(
version
)} has been added`
);
this.spinner.render();
return;
}
if (dependency.replaceWith || dependency.shouldRemove) {
// remove
this.$pluginsService.removeFromPackageJson(
dependency.packageName,
projectData.projectDir
);
// no replacement required - we're done
if (!dependency.replaceWith) {
return;
}
const replacementDep = _.find(
this.migrationDependencies,
(migrationPackage) =>
migrationPackage.packageName === dependency.replaceWith
);
if (!replacementDep) {
this.$errors.fail("Failed to find replacement dependency.");
}
const version =
replacementDep.desiredVersion ??
replacementDep.minVersion ??