import path from 'node:path' import { fileURLToPath } from 'node:url' import ansis from 'ansis' import { up } from 'empathic/package' import { x } from 'tinyexec' import type { Callbackable, Context } from './types.ts' export const COLORS = [ 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray', 'redBright', 'greenBright', 'yellowBright', 'blueBright', 'magentaBright', 'cyanBright', 'whiteBright', 'bgBlack', 'bgRed', 'bgGreen', 'bgYellow', 'bgBlue', 'bgMagenta', 'bgCyan', 'bgWhite', 'bgGray', 'bgRedBright', 'bgGreenBright', 'bgYellowBright', 'bgBlueBright', 'bgMagentaBright', 'bgCyanBright', 'bgWhiteBright', ] as const function isColor(color: string): color is (typeof COLORS)[number] { return COLORS.includes(color as any) } export function getColor(color?: string): (text: string) => string { if (!color) return (v) => v else if (isColor(color)) return ansis[color] else if (color.startsWith('#')) return ansis.hex(color) throw new Error(`Unknown color: ${color}`) } export async function which(command: string): Promise { try { const { exitCode } = await x('which', [command]) return exitCode! } catch (error: any) { return error.exitCode } } export async function cmdExists(command: string): Promise { const code = await which(command) return code === 0 } export function findConfigTypePath(): string { const filename = fileURLToPath(import.meta.url) const pkgPath = path.dirname(up({ cwd: filename })!) return pkgPath } // eslint-disable-next-line require-await export async function resolveCallbackable( cb: Callbackable, context: Context, ): Promise { if (typeof cb === 'function') { return (cb as any)(context) } return cb } export function resolveCallbackables( cbs: Callbackable[], context: Context, ): Promise { return Promise.all(cbs.map((cb) => resolveCallbackable(cb, context))) } export class CliError extends Error { constructor(message: string, options?: ErrorOptions) { super(message, options) this.name = 'CliError' } }