tar
Version:
tar for JavaScript
90 lines • 3.23 kB
JavaScript
;
// The POSIX path functions that tar paths need. Each one gives the
// same result as the function of the same name in `path.posix`.
Object.defineProperty(exports, "__esModule", { value: true });
exports.relative = exports.resolve = exports.isAbsolute = exports.basename = exports.dirname = exports.join = exports.normalize = void 0;
/** Resolve `.` and `..` parts, and remove repeated slashes. */
const normalize = (path) => {
const absolute = path.charCodeAt(0) === 47;
const out = [];
for (const part of path.split('/')) {
if (part === '' || part === '.')
continue;
if (part !== '..')
out.push(part);
else if (out.length && out[out.length - 1] !== '..')
out.pop();
else if (!absolute)
out.push(part);
}
const trail = out.length && path.charCodeAt(path.length - 1) === 47;
const res = out.join('/') + (trail ? '/' : '');
if (absolute)
return '/' + res;
return res || (path.endsWith('/') ? './' : '.');
};
exports.normalize = normalize;
/** Join the parts with a slash, then normalize the result. */
const join = (...parts) => (0, exports.normalize)(parts.filter(p => p).join('/'));
exports.join = join;
/** The path without its last part. */
const dirname = (path) => {
let end = path.length;
while (end > 1 && path.charCodeAt(end - 1) === 47)
end--;
const slash = path.lastIndexOf('/', end - 1);
if (slash === -1)
return '.';
if (slash === 0)
return '/';
if (slash === 1 && path.charCodeAt(0) === 47)
return '//';
return path.slice(0, slash);
};
exports.dirname = dirname;
/** The last part of the path. */
const basename = (path) => {
let end = path.length;
while (end > 0 && path.charCodeAt(end - 1) === 47)
end--;
return path.slice(path.lastIndexOf('/', end - 1) + 1, end);
};
exports.basename = basename;
/** True if the path starts with a slash. */
const isAbsolute = (path) => path.charCodeAt(0) === 47;
exports.isAbsolute = isAbsolute;
/**
* Resolve the parts from right to left, up to the first absolute
* part. There is no working directory here: if no part is absolute,
* the result is a relative path.
*/
const resolve = (...parts) => {
let path = '';
for (let i = parts.length - 1; i >= 0 && !(0, exports.isAbsolute)(path); i--) {
const part = parts[i];
if (part)
path = path ? part + '/' + path : part;
}
const res = (0, exports.normalize)(path);
return res.length > 1 && res.endsWith('/') ? res.slice(0, -1) : res;
};
exports.resolve = resolve;
/** The relative path from `from` to `to`. */
const relative = (from, to) => {
const f = (0, exports.resolve)(from).split('/');
const t = (0, exports.resolve)(to).split('/');
// The root gives an empty last part.
if (!f[f.length - 1])
f.pop();
if (!t[t.length - 1])
t.pop();
let same = 0;
while (same < f.length && same < t.length && f[same] === t[same])
same++;
return [
...Array.from({ length: f.length - same }, () => '..'),
...t.slice(same),
].join('/');
};
exports.relative = relative;
//# sourceMappingURL=path.js.map