@amplitude/ampli
Version:
Amplitude CLI
87 lines (86 loc) • 3.32 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_1 = require("lodash");
const child_process_1 = require("child_process");
const base_1 = require("../base");
const RubyAst_1 = require("./RubyAst");
const DEFAULT_ITLY_NAMES = ['itly', 'Itly', '_itly'];
const rubyAst = new RubyAst_1.default();
function check(node, ampliInstanceNames, addReference) {
if (!node || !(node instanceof Array) || node.length < 4) {
return false;
}
let action;
if (typeof node[0] === 'string') {
[action] = node;
}
if (!action || !['command_call', 'call'].includes(action)) {
return false;
}
const callJson = rubyAst.astArrayToJson(node);
if (callJson) {
const varRef = callJson.var_ref;
if (varRef
&& ampliInstanceNames.includes(varRef.name)
&& callJson.ident) {
const { name, location: [row, column,], } = callJson.ident;
addReference(name, row, column);
return true;
}
const constPathRef = callJson.const_path_ref;
if (constPathRef
&& constPathRef.var_ref && ampliInstanceNames.includes(constPathRef.var_ref.name)
&& constPathRef.const) {
const { name, location: [row, column,], } = constPathRef.const;
addReference(lodash_1.snakeCase(name), row, column);
return true;
}
}
return false;
}
function recurse(node, ampliInstanceNames, addReference) {
if (check(node, ampliInstanceNames, addReference)) {
return;
}
if (node instanceof Array) {
node.forEach(n => recurse(n, ampliInstanceNames, addReference));
}
}
class RubyVerifier extends base_1.Verifier {
constructor(ampliInstanceNames = DEFAULT_ITLY_NAMES) {
super('rb', ampliInstanceNames);
this.ampliInstanceNames = ampliInstanceNames;
this.getRubyAstJson = (filePath, fileContents) => {
const santizedCode = fileContents
.replace(/\\"/g, '\\\\"')
.replace(/\\'/g, `\\\\"`)
.replace(/"/g, '\\"')
.replace(/'/g, `\\'`)
.replace(/`/g, '\\`')
.replace(/\$/g, '\\$');
const script = `Ripper.sexp('${santizedCode}').to_json`;
const command = `ruby -r ripper -r json -e "print ${script}"`;
this.debug(`ruby -r ripper -r json -e "print Ripper.sexp('<contexts ${filePath}>').to_json"`);
const stdout = child_process_1.execSync(command, { encoding: 'utf-8' });
const astJson = JSON.parse(stdout);
return astJson;
};
this.getReferenceName = (eventName) => lodash_1.snakeCase(eventName);
}
checkDependencies() {
super.checkDependencies();
this.execSyncToString(`ruby --version`);
}
async doVerify(eventNames, workingDirs) {
return this.verifyEach((filePath, fileContents, addReference) => {
const astJson = this.getRubyAstJson(filePath, fileContents);
recurse(astJson, this.ampliInstanceNames, (name, row, column) => addReference({
filePath,
name,
row,
column,
}));
}, workingDirs);
}
}
exports.default = RubyVerifier;