refactor(config): return type annotations (#7915)

* refactor(config): return type annotations

* refactor: simplify configGet

* test: fix typescript errors
This commit is contained in:
Khải
2024-04-13 18:21:20 +07:00
committed by GitHub
parent 8fa4a506e5
commit ea58e1d438
17 changed files with 40 additions and 39 deletions

View File

@@ -21,17 +21,17 @@ export async function checkGlobalBinDir (
}
}
async function globalBinDirIsInPath (globalBinDir: string, env: Record<string, string | undefined>) {
async function globalBinDirIsInPath (globalBinDir: string, env: Record<string, string | undefined>): Promise<boolean> {
const dirs = env[PATH]?.split(path.delimiter) ?? []
if (dirs.some((dir) => areDirsEqual(globalBinDir, dir))) return true
const realGlobalBinDir = await fs.realpath(globalBinDir)
return dirs.some((dir) => areDirsEqual(realGlobalBinDir, dir))
}
const areDirsEqual = (dir1: string, dir2: string) =>
const areDirsEqual = (dir1: string, dir2: string): boolean =>
path.relative(dir1, dir2) === ''
function canWriteToDirAndExists (dir: string) {
function canWriteToDirAndExists (dir: string): boolean {
try {
return canWriteToDir(dir)
} catch (err: unknown) {

View File

@@ -6,7 +6,7 @@ export function getCacheDir (
env: NodeJS.ProcessEnv
platform: string
}
) {
): string {
if (opts.env.XDG_CACHE_HOME) {
return path.join(opts.env.XDG_CACHE_HOME, 'pnpm')
}
@@ -27,7 +27,7 @@ export function getStateDir (
env: NodeJS.ProcessEnv
platform: string
}
) {
): string {
if (opts.env.XDG_STATE_HOME) {
return path.join(opts.env.XDG_STATE_HOME, 'pnpm')
}
@@ -45,7 +45,7 @@ export function getDataDir (
env: NodeJS.ProcessEnv
platform: string
}
) {
): string {
if (opts.env.PNPM_HOME) {
return opts.env.PNPM_HOME
}
@@ -69,7 +69,7 @@ export function getConfigDir (
env: NodeJS.ProcessEnv
platform: string
}
) {
): string {
if (opts.env.XDG_CONFIG_HOME) {
return path.join(opts.env.XDG_CONFIG_HOME, 'pnpm')
}

View File

@@ -77,7 +77,7 @@ export function getOptionsFromRootManifest (manifestDir: string, manifest: Proje
return settings
}
function createVersionReferencesReplacer (manifest: ProjectManifest) {
function createVersionReferencesReplacer (manifest: ProjectManifest): (spec: string) => string {
const allDeps = {
...manifest.devDependencies,
...manifest.dependencies,
@@ -86,7 +86,7 @@ function createVersionReferencesReplacer (manifest: ProjectManifest) {
return replaceVersionReferences.bind(null, allDeps)
}
function replaceVersionReferences (dep: Record<string, string>, spec: string) {
function replaceVersionReferences (dep: Record<string, string>, spec: string): string {
if (!(spec[0] === '$')) return spec
const dependencyName = spec.slice(1)
const newSpec = dep[dependencyName]

View File

@@ -579,7 +579,7 @@ export async function getConfig (
return { config: pnpmConfig, warnings }
}
function getProcessEnv (env: string) {
function getProcessEnv (env: string): string | undefined {
return process.env[env] ??
process.env[env.toUpperCase()] ??
process.env[env.toLowerCase()]

View File

@@ -4,10 +4,12 @@ import camelcaseKeys from 'camelcase-keys'
import { envReplace } from '@pnpm/config.env-replace'
import { readIniFile } from 'read-ini-file'
export async function readLocalConfig (prefix: string) {
export type LocalConfig = Record<string, string> & { hoist?: boolean }
export async function readLocalConfig (prefix: string): Promise<LocalConfig> {
try {
const ini = await readIniFile(path.join(prefix, '.npmrc')) as Record<string, string>
const config = camelcaseKeys(ini) as (Record<string, string> & { hoist?: boolean })
const config = camelcaseKeys(ini) as LocalConfig
if (config.shamefullyFlatten) {
config.hoistPattern = '*'
// TODO: print a warning

View File

@@ -18,7 +18,7 @@ export function checkEngine (
packageId: string,
wantedEngine: WantedEngine,
currentEngine: Engine
) {
): UnsupportedEngineError | null {
if (!wantedEngine) return null
const unsatisfiedWanted: WantedEngine = {}
if (wantedEngine.node && !semver.satisfies(currentEngine.node, wantedEngine.node, { includePrerelease: true })) {

View File

@@ -19,7 +19,7 @@ export function checkPlatform (
packageId: string,
wantedPlatform: WantedPlatform,
supportedArchitectures?: SupportedArchitectures
) {
): UnsupportedPlatformError | null {
const current = {
os: dedupeCurrent(process.platform, supportedArchitectures?.os ?? ['current']),
cpu: dedupeCurrent(process.arch, supportedArchitectures?.cpu ?? ['current']),
@@ -82,6 +82,6 @@ function checkList (value: string | string[], list: string | string[]): boolean
return match || blc === list.length
}
function dedupeCurrent (current: string, supported: string[]) {
function dedupeCurrent (current: string, supported: string[]): string[] {
return supported.map((supported) => supported === 'current' ? current : supported)
}

View File

@@ -1,7 +1,7 @@
import mem from 'mem'
import * as execa from 'execa'
export function getSystemNodeVersionNonCached () {
export function getSystemNodeVersionNonCached (): string {
// @ts-expect-error
if (process['pkg'] != null) {
return execa.sync('node', ['--version']).stdout.toString()

View File

@@ -4,17 +4,16 @@ import { parseWantedDependency } from '@pnpm/parse-wanted-dependency'
const DELIMITER_REGEX = /[^ |@]>/
export interface VersionOverride {
parentPkg?: {
name: string
pref?: string
}
targetPkg: {
name: string
pref?: string
}
parentPkg?: PackageSelector
targetPkg: PackageSelector
newPref: string
}
export interface PackageSelector {
name: string
pref?: string
}
export function parseOverrides (
overrides: Record<string, string>
): VersionOverride[] {
@@ -38,7 +37,7 @@ export function parseOverrides (
})
}
function parsePkgSelector (selector: string) {
function parsePkgSelector (selector: string): PackageSelector {
const wantedDep = parseWantedDependency(selector)
if (!wantedDep.alias) {
throw new PnpmError('INVALID_SELECTOR', `Cannot parse the "${selector}" selector`)

View File

@@ -1,6 +1,6 @@
import { type Registries } from '@pnpm/types'
export function pickRegistryForPackage (registries: Registries, packageName: string, pref?: string) {
export function pickRegistryForPackage (registries: Registries, packageName: string, pref?: string): string {
const scope = getScope(packageName, pref)
return (scope && registries[scope]) ?? registries.default
}

View File

@@ -6,11 +6,11 @@ import { configSet } from './configSet'
import { configList } from './configList'
import { type ConfigCommandOptions } from './ConfigCommandOptions'
export function rcOptionsTypes () {
export function rcOptionsTypes (): Record<string, unknown> {
return {}
}
export function cliOptionsTypes () {
export function cliOptionsTypes (): Record<string, unknown> {
return {
global: Boolean,
location: ['global', 'project'],
@@ -20,7 +20,7 @@ export function cliOptionsTypes () {
export const commandNames = ['config', 'c']
export function help () {
export function help (): string {
return renderHelp({
description: 'Manage the pnpm configuration files.',
descriptionLists: [
@@ -75,7 +75,7 @@ export function help () {
})
}
export async function handler (opts: ConfigCommandOptions, params: string[]) {
export async function handler (opts: ConfigCommandOptions, params: string[]): Promise<string | undefined> {
if (params.length === 0) {
throw new PnpmError('CONFIG_NO_SUBCOMMAND', 'Please specify the subcommand', {
hint: help(),
@@ -99,9 +99,9 @@ export async function handler (opts: ConfigCommandOptions, params: string[]) {
key = parts.shift()!
value = parts.join('=')
}
return configSet(opts, key, value ?? '')
return configSet(opts, key, value ?? '') as Promise<undefined>
} else {
return configSet(opts, params[1], null)
return configSet(opts, params[1], null) as Promise<undefined>
}
}
case 'get': {

View File

@@ -1,6 +1,6 @@
import { type ConfigCommandOptions } from './ConfigCommandOptions'
export function configGet (opts: ConfigCommandOptions, key: string) {
export function configGet (opts: ConfigCommandOptions, key: string): string {
const config = opts.rawConfig[key]
return typeof config === 'boolean' ? config.toString() : config
return String(config)
}

View File

@@ -2,7 +2,7 @@ import { encode } from 'ini'
import sortKeys from 'sort-keys'
import { type ConfigCommandOptions } from './ConfigCommandOptions'
export async function configList (opts: ConfigCommandOptions) {
export async function configList (opts: ConfigCommandOptions): Promise<string> {
const sortedConfig = sortKeys(opts.rawConfig)
if (opts.json) {
return JSON.stringify(sortedConfig, null, 2)

View File

@@ -5,7 +5,7 @@ import { readIniFile } from 'read-ini-file'
import { writeIniFile } from 'write-ini-file'
import { type ConfigCommandOptions } from './ConfigCommandOptions'
export async function configSet (opts: ConfigCommandOptions, key: string, value: string | null) {
export async function configSet (opts: ConfigCommandOptions, key: string, value: string | null): Promise<void> {
const configPath = opts.global ? path.join(opts.configDir, 'rc') : path.join(opts.dir, '.npmrc')
if (opts.global && settingShouldFallBackToNpm(key)) {
const _runNpm = runNpm.bind(null, opts.npmPath)

View File

@@ -7,6 +7,6 @@ export const help = configCmd.help
export const commandNames = ['get']
export async function handler (opts: ConfigCommandOptions, params: string[]) {
export async function handler (opts: ConfigCommandOptions, params: string[]): Promise<string | undefined> {
return configCmd.handler(opts, ['get', ...params])
}

View File

@@ -7,6 +7,6 @@ export const help = configCmd.help
export const commandNames = ['set']
export async function handler (opts: ConfigCommandOptions, params: string[]) {
export async function handler (opts: ConfigCommandOptions, params: string[]): Promise<string | undefined> {
return configCmd.handler(opts, ['set', ...params])
}

View File

@@ -17,7 +17,7 @@ test('config list', async () => {
},
}, ['list'])
expect(normalizeNewlines(output)).toEqual(`fetch-retries=2
expect(normalizeNewlines(output!)).toEqual(`fetch-retries=2
store-dir=~/store
`)
})