Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: Add bundle symbol extractor tool #22002

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 10 additions & 1 deletion packages/core/test/bundling/hello_world/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package(default_visibility = ["//visibility:public"])

load("//tools:defaults.bzl", "ts_library")
load("//tools/symbol-extractor:index.bzl", "js_expected_symbol_test")
load("//packages/bazel/src:ng_rollup_bundle.bzl", "ng_rollup_bundle")
load("@build_bazel_rules_nodejs//:defs.bzl", "jasmine_node_test")

Expand Down Expand Up @@ -31,7 +32,9 @@ ts_library(
name = "test_lib",
testonly = 1,
srcs = ["domino_typings.d.ts"] + glob(["*_spec.ts"]),
deps = ["//packages:types"],
deps = [
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

buildifier

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"//packages:types",
],
)

jasmine_node_test(
Expand All @@ -44,3 +47,9 @@ jasmine_node_test(
],
deps = [":test_lib"],
)

js_expected_symbol_test(
name = "symbol_test",
src = ":bundle.min_debug.js",
golden = ":bundle.golden_symbols.json",
)
83 changes: 83 additions & 0 deletions packages/core/test/bundling/hello_world/bundle.golden_symbols.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
[
{
"name": "EMPTY$1"
},
{
"name": "NO_CHANGE"
},
{
"name": "Symbol$1"
},
{
"name": "__global$1"
},
{
"name": "__self$1"
},
{
"name": "__window$1"
},
{
"name": "_renderCompCount"
},
{
"name": "_root"
},
{
"name": "canInsertNativeNode"
},
{
"name": "createLNode"
},
{
"name": "createLView"
},
{
"name": "domRendererFactory3"
},
{
"name": "enterView"
},
{
"name": "executeHooks"
},
{
"name": "findFirstRNode"
},
{
"name": "getDirectiveInstance"
},
{
"name": "getNextLNodeWithProjection"
},
{
"name": "getNextOrParentSiblingNode"
},
{
"name": "invertObject"
},
{
"name": "isProceduralRenderer"
},
{
"name": "leaveView"
},
{
"name": "locateHostElement"
},
{
"name": "noop$2"
},
{
"name": "refreshDynamicChildren"
},
{
"name": "renderComponentOrTemplate"
},
{
"name": "renderEmbeddedTemplate"
},
{
"name": "stringify$1"
}
]
6 changes: 2 additions & 4 deletions packages/core/test/bundling/hello_world/treeshaking_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,8 @@ import * as domino from 'domino';

