| 1 | import * as URI from "uri-js"; |
| 2 | |
| 3 | /** Converts any OS path to cleaned up URI path segment format with no leading/trailing slashes |
| 4 | e.g. \path\to\folder\ -> path/to/folder |
| 5 | \this\is\afile.ts -> this/is/afile.ts |
| 6 | is/already/clean -> is/already/clean |
| 7 | **/ |
| 8 | export function pathToUriPathSegment(path: string) { |
| 9 | let clean = path.replace(/[\\]/g, "/"); // backslashes -> forward slashes |
| 10 | clean = clean.replace(/^\//, ""); // remove start slash |
| 11 | clean = clean.replace(/\/$/, ""); // remove end slash |
| 12 | return clean |
| 13 | .split("/") |
| 14 | .map((part) => encodeURIComponent(part)) |
| 15 | .join("/"); |
| 16 | } |
| 17 | |
| 18 | export function getCleanUriPath(uri: string) { |
| 19 | const path = URI.parse(uri).path ?? ""; |
| 20 | let clean = path.replace(/^\//, ""); // remove start slash |
| 21 | clean = clean.replace(/\/$/, ""); // remove end slash |
| 22 | return clean; |
| 23 | } |
| 24 | |
| 25 | export function findUriInDirs( |
| 26 | uri: string, |
| 27 | dirUriCandidates: string[], |
| 28 | ): { |
| 29 | uri: string; |
| 30 | relativePathOrBasename: string; |
| 31 | foundInDir: string | null; |
| 32 | } { |
| 33 | const uriComps = URI.parse(uri); |
| 34 | if (!uriComps.scheme) { |
| 35 | throw new Error(`Invalid uri: ${uri}`); |
| 36 | } |
| 37 | const uriPathParts = getCleanUriPath(uri).split("/"); |
| 38 | |
| 39 | for (const dir of dirUriCandidates) { |
| 40 | const dirComps = URI.parse(dir); |
| 41 | |
| 42 | if (!dirComps.scheme) { |
| 43 | throw new Error(`Invalid uri: ${dir}`); |
| 44 | } |
| 45 | |
| 46 | if (uriComps.scheme !== dirComps.scheme) { |
| 47 | continue; |
| 48 | } |
| 49 | // Can't just use startsWith because e.g. |
| 50 | // file:///folder/file is not within file:///fold |
| 51 | |
| 52 | // At this point we break the path up and check if each dir path part matches |
| 53 | const dirPathParts = getCleanUriPath(dir).split("/"); |
| 54 | |
| 55 | if (uriPathParts.length < dirPathParts.length) { |
| 56 | continue; |
| 57 | } |
| 58 | let allDirPartsMatch = true; |
| 59 | for (let i = 0; i < dirPathParts.length; i++) { |
| 60 | if (dirPathParts[i] !== uriPathParts[i]) { |
| 61 | allDirPartsMatch = false; |
| 62 | } |
| 63 | } |
| 64 | if (allDirPartsMatch) { |
| 65 | const relativePath = uriPathParts |
| 66 | .slice(dirPathParts.length) |
| 67 | .map(decodeURIComponent) |
| 68 | .join("/"); |
| 69 | return { |
| 70 | uri, |
| 71 | relativePathOrBasename: relativePath, |
| 72 | foundInDir: dir, |
| 73 | }; |
| 74 | } |
| 75 | } |
| 76 | // Not found |
| 77 | return { |
| 78 | uri, |
| 79 | relativePathOrBasename: getUriPathBasename(uri), |
| 80 | foundInDir: null, |
| 81 | }; |
| 82 | } |
| 83 | |
| 84 | /* |
| 85 | Returns just the file or folder name of a URI |
| 86 | */ |
| 87 | export function getUriPathBasename(uri: string): string { |
| 88 | const path = getCleanUriPath(uri); |
| 89 | const basename = path.split("/").pop() || ""; |
| 90 | return decodeURIComponent(basename); |
| 91 | } |
| 92 | |
| 93 | export function getFileExtensionFromBasename(basename: string) { |
| 94 | const parts = basename.split("."); |
| 95 | if (parts.length < 2) { |
| 96 | return ""; |
| 97 | } |
| 98 | return (parts.slice(-1)[0] ?? "").toLowerCase(); |
| 99 | } |
| 100 | |
| 101 | /* |
| 102 | Returns the file extension of a URI |
| 103 | */ |
| 104 | export function getUriFileExtension(uri: string) { |
| 105 | const baseName = getUriPathBasename(uri); |
| 106 | return getFileExtensionFromBasename(baseName); |
| 107 | } |
| 108 | |
| 109 | export function getLastNUriRelativePathParts( |
| 110 | dirUriCandidates: string[], |
| 111 | uri: string, |
| 112 | n: number, |
| 113 | ): string { |
| 114 | const { relativePathOrBasename } = findUriInDirs(uri, dirUriCandidates); |
| 115 | return getLastNPathParts(relativePathOrBasename, n); |
| 116 | } |
| 117 | |
| 118 | export function joinPathsToUri(uri: string, ...pathSegments: string[]) { |
| 119 | let baseUri = uri; |
| 120 | if (baseUri.at(-1) !== "/") { |
| 121 | baseUri += "/"; |
| 122 | } |
| 123 | const segments = pathSegments.map((segment) => pathToUriPathSegment(segment)); |
| 124 | return URI.resolve(baseUri, segments.join("/")); |
| 125 | } |
| 126 | |
| 127 | export function joinEncodedUriPathSegmentToUri( |
| 128 | uri: string, |
| 129 | pathSegment: string, |
| 130 | ) { |
| 131 | let baseUri = uri; |
| 132 | if (baseUri.at(-1) !== "/") { |
| 133 | baseUri += "/"; |
| 134 | } |
| 135 | return URI.resolve(baseUri, pathSegment); |
| 136 | } |
| 137 | |
| 138 | export function getShortestUniqueRelativeUriPaths( |
| 139 | uris: string[], |
| 140 | dirUriCandidates: string[], |
| 141 | ): { |
| 142 | uri: string; |
| 143 | uniquePath: string; |
| 144 | }[] { |
| 145 | // Split all URIs into segments and count occurrences of each suffix combination |
| 146 | const segmentCombinationsMap = new Map<string, number>(); |
| 147 | const segmentsInfo = uris.map((uri) => { |
| 148 | const { relativePathOrBasename } = findUriInDirs(uri, dirUriCandidates); |
| 149 | const segments = relativePathOrBasename.split("/"); |
| 150 | const suffixes: string[] = []; |
| 151 | |
| 152 | // Generate all possible suffix combinations, starting from the shortest (basename) |
| 153 | for (let i = segments.length - 1; i >= 0; i--) { |
| 154 | const suffix = segments.slice(i).join("/"); |
| 155 | suffixes.push(suffix); // Now pushing in order from shortest to longest |
| 156 | // Count occurrences of each suffix |
| 157 | segmentCombinationsMap.set( |
| 158 | suffix, |
| 159 | (segmentCombinationsMap.get(suffix) || 0) + 1, |
| 160 | ); |
| 161 | } |
| 162 | |
| 163 | return { uri, segments, suffixes, relativePathOrBasename }; |
| 164 | }); |
| 165 | // Find shortest unique path for each URI |
| 166 | return segmentsInfo.map(({ uri, suffixes, relativePathOrBasename }) => { |
| 167 | // Since suffixes are now ordered from shortest to longest, |
| 168 | // the first unique one we find will be the shortest |
| 169 | const uniquePath = |
| 170 | suffixes.find((suffix) => segmentCombinationsMap.get(suffix) === 1) ?? |
| 171 | relativePathOrBasename; // fallback to full path if no unique suffix found |
| 172 | return { uri, uniquePath }; |
| 173 | }); |
| 174 | } |
| 175 | |
| 176 | // Only used when working with system paths and relative paths |
| 177 | // Since doesn't account for URI segements before workspace |
| 178 | export function getLastNPathParts(filepath: string, n: number): string { |
| 179 | if (n <= 0) { |
| 180 | return ""; |
| 181 | } |
| 182 | return filepath.split(/[\\/]/).slice(-n).join("/"); |
| 183 | } |
| 184 | |
| 185 | export function getUriDescription(uri: string, dirUriCandidates: string[]) { |
| 186 | const { relativePathOrBasename, foundInDir } = findUriInDirs( |
| 187 | uri, |
| 188 | dirUriCandidates, |
| 189 | ); |
| 190 | const baseName = getUriPathBasename(uri); |
| 191 | const extension = getFileExtensionFromBasename(baseName); |
| 192 | const last2Parts = getLastNUriRelativePathParts(dirUriCandidates, uri, 2); |
| 193 | return { |
| 194 | uri, |
| 195 | relativePathOrBasename, |
| 196 | foundInDir, |
| 197 | last2Parts, |
| 198 | baseName, |
| 199 | extension, |
| 200 | }; |
| 201 | } |