import { matchDynamicName } from './matchers'; /** * Windows 환경에서 사용하는 Path 스타일을 Posix 기반으로 변경합니다. * * @example * ```ts * toPosixBasedPath(".\\index.tsx") // "./index.tsx" * toPosixBasedPath("..\\..\\index.tsx") // "../../index.tsx" * ``` */ function toPosixBasedPath(filePath: string): string { return filePath.replace(/\\/g, '/'); } /** * @name excludeFileExtension * @description fileExtension 을 제거합니다. */ export function excludeFileExtension(name: string): string { return name.replace(/\.(tsx|jsx|ts|js)$/g, ''); } /** * @name excludeRelativePath * @description path 에 상대경로를 제거합니다. * @example * ```ts * excludeRelativePath("./index.tsx") // "index.tsx" * excludeRelativePath("./list/detail.tsx") // "list/detail.tsx" * excludeRelativePath("../../index.tsx") // "index.tsx" * ``` */ export function excludeRelativePath(filePath: string): string { return filePath.replace(/^(?:\.\.?\/)+/g, ''); } /** * @name excludeDynamicNamePattern * @description dynamic route 패턴의 `[` `]` 를 제거합니다. * @example * ```ts * excludeDynamicNamePattern("[id]") // "id" * excludeDynamicNamePattern("[id]/[name]") // "id/name" * ``` */ export function excludeDynamicNamePattern(filePath: string): string { return filePath.replace(/\[|\]/g, ''); } /** * @name getRoutePath * @description route 할 path 로 변환합니다. * @example * ```ts * getRoutePath('./index.tsx') // "/" * getRoutePath('./list/index.tsx') // "/list" * getRoutePath('./list/detail.tsx') // "/list/detail" * getRoutePath('./list/[id].js') // "/list/:id" * ``` */ export function getRoutePath(filePath: string): string { const posixBasedPath = toPosixBasedPath(filePath); const normalPath = excludeRelativePath(excludeFileExtension(posixBasedPath)); const routePath = normalPath .split('/') .map((segment) => { if (segment === 'index') { return ''; } if (matchDynamicName(segment)) { return `:${excludeDynamicNamePattern(segment)}`; } return segment; }) .filter((segment) => segment.length > 0) .join('/'); return '/' + routePath; } /** * @name getFileNameFromPath * @description 파일 경로에서 파일명을 추출합니다. * @example * ```ts * getFileNameFromPath('/path/to/file.txt') // "file.txt" * getFileNameFromPath('file.txt') // "file.txt" * getFileNameFromPath('') // "" * getFileNameFromPath('/path/to/directory/') // "" * getFileNameFromPath('/path/to/file.txt', { withExtension: false }) // "file" * ``` */ export function getFileNameFromPath( filePath: string, options: { withExtension?: boolean } = { withExtension: true, } ): string { const fileName = filePath.split('/').pop() || ''; return options.withExtension ? fileName : fileName.replace(/\.[^.]+$/g, ''); }