The best way to control Claude Code, Codex and more from any computer or phone

main
ts 59 lines 2.22 KB
Raw
1 import { pipe } from "effect/Function";
2 import {
3 fileBasename,
4 stripSlashPrefixedWindowsDrive,
5 isHostPath,
6 isWindowsAbsolutePath,
7 } from "@t3tools/shared/path";
8 import { formatFilePathPosition, splitFilePathPosition } from "@t3tools/shared/fileLinks";
9
10 function normalizePathSeparators(path: string): string {
11 return path.replaceAll("\\", "/");
12 }
13
14 function trimTrailingPathSeparators(path: string): string {
15 return path.replace(/[\\/]+$/, "");
16 }
17
18 function stripRelativePrefixes(path: string): string {
19 return path.replace(/^\.\/+/, "").replace(/^\/+/, "");
20 }
21
22 export 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 });
59 }