Skip to content

Commit

Permalink
chore: refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Aug 19, 2024
1 parent 59672f5 commit 23e67f1
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 69 deletions.
26 changes: 16 additions & 10 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import process from 'node:process'
import fs from 'node:fs/promises'
import { existsSync } from 'node:fs'
import { relative, resolve } from 'node:path'
import { types } from 'node:util'

import open from 'open'
import { getPort } from 'get-port-please'
Expand All @@ -13,6 +12,7 @@ import { createHostServer } from './server'
import { distDir } from './dirs'
import { readConfig } from './configs'
import { MARK_CHECK, MARK_INFO } from './constants'
import { ConfigInspectorError } from './errors'

const cli = cac(
'eslint-config-inspector',
Expand All @@ -35,16 +35,22 @@ cli

const cwd = process.cwd()
const outDir = resolve(cwd, options.outDir)
const configs = await readConfig({
cwd,
userConfigPath: options.config,
userBasePath: options.basePath,
globMatchedFiles: options.files,
})

if (types.isNativeError(configs)) {
configs.prettyPrint()
process.exit(1)
let configs
try {
configs = await readConfig({
cwd,
userConfigPath: options.config,
userBasePath: options.basePath,
globMatchedFiles: options.files,
})
}
catch (error) {
if (error instanceof ConfigInspectorError) {
error.prettyPrint()
process.exit(1)
}
throw error
}

let baseURL = options.base
Expand Down
60 changes: 11 additions & 49 deletions src/configs.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { basename, dirname, relative, resolve } from 'node:path'
import process from 'node:process'
import { types } from 'node:util'
import { ConfigArray } from '@eslint/config-array'
import { configArrayFindFiles } from '@voxpelli/config-array-find-files'
import { bundleRequire } from 'bundle-require'
Expand All @@ -9,7 +8,8 @@ import c from 'picocolors'
import { resolve as resolveModule } from 'mlly'
import type { FlatConfigItem, MatchedFile, Payload, RuleInfo } from '../shared/types'
import { isIgnoreOnlyConfig, matchFile } from '../shared/configs'
import { MARK_CHECK, MARK_ERROR, MARK_INFO, configFilenames, legacyConfigFilenames } from './constants'
import { MARK_CHECK, MARK_INFO, configFilenames, legacyConfigFilenames } from './constants'
import { ConfigPathError, ConfigPathLegacyError } from './errors'

export interface ReadConfigOptions extends ResolveConfigPathOptions {
/**
Expand Down Expand Up @@ -41,47 +41,6 @@ export interface ResolveConfigPathOptions {
userBasePath?: string
}

export class ConfigPathError extends Error {
override name = 'ConfigPathError' as const

constructor(
public basePath: string,
public configFilenames: string[],
) {
super('Cannot find ESLint config file')
}

prettyPrint() {
console.error(MARK_ERROR, this.message, c.dim(`
Looked in ${c.underline(this.basePath)} and parent folders for:
* ${this.configFilenames.join('\n * ')}`,
))
}
}

export class ConfigPathLegacyError extends Error {
override name = 'ConfigPathLegacyError' as const

constructor(
public basePath: string,
public configFilename: string,
) {
super('Found ESLint legacy config file')
}

prettyPrint() {
console.error(MARK_ERROR, this.message, c.dim(`
Encountered unsupported legacy config ${c.underline(this.configFilename)} in ${c.underline(this.basePath)}
\`@eslint/config-inspector\` only works with the new flat config format:
https://eslint.org/docs/latest/use/configure/configuration-files-new`,
))
}
}

/**
* Search and read the ESLint config file.
*
Expand All @@ -108,7 +67,7 @@ export async function resolveConfigPath(options: ResolveConfigPathOptions) {
if (!configPath) {
const legacyConfigPath = await findUp(legacyConfigFilenames, { cwd: lookupBasePath })

return legacyConfigPath
throw legacyConfigPath
? new ConfigPathLegacyError(
`${relative(cwd, dirname(legacyConfigPath))}/`,
basename(legacyConfigPath),
Expand All @@ -124,12 +83,19 @@ export async function resolveConfigPath(options: ResolveConfigPathOptions) {
? cwd // When user explicit provide config path, use current working directory as root
: dirname(configPath) // Otherwise, use config file's directory as root
)

return {
basePath,
configPath,
}
}

export interface ESLintConfig {
configs: FlatConfigItem[]
payload: Payload
dependencies: string[]
}

/**
* Search and read the ESLint config file, processed into inspector payload with module dependencies
*
Expand All @@ -140,18 +106,14 @@ export async function resolveConfigPath(options: ResolveConfigPathOptions) {
*/
export async function readConfig(
options: ReadConfigOptions,
): Promise<ConfigPathLegacyError | ConfigPathError | { configs: FlatConfigItem[], payload: Payload, dependencies: string[] }> {
): Promise<ESLintConfig> {
const {
chdir = true,
globMatchedFiles: globFiles = true,
} = options

const resolvedConfigPath = await resolveConfigPath(options)

if (types.isNativeError(resolvedConfigPath)) {
return resolvedConfigPath
}

const { basePath, configPath } = resolvedConfigPath
if (chdir && basePath !== process.cwd())
process.chdir(basePath)
Expand Down
49 changes: 49 additions & 0 deletions src/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import c from 'picocolors'
import { MARK_ERROR } from './constants'

export class ConfigInspectorError extends Error {
prettyPrint() {
console.error(MARK_ERROR, this.message)
}
}

export class ConfigPathError extends ConfigInspectorError {
override name = 'ConfigPathError' as const

constructor(
public basePath: string,
public configFilenames: string[],
) {
super('Cannot find ESLint config file')
}

override prettyPrint() {
console.error(MARK_ERROR, this.message, c.dim(`
Looked in ${c.underline(this.basePath)} and parent folders for:
* ${this.configFilenames.join('\n * ')}`,
))
}
}

export class ConfigPathLegacyError extends ConfigInspectorError {
override name = 'ConfigPathLegacyError' as const

constructor(
public basePath: string,
public configFilename: string,
) {
super('Found ESLint legacy config file')
}

override prettyPrint() {
console.error(MARK_ERROR, this.message, c.dim(`
Encountered unsupported legacy config ${c.underline(this.configFilename)} in ${c.underline(this.basePath)}
\`@eslint/config-inspector\` only works with the new flat config format:
https://eslint.org/docs/latest/use/configure/configuration-files-new`,
))
}
}
29 changes: 19 additions & 10 deletions src/ws.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import process from 'node:process'
import { types } from 'node:util'

import chokidar from 'chokidar'
import type { WebSocket } from 'ws'
Expand All @@ -8,6 +7,7 @@ import { getPort } from 'get-port-please'
import type { ReadConfigOptions } from './configs'
import { readConfig, resolveConfigPath } from './configs'
import { MARK_CHECK } from './constants'
import { ConfigInspectorError } from './errors'
import type { Payload } from '~~/shared/types'

const readErrorWarning = `Failed to load \`eslint.config.js\`.
Expand All @@ -30,11 +30,18 @@ export async function createWsServer(options: CreateWsServerOptions) {
ws.on('close', () => wsClients.delete(ws))
})

const resolvedConfigPath = await resolveConfigPath(options)

if (types.isNativeError(resolvedConfigPath)) {
resolvedConfigPath.prettyPrint()
process.exit(1)
let resolvedConfigPath: Awaited<ReturnType<typeof resolveConfigPath>>
try {
resolvedConfigPath = await resolveConfigPath(options)
}
catch (e) {
if (e instanceof ConfigInspectorError) {
e.prettyPrint()
process.exit(1)
}
else {
throw e
}
}

const { basePath } = resolvedConfigPath
Expand Down Expand Up @@ -62,9 +69,6 @@ export async function createWsServer(options: CreateWsServerOptions) {
if (!payload) {
return await readConfig(options)
.then((res) => {
if (types.isNativeError(res)) {
throw res
}
const _payload = payload = res.payload
_payload.meta.wsPort = port
watcher.add(res.dependencies)
Expand All @@ -75,7 +79,12 @@ export async function createWsServer(options: CreateWsServerOptions) {
}
catch (e) {
console.error(readErrorWarning)
console.error(e)
if (e instanceof ConfigInspectorError) {
e.prettyPrint()
}
else {
console.error(e)
}
return {
message: readErrorWarning,
error: String(e),
Expand Down

0 comments on commit 23e67f1

Please sign in to comment.