Skip to content

Commit ea49d3d

Browse files
authored
Merge pull request microsoft#236 from Microsoft/pgonzal/api-extractor-perf-fix
Fix a perf issue where API Extractor would reread package.json
2 parents 3d95c6c + d27096c commit ea49d3d

8 files changed

Lines changed: 134 additions & 65 deletions

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"changes": [
3+
{
4+
"packageName": "@microsoft/api-extractor",
5+
"comment": "Use a cache to speed up package.json lookups",
6+
"type": "patch"
7+
}
8+
],
9+
"packageName": "@microsoft/api-extractor",
10+
"email": "pgonzal@users.noreply.github.com"
11+
}

‎common/reviews/api/api-extractor.api.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,9 @@ class Extractor {
9797
// (undocumented)
9898
public package: ApiPackage;
9999
public readonly packageFolder: string;
100+
// WARNING: The type "PackageJsonLookup" needs to be exported by the package (e.g. added to index.ts)
101+
// (undocumented)
102+
public packageJsonLookup: PackageJsonLookup;
100103
public reportError(message: string, sourceFile: ts.SourceFile, start: number): void;
101104
// (undocumented)
102105
public typeChecker: ts.TypeChecker;

‎libraries/api-extractor/src/Extractor.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import * as fsx from 'fs-extra';
33
import * as path from 'path';
44
import ApiPackage from './definitions/ApiPackage';
55
import DocItemLoader from './DocItemLoader';
6-
import PackageJsonHelpers from './PackageJsonHelpers';
6+
import PackageJsonLookup from './PackageJsonLookup';
77

88
export type ApiErrorHandler = (message: string, fileName: string, lineNumber: number) => void;
99

@@ -50,14 +50,16 @@ export interface IExtractorAnalyzeOptions {
5050
* abstract syntax tree.
5151
*/
5252
export default class Extractor {
53-
public errorHandler: ApiErrorHandler;
53+
public readonly errorHandler: ApiErrorHandler;
5454
public typeChecker: ts.TypeChecker;
5555
public package: ApiPackage;
5656
/**
5757
* One DocItemLoader is needed per analyzer to look up external API members
5858
* as needed.
5959
*/
60-
public docItemLoader: DocItemLoader;
60+
public readonly docItemLoader: DocItemLoader;
61+
62+
public readonly packageJsonLookup: PackageJsonLookup;
6163

6264
private _compilerOptions: ts.CompilerOptions;
6365

@@ -75,6 +77,7 @@ export default class Extractor {
7577
constructor(options: IExtractorOptions) {
7678
this._compilerOptions = options.compilerOptions;
7779
this.docItemLoader = new DocItemLoader(options.compilerOptions.rootDir);
80+
this.packageJsonLookup = new PackageJsonLookup();
7881
this.errorHandler = options.errorHandler || Extractor.defaultErrorHandler;
7982
}
8083

@@ -110,7 +113,7 @@ export default class Extractor {
110113
// Assign _packageFolder by probing upwards from entryPointFile until we find a package.json
111114
const currentPath: string = path.resolve(options.entryPointFile);
112115
// This is guaranteed to succeed since we do check prior to this point
113-
this._packageFolder = PackageJsonHelpers.tryFindPackagePathUpwards(currentPath);
116+
this._packageFolder = this.packageJsonLookup.tryFindPackagePathUpwards(currentPath);
114117

115118
this.package = new ApiPackage(this, rootFile); // construct members
116119
this.package.completeInitialization(); // creates ApiDocumentation

‎libraries/api-extractor/src/PackageJsonHelpers.ts‎

Lines changed: 0 additions & 56 deletions
This file was deleted.
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/* tslint:disable:no-constant-condition */
2+
3+
import * as fsx from 'fs-extra';
4+
import * as path from 'path';
5+
import JsonFile from './JsonFile';
6+
7+
/**
8+
* Represents a package.json file.
9+
*/
10+
interface IPackageJson {
11+
name: string;
12+
}
13+
14+
/**
15+
* This class provides methods for finding the nearest "package.json" for a folder
16+
* and retrieving the name of the package. The results are cached.
17+
*/
18+
export default class PackageJsonLookup {
19+
// Cached the return values for tryFindPackagePathUpwards():
20+
// sourceFilePath --> packageJsonFolder
21+
private _packageFolderCache: Map<string, string | undefined>;
22+
23+
// Cached the return values for readPackageName():
24+
// packageJsonPath --> packageName
25+
private _packageNameCache: Map<string, string>;
26+
27+
constructor() {
28+
this._packageFolderCache = new Map<string, string | undefined>();
29+
this._packageNameCache = new Map<string, string>();
30+
}
31+
32+
/**
33+
* Finds the path to the package folder of a given currentPath, by probing
34+
* upwards from the currentPath until a package.json file is found.
35+
* If no package.json can be found, undefined is returned.
36+
*
37+
* @param currentPath - a path (relative or absolute) of the current location
38+
* @returns a relative path to the package folder
39+
*/
40+
public tryFindPackagePathUpwards(sourceFilePath: string): string | undefined {
41+
// Two lookups are required, because get() cannot distinguish the undefined value
42+
// versus a missing key.
43+
if (this._packageFolderCache.has(sourceFilePath)) {
44+
return this._packageFolderCache.get(sourceFilePath);
45+
}
46+
47+
let result: string | undefined;
48+
49+
const parentFolder: string = path.dirname(sourceFilePath);
50+
if (!parentFolder || parentFolder === sourceFilePath) {
51+
result = undefined;
52+
} else if (fsx.existsSync(path.join(parentFolder, 'package.json'))) {
53+
result = path.normalize(parentFolder);
54+
} else {
55+
result = this.tryFindPackagePathUpwards(parentFolder);
56+
}
57+
58+
this._packageFolderCache.set(sourceFilePath, result);
59+
return result;
60+
}
61+
62+
/**
63+
* Loads the package.json file and returns the name of the package.
64+
*
65+
* @param packageJsonPath - an absolute path to the folder containing the
66+
* package.json file, it does not include the 'package.json' suffix.
67+
* @returns the name of the package (E.g. @microsoft/api-extractor)
68+
*/
69+
public readPackageName(packageJsonPath: string): string {
70+
let result: string = this._packageNameCache.get(packageJsonPath);
71+
if (result !== undefined) {
72+
return result;
73+
}
74+
75+
const packageJson: IPackageJson = JsonFile.loadJsonFile(path.join(packageJsonPath, 'package.json')) as IPackageJson;
76+
result = packageJson.name;
77+
78+
this._packageNameCache.set(packageJsonPath, result);
79+
return result;
80+
}
81+
}

‎libraries/api-extractor/src/definitions/ApiItem.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import Extractor from '../Extractor';
77
import ApiDocumentation, { ApiTag } from './ApiDocumentation';
88
import TypeScriptHelpers from '../TypeScriptHelpers';
99
import DocElementParser from '../DocElementParser';
10-
import PackageJsonHelpers from '../PackageJsonHelpers';
1110
import ResolvedApiItem from '../ResolvedApiItem';
1211
import ApiDefinitionReference,
1312
{ IScopedPackageName, IApiDefinintionReferenceParts } from '../ApiDefinitionReference';
@@ -503,7 +502,8 @@ abstract class ApiItem {
503502
// Walk upwards from that directory until you find a directory containing package.json,
504503
// this is where the referenced type is located.
505504
// Example: "c:\users\<username>\sp-client\spfx-core\sp-core-library"
506-
const typeReferencePackagePath: string = PackageJsonHelpers.tryFindPackagePathUpwards(sourceFile.path);
505+
const typeReferencePackagePath: string = this.extractor.packageJsonLookup
506+
.tryFindPackagePathUpwards(sourceFile.path);
507507
// Example: "@microsoft/sp-core-library"
508508
let typeReferencePackageName: string = '';
509509

@@ -512,7 +512,8 @@ abstract class ApiItem {
512512
if (!typeReferencePackagePath) {
513513
typeReferencePackageName = this.extractor.package.name;
514514
} else {
515-
typeReferencePackageName = PackageJsonHelpers.readPackageName(typeReferencePackagePath);
515+
typeReferencePackageName = this.extractor.packageJsonLookup
516+
.readPackageName(typeReferencePackagePath);
516517

517518
typingsScopeNames.every(typingScopeName => {
518519
if (typeReferencePackageName.indexOf(typingScopeName) > -1) {

‎libraries/api-extractor/src/definitions/ApiPackage.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import ApiItem, { ApiItemKind, IApiItemOptions } from './ApiItem';
99
import ApiItemContainer from './ApiItemContainer';
1010
import ApiNamespace from './ApiNamespace';
1111
import TypeScriptHelpers from '../TypeScriptHelpers';
12-
import PackageJsonHelpers from '../PackageJsonHelpers';
1312
import { IExportedSymbol } from '../IExportedSymbol';
1413

1514
/**
@@ -46,7 +45,7 @@ export default class ApiPackage extends ApiItemContainer {
4645
super(ApiPackage._getOptions(extractor, rootFile));
4746
this.kind = ApiItemKind.Package;
4847
// The scoped package name. (E.g. "@microsoft/api-extractor")
49-
this.name = PackageJsonHelpers.readPackageName(this.extractor.packageFolder);
48+
this.name = this.extractor.packageJsonLookup.readPackageName(this.extractor.packageFolder);
5049

5150
const exportSymbols: ts.Symbol[] = this.typeChecker.getExportsOfModule(this.declarationSymbol);
5251
if (exportSymbols) {
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/// <reference types="mocha" />
2+
/* tslint:disable:no-function-expression - Mocha uses a poorly scoped "this" pointer */
3+
4+
import { assert } from 'chai';
5+
import * as path from 'path';
6+
import PackageJsonLookup from '../PackageJsonLookup';
7+
8+
describe('PackageJsonLookup', function (): void {
9+
10+
describe('basic tests', function (): void {
11+
12+
it('readPackageName() test', function (): void {
13+
const packageJsonLookup: PackageJsonLookup = new PackageJsonLookup();
14+
const sourceFilePath: string = path.join(__dirname, '../../testInputs/example1');
15+
assert.equal(packageJsonLookup.readPackageName(sourceFilePath), 'example1');
16+
});
17+
18+
it('tryFindPackagePathUpwards() test', function (): void {
19+
const packageJsonLookup: PackageJsonLookup = new PackageJsonLookup();
20+
const sourceFilePath: string = path.join(__dirname, '../../testInputs/example1/folder/AliasClass.ts');
21+
22+
// Example: C:\web-build-tools\libraries\api-extractor\testInputs\example1
23+
const foundPath: string = packageJsonLookup.tryFindPackagePathUpwards(sourceFilePath);
24+
assert.isTrue(foundPath.search(/[\\/]example1$/i) >= 0, 'Unexpected result: ' + foundPath);
25+
});
26+
});
27+
});

0 commit comments

Comments
 (0)