Skip to content

Instantly share code, notes, and snippets.

@cantin
Created August 4, 2022 02:16
Show Gist options
  • Save cantin/71c598d602054e0c0a737a471b822315 to your computer and use it in GitHub Desktop.
Save cantin/71c598d602054e0c0a737a471b822315 to your computer and use it in GitHub Desktop.
I18n-tasks JS AST parser call finder function
let fs = require('fs')
let parser = require("@babel/parser")
let traverse = require("@babel/traverse")
function collectCalls(filepath) {
let results = []
let code = fs.readFileSync(filepath).toString()
let ast = parser.parse(code, {
// parse in strict mode and allow module declarations
sourceType: "module",
plugins: [
// enable jsx and flow syntax
"jsx",
],
});
traverse.default(ast, {
CallExpression(path) {
//console.log(path.node)
let { loc, start, end } = path.node
let { type, object: objectNode, property: propertyNode } = path.node.callee
if (type == 'MemberExpression' && objectNode.name == 'I18n' && (propertyNode.name == 't' || propertyNode.name == 'translate')) {
let [ { value: rawKey }, defaultArg ] = path.node.arguments
let h = {
path: filepath,
pos: start,
line_num: loc.start.line,
line_pos: loc.start.column,
line: code.substring(start, end),
raw_key: rawKey || null,
default_arg: null,
}
if (defaultArg && defaultArg.type == 'ObjectExpression') {
let node = defaultArg.properties.find(node => node.key.name == 'defaultValue')
if (node) {
if (node.value.type == 'StringLiteral') {
h.default_arg = node.value.value
} else if (node.value.type == 'ObjectExpression') {
h.default_arg = node.value.properties.reduce((obj, property) => {
obj[property.key.name] = property.value.value
return obj
}, {})
}
}
}
results.push(h)
}
},
})
return results
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment