Skip to content

Commit

Permalink
style: use unknown in try/catch (#7709)
Browse files Browse the repository at this point in the history
  • Loading branch information
zkochan authored Mar 6, 2024
1 parent 9e6bbfb commit 0564745
Show file tree
Hide file tree
Showing 41 changed files with 201 additions and 119 deletions.
17 changes: 9 additions & 8 deletions __utils__/assert-project/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import fs from 'fs'
import path from 'path'
import util from 'util'
import { assertStore } from '@pnpm/assert-store'
import { WANTED_LOCKFILE } from '@pnpm/constants'
import { type LockfileFileV7 } from '@pnpm/lockfile-types'
Expand Down Expand Up @@ -125,8 +126,8 @@ export function assertProject (projectPath: string, encodedRegistryName?: string
try {
const store = getStoreInstance()
store.storeHasNot(pkgName, version)
} catch (err: any) { // eslint-disable-line
if (err.message.startsWith('Cannot find module store')) {
} catch (err: unknown) {
if (util.types.isNativeError(err) && err.message.startsWith('Cannot find module store')) {
return
}
throw err
Expand All @@ -138,17 +139,17 @@ export function assertProject (projectPath: string, encodedRegistryName?: string
readCurrentLockfile () {
try {
return readYamlFile(path.join(getVirtualStoreDir(), 'lock.yaml'))
} catch (err: any) { // eslint-disable-line
if (err.code === 'ENOENT') return null!
} catch (err: unknown) {
if (util.types.isNativeError(err) && 'code' in err && err.code === 'ENOENT') return null!
throw err
}
},
readModulesManifest: () => readModulesManifest(modules),
readLockfile (lockfileName: string = WANTED_LOCKFILE) {
try {
return readYamlFile(path.join(projectPath, lockfileName))
} catch (err: any) { // eslint-disable-line
if (err.code === 'ENOENT') return null!
} catch (err: unknown) {
if (util.types.isNativeError(err) && 'code' in err && err.code === 'ENOENT') return null!
throw err
}
},
Expand All @@ -161,8 +162,8 @@ export function assertProject (projectPath: string, encodedRegistryName?: string
function readModulesManifest (modulesDir: string) {
try {
return readYamlFile<Modules>(path.join(modulesDir, '.modules.yaml'))
} catch (err: any) { // eslint-disable-line
if (err.code === 'ENOENT') return null!
} catch (err: unknown) {
if (util.types.isNativeError(err) && 'code' in err && err.code === 'ENOENT') return null!
throw err
}
}
2 changes: 1 addition & 1 deletion cli/cli-meta/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ if (require.main == null) {
path.join(path.dirname(require.main.filename), '../package.json')
),
}
} catch (err: any) { // eslint-disable-line
} catch {
pkgJson = defaultManifest
}
}
Expand Down
2 changes: 1 addition & 1 deletion cli/default-reporter/src/reportError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ function formatGenericError (errorMessage: string, stack: object) {
let prettyStack: string | undefined
try {
prettyStack = new StackTracey(stack).asTable()
} catch (err: any) { // eslint-disable-line
} catch {
prettyStack = stack.toString()
}
if (prettyStack) {
Expand Down
7 changes: 4 additions & 3 deletions config/config/src/checkGlobalBinDir.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { promises as fs } from 'fs'
import path from 'path'
import util from 'util'
import { PnpmError } from '@pnpm/error'
import { sync as canWriteToDir } from 'can-write-to-dir'
import PATH from 'path-name'
Expand Down Expand Up @@ -33,8 +34,8 @@ const areDirsEqual = (dir1: string, dir2: string) =>
function canWriteToDirAndExists (dir: string) {
try {
return canWriteToDir(dir)
} catch (err: any) { // eslint-disable-line
if (err.code !== 'ENOENT') throw err
return false
} catch (err: unknown) {
if (util.types.isNativeError(err) && 'code' in err && err.code === 'ENOENT') return false
throw err
}
}
7 changes: 4 additions & 3 deletions config/config/src/readLocalConfig.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import path from 'path'
import util from 'util'
import camelcaseKeys from 'camelcase-keys'
import { envReplace } from '@pnpm/config.env-replace'
import { readIniFile } from 'read-ini-file'
Expand All @@ -24,8 +25,8 @@ export async function readLocalConfig (prefix: string) {
}
}
return config
} catch (err: any) { // eslint-disable-line
if (err.code !== 'ENOENT') throw err
return {}
} catch (err: unknown) {
if (util.types.isNativeError(err) && 'code' in err && err.code === 'ENOENT') return {}
throw err
}
}
5 changes: 3 additions & 2 deletions config/plugin-commands-config/src/configSet.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import path from 'path'
import util from 'util'
import { runNpm } from '@pnpm/run-npm'
import { readIniFile } from 'read-ini-file'
import { writeIniFile } from 'write-ini-file'
Expand Down Expand Up @@ -36,8 +37,8 @@ function settingShouldFallBackToNpm (key: string): boolean {
async function safeReadIniFile (configPath: string): Promise<Record<string, unknown>> {
try {
return await readIniFile(configPath) as Record<string, unknown>
} catch (err: any) { // eslint-disable-line @typescript-eslint/no-explicit-any
if (err.code === 'ENOENT') return {}
} catch (err: unknown) {
if (util.types.isNativeError(err) && 'code' in err && err.code === 'ENOENT') return {}
throw err
}
}
2 changes: 1 addition & 1 deletion deps/graph-builder/src/lockfileToDepGraph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ export async function lockfileToDepGraph (
},
}) as any // eslint-disable-line
if (fetchResponse instanceof Promise) fetchResponse = await fetchResponse
} catch (err: any) { // eslint-disable-line
} catch (err: unknown) {
if (pkgSnapshot.optional) return
throw err
}
Expand Down
7 changes: 5 additions & 2 deletions env/plugin-commands-env/src/envRemove.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/* eslint-disable no-await-in-loop */
import util from 'util'
import assert from 'assert'
import { PnpmError } from '@pnpm/error'
import { globalInfo, logger } from '@pnpm/logger'
import { removeBin } from '@pnpm/remove-bins'
Expand Down Expand Up @@ -53,8 +55,9 @@ async function removeNodeVersion (opts: NvmNodeCommandOptions, version: string):
removeBin(npmPath),
removeBin(npxPath),
])
} catch (err: any) { // eslint-disable-line
if (err.code !== 'ENOENT') return err
} catch (err: unknown) {
assert(util.types.isNativeError(err))
if (!('code' in err && err.code === 'ENOENT')) return err
}
}

