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

filePathDisplay.ts

59 lines2.2 KB

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