1 | const fs = require('fs');
|
2 | const path = require('path');
|
3 | const crossSpawn = require('cross-spawn');
|
4 | const pkgDir = require('pkg-dir');
|
5 |
|
6 | let cachedHasYarn;
|
7 | let cachedHasNPM;
|
8 | let cachedClient;
|
9 |
|
10 | function clearCache() {
|
11 | cachedHasYarn = undefined;
|
12 | cachedHasNPM = undefined;
|
13 | cachedClient = undefined;
|
14 | }
|
15 |
|
16 | function hasYarn() {
|
17 | if (cachedHasYarn !== undefined) return cachedHasYarn;
|
18 |
|
19 | try {
|
20 | const cmd = crossSpawn.sync('yarn', ['--version']);
|
21 | const version = cmd.stdout && cmd.stdout.toString().trim();
|
22 | cachedHasYarn = !!version;
|
23 | } catch (e) {
|
24 | cachedHasYarn = false;
|
25 | }
|
26 |
|
27 | return cachedHasYarn;
|
28 | }
|
29 |
|
30 | function hasNpm() {
|
31 | if (cachedHasNPM !== undefined) return cachedHasNPM;
|
32 |
|
33 | try {
|
34 | const cmd = crossSpawn.sync('npm', ['--version']);
|
35 | const version = cmd.stdout && cmd.stdout.toString().trim();
|
36 | cachedHasNPM = !!version;
|
37 | } catch (e) {
|
38 | cachedHasNPM = false;
|
39 | }
|
40 |
|
41 | return cachedHasNPM;
|
42 | }
|
43 |
|
44 | function yarnOrNpm() {
|
45 | if (cachedClient !== undefined) return cachedClient;
|
46 |
|
47 | const pkgRoot = pkgDir.sync();
|
48 |
|
49 | if (pkgRoot) {
|
50 | const pkgLockPath = path.join(pkgRoot, 'package-lock.json');
|
51 | const yarnLockPath = path.join(pkgRoot, 'yarn.lock');
|
52 |
|
53 | try {
|
54 | fs.statSync(yarnLockPath);
|
55 | cachedClient = 'yarn';
|
56 | return cachedClient;
|
57 | } catch (e) {}
|
58 |
|
59 | try {
|
60 | fs.statSync(pkgLockPath);
|
61 | cachedClient = 'npm';
|
62 | return cachedClient;
|
63 | } catch (e) {}
|
64 | }
|
65 |
|
66 | return hasYarn() ? 'yarn' : 'npm';
|
67 | }
|
68 |
|
69 | function spawn(...args) {
|
70 | args.unshift(yarnOrNpm());
|
71 | return crossSpawn(...args);
|
72 | }
|
73 |
|
74 | function spawnSync(...args) {
|
75 | args.unshift(yarnOrNpm());
|
76 | return crossSpawn.sync(...args);
|
77 | }
|
78 |
|
79 | yarnOrNpm.hasYarn = hasYarn;
|
80 | yarnOrNpm.hasNpm = hasNpm;
|
81 | yarnOrNpm.spawn = spawn;
|
82 | yarnOrNpm.spawn.sync = spawnSync;
|
83 | yarnOrNpm.clearCache = clearCache;
|
84 |
|
85 | module.exports = yarnOrNpm;
|