@@ -16,6 +16,14 @@ interface IPackageJson {
1616 * and retrieving the name of the package. The results are cached.
1717 */
1818export default class PackageJsonLookup {
19+ private _tryFindPackagePathUpwardsCache : Map < string , string > ;
20+ private _readPackageNameCache : Map < string , string > ;
21+
22+ constructor ( ) {
23+ this . _tryFindPackagePathUpwardsCache = new Map < string , string > ( ) ;
24+ this . _readPackageNameCache = new Map < string , string > ( ) ;
25+ }
26+
1927 /**
2028 * Finds the path to the package folder of a given currentPath, by probing
2129 * upwards from the currentPath until a package.json file is found.
@@ -25,21 +33,25 @@ export default class PackageJsonLookup {
2533 * @returns a relative path to the package folder
2634 */
2735 public tryFindPackagePathUpwards ( currentPath : string ) : string {
28- let packageFolder : string = '' ;
29-
30- // no-constant-condition
31- while ( true ) {
32- const folder : string = path . dirname ( currentPath ) ;
33- if ( ! folder || folder === currentPath ) {
34- return undefined ;
35- }
36- currentPath = folder ;
37- if ( fsx . existsSync ( path . join ( currentPath , 'package.json' ) ) ) {
38- packageFolder = path . normalize ( currentPath ) ;
39- break ;
40- }
36+ // Since Map cannot store an undefined value, we use the weird "null" object to
37+ // represent "undefined".
38+ let result : string = this . _tryFindPackagePathUpwardsCache . get ( currentPath ) ;
39+ if ( result !== undefined ) {
40+ return result === null ? undefined : result ; // tslint:disable-line: no-null-keyword
41+ }
42+
43+ const parentFolder : string = path . dirname ( currentPath ) ;
44+ if ( ! parentFolder || parentFolder === currentPath ) {
45+ result = undefined ;
46+ } else if ( fsx . existsSync ( path . join ( parentFolder , 'package.json' ) ) ) {
47+ result = path . normalize ( parentFolder ) ;
48+ } else {
49+ result = this . tryFindPackagePathUpwards ( parentFolder ) ;
4150 }
42- return packageFolder ;
51+
52+ // tslint:disable-next-line: no-null-keyword
53+ this . _tryFindPackagePathUpwardsCache . set ( currentPath , result === undefined ? null : result ) ;
54+ return result ;
4355 }
4456
4557 /**
@@ -50,7 +62,15 @@ export default class PackageJsonLookup {
5062 * @returns the name of the package (E.g. @microsoft/api-extractor)
5163 */
5264 public readPackageName ( packageJsonPath : string ) : string {
65+ let result : string = this . _readPackageNameCache . get ( packageJsonPath ) ;
66+ if ( result !== undefined ) {
67+ return result ;
68+ }
69+
5370 const packageJson : IPackageJson = JsonFile . loadJsonFile ( path . join ( packageJsonPath , 'package.json' ) ) as IPackageJson ;
54- return packageJson . name ;
71+ result = packageJson . name ;
72+
73+ this . _readPackageNameCache . set ( packageJsonPath , result ) ;
74+ return result ;
5575 }
5676}
0 commit comments