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