Open History to see the last commit
1import { splitPathAndPosition } from "./terminal-links";
2
3function normalizePathSeparators(path: string): string {
4 return path.replaceAll("\\", "/");
5}
6
7function canonicalizeWindowsDrivePath(path: string): string {
8 return /^\/[A-Za-z]:\//.test(path) ? path.slice(1) : path;
9}
10
11function trimTrailingPathSeparators(path: string): string {
12 return path.replace(/[\\/]+$/, "");
13}
14
15function basenameOfPath(path: string): string {
16 const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
17 return separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
18}
19
20function stripRelativePrefixes(path: string): string {
21 return path.replace(/^\.\/+/, "").replace(/^\/+/, "");
22}
23
24export function formatWorkspaceRelativePath(
25 pathWithPosition: string,
26 workspaceRoot: string | undefined,
27): string {
28 const { path, line, column } = splitPathAndPosition(pathWithPosition);
29 const normalizedPath = canonicalizeWindowsDrivePath(normalizePathSeparators(path));
30
31 let displayPath = normalizedPath;
32 if (workspaceRoot) {
33 const normalizedWorkspaceRoot = canonicalizeWindowsDrivePath(
34 normalizePathSeparators(trimTrailingPathSeparators(workspaceRoot)),
35 );
36 const workspaceLabel = basenameOfPath(normalizedWorkspaceRoot);
37 const pathForCompare = normalizedPath.toLowerCase();
38 const workspaceForCompare = normalizedWorkspaceRoot.toLowerCase();
39 const workspaceWithSeparator = `${workspaceForCompare}/`;
40 const workspaceLabelWithSeparator = `${workspaceLabel.toLowerCase()}/`;
41
42 if (pathForCompare === workspaceForCompare) {
43 displayPath = workspaceLabel;
44 } else if (pathForCompare.startsWith(workspaceWithSeparator)) {
45 const relativeSuffix = normalizedPath.slice(normalizedWorkspaceRoot.length + 1);
46 displayPath = `${workspaceLabel}/${relativeSuffix}`;
47 } else if (!normalizedPath.startsWith("/")) {
48 const relativePath = stripRelativePrefixes(normalizedPath);
49 displayPath = pathForCompare.startsWith(workspaceLabelWithSeparator)
50 ? normalizedPath
51 : `${workspaceLabel}/${relativePath}`;
52 }
53 }
54
55 if (!line) return displayPath;
56 return `${displayPath}:${line}${column ? `:${column}` : ""}`;
57}