Expand Down
7 changes: 4 additions & 3 deletions env/plugin-commands-env/src/envUse.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { promises as fs } from 'fs'
import util from 'util'
import gfs from 'graceful-fs'
import path from 'path'
import { PnpmError } from '@pnpm/error'
Expand All @@ -23,8 +24,8 @@ export async function envUse (opts: NvmNodeCommandOptions, params: string[]) {
await symlinkDir(nodeDir, path.join(opts.pnpmHomeDir, CURRENT_NODE_DIRNAME))
try {
gfs.unlinkSync(dest)
} catch (err: any) { // eslint-disable-line
if (err.code !== 'ENOENT') throw err
} catch (err: unknown) {
if (!(util.types.isNativeError(err) && 'code' in err && err.code === 'ENOENT')) throw err
}
await symlinkOrHardLink(src, dest)
try {
Expand All @@ -42,7 +43,7 @@ export async function envUse (opts: NvmNodeCommandOptions, params: string[]) {
const cmdShimOpts = { createPwshFile: false }
await cmdShim(path.join(npmBinDir, 'npm-cli.js'), path.join(opts.bin, 'npm'), cmdShimOpts)
await cmdShim(path.join(npmBinDir, 'npx-cli.js'), path.join(opts.bin, 'npx'), cmdShimOpts)
} catch (err: any) { // eslint-disable-line
} catch {
// ignore
}
return `Node.js ${nodeVersion as string} was activated
Expand Down
5 changes: 3 additions & 2 deletions env/plugin-commands-env/src/node.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import fs from 'fs'
import path from 'path'
import util from 'util'
import { type Config } from '@pnpm/config'
import { createFetchFromRegistry, type FetchFromRegistry } from '@pnpm/fetch'
import { globalInfo } from '@pnpm/logger'
Expand Down Expand Up @@ -92,8 +93,8 @@ export async function getNodeDir (fetch: FetchFromRegistry, opts: NvmNodeCommand
async function readNodeVersionsManifest (nodesDir: string): Promise<{ default?: string }> {
try {
return await loadJsonFile<{ default?: string }>(path.join(nodesDir, 'versions.json'))
} catch (err: any) { // eslint-disable-line
if (err.code === 'ENOENT') {
} catch (err: unknown) {
if (util.types.isNativeError(err) && 'code' in err && err.code === 'ENOENT') {
return {}
}
throw err
Expand Down
10 changes: 7 additions & 3 deletions exec/build-modules/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import assert from 'assert'
import path from 'path'
import util from 'util'
import { calcDepState, type DepsStateCache } from '@pnpm/calc-dep-state'
import { skippedOptionalDependencyLogger } from '@pnpm/core-loggers'
import { runPostinstallHooks } from '@pnpm/lifecycle'
Expand Down Expand Up @@ -140,8 +142,9 @@ async function buildDependency (
sideEffectsCacheKey,
filesIndexFile: depNode.filesIndexFile,
})
} catch (err: any) { // eslint-disable-line
if (err.statusCode === 403) {
} catch (err: unknown) {
assert(util.types.isNativeError(err))
if (err && 'statusCode' in err && err.statusCode === 403) {
logger.warn({
message: `The store server disabled upload requests, could not upload ${depNode.dir}`,
prefix: opts.lockfileDir,
Expand All @@ -155,7 +158,8 @@ async function buildDependency (
}
}
}
} catch (err: any) { // eslint-disable-line
} catch (err: unknown) {
assert(util.types.isNativeError(err))
if (depNode.optional) {
// TODO: add parents field to the log
const pkg = await readPackageJsonFromDir(path.join(depNode.dir)) as DependencyManifest
Expand Down
10 changes: 7 additions & 3 deletions exec/plugin-commands-rebuild/src/implementation/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import assert from 'assert'
import path from 'path'
import util from 'util'
import { getFilePathInCafs, type PackageFilesIndex } from '@pnpm/store.cafs'
import { calcDepState, lockfileToDepGraph, type DepsStateCache } from '@pnpm/calc-dep-state'
import {
Expand Down Expand Up @@ -349,8 +351,9 @@ async function _rebuild (
sideEffectsCacheKey,
filesIndexFile,
})
} catch (err: any) { // eslint-disable-line
if (err.statusCode === 403) {
} catch (err: unknown) {
assert(util.types.isNativeError(err))
if ('statusCode' in err && err.statusCode === 403) {
logger.warn({
message: `The store server disabled upload requests, could not upload ${pkgRoot}`,
prefix: opts.lockfileDir,
Expand All @@ -365,7 +368,8 @@ async function _rebuild (
}
}
pkgsThatWereRebuilt.add(depPath)
} catch (err: any) { // eslint-disable-line
} catch (err: unknown) {
assert(util.types.isNativeError(err))
if (pkgSnapshot.optional) {
// TODO: add parents field to the log
skippedOptionalDependencyLogger.debug({
Expand Down
13 changes: 9 additions & 4 deletions exec/plugin-commands-rebuild/src/recursive.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import assert from 'assert'
import util from 'util'
import {
type RecursiveSummary,
throwOnCommandFail,
Expand Down Expand Up @@ -142,20 +144,23 @@ export async function recursiveRebuild (
}
)
result[rootDir].status = 'passed'
} catch (err: any) { // eslint-disable-line
logger.info(err)
} catch (err: unknown) {
assert(util.types.isNativeError(err))
const errWithPrefix = Object.assign(err, {
prefix: rootDir,
})
logger.info(errWithPrefix)

if (!opts.bail) {
result[rootDir] = {
status: 'failure',
error: err,
error: errWithPrefix,
message: err.message,
prefix: rootDir,
}
return
}

err['prefix'] = rootDir
throw err
}
})
Expand Down
5 changes: 3 additions & 2 deletions exec/plugin-commands-script-runners/src/dlx.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import fs from 'fs'
import path from 'path'
import util from 'util'
import { docsUrl } from '@pnpm/cli-utils'
import { OUTPUT_OPTIONS } from '@pnpm/common-cli-options-help'
import { type Config, types } from '@pnpm/config'
Expand Down Expand Up @@ -110,8 +111,8 @@ export async function handler (
stdio: 'inherit',
shell: opts.shellMode ?? false,
})
} catch (err: any) { // eslint-disable-line
if (err.exitCode != null) {
} catch (err: unknown) {
if (util.types.isNativeError(err) && 'exitCode' in err && err.exitCode != null) {
return {
exitCode: err.exitCode,
}
Expand Down
2 changes: 1 addition & 1 deletion exec/plugin-commands-script-runners/src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ so you may run "pnpm -w run ${scriptName}"`,
const _runScript = runScript.bind(null, { manifest, lifecycleOpts, runScriptOptions: { enablePrePostScripts: opts.enablePrePostScripts ?? false }, passedThruArgs })

await Promise.all(specifiedScripts.map(script => limitRun(() => _runScript(script))))
} catch (err: any) { // eslint-disable-line
} catch (err: unknown) {
if (opts.bail !== false) {
throw err
}
Expand Down
11 changes: 8 additions & 3 deletions exec/plugin-commands-script-runners/src/runRecursive.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import assert from 'assert'
import path from 'path'
import util from 'util'
import { throwOnCommandFail } from '@pnpm/cli-utils'
import { type Config } from '@pnpm/config'
import { PnpmError } from '@pnpm/error'
Expand Down Expand Up @@ -140,7 +142,8 @@ export async function runRecursive (
groupEnd?.()
result[prefix].status = 'passed'
result[prefix].duration = getExecutionDuration(startTime)
} catch (err: any) { // eslint-disable-line
} catch (err: unknown) {
assert(util.types.isNativeError(err))
result[prefix] = {
status: 'failure',
duration: getExecutionDuration(startTime),
Expand All @@ -153,8 +156,10 @@ export async function runRecursive (
return
}

err['code'] = 'ERR_PNPM_RECURSIVE_RUN_FIRST_FAIL'
err['prefix'] = prefix
Object.assign(err, {
code: 'ERR_PNPM_RECURSIVE_RUN_FIRST_FAIL',
prefix,
})
opts.reportSummary && await writeRecursiveSummary({
dir: opts.workspaceDir ?? opts.dir,
summary: result,
Expand Down
9 changes: 7 additions & 2 deletions exec/prepare-package/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import assert from 'assert'
import fs from 'fs'
import path from 'path'
import util from 'util'
import { PnpmError } from '@pnpm/error'
import { runLifecycleHook, type RunLifecycleHookOptions } from '@pnpm/lifecycle'
import { safeReadPackageJsonFromDir } from '@pnpm/read-package-json'
Expand Down Expand Up @@ -47,8 +49,11 @@ export async function preparePackage (opts: PreparePackageOptions, gitRootDir: s
// eslint-disable-next-line no-await-in-loop
await runLifecycleHook(scriptName, manifest, execOpts)
}
} catch (err: any) { // eslint-disable-line
err.code = 'ERR_PNPM_PREPARE_PACKAGE'
} catch (err: unknown) {
assert(util.types.isNativeError(err))
Object.assign(err, {
code: 'ERR_PNPM_PREPARE_PACKAGE',
})
throw err
}
await rimraf(path.join(pkgDir, 'node_modules'))
Expand Down
9 changes: 5 additions & 4 deletions fetching/directory-fetcher/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { promises as fs, type Stats } from 'fs'
import path from 'path'
import util from 'util'
import { pkgRequiresBuild } from '@pnpm/exec.pkg-requires-build'
import type { DirectoryFetcher, DirectoryFetcherOptions } from '@pnpm/fetcher-base'
import { logger } from '@pnpm/logger'
Expand Down Expand Up @@ -97,9 +98,9 @@ async function realFileStat (filePath: string): Promise<{ filePath: string, stat
filePath = await fs.realpath(filePath)
stat = await fs.stat(filePath)
return { filePath, stat }
} catch (err: any) { // eslint-disable-line @typescript-eslint/no-explicit-any
} catch (err: unknown) {
// Broken symlinks are skipped
if (err.code === 'ENOENT') {
if (util.types.isNativeError(err) && 'code' in err && err.code === 'ENOENT') {
directoryFetcherLogger.debug({ brokenSymlink: filePath })
return { filePath: null, stat: null }
}
Expand All @@ -113,9 +114,9 @@ async function fileStat (filePath: string): Promise<{ filePath: string, stat: St
filePath,
stat: await fs.stat(filePath),
}
} catch (err: any) { // eslint-disable-line @typescript-eslint/no-explicit-any
} catch (err: unknown) {
// Broken symlinks are skipped
if (err.code === 'ENOENT') {
if (util.types.isNativeError(err) && 'code' in err && err.code === 'ENOENT') {
directoryFetcherLogger.debug({ brokenSymlink: filePath })
return { filePath: null, stat: null }
}
Expand Down
Loading

0 comments on commit 0564745

Please sign in to comment.