This repository has been archived by the owner on Feb 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 63
/
installPackages.js
118 lines (103 loc) · 2.73 KB
/
installPackages.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
const spawn = require('cross-spawn')
const logUpdate = require('log-update')
const spinner = require('./spinner')
const logger = require('./logger')
const SAOError = require('./SAOError')
let cachedNpmClient = null
function setNpmClient(npmClient) {
cachedNpmClient = npmClient
}
function getNpmClient() {
if (cachedNpmClient) {
return cachedNpmClient
}
if (spawn.sync('yarn', ['--version']).status === 0) {
cachedNpmClient = 'yarn'
} else {
cachedNpmClient = 'npm'
}
return cachedNpmClient
}
module.exports = async ({
cwd,
npmClient,
installArgs,
packages,
saveDev,
registry
}) => {
npmClient = npmClient || getNpmClient()
const packageName = packages ? packages.join(', ') : 'packages'
return new Promise((resolve, reject) => {
// `npm/pnpm/yarn add <packages>`
// `npm/pnpm/yarn install`
const args = [packages ? 'add' : 'install'].concat(packages ? packages : [])
if (saveDev) {
args.push(npmClient === 'npm' ? '-D' : '--dev')
}
if (registry) {
args.push('--registry', registry)
}
if (installArgs) {
args.push(...installArgs)
}
logger.debug(npmClient, args.join(' '))
logger.debug('install directory', cwd)
spinner.start(`Installing ${packageName} with ${npmClient}`)
const ps = spawn(npmClient, args, {
stdio: [0, 'pipe', 'pipe'],
cwd,
env: Object.assign(
{
FORCE_COLOR: true,
/* eslint-disable camelcase */
npm_config_color: 'always',
npm_config_progress: true
/* eslint-enable camelcase */
},
process.env
)
})
let stdoutLogs = ''
let stderrLogs = ''
ps.stdout &&
ps.stdout.setEncoding('utf8').on('data', data => {
if (npmClient === 'pnpm') {
stdoutLogs = data
} else {
stdoutLogs += data
}
spinner.stop()
logUpdate(stdoutLogs)
spinner.start()
})
ps.stderr &&
ps.stderr.setEncoding('utf8').on('data', data => {
if (npmClient === 'pnpm') {
stderrLogs = data
} else {
stderrLogs += data
}
spinner.stop()
logUpdate.clear()
logUpdate.stderr(stderrLogs)
logUpdate(stdoutLogs)
spinner.start()
})
ps.on('close', code => {
spinner.stop()
// Clear output when succeeded
if (code === 0) {
logUpdate.clear()
logUpdate.stderr.clear()
logger.success(`Installed ${packageName}`)
} else {
throw new SAOError(`Failed to install ${packageName} in ${cwd}`)
}
resolve({ code, npmClient })
})
ps.on('error', reject)
})
}
module.exports.getNpmClient = getNpmClient
module.exports.setNpmClient = setNpmClient