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