pig-dam-core
Version:
Library that should be included in every Pig DAM project we build
80 lines (79 loc) • 2.77 kB
JavaScript
;
/**
* Date: 5/23/20
* Time: 1:03 AM
* @license MIT (see project's LICENSE file)
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.findModuleRoot = exports.getModulesRelativePath = exports.getModulesApplicationRoot = exports.getModulesApplicationPackage = void 0;
const fs_1 = require("fs");
const path_1 = require("path");
/**
* Get's this module's application package.json contents
* @throws {Error}
*/
function getModulesApplicationPackage() {
function getPackage(directory) {
const path = path_1.join(directory, "package.json");
if (fs_1.existsSync(path)) {
return JSON.parse(fs_1.readFileSync(path, "utf-8"));
}
else if (directory.length > 1) {
return getPackage(path_1.parse(directory).dir);
}
else {
throw new Error("could not find module's application package");
}
}
return getPackage(getModulesApplicationRoot());
}
exports.getModulesApplicationPackage = getModulesApplicationPackage;
/**
* Get's this module's application root directory. Actually it gets the directory of wherever the script
* that started up the application in which this is.
* @throws {Error}
*/
function getModulesApplicationRoot() {
if (require.main) {
return path_1.parse(require.main.filename).dir;
}
else {
throw new Error("could not find module's application root");
}
}
exports.getModulesApplicationRoot = getModulesApplicationRoot;
/**
* Gets the module's relative path to its own root. For example - "./src/core/module.ts"
* @throws {Error}
*/
function getModulesRelativePath(modulePath) {
// find the root of the project. Such as "/projects/xraymen". We basically want to tear that off
const root = findModuleRoot(modulePath);
return `.${modulePath.substr(root.length)}`;
}
exports.getModulesRelativePath = getModulesRelativePath;
/**
* Finds the root for the module belonging to <param>modulePath</param>. It will not include a trailing "/".
* @throws {Error}
*/
function findModuleRoot(modulePath) {
function ascendPath(path) {
const result = path_1.parse(path).dir;
if (result === path) {
// our way of detecting the top with nowhere to go.
// Strangely path.parse("/").dir returns "/"
throw new Error("could not find module root");
}
return result;
}
function findRoot(path) {
return fs_1.existsSync(`${path}/node_modules`)
? path
: findRoot(ascendPath(path));
}
const stat = fs_1.statSync(modulePath);
return (stat.isDirectory())
? findRoot(modulePath)
: findRoot(ascendPath(modulePath));
}
exports.findModuleRoot = findModuleRoot;