UNPKG

@ayanaware/logger

Version:

Useful and great looking logging made easy

71 lines 2.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PackageDetector = void 0; const fs = require("fs"); const path = require("path"); /** * @ignore */ class PackageDetector { constructor() { this.packageCache = new Map(); } getRootOf(directory) { // Find the next package.json file in the directory tree let files = this.readdirSync(directory); while (!files.includes('package.json')) { const up = path.join(directory, '..'); // If there is no package.json we will get stuck at the root directory if (up === directory) { directory = null; break; } directory = up; files = this.readdirSync(directory); } if (directory == null) throw new Error('No package.json could be found in the directory tree'); return directory; } getInfo(rootDir) { // Get package.json location const packageFile = path.resolve(rootDir, 'package.json'); // Load package.json from cache or require it let pkg; if (this.packageCache.get(packageFile) == null) { pkg = JSON.parse(this.readFileSync(packageFile, { encoding: 'utf8' })); this.packageCache.set(packageFile, pkg); } else { pkg = this.packageCache.get(packageFile); } return pkg; } // Credit: https://github.com/stefanpenner/get-caller-file/blob/master/index.ts getCallerFile(position = 2) { if (position >= Error.stackTraceLimit) { throw new TypeError('getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `' + position + '` and Error.stackTraceLimit was: `' + Error.stackTraceLimit + '`'); } const oldPrepareStackTrace = Error.prepareStackTrace; Error.prepareStackTrace = (_, stack) => stack; const stack = new Error().stack; Error.prepareStackTrace = oldPrepareStackTrace; if (stack === null || typeof stack !== 'object') return null; // stack[0] holds this file // stack[1] holds where this function was called // stack[2] holds the file we're interested in return stack[position] ? stack[position].getFileName() : undefined; } // Wrapper functions so we can test this without context /* istanbul ignore next */ readdirSync(dirPath) { return fs.readdirSync(dirPath); } /* istanbul ignore next */ readFileSync(filePath, options) { return fs.readFileSync(filePath, options); } } exports.PackageDetector = PackageDetector; //# sourceMappingURL=PackageDetector.js.map