-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
54 lines (42 loc) · 1.14 KB
/
index.js
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
var path = require('path');
var walk = require('estree-walker').walk;
function uses (prog, variables) {
var results = variables.reduce(function (o, name) {
o[name] = false;
return o;
}, {});
walk(prog.scope.block, {
enter: function (node) {
if ('Identifier' === node.type) {
if (node.name in results) {
results[node.name] = true;
}
}
}
});
return results;
}
function inject (t, prog, variable, value) {
var operator = '=';
var left = t.identifier(variable);
var right = t.stringLiteral(value);
var expr = t.expressionStatement(t.assignmentExpression(operator, left, right));
prog.scope.block.body.unshift(expr);
}
module.exports = function (o) {
var t = o.types;
return {
visitor: {
Program: function (prog, state) {
var filename = path.resolve(state.file.opts.filename);
var results = uses(prog, ['__dirname', '__filename']);
if (results.__dirname) {
inject(t, prog, '__dirname', path.dirname(filename));
}
if (results.__filename) {
inject(t, prog, '__filename', filename);
}
}
}
};
}