import { statSync } from "node:fs" import { dirname, isAbsolute, join, resolve } from "node:path" export const getCurrentWorkingDirectory = (): string => { return process.cwd() } export interface ResolveFriendlyOptions { startPath?: string | undefined } /** * @description 解析 `startPath`,返回一个绝对路径。 * - 如果 `startPath` 未定义,则返回当前工作目录。 * - 如果 `startPath` 是一个绝对路径,则直接返回它。 * - 否则,将 `startPath` 视为相对于当前工作目录的路径,并返回解析后的绝对路径。 */ export const resolveStartPath = (options: ResolveFriendlyOptions): string => { const { startPath } = options if (startPath === undefined) { return getCurrentWorkingDirectory() } if (isAbsolute(startPath)) { return startPath } return resolve(join(getCurrentWorkingDirectory(), startPath)) } /** * @description 解析 `startPath`,返回一个绝对路径,且保证该路径是一个目录。 * - 如果 `startPath` 未定义,则返回当前工作 directory。 * - 如果 `startPath` 是一个绝对路径,且它是一个目录,则直接返回它。 * - 如果 `startPath` 是一个绝对路径,但它不是一个目录,则将其父目录作为结果返回。 * - 否则,将 `startPath` 视为相对于当前工作目录的路径,并返回解析后的绝对路径, * 且保证该路径是一个目录(如果解析后的路径不是一个目录,则返回其父目录)。 */ export const resolveStartDirectory = (options: ResolveFriendlyOptions): string => { const startPath = resolveStartPath(options) try { const stat = statSync(startPath) if (stat.isDirectory()) { return startPath } } catch { // 如果路径不存在,则按“不是目录”处理并回退到父目录。 } return dirname(startPath) } export interface ResolveAbsolutePathOptions { path: string basePath?: string | undefined } /** * @description 解析一个路径,返回一个绝对路径。 * - 如果 `path` 是一个绝对路径,则直接返回它。 * - 否则,将 `path` 视为相对于 `basePath` 的路径,并返回解析后的绝对路径。 * 如果 `basePath` 未定义,则使用当前工作目录作为 `basePath`。 */ export const resolveAbsolutePath = (options: ResolveAbsolutePathOptions): string => { const { path, basePath } = options if (isAbsolute(path)) { return path } const base = basePath ?? getCurrentWorkingDirectory() return resolve(join(base, path)) }