Skip to content

Commit 894bf71

Browse files
authored
Merge pull request microsoft#451 from Microsoft/pgonzal/extractor-error-detection
Improve api-extractor invocation so it's easier to determine failure
2 parents eebc3dc + adf47bd commit 894bf71

10 files changed

Lines changed: 154 additions & 21 deletions

File tree

‎apps/api-extractor/src/DebugRun.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ const extractor: Extractor = new Extractor(
2626
}
2727
);
2828

29-
extractor.analyzeProject();
29+
if (!extractor.processProject()) {
30+
console.log('processProject() failed the build');
31+
} else {
32+
console.log('processProject() succeeded');
33+
}
3034

3135
console.log('DebugRun completed.');

‎apps/api-extractor/src/ExternalApiHelper.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,8 @@ export default class ExternalApiHelper {
6969
}
7070
});
7171

72-
extractor.analyzeProject();
72+
if (!extractor.processProject()) {
73+
throw new Error('API Extractor failed to process the input: ' + externalPackageFilePath);
74+
}
7375
}
7476
}

‎apps/api-extractor/src/cli/ApiExtractorCommandLine.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
22
// See LICENSE in the project root for license information.
33

4+
import * as os from 'os';
5+
import * as colors from 'colors';
6+
47
import { CommandLineParser } from '@microsoft/ts-command-line';
58
import { RunAction } from './RunAction';
69

@@ -16,6 +19,15 @@ export class ApiExtractorCommandLine extends CommandLineParser {
1619
protected onDefineParameters(): void { // override
1720
}
1821

22+
protected onExecute(): void { // override
23+
try {
24+
super.onExecute();
25+
} catch (error) {
26+
console.error(os.EOL + colors.red('ERROR: ' + error.message.trim()));
27+
process.exitCode = 1;
28+
}
29+
}
30+
1931
private _populateActions(): void {
2032
this.addAction(new RunAction(this));
2133
}

‎apps/api-extractor/src/cli/RunAction.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
22
// See LICENSE in the project root for license information.
33

4+
import * as colors from 'colors';
45
import * as fsx from 'fs-extra';
56
import * as os from 'os';
67
import * as path from 'path';
@@ -82,6 +83,10 @@ export class RunAction extends CommandLineAction {
8283
const extractor: Extractor = new Extractor(config, {
8384
localBuild: this._localParameter.value
8485
});
85-
extractor.analyzeProject();
86+
87+
if (!extractor.processProject()) {
88+
console.log(os.EOL + colors.yellow('API Extractor completed with errors or warnings'));
89+
process.exitCode = 1;
90+
}
8691
}
8792
}

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

Lines changed: 36 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,10 @@ import { ExtractorContext } from '../ExtractorContext';
1717
import { ILogger } from './ILogger';
1818
import ApiJsonGenerator from '../generators/ApiJsonGenerator';
1919
import ApiFileGenerator from '../generators/ApiFileGenerator';
20+
import { MonitoredLogger } from './MonitoredLogger';
2021

