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

filePathDisplay.ts

55 lines2.2 KB

1import {
2 stripSlashPrefixedWindowsDrive,
3 isHostPath,
4 isWindowsAbsolutePath,
5} from "@t3tools/shared/path";
6import { formatFilePathPosition, splitFilePathPosition } from "@t3tools/shared/fileLinks";
7​
8function normalizePathSeparators(path: string): string {
9 return path.replaceAll("\\", "/");
11​
12function stripRelativePrefixes(path: string): string {
13 return path.replace(/^\.\/+/, "").replace(/^\/+/, "");
15​
16export function formatWorkspaceRelativePath(
17 pathWithPosition: string,
18 workspaceRoot: string | undefined,
19): string {
20 const position = splitFilePathPosition(pathWithPosition);
21 // A POSIX file name may contain `\`, so only Windows roots fold it into a separator.
22 const windows =
23 !workspaceRoot ||
24 isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot)) ||
25 workspaceRoot.startsWith("//");
26 const normalize = (path: string) =>
27 windows ? stripSlashPrefixedWindowsDrive(normalizePathSeparators(path)) : path;
28 const normalizedPath = normalize(position.path);
29​
30 let displayPath = normalizedPath;
31 if (workspaceRoot) {
32 const normalizedWorkspaceRoot = normalize(workspaceRoot).replace(/\/+$/, "");
33 const workspaceLabel = normalizedWorkspaceRoot.split("/").pop() ?? "";
34 const pathForCompare = windows ? normalizedPath.toLowerCase() : normalizedPath;
35 const workspaceForCompare = windows
36 ? normalizedWorkspaceRoot.toLowerCase()
37 : normalizedWorkspaceRoot;
38 const workspaceWithSeparator = `${workspaceForCompare}/`;
39 const workspaceLabelWithSeparator = `${windows ? workspaceLabel.toLowerCase() : workspaceLabel}/`;
40​
41 if (pathForCompare === workspaceForCompare) {
42 displayPath = workspaceLabel;
43 } else if (pathForCompare.startsWith(workspaceWithSeparator)) {
44 const relativeSuffix = normalizedPath.slice(normalizedWorkspaceRoot.length + 1);
45 displayPath = `${workspaceLabel}/${relativeSuffix}`;
46 } else if (!isHostPath(normalizedPath)) {
47 const relativePath = stripRelativePrefixes(normalizedPath);
48 displayPath = pathForCompare.startsWith(workspaceLabelWithSeparator)
49 ? normalizedPath
50 : `${workspaceLabel}/${relativePath}`;
51 }
52 }
53​
54 return formatFilePathPosition({ ...position, path: displayPath });