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 });
}