import { assertArg } from "../_common/dirname.ts";import { CHAR_COLON } from "../_common/constants.ts";import { stripTrailingSeparators } from "../_common/strip_trailing_separators.ts";import { isPathSeparator, isPosixPathSeparator, isWindowsDeviceRoot,} from "./_util.ts";
export function dirname(path: string): string { assertArg(path);
const len = path.length; let rootEnd = -1; let end = -1; let matchedSlash = true; let offset = 0; const code = path.charCodeAt(0);
if (len > 1) { if (isPathSeparator(code)) {
rootEnd = offset = 1;
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) { 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) { return path; } if (j !== last) {
rootEnd = offset = j + 1; } } } } } else if (isWindowsDeviceRoot(code)) {
if (path.charCodeAt(1) === CHAR_COLON) { rootEnd = offset = 2; if (len > 2) { if (isPathSeparator(path.charCodeAt(2))) rootEnd = offset = 3; } } } } else if (isPathSeparator(code)) { return path; }
for (let i = len - 1; i >= offset; --i) { if (isPathSeparator(path.charCodeAt(i))) { if (!matchedSlash) { end = i; break; } } else { matchedSlash = false; } }
if (end === -1) { if (rootEnd === -1) return "."; else end = rootEnd; } return stripTrailingSeparators(path.slice(0, end), isPosixPathSeparator);}