Skip to content

Instantly share code, notes, and snippets.

@abiank
Created March 10, 2023 18:05
Show Gist options
  • Save abiank/e6ee754fb5d04bf6ecf61d86ae57d7d9 to your computer and use it in GitHub Desktop.
Save abiank/e6ee754fb5d04bf6ecf61d86ae57d7d9 to your computer and use it in GitHub Desktop.
// instrument all functions in a file with a call log
function transformAST(IN) {
// read the filename
const fs = require('fs');
const filename = fs.readFileSync(IN, 'utf8');
// transform the file into an AST
const esprima = require('esprima');
const ast = esprima.parseScript(filename);
// traverse the AST and find all function definitions
const traverse = require('estraverse').traverse;
traverse(ast, {
enter: function(node) {
if (node.type === 'FunctionDeclaration') {
// add a console.log() call with the names and values of all the parameters passed to the function, plus the name of the function
let logStatement = 'console.log(IN+":",';
logStatement += `'Function Name: ${node.id.name}',`;
node.params.forEach(param => {
logStatement += `'${param.name}: ' + ${param.name}, `;
});
logStatement += `);`;
node.body.body.unshift(esprima.parseScript(logStatement));
}
}
});
// return the AST as text
const escodegen = require('escodegen');
return escodegen.generate(ast);
}
//console.log(transformAST("./doushio/imager/index.js") )
console.log(transformAST("./test2.js") )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment