-
-
Notifications
You must be signed in to change notification settings - Fork 6.3k
/
Copy pathProjectPackageManager.js
360 lines (307 loc) · 10.6 KB
/
ProjectPackageManager.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
const fs = require('fs-extra')
const path = require('path')
const ini = require('ini')
const minimist = require('minimist')
const LRU = require('lru-cache')
const {
chalk,
execa,
semver,
request,
resolvePkg,
loadModule,
hasYarn,
hasProjectYarn,
hasPnpm3OrLater,
hasPnpmVersionOrLater,
hasProjectPnpm,
hasProjectNpm,
isOfficialPlugin,
resolvePluginId,
log,
warn,
error
} = require('@vue/cli-shared-utils')
const { loadOptions } = require('../options')
const { executeCommand } = require('./executeCommand')
const registries = require('./registries')
const shouldUseTaobao = require('./shouldUseTaobao')
const metadataCache = new LRU({
max: 200,
maxAge: 1000 * 60 * 30 // 30 min.
})
const isTestOrDebug = process.env.VUE_CLI_TEST || process.env.VUE_CLI_DEBUG
const SUPPORTED_PACKAGE_MANAGERS = ['yarn', 'pnpm', 'npm']
const PACKAGE_MANAGER_PNPM4_CONFIG = {
install: ['install', '--reporter', 'silent', '--shamefully-hoist'],
add: ['install', '--reporter', 'silent', '--shamefully-hoist'],
upgrade: ['update', '--reporter', 'silent'],
remove: ['uninstall', '--reporter', 'silent']
}
const PACKAGE_MANAGER_PNPM3_CONFIG = {
install: ['install', '--loglevel', 'error', '--shamefully-flatten'],
add: ['install', '--loglevel', 'error', '--shamefully-flatten'],
upgrade: ['update', '--loglevel', 'error'],
remove: ['uninstall', '--loglevel', 'error']
}
const PACKAGE_MANAGER_CONFIG = {
npm: {
install: ['install', '--loglevel', 'error'],
add: ['install', '--loglevel', 'error'],
upgrade: ['update', '--loglevel', 'error'],
remove: ['uninstall', '--loglevel', 'error']
},
pnpm: hasPnpmVersionOrLater('4.0.0') ? PACKAGE_MANAGER_PNPM4_CONFIG : PACKAGE_MANAGER_PNPM3_CONFIG,
yarn: {
install: [],
add: ['add'],
upgrade: ['upgrade'],
remove: ['remove']
}
}
// extract the package name 'xx' from the format 'xx@1.1'
function stripVersion (packageName) {
const nameRegExp = /^(@?[^@]+)(@.*)?$/
const result = packageName.match(nameRegExp)
if (!result) {
throw new Error(`Invalid package name ${packageName}`)
}
return result[1]
}
class PackageManager {
constructor ({ context, forcePackageManager } = {}) {
this.context = context || process.cwd()
if (forcePackageManager) {
this.bin = forcePackageManager
} else if (context) {
if (hasProjectYarn(context)) {
this.bin = 'yarn'
} else if (hasProjectPnpm(context)) {
this.bin = 'pnpm'
} else if (hasProjectNpm(context)) {
this.bin = 'npm'
}
}
// if no package managers specified, and no lockfile exists
if (!this.bin) {
this.bin = loadOptions().packageManager || (hasYarn() ? 'yarn' : hasPnpm3OrLater() ? 'pnpm' : 'npm')
}
if (!SUPPORTED_PACKAGE_MANAGERS.includes(this.bin)) {
log()
warn(
`The package manager ${chalk.red(this.bin)} is ${chalk.red('not officially supported')}.\n` +
`It will be treated like ${chalk.cyan('npm')}, but compatibility issues may occur.\n` +
`See if you can use ${chalk.cyan('--registry')} instead.`
)
PACKAGE_MANAGER_CONFIG[this.bin] = PACKAGE_MANAGER_CONFIG.npm
}
// Plugin may be located in another location if `resolveFrom` presents.
const projectPkg = resolvePkg(this.context)
const resolveFrom = projectPkg && projectPkg.vuePlugins && projectPkg.vuePlugins.resolveFrom
// Logically, `resolveFrom` and `context` are distinct fields.
// But in Vue CLI we only care about plugins.
// So it is fine to let all other operations take place in the `resolveFrom` directory.
if (resolveFrom) {
this.context = path.resolve(context, resolveFrom)
}
}
// Any command that implemented registry-related feature should support
// `-r` / `--registry` option
async getRegistry () {
if (this._registry) {
return this._registry
}
const args = minimist(process.argv, {
alias: {
r: 'registry'
}
})
if (args.registry) {
this._registry = args.registry
} else if (!process.env.VUE_CLI_TEST && await shouldUseTaobao(this.bin)) {
this._registry = registries.taobao
} else {
try {
this._registry = (await execa(this.bin, ['config', 'get', 'registry'])).stdout
} catch (e) {
// Yarn 2 uses `npmRegistryServer` instead of `registry`
this._registry = (await execa(this.bin, ['config', 'get', 'npmRegistryServer'])).stdout
}
}
return this._registry
}
async getAuthToken () {
// get npmrc (https://docs.npmjs.com/configuring-npm/npmrc.html#files)
const possibleRcPaths = [
path.resolve(this.context, '.npmrc'),
path.resolve(require('os').homedir(), '.npmrc')
]
if (process.env.PREFIX) {
possibleRcPaths.push(path.resolve(process.env.PREFIX, '/etc/npmrc'))
}
// there's also a '/path/to/npm/npmrc', skipped for simplicity of implementation
let npmConfig = {}
for (const loc of possibleRcPaths) {
if (fs.existsSync(loc)) {
try {
// the closer config file (the one with lower index) takes higher precedence
npmConfig = Object.assign({}, ini.parse(fs.readFileSync(loc, 'utf-8')), npmConfig)
} catch (e) {
// in case of file permission issues, etc.
}
}
}
const registry = await this.getRegistry()
const registryWithoutProtocol = registry
.replace(/https?:/, '') // remove leading protocol
.replace(/([^/])$/, '$1/') // ensure ending with slash
const authTokenKey = `${registryWithoutProtocol}:_authToken`
return npmConfig[authTokenKey]
}
async setRegistryEnvs () {
const registry = await this.getRegistry()
process.env.npm_config_registry = registry
process.env.YARN_NPM_REGISTRY_SERVER = registry
this.setBinaryMirrors()
}
// set mirror urls for users in china
async setBinaryMirrors () {
const registry = await this.getRegistry()
if (registry !== registries.taobao) {
return
}
try {
// node-sass, chromedriver, etc.
const binaryMirrorConfig = await this.getMetadata('binary-mirror-config')
const mirrors = binaryMirrorConfig.mirrors.china
for (const key in mirrors.ENVS) {
process.env[key] = mirrors.ENVS[key]
}
// Cypress
const cypressMirror = mirrors.cypress
const defaultPlatforms = {
darwin: 'osx64',
linux: 'linux64',
win32: 'win64'
}
const platforms = cypressMirror.newPlatforms || defaultPlatforms
const targetPlatform = platforms[require('os').platform()]
// Do not override user-defined env variable
// Because we may construct a wrong download url and an escape hatch is necessary
if (targetPlatform && !process.env.CYPRESS_INSTALL_BINARY) {
// We only support cypress 3 for the current major version
const latestCypressVersion = await this.getRemoteVersion('cypress', '^3')
process.env.CYPRESS_INSTALL_BINARY =
`${cypressMirror.host}/${latestCypressVersion}/${targetPlatform}/cypress.zip`
}
} catch (e) {
// get binary mirror config failed
}
}
// https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md
async getMetadata (packageName, { full = false } = {}) {
const registry = await this.getRegistry()
const authToken = await this.getAuthToken()
const metadataKey = `${this.bin}-${registry}-${packageName}`
let metadata = metadataCache.get(metadataKey)
if (metadata) {
return metadata
}
const headers = {}
if (!full) {
headers.Accept = 'application/vnd.npm.install-v1+json;q=1.0, application/json;q=0.9, */*;q=0.8'
}
if (authToken) {
headers.Authorization = `Bearer ${authToken}`
}
const url = `${registry.replace(/\/$/g, '')}/${packageName}`
try {
metadata = (await request.get(url, { headers })).body
if (metadata.error) {
throw new Error(metadata.error)
}
metadataCache.set(metadataKey, metadata)
return metadata
} catch (e) {
error(`Failed to get response from ${url}`)
throw e
}
}
async getRemoteVersion (packageName, versionRange = 'latest') {
const metadata = await this.getMetadata(packageName)
if (Object.keys(metadata['dist-tags']).includes(versionRange)) {
return metadata['dist-tags'][versionRange]
}
const versions = Array.isArray(metadata.versions) ? metadata.versions : Object.keys(metadata.versions)
return semver.maxSatisfying(versions, versionRange)
}
getInstalledVersion (packageName) {
// for first level deps, read package.json directly is way faster than `npm list`
try {
const packageJson = loadModule(`${packageName}/package.json`, this.context, true)
return packageJson.version
} catch (e) {}
}
async runCommand (command, args) {
await this.setRegistryEnvs()
return await executeCommand(
this.bin,
[
...PACKAGE_MANAGER_CONFIG[this.bin][command],
...(args || [])
],
this.context
)
}
async install () {
if (process.env.VUE_CLI_TEST) {
try {
process.env.PUPPETEER_SKIP_CHROMIUM_DOWNLOAD = true
await this.runCommand('install', ['--offline', '--silent', '--no-progress'])
delete process.env.PUPPETEER_SKIP_CHROMIUM_DOWNLOAD
} catch (e) {
delete process.env.PUPPETEER_SKIP_CHROMIUM_DOWNLOAD
await this.runCommand('install', ['--silent', '--no-progress'])
}
}
return await this.runCommand('install')
}
async add (packageName, {
tilde = false,
dev = true
} = {}) {
const args = dev ? ['-D'] : []
if (tilde) {
if (this.bin === 'yarn') {
args.push('--tilde')
} else {
process.env.npm_config_save_prefix = '~'
}
}
return await this.runCommand('add', [packageName, ...args])
}
async remove (packageName) {
return await this.runCommand('remove', [packageName])
}
async upgrade (packageName) {
// manage multiple packages separated by spaces
const packageNamesArray = []
for (const packname of packageName.split(' ')) {
const realname = stripVersion(packname)
if (
isTestOrDebug &&
(packname === '@vue/cli-service' || isOfficialPlugin(resolvePluginId(realname)))
) {
// link packages in current repo for test
const src = path.resolve(__dirname, `../../../../${realname}`)
const dest = path.join(this.context, 'node_modules', realname)
await fs.remove(dest)
await fs.symlink(src, dest, 'dir')
} else {
packageNamesArray.push(packname)
}
}
if (packageNamesArray.length) return await this.runCommand('add', packageNamesArray)
}
}
module.exports = PackageManager