2122
/**
22-
* Options for {@link Extractor.analyzeProject}.
23+
* Options for {@link Extractor.processProject}.
2324
* @public
2425
*/
2526
export interface IAnalyzeProjectOptions {
@@ -79,11 +80,11 @@ export class Extractor {
7980
logError: (message: string) => console.error(colors.red(message))
8081
};
8182

82-
private _config: IExtractorConfig;
83-
private _program: ts.Program;
84-
private _localBuild: boolean;
85-
private _logger: ILogger;
86-
private _absoluteRootFolder: string;
83+
private readonly _config: IExtractorConfig;
84+
private readonly _program: ts.Program;
85+
private readonly _localBuild: boolean;
86+
private readonly _monitoredLogger: MonitoredLogger;
87+
private readonly _absoluteRootFolder: string;
8788

8889
private static _applyConfigDefaults(config: IExtractorConfig): IExtractorConfig {
8990
// Use the provided config to override the defaults
@@ -93,17 +94,18 @@ export class Extractor {
9394
return normalized;
9495
}
9596

96-
public constructor (config: IExtractorConfig, options?: IExtractorOptions) {
97+
public constructor(config: IExtractorConfig, options?: IExtractorOptions) {
98+
let mergedLogger: ILogger;
9799
if (options && options.customLogger) {
98-
this._logger = lodash.merge(lodash.cloneDeep(Extractor._defaultLogger),
99-
options.customLogger);
100+
mergedLogger = lodash.merge(lodash.clone(Extractor._defaultLogger), options.customLogger);
100101
} else {
101-
this._logger = Extractor._defaultLogger;
102+
mergedLogger = Extractor._defaultLogger;
102103
}
104+
this._monitoredLogger = new MonitoredLogger(mergedLogger);
103105

104106
this._config = Extractor._applyConfigDefaults(config);
105107

106-
this._logger.logVerbose('API Extractor Config: ' + JSON.stringify(this._config));
108+
this._monitoredLogger.logVerbose('API Extractor Config: ' + JSON.stringify(this._config));
107109

108110
if (!options) {
109111
options = { };
@@ -160,8 +162,21 @@ export class Extractor {
160162

161163
/**
162164
* Invokes the API Extractor engine, using the configuration that was passed to the constructor.
165+
* @deprecated Use {@link Extractor.processProject} instead.
163166
*/
164167
public analyzeProject(options?: IAnalyzeProjectOptions): void {
168+
this.processProject(options);
169+
}
170+
171+
/**
172+
* Invokes the API Extractor engine, using the configuration that was passed to the constructor.
173+
* @param options - provides additional runtime state that is NOT part of the API Extractor
174+
* config file.
175+
* @returns true if there were no errors or warnings; false if the tool chain should fail the build
176+
*/
177+
public processProject(options?: IAnalyzeProjectOptions): boolean {
178+
this._monitoredLogger.resetCounters();
179+
165180
if (!options) {
166181
options = { };
167182
}
@@ -178,7 +193,7 @@ export class Extractor {
178193
const context: ExtractorContext = new ExtractorContext({
179194
program: this._program,
180195
entryPointFile: path.resolve(this._absoluteRootFolder, projectConfig.entryPointSourceFile),
181-
logger: this._logger,
196+
logger: this._monitoredLogger,
182197
policies: this._config.policies
183198
});
184199

@@ -199,7 +214,7 @@ export class Extractor {
199214
const jsonGenerator: ApiJsonGenerator = new ApiJsonGenerator();
200215
const apiJsonFilename: string = path.join(outputFolder, packageBaseName + '.api.json');
201216

202-
this._logger.logVerbose('Writing: ' + apiJsonFilename);
217+
this._monitoredLogger.logVerbose('Writing: ' + apiJsonFilename);
203218
jsonGenerator.writeJsonFile(apiJsonFilename, context);
204219
}
205220

@@ -228,30 +243,34 @@ export class Extractor {
228243
if (!ApiFileGenerator.areEquivalentApiFileContents(actualApiReviewContent, expectedApiReviewContent)) {
229244
if (!this._localBuild) {
230245
// For production, issue a warning that will break the CI build.
231-
this._logger.logWarning('You have changed the public API signature for this project.'
246+
this._monitoredLogger.logWarning('You have changed the public API signature for this project.'
232247
// @microsoft/gulp-core-build seems to run JSON.stringify() on the error messages for some reason,
233248
// so try to avoid escaped characters:
234249
+ ` Please overwrite ${expectedApiReviewShortPath} with a`
235250
+ ` copy of ${actualApiReviewShortPath}`
236251
+ ' and then request an API review. See the Git repository README.md for more info.');
237252
} else {
238253
// For a local build, just copy the file automatically.
239-
this._logger.logWarning('You have changed the public API signature for this project.'
254+
this._monitoredLogger.logWarning('You have changed the public API signature for this project.'
240255
+ ` Updating ${expectedApiReviewShortPath}`);
241256

242257
fsx.writeFileSync(expectedApiReviewPath, actualApiReviewContent);
243258
}
244259
} else {
245-
this._logger.logVerbose(`The API signature is up to date: ${actualApiReviewShortPath}`);
260+
this._monitoredLogger.logVerbose(`The API signature is up to date: ${actualApiReviewShortPath}`);
246261
}
247262
} else {
248263
// NOTE: This warning seems like a nuisance, but it has caught genuine mistakes.
249264
// For example, when projects were moved into category folders, the relative path for
250265
// the API review files ended up in the wrong place.
251-
this._logger.logError(`The API review file has not been set up. Do this by copying ${actualApiReviewShortPath}`
266+
this._monitoredLogger.logError(`The API review file has not been set up.`
267+
+ ` Do this by copying ${actualApiReviewShortPath}`
252268
+ ` to ${expectedApiReviewShortPath} and committing it.`);
253269
}
254270
}
271+
272+
// If there were any errors or warnings, then fail the build
273+
return (this._monitoredLogger.errorCount + this._monitoredLogger.warningCount) === 0;
255274
}
256275

257276
private _getShortFilePath(absolutePath: string): string {
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
2+
// See LICENSE in the project root for license information.
3+
4+
import { ILogger } from './ILogger';
5+
6+
/**
7+
* Used to collect statistics for an ILogger implementation.
8+
*/
9+
export class MonitoredLogger implements ILogger {
10+
/**
11+
* Number of calls to logError()
12+
*/
13+
public errorCount: number;
14+
15+
/**
16+
* Number of calls to logWarning()
17+
*/
18+
public warningCount: number;
19+
20+
/**
21+
* Number of calls to any logging method.
22+
*/
23+
public messageCount: number;
24+
25+
private _innerLogger: ILogger;
26+
27+
constructor(logger: ILogger) {
28+
this._innerLogger = logger;
29+
this.resetCounters();
30+
}
31+
32+
public logVerbose(message: string): void {
33+
++this.messageCount;
34+
this._innerLogger.logVerbose(message);
35+
}
36+
37+
public logInfo(message: string): void {
38+
++this.messageCount;
39+
this._innerLogger.logInfo(message);
40+
}
41+
42+
public logWarning(message: string): void {
43+
++this.messageCount;
44+
++this.warningCount;
45+
this._innerLogger.logWarning(message);
46+
}
47+
48+
public logError(message: string): void {
49+
++this.messageCount;
50+
++this.errorCount;
51+
this._innerLogger.logError(message);
52+
}
53+
54+
public resetCounters(): void {
55+
this.errorCount = 0;
56+
this.warningCount = 0;
57+
this.messageCount = 0;
58+
}
59+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"changes": [
3+
{
4+
"packageName": "@microsoft/api-extractor",
5+
"comment": "Add Extractor.processProject() whose return value indicates success",
6+
"type": "minor"
7+
},
8+
{
9+
"packageName": "@microsoft/api-extractor",
10+
"comment": "Deprecate Extractor.analyzeProject() API",
11+
"type": "patch"
12+
}
13+
],
14+
"packageName": "@microsoft/api-extractor",
15+
"email": "pgonzal@users.noreply.github.com"
16+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"changes": [
3+
{
4+
"comment": "",
5+
"packageName": "@microsoft/gulp-core-build-typescript",
6+
"type": "none"
7+
}
8+
],
9+
"packageName": "@microsoft/gulp-core-build-typescript",
10+
"email": "pgonzal@users.noreply.github.com"
11+
}

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@ class ExternalApiHelper {
1313
// @public
1414
class Extractor {
1515
public constructor(config: IExtractorConfig, options?: IExtractorOptions);
16+
// @deprecated
1617
public analyzeProject(options?: IAnalyzeProjectOptions): void;
1718
public static jsonSchema: JsonSchema;
19+
public processProject(options?: IAnalyzeProjectOptions): boolean;
1820
}
1921

2022
// @public

‎core-build/gulp-core-build-typescript/src/ApiExtractorTask.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,10 @@ export class ApiExtractorTask extends GulpTask<IApiExtractorTaskConfig> {
146146
};
147147

148148
const extractor: Extractor = new Extractor(extractorConfig, extractorOptions);
149-
extractor.analyzeProject();
149+
150+
// NOTE: processProject() returns false if errors or warnings occurred, however we
151+
// already handle this above via our customLogger
152+
extractor.processProject();
150153
} catch (e) {
151154
completeCallback(e.message);
152155
return;

0 commit comments

Comments
 (0)