Skip to content

Commit

Permalink
feat: collect calls before optimizing
Browse files Browse the repository at this point in the history
  • Loading branch information
merceyz committed Jun 8, 2019
1 parent 7ccf15f commit c2537e5
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,11 @@ const x = 'foo bar';
const y = foo === 'a' ? 'classA' : 'classB';
const z = (foo === 'a' ? 'classA ' : 'classB ') + (bar === 'c' ? 'classC' : 'classD');
```

---

| Name | Type | Default value |
| -------------- | --------- | ------------- |
| `collectCalls` | `boolean` | `false` |

Writes all function calls, before they are optimized, to a file. Used to help test the plugin on repositories.
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ import combineArguments from './visitors/combineArguments';
import createConditionalExpression from './visitors/createConditionalExpression';
import removeUnnecessaryCalls from './visitors/removeUnnecessaryCalls';
import createObjectKeyLookups from './visitors/createObjectKeyLookups';
import collectCalls from './visitors/collectCalls';

const visitors = [
findFunctionNames,
collectCalls,
extractObjectProperties,
propTypes,
stripLiterals,
Expand Down
1 change: 1 addition & 0 deletions src/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export function getOptions(options) {
libraries: ['clsx', 'classnames'],
functionNames: [],
removeUnnecessaryCalls: true,
collectCalls: false,
};
return { ...DefaultSettings, ...options };
}
32 changes: 32 additions & 0 deletions src/visitors/collectCalls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import * as t from '@babel/types';
import generate from '@babel/generator';
import fs from 'fs';
import osPath from 'path';

let stream = null;
let count = 0;

const visitor = {
CallExpression(path) {
const c = path.node.callee;
if (!t.isIdentifier(c) || !this.options.functionNames.includes(c.name)) {
return;
}

stream.write(`const x${++count} = ${generate(path.node).code};\n\n`);
},
};

export default (path, options) => {
if (!options.collectCalls) {
return;
}

if (stream === null) {
const filePath = osPath.join(__dirname, 'log.js');
stream = fs.createWriteStream(filePath, { flags: 'w' });
console.log('Writing calls to ' + filePath);
}

path.traverse(visitor, { options });
};

0 comments on commit c2537e5

Please sign in to comment.