-
-
Notifications
You must be signed in to change notification settings - Fork 941
/
index.ts
346 lines (329 loc) · 10.9 KB
/
index.ts
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
import {
docsUrl,
readDepNameCompletions,
readProjectManifestOnly,
} from '@pnpm/cli-utils'
import { type CompletionFunc } from '@pnpm/command'
import { FILTERING, OPTIONS, UNIVERSAL_OPTIONS } from '@pnpm/common-cli-options-help'
import { types as allTypes } from '@pnpm/config'
import { globalInfo } from '@pnpm/logger'
import { createMatcher } from '@pnpm/matcher'
import { outdatedDepsOfProjects } from '@pnpm/outdated'
import { PnpmError } from '@pnpm/error'
import { prompt } from 'enquirer'
import chalk from 'chalk'
import pick from 'ramda/src/pick'
import pluck from 'ramda/src/pluck'
import unnest from 'ramda/src/unnest'
import renderHelp from 'render-help'
import { type InstallCommandOptions } from '../install'
import { installDeps } from '../installDeps'
import { type ChoiceRow, getUpdateChoices } from './getUpdateChoices'
import { parseUpdateParam } from '../recursive'
export function rcOptionsTypes () {
return pick([
'cache-dir',
'depth',
'dev',
'engine-strict',
'fetch-retries',
'fetch-retry-factor',
'fetch-retry-maxtimeout',
'fetch-retry-mintimeout',
'fetch-timeout',
'force',
'global-dir',
'global-pnpmfile',
'global',
'https-proxy',
'ignore-pnpmfile',
'ignore-scripts',
'lockfile-dir',
'lockfile-directory',
'lockfile-only',
'lockfile',
'lockfile-include-tarball-url',
'network-concurrency',
'noproxy',
'npmPath',
'offline',
'only',
'optional',
'package-import-method',
'pnpmfile',
'prefer-offline',
'production',
'proxy',
'registry',
'reporter',
'save',
'save-exact',
'save-prefix',
'save-workspace-protocol',
'scripts-prepend-node-path',
'shamefully-flatten',
'shamefully-hoist',
'shared-workspace-lockfile',
'side-effects-cache-readonly',
'side-effects-cache',
'store',
'store-dir',
'unsafe-perm',
'use-running-store-server',
], allTypes)
}
export function cliOptionsTypes () {
return {
...rcOptionsTypes(),
interactive: Boolean,
latest: Boolean,
recursive: Boolean,
workspace: Boolean,
}
}
export const shorthands = {
D: '--dev',
P: '--production',
}
export const commandNames = ['update', 'up', 'upgrade']
export const completion: CompletionFunc = async (cliOpts) => {
return readDepNameCompletions(cliOpts.dir as string)
}
export function help () {
return renderHelp({
aliases: ['up', 'upgrade'],
description: 'Updates packages to their latest version based on the specified range. You can use "*" in package name to update all packages with the same pattern.',
descriptionLists: [
{
title: 'Options',
list: [
{
description: 'Update in every package found in subdirectories \
or every workspace package, when executed inside a workspace. \
For options that may be used with `-r`, see "pnpm help recursive"',
name: '--recursive',
shortAlias: '-r',
},
{
description: 'Update globally installed packages',
name: '--global',
shortAlias: '-g',
},
{
description: 'How deep should levels of dependencies be inspected. Infinity is default. 0 would mean top-level dependencies only',
name: '--depth <number>',
},
{
description: 'Ignore version ranges in package.json',
name: '--latest',
shortAlias: '-L',
},
{
description: 'Update packages only in "dependencies" and "optionalDependencies"',
name: '--prod',
shortAlias: '-P',
},
{
description: 'Update packages only in "devDependencies"',
name: '--dev',
shortAlias: '-D',
},
{
description: 'Don\'t update packages in "optionalDependencies"',
name: '--no-optional',
},
{
description: 'Tries to link all packages from the workspace. \
Versions are updated to match the versions of packages inside the workspace. \
If specific packages are updated, the command will fail if any of the updated \
dependencies is not found inside the workspace',
name: '--workspace',
},
{
description: 'Show outdated dependencies and select which ones to update',
name: '--interactive',
shortAlias: '-i',
},
OPTIONS.globalDir,
...UNIVERSAL_OPTIONS,
],
},
FILTERING,
],
url: docsUrl('update'),
usages: ['pnpm update [-g] [<pkg>...]'],
})
}
export type UpdateCommandOptions = InstallCommandOptions & {
interactive?: boolean
latest?: boolean
}
export async function handler (
opts: UpdateCommandOptions,
params: string[] = []
) {
if (opts.interactive) {
return interactiveUpdate(params, opts)
}
return update(params, opts)
}
async function interactiveUpdate (
input: string[],
opts: UpdateCommandOptions
) {
const include = makeIncludeDependenciesFromCLI(opts.cliOptions)
const projects = (opts.selectedProjectsGraph != null)
? Object.values(opts.selectedProjectsGraph).map((wsPkg) => wsPkg.package)
: [
{
dir: opts.dir,
manifest: await readProjectManifestOnly(opts.dir, opts),
},
]
const rootDir = opts.workspaceDir ?? opts.dir
const rootProject = projects.find((project) => project.dir === rootDir)
const outdatedPkgsOfProjects = await outdatedDepsOfProjects(projects, input, {
...opts,
compatible: opts.latest !== true,
ignoreDependencies: rootProject?.manifest?.pnpm?.updateConfig?.ignoreDependencies,
include,
retry: {
factor: opts.fetchRetryFactor,
maxTimeout: opts.fetchRetryMaxtimeout,
minTimeout: opts.fetchRetryMintimeout,
retries: opts.fetchRetries,
},
timeout: opts.fetchTimeout,
})
const workspacesEnabled = !!opts.workspaceDir
const choices = getUpdateChoices(unnest(outdatedPkgsOfProjects), workspacesEnabled)
if (choices.length === 0) {
if (opts.latest) {
return 'All of your dependencies are already up to date'
}
return 'All of your dependencies are already up to date inside the specified ranges. Use the --latest option to update the ranges in package.json'
}
let { updateDependencies } = await prompt({
choices,
footer: '\nEnter to start updating. Ctrl-c to cancel.',
indicator (state: any, choice: any) { // eslint-disable-line @typescript-eslint/no-explicit-any
return ` ${choice.enabled ? '●' : '○'}`
},
message: 'Choose which packages to update ' +
`(Press ${chalk.cyan('<space>')} to select, ` +
`${chalk.cyan('<a>')} to toggle all, ` +
`${chalk.cyan('<i>')} to invert selection)`,
name: 'updateDependencies',
pointer: '❯',
result () {
return this.selected
},
format () {
if (!this.state.submitted || this.state.cancelled) return ''
if (Array.isArray(this.selected)) {
return this.selected
// The custom format function is used to filter out "[dependencies]" or "[devDependencies]" or "[packageManager]" from the output.
// https://github.com/enquirer/enquirer/blob/master/lib/prompts/select.js#L98
.filter((choice: ChoiceRow) => !/^\[.+\]$/.test(choice.name))
.map((choice: ChoiceRow) => this.styles.primary(choice.name)).join(', ')
}
return this.styles.primary(this.selected.name)
},
styles: {
dark: chalk.reset,
em: chalk.bgBlack.whiteBright,
success: chalk.reset,
},
type: 'multiselect',
validate (value: string[]) {
if (value.length === 0) {
return 'You must choose at least one package.'
}
return true
},
// For Vim users (related: https://github.com/enquirer/enquirer/pull/163)
j () {
return this.down()
},
k () {
return this.up()
},
cancel () {
// By default, canceling the prompt via Ctrl+c throws an empty string.
// The custom cancel function prevents that behavior.
// Otherwise, pnpm CLI would print an error and confuse users.
// See related issue: https://github.com/enquirer/enquirer/issues/225
globalInfo('Update canceled')
process.exit(0)
},
} as any) as any // eslint-disable-line @typescript-eslint/no-explicit-any
updateDependencies = (updateDependencies as ChoiceRow[]).filter(dep => !(dep.path && dep.path.startsWith('[packageManager]')))
const packageManagerManifest = outdatedPkgsOfProjects[0].filter(pkg => pkg.belongsTo === 'packageManager')
if (opts.save !== false && packageManagerManifest.length) {
await updateProjectCorepackConfig({
...opts,
updatedVersion: packageManagerManifest[0].wanted,
updatedPackage: packageManagerManifest[0].packageName,
})
}
const updatePkgNames = pluck('value', updateDependencies as ChoiceRow[])
return update(updatePkgNames, opts)
}
async function update (
dependencies: string[],
opts: UpdateCommandOptions
) {
if (opts.latest) {
const dependenciesWithTags = dependencies.filter((name) => parseUpdateParam(name).versionSpec != null)
if (dependenciesWithTags.length) {
throw new PnpmError('LATEST_WITH_SPEC', `Specs are not allowed to be used with --latest (${dependenciesWithTags.join(', ')})`)
}
}
const includeDirect = makeIncludeDependenciesFromCLI(opts.cliOptions)
const include = {
dependencies: opts.rawConfig.production !== false,
devDependencies: opts.rawConfig.dev !== false,
optionalDependencies: opts.rawConfig.optional !== false,
}
const depth = opts.depth ?? Infinity
return installDeps({
...opts,
allowNew: false,
depth,
ignoreCurrentPrefs: false,
includeDirect,
include,
update: true,
updateToLatest: opts.latest,
updateMatching: (dependencies.length > 0) && dependencies.every(dep => !dep.substring(1).includes('@')) && depth > 0 && !opts.latest
? createMatcher(dependencies)
: undefined,
updatePackageManifest: opts.save !== false,
resolutionMode: opts.save === false ? 'highest' : opts.resolutionMode,
}, dependencies)
}
function makeIncludeDependenciesFromCLI (opts: {
production?: boolean
dev?: boolean
optional?: boolean
}) {
return {
dependencies: opts.production === true || (opts.dev !== true && opts.optional !== true),
devDependencies: opts.dev === true || (opts.production !== true && opts.optional !== true),
optionalDependencies: opts.optional === true || (opts.production !== true && opts.dev !== true),
}
}
async function updateProjectCorepackConfig (opts: {
updatedVersion: string
updatedPackage: string
} & UpdateCommandOptions) {
if (!opts.allProjects) {
return
}
const { updatedPackage, updatedVersion } = opts
return Promise.all(opts.allProjects.map((project) => {
const updatedManifest = project.manifest
updatedManifest.packageManager = `${updatedPackage}@${updatedVersion}`
return project.writeProjectManifest(updatedManifest)
}))
}