forked from pnpm/pnpm
/
recursive.ts
executable file
·537 lines (504 loc) · 17.1 KB
/
recursive.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
import { promises as fs } from 'fs'
import path from 'path'
import {
RecursiveSummary,
throwOnCommandFail,
} from '@pnpm/cli-utils'
import { Config } from '@pnpm/config'
import PnpmError from '@pnpm/error'
import { arrayOfWorkspacePackagesToMap } from '@pnpm/find-workspace-packages'
import logger from '@pnpm/logger'
import { filterDependenciesByType } from '@pnpm/manifest-utils'
import { matcherWithIndex } from '@pnpm/matcher'
import { rebuild } from '@pnpm/plugin-commands-rebuild'
import { requireHooks } from '@pnpm/pnpmfile'
import sortPackages from '@pnpm/sort-packages'
import { createOrConnectStoreController, CreateStoreControllerOptions } from '@pnpm/store-connection-manager'
import {
IncludedDependencies,
PackageManifest,
Project,
ProjectManifest,
ProjectsGraph,
} from '@pnpm/types'
import {
addDependenciesToPackage,
install,
InstallOptions,
MutatedProject,
mutateModules,
} from '@pnpm/core'
import camelcaseKeys from 'camelcase-keys'
import isSubdir from 'is-subdir'
import mem from 'mem'
import pFilter from 'p-filter'
import pLimit from 'p-limit'
import readIniFile from 'read-ini-file'
import getOptionsFromRootManifest from './getOptionsFromRootManifest'
import { createWorkspaceSpecs, updateToWorkspacePackagesFromManifest } from './updateWorkspaceDependencies'
import updateToLatestSpecsFromManifest, { createLatestSpecs } from './updateToLatestSpecsFromManifest'
import getSaveType from './getSaveType'
import getPinnedVersion from './getPinnedVersion'
import { PreferredVersions } from '@pnpm/resolver-base'
type RecursiveOptions = CreateStoreControllerOptions & Pick<Config,
| 'bail'
| 'depth'
| 'globalPnpmfile'
| 'hoistPattern'
| 'hooks'
| 'ignorePnpmfile'
| 'ignoreScripts'
| 'linkWorkspacePackages'
| 'lockfileDir'
| 'lockfileOnly'
| 'modulesDir'
| 'pnpmfile'
| 'rawLocalConfig'
| 'registries'
| 'save'
| 'saveDev'
| 'saveExact'
| 'saveOptional'
| 'savePeer'
| 'savePrefix'
| 'saveProd'
| 'saveWorkspaceProtocol'
| 'lockfileIncludeTarballUrl'
| 'sharedWorkspaceLockfile'
| 'tag'
> & {
include?: IncludedDependencies
includeDirect?: IncludedDependencies
latest?: boolean
pending?: boolean
workspace?: boolean
allowNew?: boolean
forceHoistPattern?: boolean
forcePublicHoistPattern?: boolean
ignoredPackages?: Set<string>
update?: boolean
useBetaCli?: boolean
selectedProjectsGraph: ProjectsGraph
preferredVersions?: PreferredVersions
pruneDirectDependencies?: boolean
} & Partial<
Pick<Config,
| 'sort'
| 'workspaceConcurrency'
>
> & Required<
Pick<Config, 'workspaceDir'>
>
export default async function recursive (
allProjects: Project[],
params: string[],
opts: RecursiveOptions,
cmdFullName: 'install' | 'add' | 'remove' | 'unlink' | 'update' | 'import'
): Promise<boolean | string> {
if (allProjects.length === 0) {
// It might make sense to throw an exception in this case
return false
}
const pkgs = Object.values(opts.selectedProjectsGraph).map((wsPkg) => wsPkg.package)
if (pkgs.length === 0) {
return false
}
const manifestsByPath: { [dir: string]: Omit<Project, 'dir'> } = {}
for (const { dir, manifest, writeProjectManifest } of allProjects) {
manifestsByPath[dir] = { manifest, writeProjectManifest }
}
const throwOnFail = throwOnCommandFail.bind(null, `pnpm recursive ${cmdFullName}`)
const chunks = opts.sort !== false
? sortPackages(opts.selectedProjectsGraph)
: [Object.keys(opts.selectedProjectsGraph).sort()]
const store = await createOrConnectStoreController(opts)
const workspacePackages = cmdFullName !== 'unlink'
? arrayOfWorkspacePackagesToMap(allProjects)
: {}
const targetDependenciesField = getSaveType(opts)
const installOpts = Object.assign(opts, {
...getOptionsFromRootManifest(manifestsByPath[opts.lockfileDir ?? opts.dir]?.manifest ?? {}),
linkWorkspacePackagesDepth: opts.linkWorkspacePackages === 'deep' ? Infinity : opts.linkWorkspacePackages ? 0 : -1,
ownLifecycleHooksStdio: 'pipe',
peer: opts.savePeer,
pruneLockfileImporters: ((opts.ignoredPackages == null) || opts.ignoredPackages.size === 0) &&
pkgs.length === allProjects.length,
storeController: store.ctrl,
storeDir: store.dir,
targetDependenciesField,
workspacePackages,
forceHoistPattern: typeof opts.rawLocalConfig?.['hoist-pattern'] !== 'undefined' || typeof opts.rawLocalConfig?.['hoist'] !== 'undefined',
forceShamefullyHoist: typeof opts.rawLocalConfig?.['shamefully-hoist'] !== 'undefined',
}) as InstallOptions
const result = {
fails: [],
passes: 0,
} as RecursiveSummary
const memReadLocalConfig = mem(readLocalConfig)
async function getImporters () {
const importers = [] as Array<{ buildIndex: number, manifest: ProjectManifest, rootDir: string }>
await Promise.all(chunks.map(async (prefixes: string[], buildIndex) => {
if (opts.ignoredPackages != null) {
prefixes = prefixes.filter((prefix) => !opts.ignoredPackages!.has(prefix))
}
return Promise.all(
prefixes.map(async (prefix) => {
importers.push({
buildIndex,
manifest: manifestsByPath[prefix].manifest,
rootDir: prefix,
})
})
)
}))
return importers
}
const updateToLatest = opts.update && opts.latest
const includeDirect = opts.includeDirect ?? {
dependencies: true,
devDependencies: true,
optionalDependencies: true,
}
let updateMatch: UpdateDepsMatcher | null
if (cmdFullName === 'update') {
if (params.length === 0) {
const ignoreDeps = manifestsByPath[opts.workspaceDir]?.manifest?.pnpm?.updateConfig?.ignoreDependencies
if (ignoreDeps?.length) {
params = makeIgnorePatterns(ignoreDeps)
}
}
updateMatch = params.length ? createMatcher(params) : null
} else {
updateMatch = null
}
// For a workspace with shared lockfile
if (opts.lockfileDir && ['add', 'install', 'remove', 'update', 'import'].includes(cmdFullName)) {
let importers = await getImporters()
const calculatedRepositoryRoot = await fs.realpath(calculateRepositoryRoot(opts.workspaceDir, importers.map(x => x.rootDir)))
const isFromWorkspace = isSubdir.bind(null, calculatedRepositoryRoot)
importers = await pFilter(importers, async ({ rootDir }: { rootDir: string }) => isFromWorkspace(await fs.realpath(rootDir)))
if (importers.length === 0) return true
let mutation!: string
switch (cmdFullName) {
case 'remove':
mutation = 'uninstallSome'
break
case 'import':
mutation = 'install'
break
default:
mutation = (params.length === 0 && !updateToLatest ? 'install' : 'installSome')
break
}
const writeProjectManifests = [] as Array<(manifest: ProjectManifest) => Promise<void>>
const mutatedImporters = [] as MutatedProject[]
await Promise.all(importers.map(async ({ buildIndex, rootDir }) => {
const localConfig = await memReadLocalConfig(rootDir)
const modulesDir = localConfig.modulesDir ?? opts.modulesDir
const { manifest, writeProjectManifest } = manifestsByPath[rootDir]
let currentInput = [...params]
if (updateMatch != null) {
currentInput = matchDependencies(updateMatch, manifest, includeDirect)
if ((currentInput.length === 0) && (typeof opts.depth === 'undefined' || opts.depth <= 0)) {
installOpts.pruneLockfileImporters = false
return
}
}
if (updateToLatest) {
if (!params || (params.length === 0)) {
currentInput = updateToLatestSpecsFromManifest(manifest, includeDirect)
} else {
currentInput = createLatestSpecs(currentInput, manifest)
if (currentInput.length === 0) {
installOpts.pruneLockfileImporters = false
return
}
}
}
if (opts.workspace) {
if (!currentInput || (currentInput.length === 0)) {
currentInput = updateToWorkspacePackagesFromManifest(manifest, includeDirect, workspacePackages)
} else {
currentInput = createWorkspaceSpecs(currentInput, workspacePackages)
}
}
writeProjectManifests.push(writeProjectManifest)
switch (mutation) {
case 'uninstallSome':
mutatedImporters.push({
dependencyNames: currentInput,
manifest,
modulesDir,
mutation,
rootDir,
targetDependenciesField,
} as MutatedProject)
return
case 'installSome':
mutatedImporters.push({
allowNew: cmdFullName === 'install' || cmdFullName === 'add',
dependencySelectors: currentInput,
manifest,
modulesDir,
mutation,
peer: opts.savePeer,
pinnedVersion: getPinnedVersion({
saveExact: typeof localConfig.saveExact === 'boolean' ? localConfig.saveExact : opts.saveExact,
savePrefix: typeof localConfig.savePrefix === 'string' ? localConfig.savePrefix : opts.savePrefix,
}),
rootDir,
targetDependenciesField,
} as MutatedProject)
return
case 'install':
mutatedImporters.push({
buildIndex,
manifest,
modulesDir,
mutation,
pruneDirectDependencies: opts.pruneDirectDependencies,
rootDir,
} as MutatedProject)
}
}))
if ((mutatedImporters.length === 0) && cmdFullName === 'update' && opts.depth === 0) {
throw new PnpmError('NO_PACKAGE_IN_DEPENDENCIES',
'None of the specified packages were found in the dependencies of any of the projects.')
}
const mutatedPkgs = await mutateModules(mutatedImporters, {
...installOpts,
storeController: store.ctrl,
})
if (opts.save !== false) {
await Promise.all(
mutatedPkgs
.map(async ({ manifest }, index) => writeProjectManifests[index](manifest))
)
}
return true
}
const pkgPaths = chunks.length === 0
? chunks[0]
: Object.keys(opts.selectedProjectsGraph).sort()
const limitInstallation = pLimit(opts.workspaceConcurrency ?? 4)
await Promise.all(pkgPaths.map(async (rootDir: string) =>
limitInstallation(async () => {
const hooks = opts.ignorePnpmfile
? {}
: (() => {
const pnpmfileHooks = requireHooks(rootDir, opts)
return {
...opts.hooks,
...pnpmfileHooks,
afterAllResolved: [...(pnpmfileHooks.afterAllResolved ?? []), ...(opts.hooks?.afterAllResolved ?? [])],
readPackage: [...(pnpmfileHooks.readPackage ?? []), ...(opts.hooks?.readPackage ?? [])],
}
})()
try {
if (opts.ignoredPackages?.has(rootDir)) {
return
}
const { manifest, writeProjectManifest } = manifestsByPath[rootDir]
let currentInput = [...params]
if (updateMatch != null) {
currentInput = matchDependencies(updateMatch, manifest, includeDirect)
if (currentInput.length === 0) return
}
if (updateToLatest) {
if (!params || (params.length === 0)) {
currentInput = updateToLatestSpecsFromManifest(manifest, includeDirect)
} else {
currentInput = createLatestSpecs(currentInput, manifest)
if (currentInput.length === 0) return
}
}
if (opts.workspace) {
if (!currentInput || (currentInput.length === 0)) {
currentInput = updateToWorkspacePackagesFromManifest(manifest, includeDirect, workspacePackages)
} else {
currentInput = createWorkspaceSpecs(currentInput, workspacePackages)
}
}
let action!: any // eslint-disable-line @typescript-eslint/no-explicit-any
switch (cmdFullName) {
case 'unlink':
action = (currentInput.length === 0 ? unlink : unlinkPkgs.bind(null, currentInput))
break
case 'remove':
action = async (manifest: PackageManifest, opts: any) => { // eslint-disable-line @typescript-eslint/no-explicit-any
const [{ manifest: newManifest }] = await mutateModules([
{
dependencyNames: currentInput,
manifest,
mutation: 'uninstallSome',
rootDir,
},
], opts)
return newManifest
}
break
default:
action = currentInput.length === 0
? install
: async (manifest: PackageManifest, opts: any) => addDependenciesToPackage(manifest, currentInput, opts) // eslint-disable-line @typescript-eslint/no-explicit-any
break
}
const localConfig = await memReadLocalConfig(rootDir)
const newManifest = await action(
manifest,
{
...installOpts,
...localConfig,
...getOptionsFromRootManifest(manifest),
bin: path.join(rootDir, 'node_modules', '.bin'),
dir: rootDir,
hooks,
ignoreScripts: true,
pinnedVersion: getPinnedVersion({
saveExact: typeof localConfig.saveExact === 'boolean' ? localConfig.saveExact : opts.saveExact,
savePrefix: typeof localConfig.savePrefix === 'string' ? localConfig.savePrefix : opts.savePrefix,
}),
rawConfig: {
...installOpts.rawConfig,
...localConfig,
},
storeController: store.ctrl,
}
)
if (opts.save !== false) {
await writeProjectManifest(newManifest)
}
result.passes++
} catch (err: any) { // eslint-disable-line
logger.info(err)
if (!opts.bail) {
result.fails.push({
error: err,
message: err.message,
prefix: rootDir,
})
return
}
err['prefix'] = rootDir
throw err
}
})
))
if (
!opts.lockfileOnly && !opts.ignoreScripts && (
cmdFullName === 'add' ||
cmdFullName === 'install' ||
cmdFullName === 'update' ||
cmdFullName === 'unlink'
)
) {
await rebuild.handler({
...opts,
pending: opts.pending === true,
}, [])
}
throwOnFail(result)
if (!result.passes && cmdFullName === 'update' && opts.depth === 0) {
throw new PnpmError('NO_PACKAGE_IN_DEPENDENCIES',
'None of the specified packages were found in the dependencies of any of the projects.')
}
return true
}
async function unlink (manifest: ProjectManifest, opts: any) { // eslint-disable-line @typescript-eslint/no-explicit-any
return mutateModules(
[
{
manifest,
mutation: 'unlink',
rootDir: opts.dir,
},
],
opts
)
}
async function unlinkPkgs (dependencyNames: string[], manifest: ProjectManifest, opts: any) { // eslint-disable-line @typescript-eslint/no-explicit-any
return mutateModules(
[
{
dependencyNames,
manifest,
mutation: 'unlinkSome',
rootDir: opts.dir,
},
],
opts
)
}
async function readLocalConfig (prefix: string) {
try {
const ini = await readIniFile(path.join(prefix, '.npmrc')) as Record<string, string>
const config = camelcaseKeys(ini) as (Record<string, string> & { hoist?: boolean })
if (config.shamefullyFlatten) {
config.hoistPattern = '*'
// TODO: print a warning
}
if (config.hoist === false) {
config.hoistPattern = ''
}
return config
} catch (err: any) { // eslint-disable-line
if (err.code !== 'ENOENT') throw err
return {}
}
}
function calculateRepositoryRoot (
workspaceDir: string,
projectDirs: string[]
) {
// assume repo root is workspace dir
let relativeRepoRoot = '.'
for (const rootDir of projectDirs) {
const relativePartRegExp = new RegExp(`^(\\.\\.\\${path.sep})+`)
const relativePartMatch = relativePartRegExp.exec(path.relative(workspaceDir, rootDir))
if (relativePartMatch != null) {
const relativePart = relativePartMatch[0]
if (relativePart.length > relativeRepoRoot.length) {
relativeRepoRoot = relativePart
}
}
}
return path.resolve(workspaceDir, relativeRepoRoot)
}
export function matchDependencies (
match: (input: string) => string | null,
manifest: ProjectManifest,
include: IncludedDependencies
) {
const deps = Object.keys(filterDependenciesByType(manifest, include))
const matchedDeps = []
for (const dep of deps) {
const spec = match(dep)
if (spec === null) continue
matchedDeps.push(spec ? `${dep}@${spec}` : dep)
}
return matchedDeps
}
export type UpdateDepsMatcher = (input: string) => string | null
export function createMatcher (params: string[]): UpdateDepsMatcher {
const patterns: string[] = []
const specs: string[] = []
for (const param of params) {
const atIndex = param.indexOf('@', param[0] === '!' ? 2 : 1)
if (atIndex === -1) {
patterns.push(param)
specs.push('')
} else {
patterns.push(param.slice(0, atIndex))
specs.push(param.slice(atIndex + 1))
}
}
const matcher = matcherWithIndex(patterns)
return (depName: string) => {
const index = matcher(depName)
if (index === -1) return null
return specs[index]
}
}
export function makeIgnorePatterns (ignoredDependencies: string[]): string[] {
return ignoredDependencies.map(depName => `!${depName}`)
}