-
Notifications
You must be signed in to change notification settings - Fork 702
Expand file tree
/
Copy pathBaseInstallManager.ts
More file actions
1233 lines (1089 loc) · 49.5 KB
/
Copy pathBaseInstallManager.ts
File metadata and controls
1233 lines (1089 loc) · 49.5 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.
import * as os from 'node:os';
import * as path from 'node:path';
import * as crypto from 'node:crypto';
import { existsSync } from 'node:fs';
import { readFile, unlink } from 'node:fs/promises';
import * as semver from 'semver';
import {
type ILockfile,
type ILogMessageCallbackOptions,
pnpmSyncGetJsonVersion,
pnpmSyncPrepareAsync
} from 'pnpm-sync-lib';
import {
FileSystem,
JsonFile,
PosixModeBits,
NewlineKind,
AlreadyReportedError,
type FileSystemStats,
Path,
type FolderItem,
Async
} from '@rushstack/node-core-library';
import { PrintUtilities, Colorize, type ITerminal } from '@rushstack/terminal';
import { ApprovedPackagesChecker } from '../ApprovedPackagesChecker';
import type { AsyncRecycler } from '../../utilities/AsyncRecycler';
import type { BaseShrinkwrapFile } from './BaseShrinkwrapFile';
import { EnvironmentConfiguration } from '../../api/EnvironmentConfiguration';
import { Git } from '../Git';
import {
type LastInstallFlag,
getCommonTempFlag,
type ILastInstallFlagJson
} from '../../api/LastInstallFlag';
import type { PnpmPackageManager } from '../../api/packageManager/PnpmPackageManager';
import type { PurgeManager } from '../PurgeManager';
import type { ICurrentVariantJson, RushConfiguration } from '../../api/RushConfiguration';
import { Rush } from '../../api/Rush';
import type { RushGlobalFolder } from '../../api/RushGlobalFolder';
import { RushConstants } from '../RushConstants';
import { ShrinkwrapFileFactory } from '../ShrinkwrapFileFactory';
import { Utilities } from '../../utilities/Utilities';
import { InstallHelpers } from '../installManager/InstallHelpers';
import * as PolicyValidator from '../policy/PolicyValidator';
import type { WebClient as WebClientType, IWebClientResponse } from '../../utilities/WebClient';
import { SetupPackageRegistry } from '../setup/SetupPackageRegistry';
import { PnpmfileConfiguration } from '../pnpm/PnpmfileConfiguration';
import type { IInstallManagerOptions } from './BaseInstallManagerTypes';
import { isVariableSetInNpmrcFile } from '../../utilities/npmrcUtilities';
import type { PnpmOptionsConfiguration, PnpmResolutionMode } from '../pnpm/PnpmOptionsConfiguration';
import { SubspacePnpmfileConfiguration } from '../pnpm/SubspacePnpmfileConfiguration';
import type { Subspace } from '../../api/Subspace';
import { ProjectImpactGraphGenerator } from '../ProjectImpactGraphGenerator';
import { FlagFile } from '../../api/FlagFile';
import { PnpmSyncUtilities } from '../../utilities/PnpmSyncUtilities';
import { HotlinkManager } from '../../utilities/HotlinkManager';
/**
* Pnpm don't support --ignore-compatibility-db, so use --config.ignoreCompatibilityDb for now.
*/
export const pnpmIgnoreCompatibilityDbParameter: string = '--config.ignoreCompatibilityDb';
const pnpmCacheDirParameter: string = '--config.cacheDir';
const pnpmStateDirParameter: string = '--config.stateDir';
const gitLfsHooks: ReadonlySet<string> = new Set(['post-checkout', 'post-commit', 'post-merge', 'pre-push']);
/**
* This class implements common logic between "rush install" and "rush update".
*/
export abstract class BaseInstallManager {
private readonly _commonTempLinkFlag: FlagFile;
private _npmSetupValidated: boolean = false;
private _syncNpmrcAlreadyCalled: boolean = false;
protected readonly _terminal: ITerminal;
protected readonly rushConfiguration: RushConfiguration;
protected readonly rushGlobalFolder: RushGlobalFolder;
protected readonly installRecycler: AsyncRecycler;
protected readonly options: IInstallManagerOptions;
// Mapping of subspaceName -> LastInstallFlag
protected readonly subspaceInstallFlags: Map<string, LastInstallFlag>;
public constructor(
rushConfiguration: RushConfiguration,
rushGlobalFolder: RushGlobalFolder,
purgeManager: PurgeManager,
options: IInstallManagerOptions
) {
this._terminal = options.terminal;
this.rushConfiguration = rushConfiguration;
this.rushGlobalFolder = rushGlobalFolder;
this.installRecycler = purgeManager.commonTempFolderRecycler;
this.options = options;
this._commonTempLinkFlag = new FlagFile(
options.subspace.getSubspaceTempFolderPath(),
RushConstants.lastLinkFlagFilename,
{}
);
this.subspaceInstallFlags = new Map();
if (rushConfiguration.subspacesFeatureEnabled) {
for (const subspace of rushConfiguration.subspaces) {
this.subspaceInstallFlags.set(subspace.subspaceName, getCommonTempFlag(rushConfiguration, subspace));
}
}
}
public async doInstallAsync(): Promise<void> {
const { allowShrinkwrapUpdates, selectedProjects, pnpmFilterArgumentValues, resolutionOnly, variant } =
this.options;
const isFilteredInstall: boolean = pnpmFilterArgumentValues.length > 0;
const useWorkspaces: boolean =
this.rushConfiguration.pnpmOptions && this.rushConfiguration.pnpmOptions.useWorkspaces;
// Prevent filtered installs when workspaces is disabled
if (isFilteredInstall && !useWorkspaces) {
// eslint-disable-next-line no-console
console.log();
// eslint-disable-next-line no-console
console.log(
Colorize.red(
'Project filtering arguments can only be used when running in a workspace environment. Run the ' +
'command again without specifying these arguments.'
)
);
throw new AlreadyReportedError();
}
// Prevent update when using a filter, as modifications to the shrinkwrap shouldn't be saved
if (allowShrinkwrapUpdates && isFilteredInstall) {
// Allow partial update when there are subspace projects
if (!this.rushConfiguration.subspacesFeatureEnabled) {
// eslint-disable-next-line no-console
console.log();
// eslint-disable-next-line no-console
console.log(
Colorize.red(
'Project filtering arguments cannot be used when running "rush update". Run the command again ' +
'without specifying these arguments.'
)
);
throw new AlreadyReportedError();
}
}
const subspace: Subspace = this.options.subspace;
const projectImpactGraphGenerator: ProjectImpactGraphGenerator | undefined = this.rushConfiguration
.experimentsConfiguration.configuration.generateProjectImpactGraphDuringRushUpdate
? new ProjectImpactGraphGenerator(this._terminal, this.rushConfiguration)
: undefined;
const { shrinkwrapIsUpToDate, npmrcHash, projectImpactGraphIsUpToDate, variantIsUpToDate } =
await this.prepareAsync(subspace, variant, projectImpactGraphGenerator);
if (this.options.checkOnly) {
return;
}
// eslint-disable-next-line no-console
console.log('\n' + Colorize.bold(`Checking installation in "${subspace.getSubspaceTempFolderPath()}"`));
// This marker file indicates that the last "rush install" completed successfully.
// Always perform a clean install if filter flags were provided. Additionally, if
// "--purge" was specified, or if the last install was interrupted, then we will
// need to perform a clean install. Otherwise, we can do an incremental install.
const commonTempInstallFlag: LastInstallFlag = getCommonTempFlag(this.rushConfiguration, subspace, {
npmrcHash: npmrcHash || '<NO NPMRC>'
});
if (isFilteredInstall && selectedProjects) {
const selectedProjectNames: string[] = [];
for (const { packageName } of selectedProjects) {
selectedProjectNames.push(packageName);
}
selectedProjectNames.sort();
// Get the projects involved in this filtered install
commonTempInstallFlag.mergeFromObject({
selectedProjectNames
});
}
const optionsToIgnore: (keyof ILastInstallFlagJson)[] | undefined = !this.rushConfiguration
.experimentsConfiguration.configuration.cleanInstallAfterNpmrcChanges
? ['npmrcHash'] // If the "cleanInstallAfterNpmrcChanges" experiment is disabled, ignore the npmrcHash
: undefined;
const cleanInstall: boolean = !(await commonTempInstallFlag.checkValidAndReportStoreIssuesAsync({
rushVerb: allowShrinkwrapUpdates ? 'update' : 'install',
statePropertiesToIgnore: optionsToIgnore
}));
const hotlinkManager: HotlinkManager = HotlinkManager.loadFromRushConfiguration(this.rushConfiguration);
const wasNodeModulesModifiedOutsideInstallation: boolean = await hotlinkManager.purgeLinksAsync(
this._terminal,
subspace.subspaceName
);
// Allow us to defer the file read until we need it
const canSkipInstallAsync: () => Promise<boolean> = async () => {
// Based on timestamps, can we skip this install entirely?
const outputStats: FileSystemStats = await FileSystem.getStatisticsAsync(commonTempInstallFlag.path);
return this.canSkipInstallAsync(outputStats.mtime, subspace, variant);
};
if (
resolutionOnly ||
cleanInstall ||
wasNodeModulesModifiedOutsideInstallation ||
!variantIsUpToDate ||
!shrinkwrapIsUpToDate ||
!(await canSkipInstallAsync()) ||
!projectImpactGraphIsUpToDate
) {
// eslint-disable-next-line no-console
console.log();
await this.validateNpmSetupAsync();
if (!this.rushConfiguration.rushConfigurationJson.suppressRushIsPublicVersionCheck) {
let publishedRelease: boolean | undefined;
try {
publishedRelease = await this._checkIfReleaseIsPublishedAsync();
} catch {
// If the user is working in an environment that can't reach the registry,
// don't bother them with errors.
}
if (publishedRelease === false) {
// eslint-disable-next-line no-console
console.log(
Colorize.yellow('Warning: This release of the Rush tool was unpublished; it may be unstable.')
);
}
}
if (!resolutionOnly) {
// Delete the successful install file to indicate the install transaction has started
await commonTempInstallFlag.clearAsync();
// Since we're going to be tampering with common/node_modules, delete the "rush link" flag file if it exists;
// this ensures that a full "rush link" is required next time
await this._commonTempLinkFlag.clearAsync();
}
// Give plugins an opportunity to act before invoking the installation process
if (this.options.beforeInstallAsync !== undefined) {
await this.options.beforeInstallAsync(subspace);
}
await Promise.all([
// Perform the actual install
this.installAsync(cleanInstall, subspace),
// If allowed, generate the project impact graph
allowShrinkwrapUpdates ? projectImpactGraphGenerator?.generateAsync() : undefined
]);
if (this.options.allowShrinkwrapUpdates && !shrinkwrapIsUpToDate) {
const shrinkwrapFilePath: string = subspace.getCommittedShrinkwrapFilePath(variant);
const shrinkwrapFile: BaseShrinkwrapFile | undefined = ShrinkwrapFileFactory.getShrinkwrapFile({
packageManager: this.rushConfiguration.packageManager,
shrinkwrapFilePath,
subspaceHasNoProjects: subspace.getProjects().length === 0
});
shrinkwrapFile?.validateShrinkwrapAfterUpdate(this.rushConfiguration, subspace, this._terminal);
// Copy (or delete) common\temp\pnpm-lock.yaml --> common\config\rush\pnpm-lock.yaml
Utilities.syncFile(subspace.getTempShrinkwrapFilename(), shrinkwrapFilePath);
} else {
// TODO: Validate whether the package manager updated it in a nontrivial way
}
// Always update the state file if running "rush update"
if (this.options.allowShrinkwrapUpdates) {
if (subspace.getRepoState().refreshState(this.rushConfiguration, subspace, variant)) {
// eslint-disable-next-line no-console
console.log(
Colorize.yellow(
`${RushConstants.repoStateFilename} has been modified and must be committed to source control.`
)
);
}
}
} else {
// eslint-disable-next-line no-console
console.log('Installation is already up-to-date.');
}
const { configuration: experiments } = this.rushConfiguration.experimentsConfiguration;
// if usePnpmSyncForInjectedDependencies is true
// the pnpm-sync will generate the pnpm-sync.json based on lockfile
if (this.rushConfiguration.isPnpm && experiments?.usePnpmSyncForInjectedDependencies) {
const pnpmLockfilePath: string = subspace.getTempShrinkwrapFilename();
const dotPnpmFolder: string = `${subspace.getSubspaceTempFolderPath()}/node_modules/.pnpm`;
const modulesFilePath: string = `${subspace.getSubspaceTempFolderPath()}/node_modules/.modules.yaml`;
// we have an edge case here
// if a package.json has no dependencies, pnpm will still generate the pnpm-lock.yaml but not .pnpm folder
// so we need to make sure pnpm-lock.yaml and .pnpm exists before calling the pnpmSync APIs
if (
(await FileSystem.existsAsync(pnpmLockfilePath)) &&
(await FileSystem.existsAsync(dotPnpmFolder)) &&
(await FileSystem.existsAsync(modulesFilePath))
) {
await pnpmSyncPrepareAsync({
lockfilePath: pnpmLockfilePath,
dotPnpmFolder,
lockfileId: subspace.subspaceName,
ensureFolderAsync: FileSystem.ensureFolderAsync.bind(FileSystem),
// eslint-disable-next-line @typescript-eslint/naming-convention
readPnpmLockfile: async (lockfilePath: string, options): Promise<ILockfile | undefined> => {
const pnpmLockFolder: string = path.dirname(lockfilePath);
// TODO: Rework this to pre-parse out the version first, then load
// the relevant `@rushstack/rush-pnpm-kit-*` package.
const { lockfileFs: lockfileFsV9 } = await import('@rushstack/rush-pnpm-kit-v9');
const lockfileV9: ILockfile | null = (await lockfileFsV9.readWantedLockfile(
pnpmLockFolder,
options
// TODO: pnpm-sync-lib.d.ts was at some point generalized to support multiple lockfile formats,
// however its API still returns a single "ILockfile" that is incompatible with the newer interfaces
)) as ILockfile | null;
if (lockfileV9?.lockfileVersion.toString().startsWith('9')) {
return lockfileV9;
}
const { lockfileFs: lockfileFsV6 } = await import('@rushstack/rush-pnpm-kit-v8');
const lockfileV6: ILockfile | null = await lockfileFsV6.readWantedLockfile(
pnpmLockFolder,
options
);
if (lockfileV6?.lockfileVersion.toString().startsWith('6')) {
return lockfileV6;
}
return undefined;
},
logMessageCallback: (logMessageOptions: ILogMessageCallbackOptions) =>
PnpmSyncUtilities.processLogMessage(logMessageOptions, this._terminal)
});
}
// clean up the out of date .pnpm-sync.json
for (const rushProject of subspace.getProjects()) {
const pnpmSyncJsonPath: string = `${rushProject.projectFolder}/${RushConstants.nodeModulesFolderName}/${RushConstants.pnpmSyncFilename}`;
if (!existsSync(pnpmSyncJsonPath)) {
continue;
}
let existingPnpmSyncJsonFile: { version: string } | undefined;
try {
existingPnpmSyncJsonFile = JSON.parse((await readFile(pnpmSyncJsonPath)).toString());
if (existingPnpmSyncJsonFile?.version !== pnpmSyncGetJsonVersion()) {
await unlink(pnpmSyncJsonPath);
}
} catch (e) {
await unlink(pnpmSyncJsonPath);
}
}
}
// Perform any post-install work the install manager requires
await this.postInstallAsync(subspace);
if (!resolutionOnly) {
// Create the marker file to indicate a successful install
await commonTempInstallFlag.createAsync();
}
// Give plugins an opportunity to act after a successful install
if (this.options.afterInstallAsync !== undefined) {
await this.options.afterInstallAsync(subspace);
}
// eslint-disable-next-line no-console
console.log('');
}
protected abstract prepareCommonTempAsync(
subspace: Subspace,
shrinkwrapFile: BaseShrinkwrapFile | undefined
): Promise<{ shrinkwrapIsUpToDate: boolean; shrinkwrapWarnings: string[] }>;
protected abstract installAsync(cleanInstall: boolean, subspace: Subspace): Promise<void>;
protected abstract postInstallAsync(subspace: Subspace): Promise<void>;
protected async canSkipInstallAsync(
lastModifiedDate: Date,
subspace: Subspace,
variant: string | undefined
): Promise<boolean> {
// Based on timestamps, can we skip this install entirely?
const potentiallyChangedFiles: string[] = [];
// Consider the timestamp on the node_modules folder; if someone tampered with it
// or deleted it entirely, then we can't skip this install
potentiallyChangedFiles.push(
path.join(subspace.getSubspaceTempFolderPath(), RushConstants.nodeModulesFolderName)
);
// Additionally, if they pulled an updated shrinkwrap file from Git,
// then we can't skip this install
potentiallyChangedFiles.push(subspace.getCommittedShrinkwrapFilePath(variant));
// Add common-versions.json file to the potentially changed files list.
potentiallyChangedFiles.push(subspace.getCommonVersionsFilePath(variant));
// Add pnpm-config.json file to the potentially changed files list.
potentiallyChangedFiles.push(subspace.getPnpmConfigFilePath());
if (this.rushConfiguration.isPnpm) {
// If the repo is using pnpmfile.js, consider that also
const pnpmFileFilePath: string = subspace.getPnpmfilePath(variant);
const pnpmFileExists: boolean = await FileSystem.existsAsync(pnpmFileFilePath);
if (pnpmFileExists) {
potentiallyChangedFiles.push(pnpmFileFilePath);
}
}
return await Utilities.isFileTimestampCurrentAsync(lastModifiedDate, potentiallyChangedFiles);
}
protected async prepareAsync(
subspace: Subspace,
variant: string | undefined,
projectImpactGraphGenerator: ProjectImpactGraphGenerator | undefined
): Promise<{
shrinkwrapIsUpToDate: boolean;
npmrcHash: string | undefined;
projectImpactGraphIsUpToDate: boolean;
variantIsUpToDate: boolean;
}> {
const terminal: ITerminal = this._terminal;
const { allowShrinkwrapUpdates } = this.options;
// Check the policies
await PolicyValidator.validatePolicyAsync(this.rushConfiguration, subspace, variant, this.options);
await this._installGitHooksAsync();
const approvedPackagesChecker: ApprovedPackagesChecker = new ApprovedPackagesChecker(
this.rushConfiguration
);
if (approvedPackagesChecker.approvedPackagesFilesAreOutOfDate) {
approvedPackagesChecker.rewriteConfigFiles();
if (allowShrinkwrapUpdates) {
terminal.writeLine(
Colorize.yellow(
'Approved package files have been updated. These updates should be committed to source control'
)
);
} else {
throw new Error(`Approved packages files are out-of date. Run "rush update" to update them.`);
}
}
// Ensure that the package manager is installed
await InstallHelpers.ensureLocalPackageManagerAsync(
this.rushConfiguration,
this.rushGlobalFolder,
this.options.maxInstallAttempts
);
let shrinkwrapFile: BaseShrinkwrapFile | undefined = undefined;
// (If it's a full update, then we ignore the shrinkwrap from Git since it will be overwritten)
if (!this.options.fullUpgrade) {
const shrinkwrapFilePath: string = subspace.getCommittedShrinkwrapFilePath(variant);
try {
shrinkwrapFile = ShrinkwrapFileFactory.getShrinkwrapFile({
packageManager: this.rushConfiguration.packageManager,
shrinkwrapFilePath,
subspaceHasNoProjects: subspace.getProjects().length === 0
});
} catch (ex) {
terminal.writeLine();
terminal.writeLine(
`Unable to load the ${this.rushConfiguration.shrinkwrapFilePhrase}: ${(ex as Error).message}`
);
if (!allowShrinkwrapUpdates) {
terminal.writeLine();
terminal.writeLine(Colorize.red('You need to run "rush update" to fix this problem'));
throw new AlreadyReportedError();
}
shrinkwrapFile = undefined;
}
}
// Write a file indicating which variant is being installed.
// This will be used by bulk scripts to determine the correct Shrinkwrap file to track.
const currentVariantJsonFilePath: string = this.rushConfiguration.currentVariantJsonFilePath;
const currentVariantJson: ICurrentVariantJson = {
variant: variant ?? null
};
// Determine if the variant is already current by updating current-variant.json.
// If nothing is written, the variant has not changed.
const variantIsUpToDate: boolean = !(await JsonFile.saveAsync(
currentVariantJson,
currentVariantJsonFilePath,
{
onlyIfChanged: true
}
));
this.rushConfiguration._currentVariantJsonLoadingPromise = undefined;
if (this.options.variant) {
terminal.writeLine();
terminal.writeLine(Colorize.bold(`Using variant '${this.options.variant}' for installation.`));
} else if (!variantIsUpToDate && !variant && this.rushConfiguration.variants.size > 0) {
terminal.writeLine();
terminal.writeLine(Colorize.bold('Using the default variant for installation.'));
}
const extraNpmrcLines: string[] = [];
if (this.rushConfiguration.subspacesFeatureEnabled) {
// Look for a monorepo level .npmrc file
const commonNpmrcPath: string = `${this.rushConfiguration.commonRushConfigFolder}/.npmrc`;
let commonNpmrcFileLines: string[] | undefined;
try {
commonNpmrcFileLines = (await FileSystem.readFileAsync(commonNpmrcPath)).split('\n');
} catch (e) {
if (!FileSystem.isNotExistError(e)) {
throw e;
}
}
if (commonNpmrcFileLines) {
extraNpmrcLines.push(...commonNpmrcFileLines);
}
extraNpmrcLines.push(
`global-pnpmfile=${subspace.getSubspaceTempFolderPath()}/${RushConstants.pnpmfileGlobalFilename}`
);
}
// Build lines to append to the generated .npmrc so they take precedence over user-committed values.
// pnpm does not read minimumReleaseAge/minimumReleaseAgeExclude from package.json, so we inject
// them here as minimum-release-age / minimum-release-age-exclude .npmrc settings instead.
const pnpmNpmrcAppendLines: string[] = [];
if (this.rushConfiguration.isPnpm) {
const pnpmOptions: PnpmOptionsConfiguration =
subspace.getPnpmOptions() ?? this.rushConfiguration.pnpmOptions;
if (pnpmOptions.minimumReleaseAgeMinutes !== undefined || pnpmOptions.minimumReleaseAgeExclude) {
if (
this.rushConfiguration.rushConfigurationJson.pnpmVersion !== undefined &&
semver.lt(this.rushConfiguration.rushConfigurationJson.pnpmVersion, '10.16.0')
) {
terminal.writeWarningLine(
Colorize.yellow(
`Your version of pnpm (${this.rushConfiguration.rushConfigurationJson.pnpmVersion}) ` +
`doesn't support the "minimumReleaseAgeMinutes" or "minimumReleaseAgeExclude" fields in ` +
`${this.rushConfiguration.commonRushConfigFolder}/${RushConstants.pnpmConfigFilename}. ` +
'Remove these fields or upgrade to pnpm 10.16.0 or newer.'
)
);
}
if (pnpmOptions.minimumReleaseAgeMinutes !== undefined) {
if (
isVariableSetInNpmrcFile(
subspace.getSubspaceConfigFolderPath(),
'minimum-release-age',
this.rushConfiguration.isPnpm
)
) {
terminal.writeWarningLine(
`Warning: PNPM's minimum-release-age is specified in both .npmrc and pnpm-config.json. ` +
`The value in pnpm-config.json will take precedence.`
);
}
pnpmNpmrcAppendLines.push(`minimum-release-age=${pnpmOptions.minimumReleaseAgeMinutes}`);
}
if (pnpmOptions.minimumReleaseAgeExclude) {
for (const packageName of pnpmOptions.minimumReleaseAgeExclude) {
pnpmNpmrcAppendLines.push(`minimum-release-age-exclude[]=${packageName}`);
}
}
}
}
// Also copy down the committed .npmrc file, if there is one
// "common\config\rush\.npmrc" --> "common\temp\.npmrc"
// Also ensure that we remove any old one that may be hanging around
const npmrcText: string | undefined = Utilities.syncNpmrc({
sourceNpmrcFolder: subspace.getSubspaceConfigFolderPath(),
targetNpmrcFolder: subspace.getSubspaceTempFolderPath(),
linesToPrepend: extraNpmrcLines,
linesToAppend: pnpmNpmrcAppendLines.length > 0 ? pnpmNpmrcAppendLines : undefined,
createIfMissing: this.rushConfiguration.subspacesFeatureEnabled,
supportEnvVarFallbackSyntax: this.rushConfiguration.isPnpm
});
this._syncNpmrcAlreadyCalled = true;
const npmrcHash: string | undefined = npmrcText
? crypto.createHash('sha1').update(npmrcText).digest('hex')
: undefined;
if (this.rushConfiguration.isPnpm) {
// Copy the committed patches folder if using pnpm
const commonTempPnpmPatchesFolder: string = `${subspace.getSubspaceTempFolderPath()}/${
RushConstants.pnpmPatchesFolderName
}`;
const rushPnpmPatchesFolder: string = subspace.getSubspacePnpmPatchesFolderPath();
let rushPnpmPatches: FolderItem[] | undefined;
try {
rushPnpmPatches = await FileSystem.readFolderItemsAsync(rushPnpmPatchesFolder);
} catch (e) {
if (!FileSystem.isNotExistError(e)) {
throw e;
}
}
if (rushPnpmPatches) {
await FileSystem.ensureFolderAsync(commonTempPnpmPatchesFolder);
const existingPatches: FolderItem[] =
await FileSystem.readFolderItemsAsync(commonTempPnpmPatchesFolder);
const copiedPatchNames: Set<string> = new Set();
await Async.forEachAsync(
rushPnpmPatches,
async (patch: FolderItem) => {
const name: string = patch.name;
const sourcePath: string = `${rushPnpmPatchesFolder}/${name}`;
if (patch.isFile()) {
await FileSystem.copyFileAsync({
sourcePath,
destinationPath: `${commonTempPnpmPatchesFolder}/${name}`
});
copiedPatchNames.add(name);
} else {
throw new Error(`Unexpected non-file item found in ${rushPnpmPatchesFolder}: ${sourcePath}`);
}
},
{ concurrency: 50 }
);
await Async.forEachAsync(
existingPatches,
async (patch: FolderItem) => {
const name: string = patch.name;
if (!copiedPatchNames.has(name)) {
await FileSystem.deleteFileAsync(`${commonTempPnpmPatchesFolder}/${name}`);
}
},
{ concurrency: 50 }
);
} else {
await FileSystem.deleteFolderAsync(commonTempPnpmPatchesFolder);
}
}
// Shim support for pnpmfile in.
// Additionally when in workspaces, the shim implements support for common versions.
if (this.rushConfiguration.isPnpm) {
await PnpmfileConfiguration.writeCommonTempPnpmfileShimAsync(
this.rushConfiguration,
subspace.getSubspaceTempFolderPath(),
subspace,
variant
);
if (this.rushConfiguration.subspacesFeatureEnabled) {
await SubspacePnpmfileConfiguration.writeCommonTempSubspaceGlobalPnpmfileAsync(
this.rushConfiguration,
subspace,
variant
);
}
}
// eslint-disable-next-line prefer-const
let [{ shrinkwrapIsUpToDate, shrinkwrapWarnings }, projectImpactGraphIsUpToDate = true] =
await Promise.all([
// Allow for package managers to do their own preparation and check that the shrinkwrap is up to date
this.prepareCommonTempAsync(subspace, shrinkwrapFile),
projectImpactGraphGenerator?.validateAsync()
]);
shrinkwrapIsUpToDate = shrinkwrapIsUpToDate && !this.options.recheckShrinkwrap;
this._syncTempShrinkwrap(subspace, variant, shrinkwrapFile);
// Write out the reported warnings
if (shrinkwrapWarnings.length > 0) {
terminal.writeLine();
terminal.writeLine(
Colorize.yellow(
PrintUtilities.wrapWords(
`The ${this.rushConfiguration.shrinkwrapFilePhrase} contains the following issues:`
)
)
);
for (const shrinkwrapWarning of shrinkwrapWarnings) {
terminal.writeLine(Colorize.yellow(' ' + shrinkwrapWarning));
}
terminal.writeLine();
}
let hasErrors: boolean = false;
// Force update if the shrinkwrap is out of date
if (!shrinkwrapIsUpToDate && !allowShrinkwrapUpdates) {
terminal.writeErrorLine();
terminal.writeErrorLine(
`The ${this.rushConfiguration.shrinkwrapFilePhrase} is out of date. You need to run "rush update".`
);
hasErrors = true;
}
if (!projectImpactGraphIsUpToDate && !allowShrinkwrapUpdates) {
hasErrors = true;
terminal.writeErrorLine();
terminal.writeErrorLine(
Colorize.red(
`The ${RushConstants.projectImpactGraphFilename} file is missing or out of date. You need to run "rush update".`
)
);
}
if (hasErrors) {
throw new AlreadyReportedError();
}
return { shrinkwrapIsUpToDate, npmrcHash, projectImpactGraphIsUpToDate, variantIsUpToDate };
}
/**
* Git hooks are only installed if the repo opts in by including files in /common/git-hooks
*/
private async _installGitHooksAsync(): Promise<void> {
const hookSource: string = path.join(this.rushConfiguration.commonFolder, 'git-hooks');
const git: Git = new Git(this.rushConfiguration);
const hookDestination: string | undefined = git.getHooksFolder();
if (FileSystem.exists(hookSource) && hookDestination) {
const allHookFilenames: string[] = FileSystem.readFolderItemNames(hookSource);
// Ignore the ".sample" file(s) in this folder.
const hookFilenames: string[] = allHookFilenames.filter((x) => !/\.sample$/.test(x));
if (hookFilenames.length > 0) {
// eslint-disable-next-line no-console
console.log('\n' + Colorize.bold('Found files in the "common/git-hooks" folder.'));
if (!(await git.getIsHooksPathDefaultAsync())) {
const hooksPath: string = await git.getConfigHooksPathAsync();
const color: (str: string) => string = this.options.bypassPolicy ? Colorize.yellow : Colorize.red;
// eslint-disable-next-line no-console
console.error(
color(
[
' ',
`Rush cannot install the "common/git-hooks" scripts because your Git configuration `,
`specifies "core.hooksPath=${hooksPath}". You can remove the setting by running:`,
' ',
' git config --unset core.hooksPath',
' '
].join('\n')
)
);
if (this.options.bypassPolicy) {
// If "--bypass-policy" is specified, skip installation of hooks because Rush doesn't
// own the hooks folder
return;
}
// eslint-disable-next-line no-console
console.error(
color(
[
'(Or, to temporarily ignore this problem, invoke Rush with the ' +
`"${RushConstants.bypassPolicyFlagLongName}" option.)`,
' '
].join('\n')
)
);
throw new AlreadyReportedError();
}
// Clear the currently installed git hooks and install fresh copies
FileSystem.ensureEmptyFolder(hookDestination);
// Find the relative path from Git hooks directory to the directory storing the actual scripts.
const hookRelativePath: string = Path.convertToSlashes(path.relative(hookDestination, hookSource));
// Only copy files that look like Git hook names
const filteredHookFilenames: string[] = hookFilenames.filter((x) => /^[a-z\-]+/.test(x));
for (const filename of filteredHookFilenames) {
const hookFilePath: string = `${hookSource}/${filename}`;
// Make sure the actual script in the hookSource directory has correct Linux compatible line endings
const originalHookFileContent: string = FileSystem.readFile(hookFilePath);
FileSystem.writeFile(hookFilePath, originalHookFileContent, {
convertLineEndings: NewlineKind.Lf
});
// Make sure the actual script in the hookSource directory has required permission bits
const originalPosixModeBits: PosixModeBits = FileSystem.getPosixModeBits(hookFilePath);
FileSystem.changePosixModeBits(
hookFilePath,
// eslint-disable-next-line no-bitwise
originalPosixModeBits | PosixModeBits.UserRead | PosixModeBits.UserExecute
);
const gitLfsHookHandling: string = gitLfsHooks.has(filename)
? `
# Inspired by https://github.com/git-lfs/git-lfs/issues/2865#issuecomment-365742940
if command -v git-lfs &> /dev/null; then
git lfs ${filename} "$@"
fi
`
: '';
const hookFileContent: string = `#!/usr/bin/env bash
set -e
SCRIPT_DIR="$( cd "$( dirname "\${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
SCRIPT_IMPLEMENTATION_PATH="$SCRIPT_DIR/${hookRelativePath}/${filename}"
if [[ -f "$SCRIPT_IMPLEMENTATION_PATH" ]]; then
"$SCRIPT_IMPLEMENTATION_PATH" $@
else
echo "The ${filename} Git hook no longer exists in your version of the repo. Run 'rush install' or 'rush update' to refresh your installed Git hooks." >&2
fi
${gitLfsHookHandling}
`;
// Create the hook file. Important: For Bash scripts, the EOL must not be CRLF.
FileSystem.writeFile(path.join(hookDestination, filename), hookFileContent, {
convertLineEndings: NewlineKind.Lf
});
FileSystem.changePosixModeBits(
path.join(hookDestination, filename),
// eslint-disable-next-line no-bitwise
PosixModeBits.UserRead | PosixModeBits.UserExecute
);
}
// eslint-disable-next-line no-console
console.log(
'Successfully installed these Git hook scripts: ' + filteredHookFilenames.join(', ') + '\n'
);
}
}
}
/**
* Used when invoking the NPM tool. Appends the common configuration options
* to the command-line.
*/
protected pushConfigurationArgs(args: string[], options: IInstallManagerOptions, subspace: Subspace): void {
const {
offline,
collectLogFile,
pnpmFilterArgumentValues,
onlyShrinkwrap,
networkConcurrency,
allowShrinkwrapUpdates,
resolutionOnly
} = options;
if (offline && this.rushConfiguration.packageManager !== 'pnpm') {
throw new Error('The "--offline" parameter is only supported when using the PNPM package manager.');
}
if (resolutionOnly && this.rushConfiguration.packageManager !== 'pnpm') {
throw new Error(
'The "--resolution-only" parameter is only supported when using the PNPM package manager.'
);
}
if (this.rushConfiguration.packageManager === 'npm') {
if (semver.lt(this.rushConfiguration.packageManagerToolVersion, '5.0.0')) {
// NOTE:
//
// When using an npm version older than v5.0.0, we do NOT install optional dependencies for
// Rush, because npm does not generate the shrinkwrap file consistently across platforms.
//
// Consider the "fsevents" package. This is a Mac specific package
// which is an optional second-order dependency. Optional dependencies work by attempting to install
// the package, but removes the package if the install failed.
// This means that someone running generate on a Mac WILL have fsevents included in their shrinkwrap.
// When someone using Windows attempts to install from the shrinkwrap, the install will fail.
//
// If someone generates the shrinkwrap using Windows, then fsevents will NOT be listed in the shrinkwrap.
// When someone using Mac attempts to install from the shrinkwrap, they will NOT have the
// optional dependency installed.
//
// This issue has been fixed as of npm v5.0.0: https://github.com/npm/npm/releases/tag/v5.0.0
//
// For more context, see https://github.com/microsoft/rushstack/issues/761#issuecomment-428689600
args.push('--no-optional');
}
args.push('--cache', this.rushConfiguration.npmCacheFolder);
args.push('--tmp', this.rushConfiguration.npmTmpFolder);
if (collectLogFile) {
args.push('--verbose');
}
} else if (this.rushConfiguration.isPnpm) {
// Only explicitly define the store path if `pnpmStore` is using the default, or has been set to
// 'local'. If `pnpmStore` = 'global', then allow PNPM to use the system's default
// path. In all cases, this will be overridden by RUSH_PNPM_STORE_PATH
if (
this.rushConfiguration.pnpmOptions.pnpmStore === 'local' ||
EnvironmentConfiguration.pnpmStorePathOverride
) {
args.push('--store', this.rushConfiguration.pnpmOptions.pnpmStorePath);
if (semver.gte(this.rushConfiguration.packageManagerToolVersion, '6.10.0')) {
args.push(`${pnpmCacheDirParameter}=${this.rushConfiguration.pnpmOptions.pnpmStorePath}`);
args.push(`${pnpmStateDirParameter}=${this.rushConfiguration.pnpmOptions.pnpmStorePath}`);
}
}
const { pnpmVerifyStoreIntegrity } = EnvironmentConfiguration;
if (pnpmVerifyStoreIntegrity !== undefined) {
args.push(`--verify-store-integrity`, `${pnpmVerifyStoreIntegrity}`);
}
const { configuration: experiments } = this.rushConfiguration.experimentsConfiguration;
if (experiments.usePnpmFrozenLockfileForRushInstall && !allowShrinkwrapUpdates) {
args.push('--frozen-lockfile');
if (
pnpmFilterArgumentValues.length > 0 &&
Number.parseInt(this.rushConfiguration.packageManagerToolVersion, 10) >= 8 // PNPM Major version 8+
) {
// On pnpm@8, disable the "dedupe-peer-dependents" feature when doing a filtered CI install so that filters take effect.
args.push('--config.dedupe-peer-dependents=false');
}
} else if (experiments.usePnpmPreferFrozenLockfileForRushUpdate) {
// In workspaces, we want to avoid unnecessary lockfile churn
args.push('--prefer-frozen-lockfile');
} else {
// Ensure that Rush's tarball dependencies get synchronized properly with the pnpm-lock.yaml file.
// See this GitHub issue: https://github.com/pnpm/pnpm/issues/1342
args.push('--no-prefer-frozen-lockfile');
}
if (onlyShrinkwrap) {
args.push(`--lockfile-only`);
}
if (collectLogFile) {
args.push('--reporter', 'ndjson');
}
if (networkConcurrency) {
args.push('--network-concurrency', networkConcurrency.toString());
}
if (offline) {
args.push('--offline');
}
if (this.rushConfiguration.pnpmOptions.strictPeerDependencies === false) {
args.push('--no-strict-peer-dependencies');
} else {
args.push('--strict-peer-dependencies');
}
if (resolutionOnly) {
args.push('--resolution-only');
}
/*
If user set auto-install-peers in pnpm-config.json only, use the value in pnpm-config.json
If user set auto-install-peers in pnpm-config.json and .npmrc, use the value in pnpm-config.json
If user set auto-install-peers in .npmrc only, do nothing, let pnpm handle it
If user does not set auto-install-peers in both pnpm-config.json and .npmrc, rush will default it to "false"
*/
const isAutoInstallPeersInNpmrc: boolean = isVariableSetInNpmrcFile(
subspace.getSubspaceConfigFolderPath(),
'auto-install-peers',
this.rushConfiguration.isPnpm
);
let autoInstallPeers: boolean | undefined = this.rushConfiguration.pnpmOptions.autoInstallPeers;
if (autoInstallPeers !== undefined) {
if (isAutoInstallPeersInNpmrc) {
this._terminal.writeWarningLine(
`Warning: PNPM's auto-install-peers is specified in both .npmrc and pnpm-config.json. ` +
`The value in pnpm-config.json will take precedence.`
);
}
} else if (!isAutoInstallPeersInNpmrc) {
// if auto-install-peers isn't specified in either .npmrc or pnpm-config.json,
// then rush will default it to "false"
autoInstallPeers = false;
}
if (autoInstallPeers !== undefined) {
args.push(`--config.auto-install-peers=${autoInstallPeers}`);
}
/*
If user set resolution-mode in pnpm-config.json only, use the value in pnpm-config.json
If user set resolution-mode in pnpm-config.json and .npmrc, use the value in pnpm-config.json