/
main.ts
305 lines (279 loc) · 9.96 KB
/
main.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
// Map SIGINT & SIGTERM to process exit
// so that lockfiles are removed automatically
import loudRejection from 'loud-rejection'
import packageManager from '@pnpm/cli-meta'
import { getConfig } from '@pnpm/cli-utils'
import {
Config,
} from '@pnpm/config'
import { scopeLogger } from '@pnpm/core-loggers'
import { filterPackages } from '@pnpm/filter-workspace-packages'
import findWorkspacePackages from '@pnpm/find-workspace-packages'
import logger from '@pnpm/logger'
import { ParsedCliArgs } from '@pnpm/parse-cli-args'
import { node } from '@pnpm/plugin-commands-env'
import chalk from 'chalk'
import checkForUpdates from './checkForUpdates'
import pnpmCmds, { rcOptionsTypes } from './cmd'
import { formatUnknownOptionsError } from './formatError'
import parseCliArgs from './parseCliArgs'
import initReporter, { ReporterType } from './reporter'
import isCI from 'is-ci'
import path from 'path'
import isEmpty from 'ramda/src/isEmpty.js'
import stripAnsi from 'strip-ansi'
import which from 'which'
process
.once('SIGINT', () => process.exit(0))
.once('SIGTERM', () => process.exit(0))
loudRejection()
const DEPRECATED_OPTIONS = new Set([
'independent-leaves',
'lock',
'resolution-strategy',
])
// A workaround for the https://github.com/vercel/pkg/issues/897 issue.
delete process.env.PKG_EXECPATH
export default async function run (inputArgv: string[]) {
let parsedCliArgs!: ParsedCliArgs
try {
parsedCliArgs = await parseCliArgs(inputArgv)
} catch (err: any) { // eslint-disable-line
// Reporting is not initialized at this point, so just printing the error
printError(err.message, err['hint'])
process.exitCode = 1
return
}
const {
argv,
params: cliParams,
options: cliOptions,
cmd,
fallbackCommandUsed,
unknownOptions,
workspaceDir,
} = parsedCliArgs
if (cmd !== null && !pnpmCmds[cmd]) {
printError(`Unknown command '${cmd}'`, 'For help, run: pnpm help')
process.exitCode = 1
return
}
if (unknownOptions.size > 0 && !fallbackCommandUsed) {
const unknownOptionsArray = Array.from(unknownOptions.keys())
if (unknownOptionsArray.every((option) => DEPRECATED_OPTIONS.has(option))) {
let deprecationMsg = `${chalk.bgYellow.black('\u2009WARN\u2009')}`
if (unknownOptionsArray.length === 1) {
deprecationMsg += ` ${chalk.yellow(`Deprecated option: '${unknownOptionsArray[0]}'`)}`
} else {
deprecationMsg += ` ${chalk.yellow(`Deprecated options: ${unknownOptionsArray.map(unknownOption => `'${unknownOption}'`).join(', ')}`)}`
}
console.log(deprecationMsg)
} else {
printError(formatUnknownOptionsError(unknownOptions), `For help, run: pnpm help${cmd ? ` ${cmd}` : ''}`)
process.exitCode = 1
return
}
}
let config: Config & {
forceSharedLockfile: boolean
argv: { remain: string[], cooked: string[], original: string[] }
fallbackCommandUsed: boolean
}
try {
// When we just want to print the location of the global bin directory,
// we don't need the write permission to it. Related issue: #2700
const globalDirShouldAllowWrite = cmd !== 'root'
config = await getConfig(cliOptions, {
excludeReporter: false,
globalDirShouldAllowWrite,
rcOptionsTypes,
workspaceDir,
checkUnknownSetting: false,
}) as typeof config
if (cmd === 'dlx') {
config.useStderr = true
}
config.forceSharedLockfile = typeof config.workspaceDir === 'string' && config.sharedWorkspaceLockfile === true
config.argv = argv
config.fallbackCommandUsed = fallbackCommandUsed
} catch (err: any) { // eslint-disable-line
// Reporting is not initialized at this point, so just printing the error
const hint = err['hint'] ? err['hint'] : `For help, run: pnpm help${cmd ? ` ${cmd}` : ''}`
printError(err.message, hint)
process.exitCode = 1
return
}
let write: (text: string) => void = process.stdout.write.bind(process.stdout)
// chalk reads the FORCE_COLOR env variable
if (config.color === 'always') {
process.env['FORCE_COLOR'] = '1'
} else if (config.color === 'never') {
process.env['FORCE_COLOR'] = '0'
// In some cases, it is already late to set the FORCE_COLOR env variable.
// Some text might be already generated.
//
// A better solution might be to dynamically load all the code after the settings are read
// and the env variable set.
write = (text) => process.stdout.write(stripAnsi(text))
}
const reporterType: ReporterType = (() => {
if (config.loglevel === 'silent') return 'silent'
if (config.reporter) return config.reporter as ReporterType
if (isCI || !process.stdout.isTTY) return 'append-only'
return 'default'
})()
const printLogs = !config['parseable'] && !config['json']
if (printLogs) {
initReporter(reporterType, {
cmd,
config,
})
}
global['reporterInitialized'] = reporterType
const selfUpdate = config.global && (cmd === 'add' || cmd === 'update') && cliParams.includes(packageManager.name)
if (selfUpdate) {
await pnpmCmds.server(config as any, ['stop']) // eslint-disable-line @typescript-eslint/no-explicit-any
try {
const currentPnpmDir = path.dirname(which.sync('pnpm'))
if (path.relative(currentPnpmDir, config.bin) !== '') {
console.log(`The location of the currently running pnpm differs from the location where pnpm will be installed
Current pnpm location: ${currentPnpmDir}
Target location: ${config.bin}
`)
}
} catch (err) {
// if pnpm not found, then ignore
}
}
if (
(cmd === 'install' || cmd === 'import') &&
typeof workspaceDir === 'string'
) {
cliOptions['recursive'] = true
config.recursive = true
if (!config.recursiveInstall && !config.filter && !config.filterProd) {
config.filter = ['{.}...']
}
}
if (cliOptions['recursive']) {
const wsDir = workspaceDir ?? process.cwd()
const allProjects = await findWorkspacePackages(wsDir, {
engineStrict: config.engineStrict,
patterns: cliOptions['workspace-packages'],
})
if (allProjects.length === 0) {
if (printLogs) {
console.log(`No projects found in "${wsDir}"`)
}
process.exitCode = 0
return
}
config.filter = config.filter ?? []
config.filterProd = config.filterProd ?? []
const filters = [
...config.filter.map((filter) => ({ filter, followProdDepsOnly: false })),
...config.filterProd.map((filter) => ({ filter, followProdDepsOnly: true })),
]
const relativeWSDirPath = () => path.relative(process.cwd(), wsDir) || '.'
if (config.workspaceRoot) {
filters.push({ filter: `{${relativeWSDirPath()}}`, followProdDepsOnly: false })
} else if (!config.includeWorkspaceRoot && (cmd === 'run' || cmd === 'exec' || cmd === 'add' || cmd === 'test')) {
filters.push({ filter: `!{${relativeWSDirPath()}}`, followProdDepsOnly: false })
}
const filterResults = await filterPackages(allProjects, filters, {
linkWorkspacePackages: !!config.linkWorkspacePackages,
prefix: process.cwd(),
workspaceDir: wsDir,
testPattern: config.testPattern,
changedFilesIgnorePattern: config.changedFilesIgnorePattern,
useGlobDirFiltering: !config.legacyDirFiltering,
})
config.selectedProjectsGraph = filterResults.selectedProjectsGraph
if (isEmpty(config.selectedProjectsGraph)) {
if (printLogs) {
console.log(`No projects matched the filters in "${wsDir}"`)
}
process.exitCode = 0
return
}
if (filterResults.unmatchedFilters.length !== 0 && printLogs) {
console.log(`No projects matched the filters "${filterResults.unmatchedFilters.join(', ')}" in "${wsDir}"`)
}
config.allProjects = allProjects
config.workspaceDir = wsDir
}
let { output, exitCode }: { output: string | null, exitCode: number } = await (async () => {
// NOTE: we defer the next stage, otherwise reporter might not catch all the logs
await new Promise<void>((resolve) => setTimeout(() => resolve(), 0))
if (
config.updateNotifier !== false &&
!isCI &&
!selfUpdate &&
!config.offline &&
!config.preferOffline &&
!config.fallbackCommandUsed &&
(cmd === 'install' || cmd === 'add')
) {
checkForUpdates(config).catch(() => { /* Ignore */ })
}
if (config.force === true && !config.fallbackCommandUsed) {
logger.warn({
message: 'using --force I sure hope you know what you are doing',
prefix: config.dir,
})
}
scopeLogger.debug({
...(
!cliOptions['recursive']
? { selected: 1 }
: {
selected: Object.keys(config.selectedProjectsGraph!).length,
total: config.allProjects!.length,
}
),
...(workspaceDir ? { workspacePrefix: workspaceDir } : {}),
})
if (config.useNodeVersion != null) {
const nodePath = await node.getNodeBinDir(config)
config.extraBinPaths.push(nodePath)
config.nodeVersion = config.useNodeVersion
}
let result = pnpmCmds[cmd ?? 'help'](
// TypeScript doesn't currently infer that the type of config
// is `Omit<typeof config, 'reporter'>` after the `delete config.reporter` statement
config as Omit<typeof config, 'reporter'>,
cliParams
)
if (result instanceof Promise) {
result = await result
}
if (!result) {
return { output: null, exitCode: 0 }
}
if (typeof result === 'string') {
return { output: result, exitCode: 0 }
}
return result
})()
if (output) {
if (!output.endsWith('\n')) {
output = `${output}\n`
}
write(output)
}
if (!cmd) {
exitCode = 1
}
if (exitCode) {
// In this case, the non-zero exit code is expected,
// so there is no need to write a debug file.
global['writeDebugLogFile'] = false
process.exitCode = exitCode
}
}
function printError (message: string, hint?: string) {
console.log(`${chalk.bgRed.black('\u2009ERROR\u2009')} ${chalk.red(message)}`)
if (hint) {
console.log(hint)
}
}