@@ -31,7 +31,7 @@ export interface IPackageJsonLookupParameters {
3131 * @public
3232 */
3333export class PackageJsonLookup {
34- private static _loadOwnPackageJsonCache : Map < string , IPackageJson > = new Map < string , IPackageJson > ( ) ;
34+ private static _loadOwnPackageJsonLookup : PackageJsonLookup = new PackageJsonLookup ( { loadExtraFields : true } ) ;
3535
3636 private _loadExtraFields : boolean = false ;
3737
@@ -51,28 +51,30 @@ export class PackageJsonLookup {
5151 * This function provides a concise and efficient way for an NPM package to report metadata about itself.
5252 * For example, a tool might want to report its version.
5353 *
54- * The `loadOwnPackageJson()` caches the result, under the assumption that a tool's own package.json will never
55- * change during the lifetime of the process.
54+ * The `loadOwnPackageJson()` probes upwards from the caller's folder, expecting to find a package.json file,
55+ * which is assumed to be the caller's package. The result is cached, under the assumption that a tool's
56+ * own package.json (and intermediary folders) will never change during the lifetime of the process.
5657 *
5758 * @example
5859 * ```ts
5960 * // Report the version of our NPM package
60- * const myPackageVersion: string = PackageJsonLookup.loadOwnPackageJson(__dirname, '../..' ).version;
61+ * const myPackageVersion: string = PackageJsonLookup.loadOwnPackageJson(__dirname).version;
6162 * console.log(`Cool Tool - Version ${myPackageVersion}`);
6263 * ```
6364 *
6465 * @param dirnameOfCaller - The NodeJS `__dirname` macro for the caller.
65- * @param pathToPackageJson - A relative path to the caller's package.json file, omitting the "package.json" part.
6666 * @returns This function always returns a valid `IPackageJson` object. If any problems are encountered during
6767 * loading, an exception will be thrown instead.
6868 */
69- public static loadOwnPackageJson ( dirnameOfCaller : string , pathToPackageJsonFolder : string ) : IPackageJson {
70- const packageJsonPath : string = path . join ( dirnameOfCaller , pathToPackageJsonFolder , FileConstants . PackageJson ) ;
71- let packageJson : IPackageJson | undefined = PackageJsonLookup . _loadOwnPackageJsonCache . get ( packageJsonPath ) ;
69+ public static loadOwnPackageJson ( dirnameOfCaller : string ) : IPackageJson {
70+ const packageJson : IPackageJson | undefined = PackageJsonLookup . _loadOwnPackageJsonLookup
71+ . tryLoadPackageJsonFor ( dirnameOfCaller ) ;
72+
7273 if ( packageJson === undefined ) {
73- packageJson = JsonFile . load ( packageJsonPath ) as IPackageJson ;
74- PackageJsonLookup . _loadOwnPackageJsonCache . set ( packageJsonPath , packageJson ) ;
74+ throw new Error ( `PackageJsonLookup.loadOwnPackageJson() failed to find the caller's package.json.`
75+ + ` The __dirname was: ${ dirnameOfCaller } ` ) ;
7576 }
77+
7678 return packageJson ;
7779 }
7880
0 commit comments