Repository navigation
Expand file tree
/
Copy pathinstrument-code.js
More file actions
78 lines (65 loc) · 2.18 KB
/
Copy pathinstrument-code.js
File metadata and controls
78 lines (65 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
var falafel = require('falafel');
var call = function (name) {
return function (arg) {
return arg[name]();
};
};
var instruments = {
ExpressionStatement: function (id, node, before, after) {
node.update(node.source() + ';');
},
CallExpression: function (id, node, before, after) {
var source = node.source();
if (node.callee.source() === 'console.log') {
source = "_console.log(" + node.loc.start.line + ", " + node.arguments.map(call('source')).join(', ') + ")";
}
var newString = '(' + before(id, node) + ', ' + source + ', ' + after(id, node) + ')\n';
node.update(newString);
},
BinaryExpression: function (id, node, before, after) {
var newString = '(' + before(id, node) + ', ' + after(id, node) + ', ' + node.source() + ')';
node.update(newString);
},
//MemberExpression: function (id, node, before, after) {
// var source = node.source();
// if (source === 'console.log') {
// source = '_console.log';
// }
// node.update(source);
//}
};
var isInstrumentable = function (node) {
return !!instruments[node.type];
};
var instrumentNode = function (id, node, before, after) {
instruments[node.type](id, node, before, after);
};
module.exports = function (code, options) {
var before = options.before || function () { return ''; };
var after = options.after || function () { return ''; };
var insertionPoints = [];
var id = 1;
var instrumented = falafel(code, { loc: true, range: true }, function (node) {
if (!isInstrumentable(node)) return;
insertionPoints.push({
id: id,
type: 'start',
loc: node.loc.start
});
insertionPoints.push({
id: id,
type: 'end',
loc: node.loc.end
});
instrumentNode(id, node, before, after);
id++;
});
insertionPoints.sort(function (a, b) {
if (a.loc.line === b.loc.line) return a.loc.column - b.loc.column;
return a.loc.line - b.loc.line;
});
return {
code: instrumented,
insertionPoints: insertionPoints
};
};