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