-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
install.js
871 lines (724 loc) · 24.8 KB
/
install.js
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
/* @flow */
import type {Reporter} from '../../reporters/index.js';
import type {ReporterSelectOption} from '../../reporters/types.js';
import type {Manifest, DependencyRequestPatterns} from '../../types.js';
import type Config from '../../config.js';
import type {RegistryNames} from '../../registries/index.js';
import normalizeManifest from '../../util/normalize-manifest/index.js';
import {registryNames} from '../../registries/index.js';
import {MessageError} from '../../errors.js';
import Lockfile from '../../lockfile/wrapper.js';
import lockStringify from '../../lockfile/stringify.js';
import PackageFetcher from '../../package-fetcher.js';
import PackageInstallScripts from '../../package-install-scripts.js';
import PackageCompatibility from '../../package-compatibility.js';
import PackageResolver from '../../package-resolver.js';
import PackageLinker from '../../package-linker.js';
import PackageRequest from '../../package-request.js';
import {registries} from '../../registries/index.js';
import {clean} from './clean.js';
import * as constants from '../../constants.js';
import * as fs from '../../util/fs.js';
import * as crypto from '../../util/crypto.js';
import map from '../../util/map.js';
import {sortAlpha} from '../../util/misc.js';
const invariant = require('invariant');
const semver = require('semver');
const emoji = require('node-emoji');
const isCI = require('is-ci');
const path = require('path');
const {version: YARN_VERSION, installationMethod: YARN_INSTALL_METHOD} = require('../../../package.json');
const ONE_DAY = 1000 * 60 * 60 * 24;
export type InstallCwdRequest = {
requests: DependencyRequestPatterns,
patterns: Array<string>,
ignorePatterns: Array<string>,
usedPatterns: Array<string>,
manifest: Object,
};
export type IntegrityMatch = {
actual: string,
expected: string,
loc: string,
matches: boolean,
};
type Flags = {
// install
ignorePlatform: boolean,
ignoreEngines: boolean,
ignoreScripts: boolean,
ignoreOptional: boolean,
har: boolean,
force: boolean,
flat: boolean,
lockfile: boolean,
pureLockfile: boolean,
skipIntegrity: boolean,
// add
peer: boolean,
dev: boolean,
optional: boolean,
exact: boolean,
tilde: boolean,
};
/**
* Try and detect the installation method for Yarn and provide a command to update it with.
*/
function getUpdateCommand(): ?string {
if (YARN_INSTALL_METHOD === 'tar') {
return 'curl -o- -L https://yarnpkg.com/install.sh | bash';
}
if (YARN_INSTALL_METHOD === 'homebrew') {
return 'brew upgrade yarn';
}
if (YARN_INSTALL_METHOD === 'deb') {
return 'sudo apt-get update && sudo apt-get install yarn';
}
if (YARN_INSTALL_METHOD === 'rpm') {
return 'sudo yum install yarn';
}
if (YARN_INSTALL_METHOD === 'npm') {
return 'npm upgrade --global yarn';
}
if (YARN_INSTALL_METHOD === 'chocolatey') {
return 'choco upgrade yarn';
}
return null;
}
function getUpdateInstaller(): ?string {
// Windows
if (YARN_INSTALL_METHOD === 'msi') {
return 'https://yarnpkg.com/latest.msi';
}
return null;
}
function normalizeFlags(config: Config, rawFlags: Object): Flags {
const flags = {
// install
har: !!rawFlags.har,
ignorePlatform: !!rawFlags.ignorePlatform,
ignoreEngines: !!rawFlags.ignoreEngines,
ignoreScripts: !!rawFlags.ignoreScripts,
ignoreOptional: !!rawFlags.ignoreOptional,
force: !!rawFlags.force,
flat: !!rawFlags.flat,
lockfile: rawFlags.lockfile !== false,
pureLockfile: !!rawFlags.pureLockfile,
skipIntegrity: !!rawFlags.skipIntegrity,
frozenLockfile: !!rawFlags.frozenLockfile,
// add
peer: !!rawFlags.peer,
dev: !!rawFlags.dev,
optional: !!rawFlags.optional,
exact: !!rawFlags.exact,
tilde: !!rawFlags.tilde,
};
if (config.getOption('ignore-scripts')) {
flags.ignoreScripts = true;
}
if (config.getOption('ignore-platform')) {
flags.ignorePlatform = true;
}
if (config.getOption('ignore-engines')) {
flags.ignoreEngines = true;
}
if (config.getOption('ignore-optional')) {
flags.ignoreOptional = true;
}
if (config.getOption('force')) {
flags.force = true;
}
return flags;
}
export class Install {
constructor(
flags: Object,
config: Config,
reporter: Reporter,
lockfile: Lockfile,
) {
this.rootManifestRegistries = [];
this.rootPatternsToOrigin = map();
this.resolutions = map();
this.lockfile = lockfile;
this.reporter = reporter;
this.config = config;
this.flags = normalizeFlags(config, flags);
this.resolver = new PackageResolver(config, lockfile);
this.fetcher = new PackageFetcher(config, this.resolver);
this.compatibility = new PackageCompatibility(config, this.resolver, this.flags.ignoreEngines);
this.linker = new PackageLinker(config, this.resolver);
this.scripts = new PackageInstallScripts(config, this.resolver, this.flags.force);
}
flags: Flags;
rootManifestRegistries: Array<RegistryNames>;
registries: Array<RegistryNames>;
lockfile: Lockfile;
resolutions: { [packageName: string]: string };
config: Config;
reporter: Reporter;
resolver: PackageResolver;
scripts: PackageInstallScripts;
linker: PackageLinker;
compatibility: PackageCompatibility;
fetcher: PackageFetcher;
rootPatternsToOrigin: { [pattern: string]: string };
/**
* Create a list of dependency requests from the current directories manifests.
*/
async fetchRequestFromCwd(excludePatterns?: Array<string> = []): Promise<InstallCwdRequest> {
const patterns = [];
const deps = [];
const manifest = {};
const ignorePatterns = [];
const usedPatterns = [];
// exclude package names that are in install args
const excludeNames = [];
for (const pattern of excludePatterns) {
// can't extract a package name from this
if (PackageRequest.getExoticResolver(pattern)) {
continue;
}
// extract the name
const parts = PackageRequest.normalizePattern(pattern);
excludeNames.push(parts.name);
}
for (const registry of Object.keys(registries)) {
const {filename} = registries[registry];
const loc = path.join(this.config.cwd, filename);
if (!(await fs.exists(loc))) {
continue;
}
this.rootManifestRegistries.push(registry);
const json = await this.config.readJson(loc);
await normalizeManifest(json, this.config.cwd, this.config, true);
Object.assign(this.resolutions, json.resolutions);
Object.assign(manifest, json);
const pushDeps = (depType, {hint, optional}, isUsed) => {
const depMap = json[depType];
for (const name in depMap) {
if (excludeNames.indexOf(name) >= 0) {
continue;
}
let pattern = name;
if (!this.lockfile.getLocked(pattern, true)) {
// when we use --save we save the dependency to the lockfile with just the name rather than the
// version combo
pattern += '@' + depMap[name];
}
if (isUsed) {
usedPatterns.push(pattern);
} else {
ignorePatterns.push(pattern);
}
this.rootPatternsToOrigin[pattern] = depType;
patterns.push(pattern);
deps.push({pattern, registry, hint, optional});
}
};
pushDeps('dependencies', {hint: null, optional: false}, true);
pushDeps('devDependencies', {hint: 'dev', optional: false}, !this.config.production);
pushDeps('optionalDependencies', {hint: 'optional', optional: true}, !this.flags.ignoreOptional);
break;
}
// inherit root flat flag
if (manifest.flat) {
this.flags.flat = true;
}
return {
requests: deps,
patterns,
manifest,
usedPatterns,
ignorePatterns,
};
}
/**
* TODO description
*/
prepareRequests(requests: DependencyRequestPatterns): DependencyRequestPatterns {
return requests;
}
preparePatterns(
patterns: Array<string>,
): Array<string> {
return patterns;
}
async bailout(
patterns: Array<string>,
): Promise<boolean> {
const match = await this.matchesIntegrityHash(patterns);
const haveLockfile = await fs.exists(path.join(this.config.cwd, constants.LOCKFILE_FILENAME));
if (this.flags.frozenLockfile && !this.lockFileInSync(patterns)) {
this.reporter.error(this.reporter.lang('frozenLockfileError'));
return true;
}
if (!this.flags.skipIntegrity && !this.flags.force && match.matches && haveLockfile) {
this.reporter.success(this.reporter.lang('upToDate'));
return true;
}
if (!patterns.length && !match.expected) {
this.reporter.success(this.reporter.lang('nothingToInstall'));
await this.createEmptyManifestFolders();
await this.saveLockfileAndIntegrity(patterns);
return true;
}
return false;
}
/**
* Produce empty folders for all used root manifests.
*/
async createEmptyManifestFolders(): Promise<void> {
if (this.config.modulesFolder) {
// already created
return;
}
for (const registryName of this.rootManifestRegistries) {
const {folder} = this.config.registries[registryName];
await fs.mkdirp(path.join(this.config.cwd, folder));
}
}
/**
* TODO description
*/
markIgnored(patterns: Array<string>) {
for (const pattern of patterns) {
const manifest = this.resolver.getStrictResolvedPattern(pattern);
const ref = manifest._reference;
invariant(ref, 'expected package reference');
if (ref.requests.length === 1) {
// this module was only depended on once by the root so we can safely ignore it
// if it was requested more than once then ignoring it would break a transitive
// dep that resolved to it
ref.ignore = true;
}
}
}
/**
* TODO description
*/
async init(): Promise<Array<string>> {
this.checkUpdate();
// warn if we have a shrinkwrap
if (await fs.exists(path.join(this.config.cwd, 'npm-shrinkwrap.json'))) {
this.reporter.warn(this.reporter.lang('shrinkwrapWarning'));
}
let patterns: Array<string> = [];
const steps: Array<(curr: number, total: number) => Promise<{bailout: boolean} | void>> = [];
const {
requests: depRequests,
patterns: rawPatterns,
ignorePatterns,
usedPatterns,
} = await this.fetchRequestFromCwd();
steps.push(async (curr: number, total: number) => {
this.reporter.step(curr, total, this.reporter.lang('resolvingPackages'), emoji.get('mag'));
await this.resolver.init(this.prepareRequests(depRequests), this.flags.flat);
patterns = await this.flatten(this.preparePatterns(rawPatterns));
return {bailout: await this.bailout(usedPatterns)};
});
steps.push(async (curr: number, total: number) => {
this.markIgnored(ignorePatterns);
this.reporter.step(curr, total, this.reporter.lang('fetchingPackages'), emoji.get('truck'));
await this.fetcher.init();
await this.compatibility.init();
});
steps.push(async (curr: number, total: number) => {
// remove integrity hash to make this operation atomic
const loc = await this.getIntegrityHashLocation();
await fs.unlink(loc);
this.reporter.step(curr, total, this.reporter.lang('linkingDependencies'), emoji.get('link'));
await this.linker.init(patterns);
});
steps.push(async (curr: number, total: number) => {
this.reporter.step(
curr,
total,
this.flags.force ? this.reporter.lang('rebuildingPackages') : this.reporter.lang('buildingFreshPackages'),
emoji.get('page_with_curl'),
);
if (this.flags.ignoreScripts) {
this.reporter.warn(this.reporter.lang('ignoredScripts'));
} else {
await this.scripts.init(patterns);
}
});
if (this.flags.har) {
steps.push(async (curr: number, total: number) => {
const formattedDate = new Date().toISOString().replace(/:/g, '-');
const filename = `yarn-install_${formattedDate}.har`;
this.reporter.step(
curr,
total,
this.reporter.lang('savingHar', filename),
emoji.get('black_circle_for_record'),
);
await this.config.requestManager.saveHar(filename);
});
}
if (await this.shouldClean()) {
steps.push(async (curr: number, total: number) => {
this.reporter.step(curr, total, this.reporter.lang('cleaningModules'), emoji.get('recycle'));
await clean(this.config, this.reporter);
});
}
let currentStep = 0;
for (const step of steps) {
const stepResult = await step(++currentStep, steps.length);
if (stepResult && stepResult.bailout) {
return patterns;
}
}
// fin!
await this.saveLockfileAndIntegrity(patterns);
this.maybeOutputUpdate();
this.config.requestManager.clearCache();
return patterns;
}
/**
* Check if we should run the cleaning step.
*/
shouldClean(): Promise<boolean> {
return fs.exists(path.join(this.config.cwd, constants.CLEAN_FILENAME));
}
/**
* TODO
*/
async flatten(patterns: Array<string>): Promise<Array<string>> {
if (!this.flags.flat) {
return patterns;
}
const flattenedPatterns = [];
for (const name of this.resolver.getAllDependencyNamesByLevelOrder(patterns)) {
const infos = this.resolver.getAllInfoForPackageName(name).filter((manifest: Manifest): boolean => {
const ref = manifest._reference;
invariant(ref, 'expected package reference');
return !ref.ignore;
});
if (infos.length === 0) {
continue;
}
if (infos.length === 1) {
// single version of this package
// take out a single pattern as multiple patterns may have resolved to this package
flattenedPatterns.push(this.resolver.patternsByPackage[name][0]);
continue;
}
const options = infos.map((info): ReporterSelectOption => {
const ref = info._reference;
invariant(ref, 'expected reference');
return {
// TODO `and is required by {PARENT}`,
name: this.reporter.lang('manualVersionResolutionOption', ref.patterns.join(', '), info.version),
value: info.version,
};
});
const versions = infos.map((info): string => info.version);
let version: ?string;
const resolutionVersion = this.resolutions[name];
if (resolutionVersion && versions.indexOf(resolutionVersion) >= 0) {
// use json `resolution` version
version = resolutionVersion;
} else {
version = await this.reporter.select(
this.reporter.lang('manualVersionResolution', name),
this.reporter.lang('answer'),
options,
);
this.resolutions[name] = version;
}
flattenedPatterns.push(this.resolver.collapseAllVersionsOfPackage(name, version));
}
// save resolutions to their appropriate root manifest
if (Object.keys(this.resolutions).length) {
const manifests = await this.config.getRootManifests();
for (const name in this.resolutions) {
const version = this.resolutions[name];
const patterns = this.resolver.patternsByPackage[name];
if (!patterns) {
continue;
}
let manifest;
for (const pattern of patterns) {
manifest = this.resolver.getResolvedPattern(pattern);
if (manifest) {
break;
}
}
invariant(manifest, 'expected manifest');
const ref = manifest._reference;
invariant(ref, 'expected reference');
const object = manifests[ref.registry].object;
object.resolutions = object.resolutions || {};
object.resolutions[name] = version;
}
await this.config.saveRootManifests(manifests);
}
return flattenedPatterns;
}
/**
* Check if the loaded lockfile has all the included patterns
*/
lockFileInSync(patterns: Array<string>): boolean {
let inSync = true;
for (const pattern of patterns) {
if (!this.lockfile.getLocked(pattern)) {
inSync = false;
break;
}
}
return inSync;
}
/**
* Save updated integrity and lockfiles.
*/
async saveLockfileAndIntegrity(patterns: Array<string>): Promise<void> {
// stringify current lockfile
const lockSource = lockStringify(this.lockfile.getLockfile(this.resolver.patterns));
// write integrity hash
await this.writeIntegrityHash(lockSource, patterns);
// --no-lockfile or --pure-lockfile flag
if (this.flags.lockfile === false || this.flags.pureLockfile) {
return;
}
const inSync = this.lockFileInSync(patterns);
// remove is followed by install with force on which we rewrite lockfile
if (inSync && patterns.length && !this.flags.force) {
return;
}
// build lockfile location
const loc = path.join(this.config.cwd, constants.LOCKFILE_FILENAME);
// write lockfile
await fs.writeFilePreservingEol(loc, lockSource);
this._logSuccessSaveLockfile();
}
_logSuccessSaveLockfile() {
this.reporter.success(this.reporter.lang('savedLockfile'));
}
/**
* Check if the integrity hash of this installation matches one on disk.
*/
async matchesIntegrityHash(patterns: Array<string>): Promise<IntegrityMatch> {
const loc = await this.getIntegrityHashLocation();
if (!await fs.exists(loc)) {
return {
actual: '',
expected: '',
loc,
matches: false,
};
}
const lockSource = lockStringify(this.lockfile.getLockfile(this.resolver.patterns));
const actual = this.generateIntegrityHash(lockSource, patterns);
const expected = (await fs.readFile(loc)).trim();
return {
actual,
expected,
loc,
matches: actual === expected,
};
}
/**
* Get the location of an existing integrity hash. If none exists then return the location where we should
* write a new one.
*/
async getIntegrityHashLocation(): Promise<string> {
// build up possible folders
const possibleFolders = [];
if (this.config.modulesFolder) {
possibleFolders.push(this.config.modulesFolder);
}
// get a list of registry names to check existence in
let checkRegistryNames = this.resolver.usedRegistries;
if (!checkRegistryNames.length) {
// we haven't used any registries yet
checkRegistryNames = registryNames;
}
// ensure we only write to a registry folder that was used
for (const name of checkRegistryNames) {
const loc = path.join(this.config.cwd, this.config.registries[name].folder);
possibleFolders.push(loc);
}
// if we already have an integrity hash in one of these folders then use it's location otherwise use the
// first folder
const possibles = possibleFolders.map((folder): string => path.join(folder, constants.INTEGRITY_FILENAME));
let loc = possibles[0];
for (const possibleLoc of possibles) {
if (await fs.exists(possibleLoc)) {
loc = possibleLoc;
break;
}
}
return loc;
}
/**
* Write the integrity hash of the current install to disk.
*/
async writeIntegrityHash(lockSource: string, patterns: Array<string>): Promise<void> {
const loc = await this.getIntegrityHashLocation();
invariant(loc, 'expected integrity hash location');
await fs.mkdirp(path.dirname(loc));
await fs.writeFile(loc, this.generateIntegrityHash(lockSource, patterns));
}
/**
* Generate integrity hash of input lockfile.
*/
generateIntegrityHash(lockfile: string, patterns: Array<string>): string {
const opts = [lockfile];
opts.push(`patterns:${patterns.sort(sortAlpha).join(',')}`);
if (this.flags.flat) {
opts.push('flat');
}
if (this.config.production) {
opts.push('production');
}
const linkedModules = this.config.linkedModules;
if (linkedModules.length) {
opts.push(`linked:${linkedModules.join(',')}`);
}
const mirror = this.config.getOfflineMirrorPath();
if (mirror != null) {
opts.push(`mirror:${mirror}`);
}
return crypto.hash(opts.join('-'), 'sha256');
}
/**
* Load the dependency graph of the current install. Only does package resolving and wont write to the cwd.
*/
async hydrate(fetch?: boolean): Promise<InstallCwdRequest> {
const request = await this.fetchRequestFromCwd();
const {requests: depRequests, patterns: rawPatterns, ignorePatterns} = request;
await this.resolver.init(depRequests, this.flags.flat);
await this.flatten(rawPatterns);
this.markIgnored(ignorePatterns);
if (fetch) {
// fetch packages, should hit cache most of the time
await this.fetcher.init();
await this.compatibility.init();
// expand minimal manifests
for (const manifest of this.resolver.getManifests()) {
const ref = manifest._reference;
invariant(ref, 'expected reference');
const loc = this.config.generateHardModulePath(ref);
const newPkg = await this.config.readManifest(loc);
await this.resolver.updateManifest(ref, newPkg);
}
}
return request;
}
/**
* Check for updates every day and output a nag message if there's a newer version.
*/
checkUpdate() {
if (!process.stdout.isTTY || isCI) {
// don't show upgrade dialog on CI or non-TTY terminals
return;
}
// only check for updates once a day
const lastUpdateCheck = Number(this.config.getOption('lastUpdateCheck')) || 0;
if (lastUpdateCheck && Date.now() - lastUpdateCheck < ONE_DAY) {
return;
}
// don't bug for updates on tagged releases
if (YARN_VERSION.indexOf('-') >= 0) {
return;
}
this._checkUpdate().catch(() => {
// swallow errors
});
}
async _checkUpdate(): Promise<void> {
let latestVersion = await this.config.requestManager.request({
url: 'https://yarnpkg.com/latest-version',
});
invariant(typeof latestVersion === 'string', 'expected string');
latestVersion = latestVersion.trim();
if (!semver.valid(latestVersion)) {
return;
}
// ensure we only check for updates periodically
this.config.registries.yarn.saveHomeConfig({
lastUpdateCheck: Date.now(),
});
if (semver.gt(latestVersion, YARN_VERSION)) {
this.maybeOutputUpdate = () => {
this.reporter.warn(this.reporter.lang('yarnOutdated', latestVersion, YARN_VERSION));
const command = getUpdateCommand();
if (command) {
this.reporter.info(this.reporter.lang('yarnOutdatedCommand'));
this.reporter.command(command);
} else {
const installer = getUpdateInstaller();
if (installer) {
this.reporter.info(this.reporter.lang('yarnOutdatedInstaller', installer));
}
}
};
}
}
/**
* Method to override with a possible upgrade message.
*/
maybeOutputUpdate() {}
maybeOutputUpdate: any;
}
export function setFlags(commander: Object) {
commander.usage('install [flags]');
commander.option('-g, --global', 'DEPRECATED');
commander.option('-S, --save', 'DEPRECATED - save package to your `dependencies`');
commander.option('-D, --save-dev', 'DEPRECATED - save package to your `devDependencies`');
commander.option('-P, --save-peer', 'DEPRECATED - save package to your `peerDependencies`');
commander.option('-O, --save-optional', 'DEPRECATED - save package to your `optionalDependencies`');
commander.option('-E, --save-exact', 'DEPRECATED');
commander.option('-T, --save-tilde', 'DEPRECATED');
}
export async function run(
config: Config,
reporter: Reporter,
flags: Object,
args: Array<string>,
): Promise<void> {
let lockfile;
if (flags.lockfile === false) {
lockfile = new Lockfile();
} else {
lockfile = await Lockfile.fromDirectory(config.cwd, reporter);
}
if (args.length) {
const exampleArgs = args.slice();
if (flags.saveDev) {
exampleArgs.push('--dev');
}
if (flags.savePeer) {
exampleArgs.push('--peer');
}
if (flags.saveOptional) {
exampleArgs.push('--optional');
}
if (flags.saveExact) {
exampleArgs.push('--exact');
}
if (flags.saveTilde) {
exampleArgs.push('--tilde');
}
let command = 'add';
if (flags.global) {
command = 'global add';
}
throw new MessageError(reporter.lang('installCommandRenamed', `yarn ${command} ${exampleArgs.join(' ')}`));
}
await wrapLifecycle(config, flags, async () => {
const install = new Install(flags, config, reporter, lockfile);
await install.init();
});
}
export async function wrapLifecycle(config: Config, flags: Object, factory: () => Promise<void>): Promise<void> {
await config.executeLifecycleScript('preinstall');
await factory();
// npm behaviour, seems kinda funky but yay compatibility
await config.executeLifecycleScript('install');
await config.executeLifecycleScript('postinstall');
if (!config.production) {
await config.executeLifecycleScript('prepublish');
}
}