57 lines
2.2 KiB
TypeScript
57 lines
2.2 KiB
TypeScript
import {
|
|
fileBasename,
|
|
formatFilePathPosition,
|
|
splitFilePathPosition,
|
|
stripSlashPrefixedWindowsDrive,
|
|
} from "@t3tools/client-runtime/markdown-links";
|
|
import { isWindowsAbsolutePath } from "@t3tools/shared/path";
|
|
|
|
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 });
|
|
}
|