-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
deps.js
260 lines (222 loc) · 7.13 KB
/
deps.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
/**
* @typedef PackageVersionsInfo
* @prop {string?} current Current installed version
* @prop {string?} wanted Wanted version depending on version range in package.json
* @prop {string?} latest Latest version from registry (with 'latest' tag)
*/
const { default: chalk } = require('chalk')
const execa = require('execa')
const readline = require('readline')
const registries = require('./registries')
const shouldUseTaobao = require('./shouldUseTaobao')
const { request } = require('./request')
const { resolveModule } = require('@nodepack/module')
const semver = require('semver')
const path = require('path')
const fs = require('fs-extra')
const { warn, error } = require('./logger')
const LRU = require('lru-cache')
const TAOBAO_DIST_URL = 'https://npm.taobao.org/dist'
const metadataCache = new LRU({
max: 200,
maxAge: 3 * 60 * 1000,
})
function toStartOfLine (stream) {
if (!chalk.supportsColor) {
stream.write('\r')
return
}
readline.cursorTo(stream, 0)
}
function renderProgressBar (curr, total) {
const ratio = Math.min(Math.max(curr / total, 0), 1)
const bar = ` ${curr}/${total}`
const availableSpace = Math.max(0, (process.stderr.columns || 100) - bar.length - 3)
const width = Math.min(total, availableSpace)
const completeLength = Math.round(width * ratio)
const complete = `#`.repeat(completeLength)
const incomplete = `-`.repeat(width - completeLength)
toStartOfLine(process.stderr)
process.stderr.write(`[${complete}${incomplete}]${bar}`)
}
async function addRegistryToArgs (command, args, cliRegistry) {
const altRegistry = (
cliRegistry || (
(await shouldUseTaobao(command))
? registries.taobao
: null
)
)
if (altRegistry) {
args.push(`--registry=${altRegistry}`)
if (altRegistry === registries.taobao) {
args.push(`--disturl=${TAOBAO_DIST_URL}`)
}
}
}
function executeCommand (command, args, targetDir) {
return new Promise((resolve, reject) => {
const apiMode = process.env.VUE_CLI_API_MODE
if (apiMode) {
if (command === 'npm') {
// TODO when this is supported
} else if (command === 'yarn') {
args.push('--json')
}
}
const child = execa(command, args, {
cwd: targetDir,
stdio: ['inherit', apiMode ? 'pipe' : 'inherit', !apiMode && command === 'yarn' ? 'pipe' : 'inherit'],
})
// filter out unwanted yarn output
if (command === 'yarn') {
child.stderr.on('data', buf => {
const str = buf.toString()
if (/warning/.test(str)) {
return
}
// progress bar
const progressBarMatch = str.match(/\[.*\] (\d+)\/(\d+)/)
if (progressBarMatch) {
// since yarn is in a child process, it's unable to get the width of
// the terminal. reimplement the progress bar ourselves!
renderProgressBar(progressBarMatch[1], progressBarMatch[2])
return
}
process.stderr.write(buf)
})
}
child.on('close', code => {
if (code !== 0) {
reject(`command failed: ${command} ${args.join(' ')}`)
return
}
resolve()
})
})
}
exports.installDeps = async function installDeps (targetDir, command, cliRegistry) {
const args = []
if (command === 'npm') {
args.push('install', '--loglevel', 'error')
} else if (command === 'yarn') {
// do nothing
} else {
throw new Error(`Unknown package manager: ${command}`)
}
await addRegistryToArgs(command, args, cliRegistry)
await executeCommand(command, args, targetDir)
}
exports.installPackage = async function (targetDir, command, cliRegistry, packageName, dev = true) {
const args = []
if (command === 'npm') {
args.push('install', '--loglevel', 'error')
} else if (command === 'yarn') {
args.push('add')
} else {
throw new Error(`Unknown package manager: ${command}`)
}
if (dev) args.push('-D')
await addRegistryToArgs(command, args, cliRegistry)
args.push(packageName)
await executeCommand(command, args, targetDir)
}
exports.uninstallPackage = async function (targetDir, command, cliRegistry, packageName) {
const args = []
if (command === 'npm') {
args.push('uninstall', '--loglevel', 'error')
} else if (command === 'yarn') {
args.push('remove')
} else {
throw new Error(`Unknown package manager: ${command}`)
}
await addRegistryToArgs(command, args, cliRegistry)
args.push(packageName)
await executeCommand(command, args, targetDir)
}
exports.updatePackage = async function (targetDir, command, cliRegistry, packageName) {
const args = []
if (command === 'npm') {
args.push('update', '--loglevel', 'error')
} else if (command === 'yarn') {
args.push('upgrade')
} else {
throw new Error(`Unknown package manager: ${command}`)
}
await addRegistryToArgs(command, args, cliRegistry)
packageName.split(' ').forEach(name => args.push(name))
await executeCommand(command, args, targetDir)
}
exports.getPackageMetadata = async function (id, range = '') {
const cacheId = `${id}@${range}`
const cached = metadataCache.get(cacheId)
if (cached) return cached
const registry = (await shouldUseTaobao())
? `https://registry.npm.taobao.org`
: `https://registry.npmjs.org`
let result
try {
result = (await request.get(`${registry}/${encodeURIComponent(id).replace(/^%40/, '@')}/${range}`)).body
if (result) metadataCache.set(cacheId, result)
} catch (e) {
warn(`Couldn't get medata for ${cacheId}: ${e.message}`)
return null
}
return result
}
/**
* @param {string} id Package id
* @param {string} tag Release tag
* @returns {Promise.<string?>}
*/
exports.getPackageTaggedVersion = async function (id, tag = 'latest') {
try {
const res = await exports.getPackageMetadata(id)
if (res) res['dist-tags'][tag]
} catch (e) {
error(e)
}
return null
}
/**
* @param {string} cwd Current working directory
* @param {string} id Package id
* @param {string} versionRange Wanted version range (ex: from package.json)
* @returns {Promise.<PackageVersionsInfo>}
*/
exports.getPackageVersionsInfo = async function (cwd, id, versionRange) {
/** @type {PackageVersionsInfo} */
const result = {
current: null,
latest: null,
wanted: null,
}
const pkgFile = path.resolve(exports.getPackageRoot(cwd, id), 'package.json')
if (fs.existsSync(pkgFile)) {
result.current = (await fs.readJson(pkgFile)).version
}
const metadata = await exports.getPackageMetadata(id)
if (metadata) {
result.latest = metadata['dist-tags'].latest
const wantedTagVersion = metadata['dist-tags'][versionRange]
if (wantedTagVersion) {
result.wanted = wantedTagVersion
} else {
const versions = Array.isArray(metadata.versions) ? metadata.versions : Object.keys(metadata.versions)
result.wanted = semver.maxSatisfying(versions, versionRange)
}
}
return result
}
/**
* @param {string} cwd Current working directory
* @param {string} id Package id
* @returns {string}
*/
exports.getPackageRoot = function (cwd, id) {
const filePath = resolveModule(path.join(id, 'package.json'), cwd)
if (!filePath) {
return path.join(cwd, `node_modules`, id)
}
return path.dirname(filePath)
}