Co-authored-by: Yash Singh <[email protected]> Co-authored-by: Julius Marminge <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
56 lines
2.2 KiB
TypeScript
56 lines
2.2 KiB
TypeScript
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 = stripSlashPrefixedWindowsDrive(
|
|
normalizePathSeparators(trimTrailingPathSeparators(workspaceRoot)),
|
|
);
|
|
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 });
|
|
}
|