@stryke/path
Version:
A package containing various utilities that expand the functionality of NodeJs's built-in `path` module
61 lines (60 loc) • 2.47 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.correctPath = correctPath;
exports.normalizeString = normalizeString;
exports.normalizeWindowsPath = normalizeWindowsPath;
exports.toAbsolutePath = toAbsolutePath;
exports.toRelativePath = toRelativePath;
var _isFile = require("./is-file.cjs");
var _joinPaths = require("./join-paths.cjs");
var _regex = require("./regex.cjs");
var _slash = require("./slash.cjs");
function normalizeWindowsPath(e = "") {
return e && (0, _slash.slash)(e).replace(_regex.DRIVE_LETTER_START_REGEX, n => n.toUpperCase());
}
function correctPath(e) {
if (!e || e.length === 0) return ".";
e = normalizeWindowsPath(e);
const n = e.match(_regex.UNC_REGEX),
r = (0, _isFile.isAbsolutePath)(e),
i = e.endsWith("/");
return e = normalizeString(e, !r), e.length === 0 ? r ? "/" : i ? "./" : "." : (i && (e += "/"), _regex.DRIVE_LETTER_REGEX.test(e) && (e += "/"), n ? r ? `//${e}` : `//./${e}` : !e.startsWith("/") && r && !_regex.DRIVE_LETTER_REGEX.test(e) ? `/${e}` : e);
}
function normalizeString(e, n) {
let r = "",
i = 0,
l = -1,
s = 0,
o = null;
for (let t = 0; t <= e.length; ++t) {
if (t < e.length) o = e[t];else {
if (o === "/") break;
o = "/";
}
if (o === "/") {
if (!(l === t - 1 || s === 1)) if (s === 2) {
if (r.length < 2 || i !== 2 || r[r.length - 1] !== "." || r[r.length - 2] !== ".") {
if (r.length > 2) {
const u = r.lastIndexOf("/");
u === -1 ? (r = "", i = 0) : (r = r.slice(0, u), i = r.length - 1 - r.lastIndexOf("/")), l = t, s = 0;
continue;
} else if (r.length > 0) {
r = "", i = 0, l = t, s = 0;
continue;
}
}
n && (r += r.length > 0 ? "/.." : "..", i = 2);
} else r.length > 0 ? r += `/${e.slice(l + 1, t)}` : r = e.slice(l + 1, t), i = t - l - 1;
l = t, s = 0;
} else o === "." && s !== -1 ? ++s : s = -1;
}
return r;
}
function toAbsolutePath(e, n) {
return (0, _isFile.isAbsolutePath)(e) ? e : (0, _slash.slash)(normalizeString((0, _joinPaths.joinPaths)(n || process.cwd(), e), !0));
}
function toRelativePath(e, n) {
return !e || e.length === 0 ? "." : ((0, _isFile.isAbsolutePath)(e) ? e = (0, _slash.slash)(normalizeString(e, !0)) : e = (0, _slash.slash)(normalizeString((0, _joinPaths.joinPaths)(n || process.cwd(), e), !0)), e.startsWith("./") ? e.slice(2) : e);
}