Open History to see the last commit
1import {
2 fileBasename,
3 formatFilePathPosition,
4 splitFilePathPosition,
5 stripSlashPrefixedWindowsDrive,
6} from "@t3tools/client-runtime/markdown-links";
7import { isWindowsAbsolutePath } from "@t3tools/shared/path";
8
9function normalizePathSeparators(path: string): string {
10 return path.replaceAll("\\", "/");
11}
12
13function trimTrailingPathSeparators(path: string): string {
14 return path.replace(/[\\/]+$/, "");
15}
16
17function stripRelativePrefixes(path: string): string {
18 return path.replace(/^\.\/+/, "").replace(/^\/+/, "");
19}
20
21export function formatWorkspaceRelativePath(
22 pathWithPosition: string,
23 workspaceRoot: string | undefined,
24): string {
25 const position = splitFilePathPosition(pathWithPosition);
26 const normalizedPath = stripSlashPrefixedWindowsDrive(normalizePathSeparators(position.path));
27
28 let displayPath = normalizedPath;
29 if (workspaceRoot) {
30 const normalizedWorkspaceRoot = stripSlashPrefixedWindowsDrive(
31 normalizePathSeparators(trimTrailingPathSeparators(workspaceRoot)),
32 );
33 const workspaceLabel = fileBasename(normalizedWorkspaceRoot);
34 const caseInsensitive = isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot));
35 const pathForCompare = caseInsensitive ? normalizedPath.toLowerCase() : normalizedPath;
36 const workspaceForCompare = caseInsensitive
37 ? normalizedWorkspaceRoot.toLowerCase()
38 : normalizedWorkspaceRoot;
39 const workspaceWithSeparator = `${workspaceForCompare}/`;
40 const workspaceLabelWithSeparator = `${caseInsensitive ? workspaceLabel.toLowerCase() : workspaceLabel}/`;
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 return formatFilePathPosition({ ...position, path: displayPath });
56}