| export function isAbsolute (path: string): boolean { |
| return /^(?:\/|[a-z]:)/i.test(normalize(path)) |
| } |
|
|
| export function normalize (path: string): string { |
| if (!path) { |
| return '' |
| } |
| |
| path = path.replace(/\\/g, '/') |
|
|
| |
| path = path.replace(/\/+/g, '/') |
|
|
| |
| const parts = path.split('/') |
| const newParts = [] |
| for (let i = 0; i < parts.length; i++) { |
| const part = parts[i] |
| if (part === '..') { |
| newParts.pop() |
| } else if (part !== '' && part !== '.') { |
| newParts.push(part) |
| } |
| } |
|
|
| |
| const result = newParts.join('/') |
|
|
| const startWithSlash = path.startsWith('/') |
| if (startWithSlash) { |
| return '/' + result |
| } else { |
| return result |
| } |
| } |
|
|
| export function join (...paths: string[]): string { |
| if (!paths.length) { |
| return '' |
| } |
| |
| let result = paths.join('/') |
|
|
| |
| result = normalize(result) |
| |
| const endsWithSlash = paths[paths.length - 1].endsWith('/') |
| if (endsWithSlash && !result.endsWith('/')) { |
| return result + '/' |
| } else { |
| return result |
| } |
| } |
|
|
|
|
| export const normalizeRelativePathToAbsolute = (relativePath: string, cwd: string) => { |
| const absolutePath = isAbsolute(relativePath) |
| ? relativePath |
| : normalize(join(cwd, relativePath)) |
| return normalize(absolutePath) |
| } |
|
|
| export const splitPath = (path: string) => { |
| path = normalize(path) |
| const frags = path.split('/').filter(v => v) |
| if (frags[0].endsWith(':')) { |
| frags[0] = frags[0] + '/' |
| } |
| return frags |
| } |
| export function getParentDirectory(filePath: string) { |
| const lastSlashIndex = filePath.lastIndexOf('/'); |
| const lastBackslashIndex = filePath.lastIndexOf('\\'); |
| const lastSeparatorIndex = Math.max(lastSlashIndex, lastBackslashIndex); |
| if (lastSeparatorIndex === -1) { |
| return '.'; |
| } |
| return filePath.substring(0, lastSeparatorIndex); |
| } |