| 1 | 1 | var Path = require('path'), |
| 2 | | LRU = require('lru-cache') |
| 3 | | |
| 4 | 1 | module.exports = Object.create({ |
| 5 | | CWD: process.cwd(), // For overrides |
| 6 | | pathPrefix: './', // Also for overrides |
| 7 | | packageFileName: 'package.json', // Also for overrides |
| 8 | | didCachePackageMembers: false, // For package member caching |
| 9 | | allowCacheOverwrites: false, |
| 10 | | cache: LRU(), |
| 11 | | previousRequireCwd: null, |
| 12 | | fromCache: function (key, creationLambda) { |
| 13 | 13 | var retVal |
| 14 | 13 | if (!(retVal = this.cache.get(key))) { |
| 15 | 3 | this.cache.set(key, (retVal = creationLambda(key))) |
| 16 | | } |
| 17 | 13 | return retVal |
| 18 | | }, |
| 19 | | relativePath: function relativePath(pathRelativeToCwd) { |
| 20 | 2 | return this.fromCache(this.pathPrefix + pathRelativeToCwd, Path.join.bind(Path, this.CWD)) |
| 21 | | }, |
| 22 | | relativeRequire: function relativeRequire(pathRelativeToCwd) { |
| 23 | 2 | var path = this.relativePath(pathRelativeToCwd) |
| 24 | 2 | return require(path) |
| 25 | | }, |
| 26 | | uninstallRelativeRequire: function installRelativeRequire() { |
| 27 | 4 | global.requireCwd = this.previousRequireCwd |
| 28 | 4 | this.previousRequireCwd = null |
| 29 | | }, |
| 30 | | installRelativeRequire: function installRelativeRequire() { |
| 31 | 2 | this.previousRequireCwd = global.requireCwd |
| 32 | 2 | global.requireCwd = this.relativeRequire.bind(this) |
| 33 | | }, |
| 34 | | get packageJSON() { |
| 35 | 11 | var packageJSON = this.fromCache(this.packageFileName, this.relativeRequire.bind(this, this.packageFileName)) |
| 36 | 11 | if (!this.didCachePackageMembers) { |
| 37 | 1 | Object.keys(packageJSON).forEach(function (key) { |
| 38 | 14 | if (!this.cache.has(key) || this.allowCacheOverwrites) { |
| 39 | 14 | this.cache.set(key, packageJSON[key]) |
| 40 | | } |
| 41 | | }.bind(this)) |
| 42 | 1 | this.didCachePackageMembers = true |
| 43 | | } |
| 44 | 11 | return packageJSON |
| 45 | | } |
| 46 | | }) |
| 47 | | |