describe('treeshaking with uglify', () => {
let content: string;
beforeAll(() => {
content = fs.readFileSync(
path.join(process.env['TEST_SRCDIR'], PACKAGE, 'bundle.min_debug.js'), UTF8);
});
const contentPath = require.resolve(path.join(PACKAGE, 'bundle.min_debug.js'));
beforeAll(() => { content = fs.readFileSync(contentPath, UTF8); });

it('should drop unused TypeScript helpers',
() => { expect(content).not.toContain('__asyncGenerator'); });
Expand Down
40 changes: 40 additions & 0 deletions tools/symbol-extractor/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package(default_visibility = ["//visibility:public"])

load("//tools:defaults.bzl", "ts_library")
load("@build_bazel_rules_nodejs//:defs.bzl", "jasmine_node_test")

ts_library(
name = "lib",
testonly = 1,
srcs = glob(
["**/*.ts"],
exclude = [
"**/*_spec.ts",
"**/*_spec",
],
),
deps = [
"//packages:types",
],
)

ts_library(
name = "test_lib",
testonly = 1,
srcs = glob(
["**/*_spec.ts"],
exclude = ["symbol_extractor_spec/**"],
),
deps = [
":lib",
"//packages:types",
],
)

jasmine_node_test(
name = "test",
data = glob(["symbol_extractor_spec/**"]),
deps = [
":test_lib",
],
)
54 changes: 54 additions & 0 deletions tools/symbol-extractor/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import * as fs from 'fs';
import * as path from 'path';
import {SymbolExtractor} from './symbol_extractor';

// These keys are arbitrary and local to this test.
const update_var = 'UPDATE_GOLDEN';
const update_val = 1;

if (require.main === module) {
const doUpdate = process.env[update_var] == update_val;
const args = process.argv.slice(2) as[string, string];
process.exitCode = main(args, doUpdate) ? 0 : 1;
}

/**
* CLI main method.
*
* ```
* cli javascriptFilePath.js goldenFilePath.json
* ```
*/
function main(argv: [string, string], doUpdate: boolean): boolean {
const javascriptFilePath = require.resolve(argv[0]);
const goldenFilePath = require.resolve(argv[1]);

const javascriptContent = fs.readFileSync(javascriptFilePath).toString();
const goldenContent = fs.readFileSync(goldenFilePath).toString();

const symbolExtractor = new SymbolExtractor(javascriptFilePath, javascriptContent);

let passed: boolean = false;
if (doUpdate) {
fs.writeFileSync(goldenFilePath, JSON.stringify(symbolExtractor.actual, undefined, 2));
console.error('Updated gold file:', goldenFilePath);
passed = true;
} else {
passed = symbolExtractor.compareAndPrintError(goldenFilePath, goldenContent);
if (!passed) {
console.error(`TEST FAILED!`);
console.error(` To update the golden file run: `);
console.error(
` bazel run --define ${update_var}=${update_val} ${process.env['BAZEL_TARGET']}`);
}
}
return passed;
}
22 changes: 22 additions & 0 deletions tools/symbol-extractor/index.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Copyright Google Inc. All Rights Reserved.
#
# Use of this source code is governed by an MIT-style license that can be
# found in the LICENSE file at https://angular.io/license

"""This test verifies that a set of top level symbols from a javascript file match a gold file.
"""

load("@build_bazel_rules_nodejs//:defs.bzl", "nodejs_test")

def js_expected_symbol_test(name, src, golden, **kwargs):
all_data = [src, golden]
all_data += [Label("//tools/symbol-extractor:lib")]
entry_point = "angular/tools/symbol-extractor/cli.js"

nodejs_test(
name = name,
data = all_data,
entry_point = entry_point,
templated_args = ["$(location %s)" % src, "$(location %s)" % golden],
**kwargs
)
116 changes: 116 additions & 0 deletions tools/symbol-extractor/symbol_extractor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import * as fs from 'fs';
import * as ts from 'typescript';


export interface Symbol { name: string; }

export class SymbolExtractor {
public actual: Symbol[];

static symbolSort(a: Symbol, b: Symbol): number {
return a.name == b.name ? 0 : a.name < b.name ? -1 : 1;
}

static parse(path: string, contents: string): Symbol[] {
const symbols: Symbol[] = [];
const source: ts.SourceFile = ts.createSourceFile(path, contents, ts.ScriptTarget.Latest, true);
let fnDepth = 0;
function visitor(child: ts.Node) {
switch (child.kind) {
case ts.SyntaxKind.FunctionExpression:
fnDepth++;
if (fnDepth <= 1) {
// Only go into function expression once for the outer closure.
ts.forEachChild(child, visitor);
}
break;
case ts.SyntaxKind.SourceFile:
case ts.SyntaxKind.VariableStatement:
case ts.SyntaxKind.VariableDeclarationList:
case ts.SyntaxKind.ExpressionStatement:
case ts.SyntaxKind.CallExpression:
case ts.SyntaxKind.ParenthesizedExpression:
case ts.SyntaxKind.Block:
case ts.SyntaxKind.PrefixUnaryExpression:
ts.forEachChild(child, visitor);
break;
case ts.SyntaxKind.VariableDeclaration:
const varDecl = child as ts.VariableDeclaration;
if (varDecl.initializer) {
symbols.push({name: varDecl.name.getText()});
}
break;
case ts.SyntaxKind.FunctionDeclaration:
const funcDecl = child as ts.FunctionDeclaration;
funcDecl.name && symbols.push({name: funcDecl.name.getText()});
break;
default:
// Left for easier debugging.
// console.log('###', ts.SyntaxKind[child.kind], child.getText());
}
if (symbols.length && symbols[symbols.length - 1].name == 'type') {
debugger;
}
}
visitor(source);
symbols.sort(SymbolExtractor.symbolSort);
return symbols;
}

static diff(actual: Symbol[], expected: string|((Symbol | string)[])): {[name: string]: string} {
if (typeof expected == 'string') {
expected = JSON.parse(expected);
}
const diff: {[name: string]: ('missing' | 'extra')} = {};
(expected as(Symbol | string)[]).forEach((nameOrSymbol) => {
diff[typeof nameOrSymbol == 'string' ? nameOrSymbol : nameOrSymbol.name] = 'missing';
});

actual.forEach((s) => {
if (diff[s.name] === 'missing') {
delete diff[s.name];
} else {
diff[s.name] = 'extra';
}
});
return diff;
}

constructor(private path: string, private contents: string) {
this.actual = SymbolExtractor.parse(path, contents);
}

expect(expectedSymbols: (string|Symbol)[]) {
expect(SymbolExtractor.diff(this.actual, expectedSymbols)).toEqual({});
}

compareAndPrintError(goldenFilePath: string, expected: string|((Symbol | string)[])): boolean {
let passed = true;
const diff = SymbolExtractor.diff(this.actual, expected);
Object.keys(diff).forEach((key) => {
if (passed) {
console.error(`Expected symbols in '${this.path}' did not match gold file.`);
passed = false;
}
console.error(` Symbol: ${key} => ${diff[key]}`);
});

return passed;
}
}

function toSymbol(v: string | Symbol): Symbol {
return typeof v == 'string' ? {'name': v} : v as Symbol;
}

function toName(symbol: Symbol): string {
return symbol.name;
}