Skip to content

Instantly share code, notes, and snippets.

@ndruger
Last active August 29, 2015 13:59
Show Gist options
  • Save ndruger/10446010 to your computer and use it in GitHub Desktop.
Save ndruger/10446010 to your computer and use it in GitHub Desktop.
_ = require("lodash")
esprima = require('esprima')
escodegen = require('escodegen')
handleFunctionBody = (body, newStatements) ->
body.body = newStatements.concat(body.body)
insertStatementsIntoFunction = (s, newStatements) ->
if s.type == 'FunctionDeclaration' && s.body && s.body.type == 'BlockStatement'
handleFunctionBody(s.body, newStatements)
if _.isArray(s.body)
_.each(s.body, (b) =>
insertStatementsIntoFunction(b, newStatements)
)
else if s.body
insertStatementsIntoFunction(s.body, newStatements)
addLogger = (orig) ->
logger = esprima.parse('console.log("inserted console log", arguments);').body
tree = esprima.parse(orig)
# console.log(JSON.stringify(tree))
insertStatementsIntoFunction(tree, logger)
escodegen.generate(tree)
origCode = '' +
'function test(arg) {' +
'console.log("test function");' +
'};' +
'test("arg1");'
newCode = addLogger(origCode)
console.log(origCode)
console.log(newCode)
eval(newCode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment