Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

fileLinks.ts

215 lines7.5 KB

1import {
2 fileBasename,
3 isAbsolutePath,
4 isPosixAbsolutePath,
5 isWindowsAbsolutePath,
6 stripSlashPrefixedWindowsDrive,
7} from "./path.ts";
8​
9const POSITION_SUFFIX_CAPTURE_PATTERN = /:(\d+)(?::(\d+)|-(\d+))?$/;
10​
11const POSITION_HASH_PATTERN = /^#L(\d+)(?:C(\d+)|-L?(\d+))?$/i;
12​
13/**
14 * Keeps paths percent-encoded to avoid double decoding. `localhost` and `localHostname` (the
15 * machine the path lives on) are local authorities; any other becomes a UNC share.
16 */
17export function parseFileUrlHref(
18 href: string,
19 localHostname?: string,
20): { readonly path: string; readonly hash: string } | null {
21 // Chromium on Windows parses any one-letter scheme as a drive letter
22 // (`new URL("d:x")` is `file:///D:/x`), so the protocol check alone would turn
23 // such links into file links only on Windows.
24 if (!href.trim().toLowerCase().startsWith("file:")) return null;
25 try {
26 const parsed = new URL(href);
27 if (parsed.protocol.toLowerCase() !== "file:") return null;
28​
29 const host = parsed.hostname.toLowerCase();
30 let localHost = "";
31 if (host && localHostname) {
32 try {
33 localHost = new URL(`file://${encodeURIComponent(localHostname)}/`).hostname;
34 } catch {
35 // System hostnames need not be valid URL authorities; they cannot match a file URI.
36 }
37 }
38 const uncHostname = host === "localhost" || host === localHost ? "" : parsed.hostname;
39 const path = uncHostname
40 ? `\\\\${uncHostname}${parsed.pathname.replaceAll("/", "\\")}`
41 : parsed.pathname;
42 if (path.length === 0) return null;
43 return { path: stripSlashPrefixedWindowsDrive(quoteStrayPercents(path)), hash: parsed.hash };
44 } catch {
45 return null;
46 }
48​
49// URL parsing keeps a literal `%` (`100%/`), which would stop the escapes beside it decoding.
50// A path that still cannot decode (`%FF`) keeps its original spelling for callers' fallback.
51function quoteStrayPercents(path: string): string {
52 const quoted = path.replace(/%(?![0-9A-Fa-f]{2})/g, "%25");
53 try {
54 decodeURIComponent(quoted);
55 return quoted;
56 } catch {
57 return path;
58 }
60​
61export interface FilePathPosition {
62 readonly path: string;
63 readonly line?: number;
64 readonly column?: number;
65 /** The last line of a range such as `:42-64`. Editors open at `line`. */
66 readonly endLine?: number;
68​
69export function splitFilePathPosition(path: string, hash = ""): FilePathPosition {
70 const suffixMatch = path.match(POSITION_SUFFIX_CAPTURE_PATTERN);
71 const match = suffixMatch ?? hash.match(POSITION_HASH_PATTERN);
72 if (!match?.[1]) return { path };
73​
74 const line = Number.parseInt(match[1], 10);
75 const column = match[2] === undefined ? undefined : Number.parseInt(match[2], 10);
76 const endLine = match[3] === undefined ? undefined : Number.parseInt(match[3], 10);
77 return {
78 path: suffixMatch ? path.slice(0, -suffixMatch[0].length) : path,
79 ...(line > 0 ? { line } : {}),
80 ...(column !== undefined && column > 0 ? { column } : {}),
81 ...(line > 0 && endLine !== undefined && endLine > line ? { endLine } : {}),
82 };
84​
85export function formatFilePathPosition(position: FilePathPosition): string {
86 if (!position.line) return position.path;
87 return `${position.path}:${position.line}${position.column ? `:${position.column}` : ""}`;
89​
90export function joinPath(base: string, next: string, separator: "/" | "\\"): string {
91 if (separator === "\\") {
92 const cleanBase = base.replace(/[\\/]+$/, "");
93 return `${cleanBase}\\${next.replaceAll("/", "\\")}`;
94 }
95 const cleanBase = base.replace(/\/+$/, "");
96 return `${cleanBase}/${next.replace(/^\/+/, "")}`;
98​
99function inferHomeFromCwd(cwd: string): string | undefined {
100 const posixUser = cwd.match(/^\/Users\/([^/]+)/);
101 if (posixUser?.[1]) {
102 return `/Users/${posixUser[1]}`;
103 }
104​
105 const posixHome = cwd.match(/^\/home\/([^/]+)/);
106 if (posixHome?.[1]) {
107 return `/home/${posixHome[1]}`;
108 }
109​
110 const windowsUser = cwd.match(/^([A-Za-z]:[\\/]Users[\\/][^\\/]+)/i);
111 if (windowsUser?.[1]) {
112 return windowsUser[1];
113 }
114​
115 return undefined;
117​
118export function resolvePathLinkTarget(rawPath: string, cwd: string): string {
119 const position = splitFilePathPosition(rawPath);
120 const { path } = position;
121​
122 let resolvedPath = path;
123 if (path.startsWith("~/") || (isWindowsAbsolutePath(cwd) && path.startsWith("~\\"))) {
124 const home = inferHomeFromCwd(cwd);
125 if (home) {
126 const separator: "/" | "\\" = isWindowsAbsolutePath(home) ? "\\" : "/";
127 resolvedPath = joinPath(home, path.slice(2), separator);
128 }
129 } else if (!isAbsolutePath(path)) {
130 const separator: "/" | "\\" = isWindowsAbsolutePath(cwd) ? "\\" : "/";
131 resolvedPath = joinPath(cwd, path.replace(/^(?:\.\/)+/, ""), separator);
132 }
133​
134 return formatFilePathPosition({ ...position, path: resolvedPath });
136​
137function fileLinkPathKey(path: string): string {
138 return isPosixAbsolutePath(path) ? path : path.replaceAll("\\", "/");
140​
141function pathParentSegments(pathKey: string): string[] {
142 const segments = pathKey.split("/").filter((segment) => segment.length > 0);
143 return segments.slice(0, -1);
145​
146export function buildFileLinkParentSuffixByPath(
147 filePaths: ReadonlyArray<string>,
148): Map<string, string> {
149 const groups = new Map<string, Set<string>>();
150 for (const filePath of filePaths) {
151 const pathKey = fileLinkPathKey(filePath);
152 const pathSegments = pathKey.split("/").filter((segment) => segment.length > 0);
153 // Group by the composed name the label shows, so NFC and NFD spellings get suffixes.
154 const basename = pathSegments[pathSegments.length - 1]?.normalize("NFC");
155 if (!basename) continue;
156 const group = groups.get(basename) ?? new Set<string>();
157 group.add(pathKey);
158 groups.set(basename, group);
159 }
160​
161 const suffixByPath = new Map<string, string>();
162 for (const group of groups.values()) {
163 const uniquePaths = [...group];
164 if (uniquePaths.length < 2) continue;
165​
166 // Compare folders as displayed so canonically equivalent names reach a deeper suffix.
167 const parentSegmentsByPath = new Map(
168 uniquePaths.map((filePath) => [filePath, pathParentSegments(filePath.normalize("NFC"))]),
169 );
170 const suffixCounts = new Map<string, number>();
171 for (const segments of parentSegmentsByPath.values()) {
172 for (let depth = 1; depth <= segments.length; depth += 1) {
173 const suffix = segments.slice(-depth).join("/");
174 suffixCounts.set(suffix, (suffixCounts.get(suffix) ?? 0) + 1);
175 }
176 }
177​
178 for (const filePath of uniquePaths) {
179 const segments = parentSegmentsByPath.get(filePath) ?? [];
180 let resolvedDepth = segments.length;
181 for (let depth = 1; depth <= segments.length; depth += 1) {
182 const candidate = segments.slice(-depth).join("/");
183 if (suffixCounts.get(candidate) === 1) {
184 resolvedDepth = depth;
185 break;
186 }
187 }
188 if (segments.length === 0) continue;
189 const suffixDepth = Math.min(segments.length, Math.max(resolvedDepth, 2));
190 suffixByPath.set(filePath, segments.slice(-suffixDepth).join("/"));
191 }
192 }
193​
194 return suffixByPath;
196​
197export function fileLinkLabel(
198 file: FilePathPosition,
199 parentSuffixByPath: ReadonlyMap<string, string>,
200): string {
201 const suffix = parentSuffixByPath.get(fileLinkPathKey(file.path));
202 return (
203 [
204 fileBasename(file.path),
205 suffix,
206 file.line
207 ? `L${file.line}${file.endLine ? `–${file.endLine}` : file.column ? `:C${file.column}` : ""}`
208 : undefined,
209 ]
210 .filter(Boolean)
211 .join(" · ")
212 // macOS stores many names in NFD; compose them for display only.
213 .normalize("NFC")
214 );