Skip to content

Commit

Permalink
test(perftool): add ast tree for exports name
Browse files Browse the repository at this point in the history
  • Loading branch information
Troff8 committed May 11, 2023
1 parent 68ea671 commit 18e464a
Show file tree
Hide file tree
Showing 4 changed files with 326 additions and 170 deletions.
4 changes: 4 additions & 0 deletions packages/perftool/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,11 @@
"react-dom": ">=16.8.0"
},
"dependencies": {
"@babel/parser": "^7.21.4",
"@babel/preset-env": "7.21.4",
"@babel/preset-react": "7.18.6",
"@babel/preset-typescript": "7.21.4",
"@babel/traverse": "^7.21.4",
"@swc/core": "1.3.50",
"babel-loader": "9.1.2",
"chalk": "5.2.0",
Expand All @@ -59,6 +61,8 @@
},
"devDependencies": {
"@jest/globals": "29.5.0",
"@types/babel__parser": "^7.1.1",
"@types/babel__traverse": "^7.18.4",
"@types/express": "4.17.17",
"@types/jest": "29.5.0",
"@types/morgan": "1.9.4",
Expand Down
45 changes: 41 additions & 4 deletions packages/perftool/src/build/collect.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { readFile } from 'fs/promises';
import fg from 'fast-glob';
import { parse } from '@babel/parser';
import * as _traverse from '@babel/traverse';

import getSubjectId from '../utils/subjectId';
import checkPath from '../utils/checkPath';
import { Config } from '../config';
import { debug, info, warn } from '../utils/logger';

export type ExportPickRule = 'named'; // | 'default' | 'all'
const traverse = (_traverse.default as unknown as typeof _traverse).default;

export type TestSubject = {
id: string;
Expand All @@ -18,12 +21,46 @@ export type TestModule = {
subjects: TestSubject[];
};

function getAst(content: string) {
const data = parse(content, {
sourceType: 'module',
plugins: [
'jsx',
'objectRestSpread',
'classProperties',
'optionalCatchBinding',
'asyncGenerators',
'decorators-legacy',
'flow',
'dynamicImport',
'estree',
],
});

return data;
}
function getExportsName(ast: any) {
const exports: any[] = [];
traverse(ast, {
ExportNamedDeclaration(path: any) {
if (path.node.declaration) {
exports.push(path.node.declaration.id?.name || '');
} else {
path.node.specifiers.array.forEach((specifier: any) => {
exports.push(specifier.exported.name);
});
}
},
});
return exports;
}

const PICK_RULE_METHODS: Record<ExportPickRule, (fileContents: string) => string[]> = {
named(fileContents) {
const regex = /export\s+(?:const|var|let|function)\s+?([\w$_][\w\d$_]*)/g;
const matches = [...fileContents.matchAll(regex)];

return matches.map(([, name]) => name);
debug(fileContents);
const ast = getAst(fileContents);
const exportsName = getExportsName(ast);
return exportsName;
},
};

Expand Down
Loading

0 comments on commit 18e464a

Please sign in to comment.