forked from microsoft/rushstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRushConfiguration.ts
More file actions
1457 lines (1265 loc) · 50.8 KB
/
RushConfiguration.ts
File metadata and controls
1457 lines (1265 loc) · 50.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
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
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
/* eslint max-lines: off */
import * as path from 'path';
import * as fs from 'fs';
import * as semver from 'semver';
import {
JsonFile,
JsonSchema,
Path,
PackageName,
FileSystem
} from '@rushstack/node-core-library';
import { trueCasePathSync } from 'true-case-path';
import { Rush } from '../api/Rush';
import { RushConfigurationProject, IRushConfigurationProjectJson } from './RushConfigurationProject';
import { RushConstants } from '../logic/RushConstants';
import { ApprovedPackagesPolicy } from './ApprovedPackagesPolicy';
import { EventHooks } from './EventHooks';
import { VersionPolicyConfiguration } from './VersionPolicyConfiguration';
import { EnvironmentConfiguration } from './EnvironmentConfiguration';
import { CommonVersionsConfiguration } from './CommonVersionsConfiguration';
import { Utilities } from '../utilities/Utilities';
import { PackageManagerName, PackageManager } from './packageManager/PackageManager';
import { NpmPackageManager } from './packageManager/NpmPackageManager';
import { YarnPackageManager } from './packageManager/YarnPackageManager';
import { PnpmPackageManager } from './packageManager/PnpmPackageManager';
import { ExperimentsConfiguration } from './ExperimentsConfiguration';
const MINIMUM_SUPPORTED_RUSH_JSON_VERSION: string = '0.0.0';
const DEFAULT_BRANCH: string = 'master';
const DEFAULT_REMOTE: string = 'origin';
/**
* A list of known config filenames that are expected to appear in the "./common/config/rush" folder.
* To avoid confusion/mistakes, any extra files will be reported as an error.
*/
const knownRushConfigFilenames: string[] = [
'.npmrc',
'.npmrc-publish',
RushConstants.pinnedVersionsFilename,
RushConstants.commonVersionsFilename,
RushConstants.browserApprovedPackagesFilename,
RushConstants.nonbrowserApprovedPackagesFilename,
RushConstants.versionPoliciesFilename,
RushConstants.commandLineFilename,
RushConstants.experimentsFilename
];
/**
* Part of IRushConfigurationJson.
*/
export interface IApprovedPackagesPolicyJson {
reviewCategories?: string[];
ignoredNpmScopes?: string[];
}
/**
* Part of IRushConfigurationJson.
*/
export interface IRushGitPolicyJson {
allowedEmailRegExps?: string[];
sampleEmail?: string;
versionBumpCommitMessage?: string;
}
/**
* Part of IRushConfigurationJson.
* @beta
*/
export interface IEventHooksJson {
/**
* The list of scripts to run after every Rush build command finishes
*/
postRushBuild?: string[];
}
/**
* Part of IRushConfigurationJson.
*/
export interface IRushRepositoryJson {
/**
* The remote url of the repository. This helps "rush change" find the right remote to compare against.
*/
url?: string;
/**
* The default branch name. This tells "rush change" which remote branch to compare against.
*/
defaultBranch?: string;
/**
* The default remote. This tells "rush change" which remote to compare against if the remote URL is not set
* or if a remote matching the provided remote URL is not found.
*/
defaultRemote?: string;
}
/**
* This represents the available PNPM store options
* @public
*/
export type PnpmStoreOptions = 'local' | 'global';
/**
* Options for the package manager.
* @public
*/
export interface IPackageManagerOptionsJsonBase {
/**
* Enviroment variables for the package manager
*/
environmentVariables?: IConfigurationEnvironment
}
/**
* A collection of environment variables
* @public
*/
export interface IConfigurationEnvironment {
/**
* Environment variables
*/
[environmentVariableName: string]: IConfigurationEnvironmentVariable;
}
/**
* Represents the value of an environment variable, and if the value should be overridden if the variable is set
* in the parent environment.
* @public
*/
export interface IConfigurationEnvironmentVariable {
/**
* Value of the environment variable
*/
value: string;
/**
* Set to true to override the environment variable even if it is set in the parent environment.
* The default value is false.
*/
override?: boolean;
}
/**
* Part of IRushConfigurationJson.
* @internal
*/
export interface INpmOptionsJson extends IPackageManagerOptionsJsonBase {
}
/**
* Part of IRushConfigurationJson.
* @internal
*/
export interface IPnpmOptionsJson extends IPackageManagerOptionsJsonBase {
/**
* The store resolution method for PNPM to use
*/
pnpmStore?: PnpmStoreOptions;
/**
* Should PNPM fail if peer dependencies aren't installed?
*/
strictPeerDependencies?: boolean;
/**
* Defines the dependency resolution strategy PNPM will use
*/
resolutionStrategy?: ResolutionStrategy;
}
/**
* Part of IRushConfigurationJson.
* @internal
*/
export interface IYarnOptionsJson extends IPackageManagerOptionsJsonBase {
/**
* If true, then Rush will add the "--ignore-engines" option when invoking Yarn.
* This allows "rush install" to succeed if there are dependencies with engines defined in
* package.json which do not match the current environment.
*
* The default value is false.
*/
ignoreEngines?: boolean;
}
/**
* Options defining an allowed variant as part of IRushConfigurationJson.
*/
export interface IRushVariantOptionsJson {
variantName: string;
description: string;
}
/**
* This represents the JSON data structure for the "rush.json" configuration file.
* See rush.schema.json for documentation.
*/
export interface IRushConfigurationJson {
$schema: string;
npmVersion?: string;
pnpmVersion?: string;
yarnVersion?: string;
rushVersion: string;
repository?: IRushRepositoryJson;
nodeSupportedVersionRange?: string;
suppressNodeLtsWarning?: boolean;
projectFolderMinDepth?: number;
projectFolderMaxDepth?: number;
approvedPackagesPolicy?: IApprovedPackagesPolicyJson;
gitPolicy?: IRushGitPolicyJson;
telemetryEnabled?: boolean;
projects: IRushConfigurationProjectJson[];
eventHooks?: IEventHooksJson;
hotfixChangeEnabled?: boolean;
npmOptions?: INpmOptionsJson;
pnpmOptions?: IPnpmOptionsJson;
yarnOptions?: IYarnOptionsJson;
ensureConsistentVersions?: boolean;
variants?: IRushVariantOptionsJson[];
}
/**
* This represents the JSON data structure for the "rush-link.json" data file.
*/
export interface IRushLinkJson {
localLinks: {
[name: string]: string[]
};
}
/**
* This represents the JSON data structure for the "current-variant.json" data file.
*/
export interface ICurrentVariantJson {
variant: string | null; // Use `null` instead of `undefined` because `undefined` is not handled by JSON.
}
/**
* Options that all package managers share.
*
* @public
*/
export abstract class PackageManagerOptionsConfigurationBase implements IPackageManagerOptionsJsonBase {
/**
* Enviroment variables for the package manager
*/
public readonly environmentVariables?: IConfigurationEnvironment
/** @internal */
protected constructor(json: IPackageManagerOptionsJsonBase) {
this.environmentVariables = json.environmentVariables;
}
}
/**
* Options that are only used when the NPM package manager is selected.
*
* @remarks
* It is valid to define these options in rush.json even if the NPM package manager
* is not being used.
*
* @public
*/
export class NpmOptionsConfiguration extends PackageManagerOptionsConfigurationBase {
/** @internal */
public constructor(json: INpmOptionsJson) {
super(json);
}
}
/**
* Options that are only used when the PNPM package manager is selected.
*
* @remarks
* It is valid to define these options in rush.json even if the PNPM package manager
* is not being used.
*
* @public
*/
export class PnpmOptionsConfiguration extends PackageManagerOptionsConfigurationBase {
/**
* The method used to resolve the store used by PNPM.
*
* @remarks
* Available options:
* - local: Use the standard Rush store path: common/temp/pnpm-store
* - global: Use PNPM's global store path
*/
public readonly pnpmStore: PnpmStoreOptions;
/**
* The path for PNPM to use as the store directory.
*
* Will be overridden by environment variable RUSH_PNPM_STORE_PATH
*/
public readonly pnpmStorePath: string;
/**
* If true, then Rush will add the "--strict-peer-dependencies" option when invoking PNPM.
*
* @remarks
* This causes "rush install" to fail if there are unsatisfied peer dependencies, which is
* an invalid state that can cause build failures or incompatible dependency versions.
* (For historical reasons, JavaScript package managers generally do not treat this invalid state
* as an error.)
*
* The default value is false. (For now.)
*/
public readonly strictPeerDependencies: boolean;
/**
* The resolution strategy that will be used by PNPM.
*
* @remarks
* Configures the strategy used to select versions during installation.
*
* This feature requires PNPM version 3.1 or newer. It corresponds to the `--resolution-strategy` command-line
* option for PNPM. Possible values are `"fast"` and `"fewer-dependencies"`. PNPM's default is `"fast"`, but this
* may be incompatible with certain packages, for example the `@types` packages from DefinitelyTyped. Rush's default
* is `"fewer-dependencies"`, which causes PNPM to avoid installing a newer version if an already installed version
* can be reused; this is more similar to NPM's algorithm.
*
* For more background, see this discussion: {@link https://github.com/pnpm/pnpm/issues/1187}
*/
public readonly resolutionStrategy: ResolutionStrategy;
/** @internal */
public constructor(json: IPnpmOptionsJson, commonTempFolder: string) {
super(json);
this.pnpmStore = json.pnpmStore || 'local';
if (EnvironmentConfiguration.pnpmStorePathOverride) {
this.pnpmStorePath = EnvironmentConfiguration.pnpmStorePathOverride;
} else if (this.pnpmStore === 'global') {
this.pnpmStorePath = '';
} else {
this.pnpmStorePath = path.resolve(path.join(commonTempFolder, 'pnpm-store'));
}
this.strictPeerDependencies = !!json.strictPeerDependencies;
this.resolutionStrategy = json.resolutionStrategy || 'fewer-dependencies';
}
}
/**
* Options that are only used when the yarn package manager is selected.
*
* @remarks
* It is valid to define these options in rush.json even if the yarn package manager
* is not being used.
*
* @public
*/
export class YarnOptionsConfiguration extends PackageManagerOptionsConfigurationBase {
/**
* If true, then Rush will add the "--ignore-engines" option when invoking Yarn.
* This allows "rush install" to succeed if there are dependencies with engines defined in
* package.json which do not match the current environment.
*
* The default value is false.
*/
public readonly ignoreEngines: boolean;
/** @internal */
public constructor(json: IYarnOptionsJson) {
super(json);
this.ignoreEngines = !!json.ignoreEngines;
}
}
/**
* Options for `RushConfiguration.tryFindRushJsonLocation`.
* @public
*/
export interface ITryFindRushJsonLocationOptions {
/**
* Whether to show verbose console messages. Defaults to false.
*/
showVerbose?: boolean; // Defaults to false (inverse of old `verbose` parameter)
/**
* The folder path where the search will start. Defaults tot he current working directory.
*/
startingFolder?: string; // Defaults to cwd
}
/**
* This represents the available PNPM resolution strategies as a string
* @public
*/
export type ResolutionStrategy = 'fewer-dependencies' | 'fast';
/**
* This represents the Rush configuration for a repository, based on the "rush.json"
* configuration file.
* @public
*/
export class RushConfiguration {
private static _jsonSchema: JsonSchema = JsonSchema.fromFile(path.join(__dirname, '../schemas/rush.schema.json'));
private _rushJsonFile: string;
private _rushJsonFolder: string;
private _changesFolder: string;
private _commonFolder: string;
private _commonTempFolder: string;
private _commonScriptsFolder: string;
private _commonRushConfigFolder: string;
private _packageManager: PackageManagerName;
private _packageManagerWrapper: PackageManager;
private _npmCacheFolder: string;
private _npmTmpFolder: string;
private _yarnCacheFolder: string;
private _shrinkwrapFilename: string;
private _tempShrinkwrapFilename: string;
private _tempShrinkwrapPreinstallFilename: string;
private _rushLinkJsonFilename: string;
private _currentVariantJsonFilename: string;
private _packageManagerToolVersion: string;
private _packageManagerToolFilename: string;
private _projectFolderMinDepth: number;
private _projectFolderMaxDepth: number;
private _ensureConsistentVersions: boolean;
private _suppressNodeLtsWarning: boolean;
private _variants: {
[variantName: string]: boolean;
};
// "approvedPackagesPolicy" feature
private _approvedPackagesPolicy: ApprovedPackagesPolicy;
// "gitPolicy" feature
private _gitAllowedEmailRegExps: string[];
private _gitSampleEmail: string;
private _gitVersionBumpCommitMessage: string | undefined;
// "hotfixChangeEnabled" feature
private _hotfixChangeEnabled: boolean;
// Repository info
private _repositoryUrl: string | undefined;
private _repositoryDefaultBranch: string;
private _repositoryDefaultRemote: string;
private _npmOptions: NpmOptionsConfiguration;
private _pnpmOptions: PnpmOptionsConfiguration;
private _yarnOptions: YarnOptionsConfiguration;
// Rush hooks
private _eventHooks: EventHooks;
private _telemetryEnabled: boolean;
private _projects: RushConfigurationProject[];
private _projectsByName: Map<string, RushConfigurationProject>;
private _versionPolicyConfiguration: VersionPolicyConfiguration;
private _experimentsConfiguration: ExperimentsConfiguration;
/**
* Use RushConfiguration.loadFromConfigurationFile() or Use RushConfiguration.loadFromDefaultLocation()
* instead.
*/
private constructor(rushConfigurationJson: IRushConfigurationJson, rushJsonFilename: string) {
EnvironmentConfiguration.initialize();
if (rushConfigurationJson.nodeSupportedVersionRange) {
if (!semver.validRange(rushConfigurationJson.nodeSupportedVersionRange)) {
throw new Error('Error parsing the node-semver expression in the "nodeSupportedVersionRange"'
+ ` field from rush.json: "${rushConfigurationJson.nodeSupportedVersionRange}"`);
}
if (!semver.satisfies(process.version, rushConfigurationJson.nodeSupportedVersionRange)) {
const message: string = `Your dev environment is running Node.js version ${process.version} which does`
+ ` not meet the requirements for building this repository. (The rush.json configuration`
+ ` requires nodeSupportedVersionRange="${rushConfigurationJson.nodeSupportedVersionRange}")`;
if (EnvironmentConfiguration.allowUnsupportedNodeVersion) {
console.warn(message);
} else {
throw new Error(message);
}
}
}
this._rushJsonFile = rushJsonFilename;
this._rushJsonFolder = path.dirname(rushJsonFilename);
this._commonFolder = path.resolve(path.join(this._rushJsonFolder, RushConstants.commonFolderName));
this._commonRushConfigFolder = path.join(this._commonFolder, 'config', 'rush');
this._commonTempFolder = EnvironmentConfiguration.rushTempFolderOverride ||
path.join(this._commonFolder, RushConstants.rushTempFolderName);
this._commonScriptsFolder = path.join(this._commonFolder, 'scripts');
this._npmCacheFolder = path.resolve(path.join(this._commonTempFolder, 'npm-cache'));
this._npmTmpFolder = path.resolve(path.join(this._commonTempFolder, 'npm-tmp'));
this._yarnCacheFolder = path.resolve(path.join(this._commonTempFolder, 'yarn-cache'));
this._changesFolder = path.join(this._commonFolder, RushConstants.changeFilesFolderName);
this._rushLinkJsonFilename = path.join(this._commonTempFolder, 'rush-link.json');
this._currentVariantJsonFilename = path.join(this._commonTempFolder, 'current-variant.json');
this._suppressNodeLtsWarning = !!rushConfigurationJson.suppressNodeLtsWarning;
this._ensureConsistentVersions = !!rushConfigurationJson.ensureConsistentVersions;
const experimentsConfigFile: string = path.join(
this._commonRushConfigFolder,
RushConstants.experimentsFilename
);
this._experimentsConfiguration = new ExperimentsConfiguration(experimentsConfigFile);
this._npmOptions = new NpmOptionsConfiguration(rushConfigurationJson.npmOptions || {});
this._pnpmOptions = new PnpmOptionsConfiguration(rushConfigurationJson.pnpmOptions || {},
this._commonTempFolder);
this._yarnOptions = new YarnOptionsConfiguration(rushConfigurationJson.yarnOptions || {});
// TODO: Add an actual "packageManager" field in rush.json
const packageManagerFields: string[] = [];
if (rushConfigurationJson.npmVersion) {
this._packageManager = 'npm';
packageManagerFields.push('npmVersion');
}
if (rushConfigurationJson.pnpmVersion) {
this._packageManager = 'pnpm';
packageManagerFields.push('pnpmVersion');
}
if (rushConfigurationJson.yarnVersion) {
this._packageManager = 'yarn';
packageManagerFields.push('yarnVersion');
}
if (packageManagerFields.length === 0) {
throw new Error(`The rush.json configuration must specify one of: npmVersion, pnpmVersion, or yarnVersion`);
}
if (packageManagerFields.length > 1) {
throw new Error(`The rush.json configuration cannot specify both ${packageManagerFields[0]}`
+ ` and ${packageManagerFields[1]} `);
}
if (this._packageManager === 'npm') {
this._packageManagerToolVersion = rushConfigurationJson.npmVersion!;
this._packageManagerWrapper = new NpmPackageManager(this._packageManagerToolVersion);
} else if (this._packageManager === 'pnpm') {
this._packageManagerToolVersion = rushConfigurationJson.pnpmVersion!;
this._packageManagerWrapper = new PnpmPackageManager(this._packageManagerToolVersion);
} else {
this._packageManagerToolVersion = rushConfigurationJson.yarnVersion!;
this._packageManagerWrapper = new YarnPackageManager(this._packageManagerToolVersion);
}
this._shrinkwrapFilename = this._packageManagerWrapper.shrinkwrapFilename;
this._tempShrinkwrapFilename = path.join(
this._commonTempFolder, this._shrinkwrapFilename
);
this._packageManagerToolFilename = path.resolve(path.join(
this._commonTempFolder, `${this.packageManager}-local`, 'node_modules', '.bin', `${this.packageManager}`
));
/// From "C:\repo\common\temp\pnpm-lock.yaml" --> "C:\repo\common\temp\pnpm-lock-preinstall.yaml"
const parsedPath: path.ParsedPath = path.parse(this._tempShrinkwrapFilename);
this._tempShrinkwrapPreinstallFilename = path.join(parsedPath.dir,
parsedPath.name + '-preinstall' + parsedPath.ext);
RushConfiguration._validateCommonRushConfigFolder(
this._commonRushConfigFolder,
this.packageManager,
this._shrinkwrapFilename
);
this._projectFolderMinDepth = rushConfigurationJson.projectFolderMinDepth !== undefined
? rushConfigurationJson.projectFolderMinDepth : 1;
if (this._projectFolderMinDepth < 1) {
throw new Error('Invalid projectFolderMinDepth; the minimum possible value is 1');
}
this._projectFolderMaxDepth = rushConfigurationJson.projectFolderMaxDepth !== undefined
? rushConfigurationJson.projectFolderMaxDepth : 2;
if (this._projectFolderMaxDepth < this._projectFolderMinDepth) {
throw new Error('The projectFolderMaxDepth cannot be smaller than the projectFolderMinDepth');
}
this._approvedPackagesPolicy = new ApprovedPackagesPolicy(this, rushConfigurationJson);
this._gitAllowedEmailRegExps = [];
this._gitSampleEmail = '';
if (rushConfigurationJson.gitPolicy) {
if (rushConfigurationJson.gitPolicy.sampleEmail) {
this._gitSampleEmail = rushConfigurationJson.gitPolicy.sampleEmail;
}
if (rushConfigurationJson.gitPolicy.allowedEmailRegExps) {
this._gitAllowedEmailRegExps = rushConfigurationJson.gitPolicy.allowedEmailRegExps;
if (this._gitSampleEmail.trim().length < 1) {
throw new Error('The rush.json file is missing the "sampleEmail" option, ' +
'which is required when using "allowedEmailRegExps"');
}
}
if (rushConfigurationJson.gitPolicy.versionBumpCommitMessage) {
this._gitVersionBumpCommitMessage = rushConfigurationJson.gitPolicy.versionBumpCommitMessage;
}
}
this._hotfixChangeEnabled = false;
if (rushConfigurationJson.hotfixChangeEnabled) {
this._hotfixChangeEnabled = rushConfigurationJson.hotfixChangeEnabled;
}
if (!rushConfigurationJson.repository) {
rushConfigurationJson.repository = {};
}
this._repositoryUrl = rushConfigurationJson.repository.url;
this._repositoryDefaultBranch = rushConfigurationJson.repository.defaultBranch || DEFAULT_BRANCH;
this._repositoryDefaultRemote = rushConfigurationJson.repository.defaultRemote || DEFAULT_REMOTE;
this._telemetryEnabled = !!rushConfigurationJson.telemetryEnabled;
if (rushConfigurationJson.eventHooks) {
this._eventHooks = new EventHooks(rushConfigurationJson.eventHooks);
}
const versionPolicyConfigFile: string = path.join(
this._commonRushConfigFolder,
RushConstants.versionPoliciesFilename
);
this._versionPolicyConfiguration = new VersionPolicyConfiguration(versionPolicyConfigFile);
this._projects = [];
this._projectsByName = new Map<string, RushConfigurationProject>();
// We sort the projects array in alphabetical order. This ensures that the packages
// are processed in a deterministic order by the various Rush algorithms.
const sortedProjectJsons: IRushConfigurationProjectJson[] = rushConfigurationJson.projects.slice(0);
sortedProjectJsons.sort(
(a: IRushConfigurationProjectJson, b: IRushConfigurationProjectJson) => a.packageName.localeCompare(b.packageName)
);
const tempNamesByProject: Map<IRushConfigurationProjectJson, string>
= RushConfiguration._generateTempNamesForProjects(sortedProjectJsons);
for (const projectJson of sortedProjectJsons) {
const tempProjectName: string | undefined = tempNamesByProject.get(projectJson);
if (tempProjectName) {
const project: RushConfigurationProject = new RushConfigurationProject(projectJson, this, tempProjectName);
this._projects.push(project);
if (this._projectsByName.get(project.packageName)) {
throw new Error(`The project name "${project.packageName}" was specified more than once`
+ ` in the rush.json configuration file.`);
}
this._projectsByName.set(project.packageName, project);
}
}
for (const project of this._projects) {
project.cyclicDependencyProjects.forEach((cyclicDependencyProject: string) => {
if (!this.getProjectByName(cyclicDependencyProject)) {
throw new Error(`In rush.json, the "${cyclicDependencyProject}" project does not exist,`
+ ` but was referenced by the cyclicDependencyProjects for ${project.packageName}`);
}
});
// Compute the downstream dependencies within the list of Rush projects.
this._populateDownstreamDependencies(project.packageJson.dependencies, project.packageName);
this._populateDownstreamDependencies(project.packageJson.devDependencies, project.packageName);
this._versionPolicyConfiguration.validate(this._projectsByName);
}
const variants: {
[variantName: string]: boolean;
} = {};
if (rushConfigurationJson.variants) {
for (const variantOptions of rushConfigurationJson.variants) {
const {
variantName
} = variantOptions;
if (variants[variantName]) {
throw new Error(`Duplicate variant named '${variantName}' specified in configuration.`);
}
variants[variantName] = true;
}
}
this._variants = variants;
}
/**
* Loads the configuration data from an Rush.json configuration file and returns
* an RushConfiguration object.
*/
public static loadFromConfigurationFile(rushJsonFilename: string): RushConfiguration {
let resolvedRushJsonFilename: string = path.resolve(rushJsonFilename);
// Load the rush.json before we fix the casing. If the case is wrong on a case-sensitive filesystem,
// the next line show throw.
const rushConfigurationJson: IRushConfigurationJson = JsonFile.load(resolvedRushJsonFilename);
try {
resolvedRushJsonFilename = trueCasePathSync(resolvedRushJsonFilename);
} catch (error) {
/* ignore errors from true-case-path */
}
// Check the Rush version *before* we validate the schema, since if the version is outdated
// then the schema may have changed. This should no longer be a problem after Rush 4.0 and the C2R wrapper,
// but we'll validate anyway.
const expectedRushVersion: string = rushConfigurationJson.rushVersion;
const rushJsonBaseName: string = path.basename(resolvedRushJsonFilename);
// If the version is missing or malformed, fall through and let the schema handle it.
if (expectedRushVersion && semver.valid(expectedRushVersion)) {
// Make sure the requested version isn't too old
if (semver.lt(expectedRushVersion, MINIMUM_SUPPORTED_RUSH_JSON_VERSION)) {
throw new Error(`${rushJsonBaseName} is version ${expectedRushVersion}, which is too old for this tool. ` +
`The minimum supported version is ${MINIMUM_SUPPORTED_RUSH_JSON_VERSION}.`);
}
// Make sure the requested version isn't too new.
//
// If the major/minor versions are the same, then we consider the file to be compatible.
// This is somewhat lax, e.g. "5.0.2-dev.3" will be assumed to be loadable by rush-lib 5.0.0.
//
// IMPORTANT: Whenever a breaking change is introduced for one of the config files, we must
// increment the minor version number for Rush.
if (semver.major(Rush.version) !== semver.major(expectedRushVersion)
|| semver.minor(Rush.version) !== semver.minor(expectedRushVersion)) {
// If the major/minor are different, then make sure it's an older version.
if (semver.lt(Rush.version, expectedRushVersion)) {
throw new Error(`Unable to load ${rushJsonBaseName} because its RushVersion is`
+ ` ${rushConfigurationJson.rushVersion}, whereas @microsoft/rush-lib is version ${Rush.version}.`
+ ` Consider upgrading the library.`);
}
}
}
RushConfiguration._jsonSchema.validateObject(rushConfigurationJson, resolvedRushJsonFilename);
return new RushConfiguration(rushConfigurationJson, resolvedRushJsonFilename);
}
public static loadFromDefaultLocation(options?: ITryFindRushJsonLocationOptions): RushConfiguration {
const rushJsonLocation: string | undefined = RushConfiguration.tryFindRushJsonLocation(options);
if (rushJsonLocation) {
return RushConfiguration.loadFromConfigurationFile(rushJsonLocation);
} else {
throw Utilities.getRushConfigNotFoundError();
}
}
/**
* Find the rush.json location and return the path, or undefined if a rush.json can't be found.
*/
public static tryFindRushJsonLocation(options?: ITryFindRushJsonLocationOptions): string | undefined {
const optionsIn: ITryFindRushJsonLocationOptions = options || {};
const verbose: boolean = optionsIn.showVerbose || false;
let currentFolder: string = optionsIn.startingFolder || process.cwd();
// Look upwards at parent folders until we find a folder containing rush.json
for (let i: number = 0; i < 10; ++i) {
const rushJsonFilename: string = path.join(currentFolder, 'rush.json');
if (FileSystem.exists(rushJsonFilename)) {
if (i > 0 && verbose) {
console.log('Found configuration in ' + rushJsonFilename);
}
if (verbose) {
console.log('');
}
return rushJsonFilename;
}
const parentFolder: string = path.dirname(currentFolder);
if (parentFolder === currentFolder) {
break;
}
currentFolder = parentFolder;
}
return undefined;
}
/**
* This generates the unique names that are used to create temporary projects
* in the Rush common folder.
* NOTE: sortedProjectJsons is sorted by the caller.
*/
private static _generateTempNamesForProjects(sortedProjectJsons: IRushConfigurationProjectJson[]):
Map<IRushConfigurationProjectJson, string> {
const tempNamesByProject: Map<IRushConfigurationProjectJson, string> =
new Map<IRushConfigurationProjectJson, string>();
const usedTempNames: Set<string> = new Set<string>();
// NOTE: projectJsons was already sorted in alphabetical order by the caller.
for (const projectJson of sortedProjectJsons) {
// If the name is "@ms/MyProject", extract the "MyProject" part
const unscopedName: string = PackageName.getUnscopedName(projectJson.packageName);
// Generate a unique like name "@rush-temp/MyProject", or "@rush-temp/MyProject-2" if
// there is a naming conflict
let counter: number = 0;
let tempProjectName: string = `${RushConstants.rushTempNpmScope}/${unscopedName}`;
while (usedTempNames.has(tempProjectName)) {
++counter;
tempProjectName = `${RushConstants.rushTempNpmScope}/${unscopedName}-${counter}`;
}
usedTempNames.add(tempProjectName);
tempNamesByProject.set(projectJson, tempProjectName);
}
return tempNamesByProject;
}
/**
* If someone adds a config file in the "common/rush/config" folder, it would be a bad
* experience for Rush to silently ignore their file simply because they misspelled the
* filename, or maybe it's an old format that's no longer supported. The
* _validateCommonRushConfigFolder() function makes sure that this folder only contains
* recognized config files.
*/
private static _validateCommonRushConfigFolder(
commonRushConfigFolder: string,
packageManager: PackageManagerName,
shrinkwrapFilename: string
): void {
if (!FileSystem.exists(commonRushConfigFolder)) {
console.log(`Creating folder: ${commonRushConfigFolder}`);
FileSystem.ensureFolder(commonRushConfigFolder);
return;
}
for (const filename of FileSystem.readFolder(commonRushConfigFolder)) {
// Ignore things that aren't actual files
const stat: fs.Stats = FileSystem.getLinkStatistics(path.join(commonRushConfigFolder, filename));
if (!stat.isFile() && !stat.isSymbolicLink()) {
continue;
}
// Ignore harmless file extensions
const fileExtension: string = path.extname(filename);
if (['.bak', '.disabled', '.md', '.old', '.orig'].indexOf(fileExtension) >= 0) {
continue;
}
const knownSet: Set<string> = new Set<string>(knownRushConfigFilenames.map(x => x.toUpperCase()));
// Add the shrinkwrap filename for the package manager to the known set.
knownSet.add(shrinkwrapFilename.toUpperCase());
// If the package manager is pnpm, then also add the pnpm file to the known set.
if (packageManager === 'pnpm') {
knownSet.add(RushConstants.pnpmfileFilename.toUpperCase());
}
// Is the filename something we know? If not, report an error.
if (!knownSet.has(filename.toUpperCase())) {
throw new Error(`An unrecognized file "${filename}" was found in the Rush config folder:`
+ ` ${commonRushConfigFolder}`);
}
}
const pinnedVersionsFilename: string = path.join(commonRushConfigFolder, RushConstants.pinnedVersionsFilename);
if (FileSystem.exists(pinnedVersionsFilename)) {
throw new Error('The "pinned-versions.json" config file is no longer supported;'
+ ' please move your settings to the "preferredVersions" field of a "common-versions.json" config file.'
+ ` (See the ${RushConstants.rushWebSiteUrl} documentation for details.)\n\n`
+ pinnedVersionsFilename);
}
}
/**
* The name of the package manager being used to install dependencies
*/
public get packageManager(): PackageManagerName {
return this._packageManager;
}
/**
* {@inheritdoc PackageManager}
*
* @privateremarks
* In the next major breaking API change, we will rename this property to "packageManager" and eliminate the
* old property with that name.
*
* @beta
*/
public get packageManagerWrapper(): PackageManager {
return this._packageManagerWrapper;
}
/**
* The absolute path to the "rush.json" configuration file that was loaded to construct this object.
*/
public get rushJsonFile(): string {
return this._rushJsonFile;
}
/**
* The absolute path of the folder that contains rush.json for this project.
*/
public get rushJsonFolder(): string {
return this._rushJsonFolder;
}
/**
* The folder that contains all change files.
*/
public get changesFolder(): string {
return this._changesFolder;
}
/**
* The fully resolved path for the "common" folder where Rush will store settings that
* affect all Rush projects. This is always a subfolder of the folder containing "rush.json".
* Example: `C:\MyRepo\common`
*/
public get commonFolder(): string {
return this._commonFolder;
}
/**
* The folder where Rush's additional config files are stored. This folder is always a
* subfolder called `config\rush` inside the common folder. (The `common\config` folder
* is reserved for configuration files used by other tools.) To avoid confusion or mistakes,
* Rush will report an error if this this folder contains any unrecognized files.
*
* Example: `C:\MyRepo\common\config\rush`
*/
public get commonRushConfigFolder(): string {
return this._commonRushConfigFolder;
}
/**
* The folder where temporary files will be stored. This is always a subfolder called "temp"
* under the common folder.
* Example: `C:\MyRepo\common\temp`
*/
public get commonTempFolder(): string {
return this._commonTempFolder;
}
/**
* The folder where automation scripts are stored. This is always a subfolder called "scripts"
* under the common folder.
* Example: `C:\MyRepo\common\scripts`
*/
public get commonScriptsFolder(): string {
return this._commonScriptsFolder;
}
/**
* The local folder that will store the NPM package cache. Rush does not rely on the
* npm's default global cache folder, because npm's caching implementation does not
* reliably handle multiple processes. (For example, if a build box is running
* "rush install" simultaneously for two different working folders, it may fail randomly.)
*
* Example: `C:\MyRepo\common\temp\npm-cache`
*/
public get npmCacheFolder(): string {
return this._npmCacheFolder;
}
/**
* The local folder where npm's temporary files will be written during installation.
* Rush does not rely on the global default folder, because it may be on a different
* hard disk.
*
* Example: `C:\MyRepo\common\temp\npm-tmp`
*/
public get npmTmpFolder(): string {
return this._npmTmpFolder;
}
/**
* The local folder that will store the Yarn package cache.
*
* Example: `C:\MyRepo\common\temp\yarn-cache`
*/
public get yarnCacheFolder(): string {
return this._yarnCacheFolder;
}
/**
* The full path of the shrinkwrap file that is tracked by Git. (The "rush install"