-
-
Notifications
You must be signed in to change notification settings - Fork 936
/
exec.ts
328 lines (301 loc) · 9.55 KB
/
exec.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
import path from 'path'
import { docsUrl, type RecursiveSummary, throwOnCommandFail, readProjectManifestOnly } from '@pnpm/cli-utils'
import { type Config, types } from '@pnpm/config'
import { makeNodeRequireOption } from '@pnpm/lifecycle'
import { logger } from '@pnpm/logger'
import { tryReadProjectManifest } from '@pnpm/read-project-manifest'
import { sortPackages } from '@pnpm/sort-packages'
import { type Project, type ProjectsGraph } from '@pnpm/types'
import execa from 'execa'
import pLimit from 'p-limit'
import PATH from 'path-name'
import pick from 'ramda/src/pick'
import renderHelp from 'render-help'
import { existsInDir } from './existsInDir'
import { makeEnv } from './makeEnv'
import {
PARALLEL_OPTION_HELP,
REPORT_SUMMARY_OPTION_HELP,
RESUME_FROM_OPTION_HELP,
shorthands as runShorthands,
} from './run'
import { PnpmError } from '@pnpm/error'
import which from 'which'
import writeJsonFile from 'write-json-file'
import { getNearestProgram, getNearestScript } from './buildCommandNotFoundHint'
export const shorthands = {
parallel: runShorthands.parallel,
c: '--shell-mode',
}
export const commandNames = ['exec']
export function rcOptionsTypes () {
return {
...pick([
'bail',
'sort',
'use-node-version',
'unsafe-perm',
'workspace-concurrency',
], types),
'shell-mode': Boolean,
'resume-from': String,
'report-summary': Boolean,
}
}
export const cliOptionsTypes = () => ({
...rcOptionsTypes(),
recursive: Boolean,
reverse: Boolean,
})
export function help () {
return renderHelp({
description: 'Run a shell command in the context of a project.',
descriptionLists: [
{
title: 'Options',
list: [
PARALLEL_OPTION_HELP,
{
description: 'Run the shell command 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: 'If exist, runs file inside of a shell. \
Uses /bin/sh on UNIX and \\cmd.exe on Windows. \
The shell should understand the -c switch on UNIX or /d /s /c on Windows.',
name: '--shell-mode',
shortAlias: '-c',
},
RESUME_FROM_OPTION_HELP,
REPORT_SUMMARY_OPTION_HELP,
],
},
],
url: docsUrl('exec'),
usages: ['pnpm [-r] [-c] exec <command> [args...]'],
})
}
export function getResumedPackageChunks ({
resumeFrom,
chunks,
selectedProjectsGraph,
}: {
resumeFrom: string
chunks: string[][]
selectedProjectsGraph: ProjectsGraph
}) {
const resumeFromPackagePrefix = Object.keys(selectedProjectsGraph)
.find((prefix) => selectedProjectsGraph[prefix]?.package.manifest.name === resumeFrom)
if (!resumeFromPackagePrefix) {
throw new PnpmError('RESUME_FROM_NOT_FOUND', `Cannot find package ${resumeFrom}. Could not determine where to resume from.`)
}
const chunkPosition = chunks.findIndex(chunk => chunk.includes(resumeFromPackagePrefix))
return chunks.slice(chunkPosition)
}
export async function writeRecursiveSummary (opts: { dir: string, summary: RecursiveSummary }) {
await writeJsonFile(path.join(opts.dir, 'pnpm-exec-summary.json'), {
executionStatus: opts.summary,
})
}
export function createEmptyRecursiveSummary (chunks: string[][]) {
return chunks.flat().reduce<RecursiveSummary>((acc, prefix) => {
acc[prefix] = { status: 'queued' }
return acc
}, {})
}
export function getExecutionDuration (start: [number, number]) {
const end = process.hrtime(start)
return (end[0] * 1e9 + end[1]) / 1e6
}
export async function handler (
opts: Required<Pick<Config, 'selectedProjectsGraph'>> & {
bail?: boolean
unsafePerm?: boolean
reverse?: boolean
sort?: boolean
workspaceConcurrency?: number
shellMode?: boolean
resumeFrom?: string
reportSummary?: boolean
implicitlyFellbackFromRun?: boolean
} & Pick<Config, 'extraBinPaths' | 'extraEnv' | 'lockfileDir' | 'modulesDir' | 'dir' | 'userAgent' | 'recursive' | 'workspaceDir' | 'nodeOptions'>,
params: string[]
) {
// For backward compatibility
if (params[0] === '--') {
params.shift()
}
const limitRun = pLimit(opts.workspaceConcurrency ?? 4)
let chunks!: string[][]
if (opts.recursive) {
chunks = opts.sort
? sortPackages(opts.selectedProjectsGraph)
: [Object.keys(opts.selectedProjectsGraph).sort()]
if (opts.reverse) {
chunks = chunks.reverse()
}
} else {
chunks = [[opts.dir]]
const project = await tryReadProjectManifest(opts.dir)
if (project.manifest != null) {
opts.selectedProjectsGraph = {
[opts.dir]: {
dependencies: [],
package: {
...project,
dir: opts.dir,
} as Project,
},
}
}
}
if (opts.resumeFrom) {
chunks = getResumedPackageChunks({
resumeFrom: opts.resumeFrom,
chunks,
selectedProjectsGraph: opts.selectedProjectsGraph,
})
}
const result = createEmptyRecursiveSummary(chunks)
const existsPnp = existsInDir.bind(null, '.pnp.cjs')
const workspacePnpPath = opts.workspaceDir && await existsPnp(opts.workspaceDir)
let exitCode = 0
const prependPaths = [
'./node_modules/.bin',
...opts.extraBinPaths,
]
for (const chunk of chunks) {
// eslint-disable-next-line no-await-in-loop
await Promise.all(chunk.map(async (prefix: string) =>
limitRun(async () => {
result[prefix].status = 'running'
const startTime = process.hrtime()
try {
const pnpPath = workspacePnpPath ?? await existsPnp(prefix)
const extraEnv = {
...opts.extraEnv,
...(pnpPath ? makeNodeRequireOption(pnpPath) : {}),
}
const env = makeEnv({
extraEnv: {
...extraEnv,
PNPM_PACKAGE_NAME: opts.selectedProjectsGraph[prefix]?.package.manifest.name,
...(opts.nodeOptions ? { NODE_OPTIONS: opts.nodeOptions } : {}),
},
prependPaths,
userAgent: opts.userAgent,
})
await execa(params[0], params.slice(1), {
cwd: prefix,
env,
stdio: 'inherit',
shell: opts.shellMode ?? false,
})
result[prefix].status = 'passed'
result[prefix].duration = getExecutionDuration(startTime)
} catch (err: any) { // eslint-disable-line
if (isErrorCommandNotFound(params[0], err, prependPaths)) {
err.message = `Command "${params[0]}" not found`
err.hint = await createExecCommandNotFoundHint(params[0], {
implicitlyFellbackFromRun: opts.implicitlyFellbackFromRun ?? false,
dir: opts.dir,
workspaceDir: opts.workspaceDir,
modulesDir: opts.modulesDir ?? 'node_modules',
})
} else if (!opts.recursive && typeof err.exitCode === 'number') {
exitCode = err.exitCode
return
}
logger.info(err)
result[prefix] = {
status: 'failure',
duration: getExecutionDuration(startTime),
error: err,
message: err.message,
prefix,
}
if (!opts.bail) {
return
}
if (!err['code']?.startsWith('ERR_PNPM_')) {
err['code'] = 'ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL'
}
err['prefix'] = prefix
opts.reportSummary && await writeRecursiveSummary({
dir: opts.lockfileDir ?? opts.dir,
summary: result,
})
throw err
}
}
)))
}
opts.reportSummary && await writeRecursiveSummary({
dir: opts.lockfileDir ?? opts.dir,
summary: result,
})
throwOnCommandFail('pnpm recursive exec', result)
return { exitCode }
}
async function createExecCommandNotFoundHint (
programName: string,
opts: {
dir: string
implicitlyFellbackFromRun: boolean
workspaceDir?: string
modulesDir: string
}
): Promise<string | undefined> {
if (opts.implicitlyFellbackFromRun) {
let nearestScript: string | null | undefined
try {
nearestScript = getNearestScript(programName, (await readProjectManifestOnly(opts.dir)).scripts)
} catch (_err) {}
if (nearestScript) {
return `Did you mean "pnpm ${nearestScript}"?`
}
const nearestProgram = getNearestProgram({
programName,
dir: opts.dir,
workspaceDir: opts.workspaceDir,
modulesDir: opts.modulesDir,
})
if (nearestProgram) {
return `Did you mean "pnpm ${nearestProgram}"?`
}
return undefined
}
const nearestProgram = getNearestProgram({
programName,
dir: opts.dir,
workspaceDir: opts.workspaceDir,
modulesDir: opts.modulesDir,
})
if (nearestProgram) {
return `Did you mean "pnpm exec ${nearestProgram}"?`
}
return undefined
}
interface CommandError extends Error {
originalMessage: string
shortMessage: string
}
function isErrorCommandNotFound (command: string, error: CommandError, prependPaths: string[]) {
// Mac/Linux
if (process.platform === 'linux' || process.platform === 'darwin') {
return error.originalMessage === `spawn ${command} ENOENT`
}
// Windows
if (process.platform === 'win32') {
const prepend = prependPaths.join(path.delimiter)
const whichPath = process.env[PATH] ? `${prepend}${path.delimiter}${process.env[PATH] as string}` : prepend
return !which.sync(command, {
nothrow: true,
path: whichPath,
})
}
return false
}