import { CHAR_COLON } from "../_common/constants.ts";import { normalizeString } from "../_common/normalize_string.ts";import { assertPath } from "../_common/assert_path.ts";import { isPathSeparator, isWindowsDeviceRoot } from "./_util.ts";
export function resolve(...pathSegments: string[]): string { let resolvedDevice = ""; let resolvedTail = ""; let resolvedAbsolute = false;
for (let i = pathSegments.length - 1; i >= -1; i--) { let path: string; const { Deno } = globalThis as any; if (i >= 0) { path = pathSegments[i]!; } else if (!resolvedDevice) { if (typeof Deno?.cwd !== "function") { throw new TypeError("Resolved a drive-letter-less path without a CWD."); } path = Deno.cwd(); } else { if ( typeof Deno?.env?.get !== "function" || typeof Deno?.cwd !== "function" ) { throw new TypeError("Resolved a relative path without a CWD."); } path = Deno.cwd();
if ( path === undefined || path.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\` ) { path = `${resolvedDevice}\\`; } }
assertPath(path);
const len = path.length;
if (len === 0) continue;
let rootEnd = 0; let device = ""; let isAbsolute = false; const code = path.charCodeAt(0);
if (len > 1) { if (isPathSeparator(code)) {
isAbsolute = true;
if (isPathSeparator(path.charCodeAt(1))) { let j = 2; let last = j; for (; j < len; ++j) { if (isPathSeparator(path.charCodeAt(j))) break; } if (j < len && j !== last) { const firstPart = path.slice(last, j); last = j; for (; j < len; ++j) { if (!isPathSeparator(path.charCodeAt(j))) break; } if (j < len && j !== last) { last = j; for (; j < len; ++j) { if (isPathSeparator(path.charCodeAt(j))) break; } if (j === len) { device = `\\\\${firstPart}\\${path.slice(last)}`; rootEnd = j; } else if (j !== last) {
device = `\\\\${firstPart}\\${path.slice(last, j)}`; rootEnd = j; } } } } else { rootEnd = 1; } } else if (isWindowsDeviceRoot(code)) {
if (path.charCodeAt(1) === CHAR_COLON) { device = path.slice(0, 2); rootEnd = 2; if (len > 2) { if (isPathSeparator(path.charCodeAt(2))) { isAbsolute = true; rootEnd = 3; } } } } } else if (isPathSeparator(code)) { rootEnd = 1; isAbsolute = true; }
if ( device.length > 0 && resolvedDevice.length > 0 && device.toLowerCase() !== resolvedDevice.toLowerCase() ) { continue; }
if (resolvedDevice.length === 0 && device.length > 0) { resolvedDevice = device; } if (!resolvedAbsolute) { resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; resolvedAbsolute = isAbsolute; }
if (resolvedAbsolute && resolvedDevice.length > 0) break; }
resolvedTail = normalizeString( resolvedTail, !resolvedAbsolute, "\\", isPathSeparator, );
return resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || ".";}