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

fileLinks.ts

196 lines6.7 KB

1import {
2 fileBasename,
3 isAbsolutePath,
4 isWindowsAbsolutePath,
5 stripSlashPrefixedWindowsDrive,
6} from "./path.ts";
7​
8const POSITION_SUFFIX_CAPTURE_PATTERN = /:(\d+)(?::(\d+)|-(\d+))?$/;
9​
10const POSITION_HASH_PATTERN = /^#L(\d+)(?:C(\d+)|-L?(\d+))?$/i;
11​
12/**
13 * Keeps paths percent-encoded to avoid double decoding. `localhost` and `localHostname` (the
14 * machine the path lives on) are local authorities; any other becomes a UNC share.
15 */
16export function parseFileUrlHref(
17 href: string,
18 localHostname?: string,
19): { readonly path: string; readonly hash: string } | null {
20 // Chromium on Windows parses any one-letter scheme as a drive letter
21 // (`new URL("d:x")` is `file:///D:/x`), so the protocol check alone would turn
22 // such links into file links only on Windows.
23 if (!href.trim().toLowerCase().startsWith("file:")) return null;
24 try {
25 const parsed = new URL(href);
26 if (parsed.protocol.toLowerCase() !== "file:") return null;
27​
28 const host = parsed.hostname.toLowerCase();
29 let localHost = "";
30 if (host && localHostname) {
31 try {
32 localHost = new URL(`file://${encodeURIComponent(localHostname)}/`).hostname;
33 } catch {
34 // System hostnames need not be valid URL authorities; they cannot match a file URI.
35 }
36 }
37 const uncHostname = host === "localhost" || host === localHost ? "" : parsed.hostname;
38 const path = uncHostname
39 ? `\\\\${uncHostname}${parsed.pathname.replaceAll("/", "\\")}`
40 : parsed.pathname;
41 if (path.length === 0) return null;
42 return { path: stripSlashPrefixedWindowsDrive(path), hash: parsed.hash };
43 } catch {
44 return null;
45 }
47​
48export interface FilePathPosition {
49 readonly path: string;
50 readonly line?: number;
51 readonly column?: number;
52 /** The last line of a range such as `:42-64`. Editors open at `line`. */
53 readonly endLine?: number;
55​
56export function splitFilePathPosition(path: string, hash = ""): FilePathPosition {
57 const suffixMatch = path.match(POSITION_SUFFIX_CAPTURE_PATTERN);
58 const match = suffixMatch ?? hash.match(POSITION_HASH_PATTERN);
59 if (!match?.[1]) return { path };
60​
61 const line = Number.parseInt(match[1], 10);
62 const column = match[2] === undefined ? undefined : Number.parseInt(match[2], 10);
63 const endLine = match[3] === undefined ? undefined : Number.parseInt(match[3], 10);
64 return {
65 path: suffixMatch ? path.slice(0, -suffixMatch[0].length) : path,
66 ...(line > 0 ? { line } : {}),
67 ...(column !== undefined && column > 0 ? { column } : {}),
68 ...(line > 0 && endLine !== undefined && endLine > line ? { endLine } : {}),
69 };
71​
72export function formatFilePathPosition(position: FilePathPosition): string {
73 if (!position.line) return position.path;
74 return `${position.path}:${position.line}${position.column ? `:${position.column}` : ""}`;
76​
77function isWindowsPathStyle(value: string): boolean {
78 return isWindowsAbsolutePath(value) || /[A-Za-z]:\\/.test(value);
80​
81export function joinPath(base: string, next: string, separator: "/" | "\\"): string {
82 const cleanBase = base.replace(/[\\/]+$/, "");
83 if (separator === "\\") {
84 return `${cleanBase}\\${next.replaceAll("/", "\\")}`;
85 }
86 return `${cleanBase}/${next.replace(/^\/+/, "")}`;
88​
89function inferHomeFromCwd(cwd: string): string | undefined {
90 const posixUser = cwd.match(/^\/Users\/([^/]+)/);
91 if (posixUser?.[1]) {
92 return `/Users/${posixUser[1]}`;
93 }
94​
95 const posixHome = cwd.match(/^\/home\/([^/]+)/);
96 if (posixHome?.[1]) {
97 return `/home/${posixHome[1]}`;
98 }
99​
100 const windowsUser = cwd.match(/^([A-Za-z]:[\\/]Users[\\/][^\\/]+)/i);
101 if (windowsUser?.[1]) {
102 return windowsUser[1];
103 }
104​
105 return undefined;
107​
108export function resolvePathLinkTarget(rawPath: string, cwd: string): string {
109 const position = splitFilePathPosition(rawPath);
110 const { path } = position;
111​
112 let resolvedPath = path;
113 if (path.startsWith("~/") || (isWindowsPathStyle(cwd) && path.startsWith("~\\"))) {
114 const home = inferHomeFromCwd(cwd);
115 if (home) {
116 const separator: "/" | "\\" = isWindowsPathStyle(home) ? "\\" : "/";
117 resolvedPath = joinPath(home, path.slice(2), separator);
118 }
119 } else if (!isAbsolutePath(path)) {
120 const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";
121 resolvedPath = joinPath(cwd, path.replace(/^(?:\.\/)+/, ""), separator);
122 }
123​
124 return formatFilePathPosition({ ...position, path: resolvedPath });
126​
127function pathParentSegments(path: string): string[] {
128 const normalized = path.replaceAll("\\", "/");
129 const segments = normalized.split("/").filter((segment) => segment.length > 0);
130 return segments.slice(0, -1);
132​
133export function buildFileLinkParentSuffixByPath(
134 filePaths: ReadonlyArray<string>,
135): Map<string, string> {
136 const groups = new Map<string, Set<string>>();
137 for (const filePath of filePaths) {
138 const normalizedPath = filePath.replaceAll("\\", "/");
139 const pathSegments = normalizedPath.split("/").filter((segment) => segment.length > 0);
140 const basename = pathSegments[pathSegments.length - 1];
141 if (!basename) continue;
142 const group = groups.get(basename) ?? new Set<string>();
143 group.add(normalizedPath);
144 groups.set(basename, group);
145 }
146​
147 const suffixByPath = new Map<string, string>();
148 for (const group of groups.values()) {
149 const uniquePaths = [...group];
150 if (uniquePaths.length < 2) continue;
151​
152 const parentSegmentsByPath = new Map(
153 uniquePaths.map((filePath) => [filePath, pathParentSegments(filePath)]),
154 );
155 const suffixCounts = new Map<string, number>();
156 for (const segments of parentSegmentsByPath.values()) {
157 for (let depth = 1; depth <= segments.length; depth += 1) {
158 const suffix = segments.slice(-depth).join("/");
159 suffixCounts.set(suffix, (suffixCounts.get(suffix) ?? 0) + 1);
160 }
161 }
162​
163 for (const filePath of uniquePaths) {
164 const segments = parentSegmentsByPath.get(filePath) ?? [];
165 let resolvedDepth = segments.length;
166 for (let depth = 1; depth <= segments.length; depth += 1) {
167 const candidate = segments.slice(-depth).join("/");
168 if (suffixCounts.get(candidate) === 1) {
169 resolvedDepth = depth;
170 break;
171 }
172 }
173 if (segments.length === 0) continue;
174 const suffixDepth = Math.min(segments.length, Math.max(resolvedDepth, 2));
175 suffixByPath.set(filePath, segments.slice(-suffixDepth).join("/"));
176 }
177 }
178​
179 return suffixByPath;
181​
182export function fileLinkLabel(
183 file: FilePathPosition,
184 parentSuffixByPath: ReadonlyMap<string, string>,
185): string {
186 const suffix = parentSuffixByPath.get(file.path.replaceAll("\\", "/"));
187 return [
188 fileBasename(file.path),
189 suffix,
190 file.line
191 ? `L${file.line}${file.endLine ? `–${file.endLine}` : file.column ? `:C${file.column}` : ""}`
192 : undefined,
193 ]
194 .filter(Boolean)
195 .join(" · ");