|
| 1 | +import * as path from 'node:path' |
| 2 | +import {resolveAbsolutePath} from '../ProtectedDeletionGuard' |
| 3 | + |
| 4 | +export interface CompactedDeletionTargets { |
| 5 | + readonly files: string[] |
| 6 | + readonly dirs: string[] |
| 7 | +} |
| 8 | + |
| 9 | +function stripTrailingSeparator(rawPath: string): string { |
| 10 | + const {root} = path.parse(rawPath) |
| 11 | + if (rawPath === root) return rawPath |
| 12 | + return rawPath.endsWith(path.sep) ? rawPath.slice(0, -1) : rawPath |
| 13 | +} |
| 14 | + |
| 15 | +export function isSameOrChildDeletionPath(candidate: string, parent: string): boolean { |
| 16 | + const normalizedCandidate = stripTrailingSeparator(candidate) |
| 17 | + const normalizedParent = stripTrailingSeparator(parent) |
| 18 | + if (normalizedCandidate === normalizedParent) return true |
| 19 | + return normalizedCandidate.startsWith(`${normalizedParent}${path.sep}`) |
| 20 | +} |
| 21 | + |
| 22 | +export function compactDeletionTargets( |
| 23 | + files: readonly string[], |
| 24 | + dirs: readonly string[] |
| 25 | +): CompactedDeletionTargets { |
| 26 | + const filesByKey = new Map<string, string>() |
| 27 | + const dirsByKey = new Map<string, string>() |
| 28 | + |
| 29 | + for (const filePath of files) { |
| 30 | + const resolvedPath = resolveAbsolutePath(filePath) |
| 31 | + filesByKey.set(resolvedPath, resolvedPath) |
| 32 | + } |
| 33 | + |
| 34 | + for (const dirPath of dirs) { |
| 35 | + const resolvedPath = resolveAbsolutePath(dirPath) |
| 36 | + dirsByKey.set(resolvedPath, resolvedPath) |
| 37 | + } |
| 38 | + |
| 39 | + const compactedDirs = new Map<string, string>() |
| 40 | + const sortedDirEntries = [...dirsByKey.entries()].sort((a, b) => a[0].length - b[0].length) |
| 41 | + |
| 42 | + for (const [dirKey, dirPath] of sortedDirEntries) { |
| 43 | + let coveredByParent = false |
| 44 | + for (const existingParentKey of compactedDirs.keys()) { |
| 45 | + if (isSameOrChildDeletionPath(dirKey, existingParentKey)) { |
| 46 | + coveredByParent = true |
| 47 | + break |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + if (!coveredByParent) compactedDirs.set(dirKey, dirPath) |
| 52 | + } |
| 53 | + |
| 54 | + const compactedFiles: string[] = [] |
| 55 | + for (const [fileKey, filePath] of filesByKey) { |
| 56 | + let coveredByDir = false |
| 57 | + for (const dirKey of compactedDirs.keys()) { |
| 58 | + if (isSameOrChildDeletionPath(fileKey, dirKey)) { |
| 59 | + coveredByDir = true |
| 60 | + break |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + if (!coveredByDir) compactedFiles.push(filePath) |
| 65 | + } |
| 66 | + |
| 67 | + compactedFiles.sort((a, b) => a.localeCompare(b)) |
| 68 | + const compactedDirPaths = [...compactedDirs.values()].sort((a, b) => a.localeCompare(b)) |
| 69 | + |
| 70 | + return {files: compactedFiles, dirs: compactedDirPaths} |
| 71 | +} |
0 commit comments