(pathA: string, pathB: string)
| 20 | * returns `undefined`. |
| 21 | */ |
| 22 | export function longestCommonPathPrefix(pathA: string, pathB: string): string | undefined { |
| 23 | if (!path.isAbsolute(pathA) || !path.isAbsolute(pathB)) { |
| 24 | throw new Error('longestCommonPathPrefix expects absolute paths') |
| 25 | } |
| 26 | |
| 27 | if (process.platform === 'win32' && (pathA.startsWith('\\\\') || pathB.startsWith('\\\\'))) { |
| 28 | // Make both paths namespaced if at least one of them is. |
| 29 | pathA = path.toNamespacedPath(pathA) |
| 30 | pathB = path.toNamespacedPath(pathB) |
| 31 | } |
| 32 | |
| 33 | const commonPrefix = longestCommonPrefix(pathA.split(path.sep), pathB.split(path.sep)).join(path.sep) |
| 34 | |
| 35 | if (commonPrefix === '') { |
| 36 | return process.platform === 'win32' ? undefined : '/' |
| 37 | } |
| 38 | |
| 39 | if (process.platform === 'win32' && ['\\', '\\\\?', '\\\\.'].includes(commonPrefix)) { |
| 40 | return undefined |
| 41 | } |
| 42 | |
| 43 | if (process.platform === 'win32' && commonPrefix.endsWith(':')) { |
| 44 | // Disk specifier without a backslash at the end is not an absolute path on windows, |
| 45 | // it refers to current working directory on that disk. |
| 46 | return commonPrefix + '\\' |
| 47 | } |
| 48 | |
| 49 | return commonPrefix |
| 50 | } |
| 51 | |
| 52 | function longestCommonPrefix<T>(sequenceA: T[], sequenceB: T[]): T[] { |
| 53 | const maxLen = Math.min(sequenceA.length, sequenceB.length) |
no test coverage detected