63 lines
2.0 KiB
JavaScript
63 lines
2.0 KiB
JavaScript
"use strict";
|
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
};
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
const path_1 = __importDefault(require("path"));
|
|
const error_1 = __importDefault(require("./error"));
|
|
// Normalize a filename
|
|
function normalizePath(filename) {
|
|
return path_1.default.normalize(filename);
|
|
}
|
|
// Return true if file path is inside a folder
|
|
function isInRoot(root, filename) {
|
|
root = path_1.default.normalize(root);
|
|
filename = path_1.default.normalize(filename);
|
|
if (root === ".") {
|
|
return true;
|
|
}
|
|
if (root[root.length - 1] != path_1.default.sep) {
|
|
root = root + path_1.default.sep;
|
|
}
|
|
return filename.substr(0, root.length) === root;
|
|
}
|
|
// Resolve paths in a specific folder
|
|
// Throw error if file is outside this folder
|
|
function resolveInRoot(root) {
|
|
const args = Array.prototype.slice.call(arguments, 1);
|
|
const input = args.reduce((current, p) => {
|
|
// Handle path relative to book root ("/README.md")
|
|
if (p[0] == "/" || p[0] == "\\")
|
|
return p.slice(1);
|
|
return current ? path_1.default.join(current, p) : path_1.default.normalize(p);
|
|
}, "");
|
|
const result = path_1.default.resolve(root, input);
|
|
if (!isInRoot(root, result)) {
|
|
throw new error_1.default.FileOutOfScopeError({
|
|
filename: result,
|
|
root: root
|
|
});
|
|
}
|
|
return result;
|
|
}
|
|
// Chnage extension of a file
|
|
function setExtension(filename, ext) {
|
|
return path_1.default.join(path_1.default.dirname(filename), path_1.default.basename(filename, path_1.default.extname(filename)) + ext);
|
|
}
|
|
/*
|
|
Return true if a filename is relative.
|
|
|
|
@param {string}
|
|
@return {boolean}
|
|
*/
|
|
function isPureRelative(filename) {
|
|
return filename.indexOf("./") === 0 || filename.indexOf("../") === 0;
|
|
}
|
|
exports.default = {
|
|
isInRoot: isInRoot,
|
|
resolveInRoot: resolveInRoot,
|
|
normalize: normalizePath,
|
|
setExtension: setExtension,
|
|
isPureRelative: isPureRelative
|
|
};
|