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

filePathDisplay.ts

52 lines1.9 KB

1import {
2 fileBasename,
3 formatFilePathPosition,
4 splitFilePathPosition,
5 stripSlashPrefixedWindowsDrive,
6} from "@t3tools/client-runtime/markdown-links";
7​
8function normalizePathSeparators(path: string): string {
9 return path.replaceAll("\\", "/");
11​
12function trimTrailingPathSeparators(path: string): string {
13 return path.replace(/[\\/]+$/, "");
15​
16function stripRelativePrefixes(path: string): string {
17 return path.replace(/^\.\/+/, "").replace(/^\/+/, "");
19​
20export function formatWorkspaceRelativePath(
21 pathWithPosition: string,
22 workspaceRoot: string | undefined,
23): string {
24 const position = splitFilePathPosition(pathWithPosition);
25 const normalizedPath = stripSlashPrefixedWindowsDrive(normalizePathSeparators(position.path));
26​
27 let displayPath = normalizedPath;
28 if (workspaceRoot) {
29 const normalizedWorkspaceRoot = stripSlashPrefixedWindowsDrive(
30 normalizePathSeparators(trimTrailingPathSeparators(workspaceRoot)),
31 );
32 const workspaceLabel = fileBasename(normalizedWorkspaceRoot);
33 const pathForCompare = normalizedPath.toLowerCase();
34 const workspaceForCompare = normalizedWorkspaceRoot.toLowerCase();
35 const workspaceWithSeparator = `${workspaceForCompare}/`;
36 const workspaceLabelWithSeparator = `${workspaceLabel.toLowerCase()}/`;
37​
38 if (pathForCompare === workspaceForCompare) {
39 displayPath = workspaceLabel;
40 } else if (pathForCompare.startsWith(workspaceWithSeparator)) {
41 const relativeSuffix = normalizedPath.slice(normalizedWorkspaceRoot.length + 1);
42 displayPath = `${workspaceLabel}/${relativeSuffix}`;
43 } else if (!normalizedPath.startsWith("/")) {
44 const relativePath = stripRelativePrefixes(normalizedPath);
45 displayPath = pathForCompare.startsWith(workspaceLabelWithSeparator)
46 ? normalizedPath
47 : `${workspaceLabel}/${relativePath}`;
48 }
49 }
50​
51 return formatFilePathPosition({ ...position, path: displayPath });