-
-
Notifications
You must be signed in to change notification settings - Fork 6.3k
/
Copy pathProjectPackageManager.js
263 lines (226 loc) · 8.02 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
const fs = require('fs-extra')
const path = require('path')
const execa = require('execa')
const minimist = require('minimist')
const semver = require('semver')
const LRU = require('lru-cache')
const chalk = require('chalk')
const {
hasYarn,
hasProjectYarn,
hasPnpm3OrLater,
hasPnpmVersionOrLater,
hasProjectPnpm
} = require('@vue/cli-shared-utils/lib/env')
const { isOfficialPlugin, resolvePluginId } = require('@vue/cli-shared-utils/lib/pluginResolution')
const { log, warn } = require('@vue/cli-shared-utils/lib/logger')
const { loadOptions } = require('../options')
const getPackageJson = require('./getPackageJson')
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 '[email protected]'
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
if (forcePackageManager) {
this.bin = forcePackageManager
} else if (context) {
this.bin = hasProjectYarn(context) ? 'yarn' : hasProjectPnpm(context) ? 'pnpm' : 'npm'
} else {
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
}
}
// 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 (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 addRegistryToArgs (args) {
const registry = await this.getRegistry()
args.push(`--registry=${registry}`)
return args
}
// 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
}
}
async getMetadata (packageName, { field = '' } = {}) {
const registry = await this.getRegistry()
const metadataKey = `${this.bin}-${registry}-${packageName}`
let metadata = metadataCache.get(metadataKey)
if (metadata) {
return metadata
}
const args = await this.addRegistryToArgs(['info', packageName, field, '--json'])
const { stdout } = await execa(this.bin, args)
metadata = JSON.parse(stdout)
if (this.bin === 'yarn') {
// `yarn info` outputs messages in the form of `{"type": "inspect", data: {}}`
metadata = metadata.data
}
metadataCache.set(metadataKey, metadata)
return metadata
}
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 = getPackageJson(
path.resolve(this.context, 'node_modules', packageName)
)
return packageJson.version
} catch (e) {
return 'N/A'
}
}
async install () {
await this.setBinaryMirrors()
const args = await this.addRegistryToArgs(PACKAGE_MANAGER_CONFIG[this.bin].install)
return executeCommand(this.bin, args, this.context)
}
async add (packageName, isDev = true) {
await this.setBinaryMirrors()
const args = await this.addRegistryToArgs([
...PACKAGE_MANAGER_CONFIG[this.bin].add,
packageName,
...(isDev ? ['-D'] : [])
])
return executeCommand(this.bin, args, this.context)
}
async upgrade (packageName) {
const realname = stripVersion(packageName)
if (
isTestOrDebug &&
(packageName === '@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')
return
}
await this.setBinaryMirrors()
const args = await this.addRegistryToArgs([
...PACKAGE_MANAGER_CONFIG[this.bin].add,
packageName
])
return executeCommand(this.bin, args, this.context)
}
async remove (packageName) {
const args = [
...PACKAGE_MANAGER_CONFIG[this.bin].remove,
packageName
]
return executeCommand(this.bin, args, this.context)
}
}
module.exports = PackageManager