forked from xiemaisi/acg.js
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathrequireJsGraph.js
More file actions
70 lines (62 loc) · 2.72 KB
/
requireJsGraph.js
File metadata and controls
70 lines (62 loc) · 2.72 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
if (typeof define !== 'function') {
var define = require('amdefine')(module);
}
define(function(require, exports) {
var assert = require('assert'),
astutil = require('./astutil'),
_ = require('./underscore'),
fs = require('fs');
function makeRequireJsGraph(ast) {
assert.equal(1, ast.programs.length, "Can only have one starting point at the moment.");
var rx = /^.*\\(.+\\)*(.+)\.(.+)$/g;
var regexParse = rx.exec(ast.programs[0].attr.filename);
var partialFileName = regexParse[2] + ".js",
fileName = "./" + partialFileName,
folder = regexParse[0].split(/[a-zA-Z]+\.js/)[0].replace(/\/$/, "\\");
var dependencyGraph = [];
astutil.visit(ast, function(node) {
switch (node.type) {
case 'CallExpression' :
if (node.callee.name === "define" || node.callee.name === "require") {
var dependencies = [], argument = node.arguments[0];
if (argument.type === "ArrayExpression") {
argument.elements.forEach(function(element) {
dependencies.push(element.value + ".js");
});
} else if (argument.type === "Literal") {
dependencies.push(argument.value + ".js");
}
dependencies.forEach(function(dependency) {
dependencyGraph.push(new Dependency(fileName, dependency));
});
}
break;
}
});
dependencyGraph.map(function(dep){return dep.to}).forEach(function(outgoingDep) {
var normOutgoingDep = outgoingDep.replace(/^.\//, "");
normOutgoingDep = normOutgoingDep.replace(/^\//, "");
normOutgoingDep = normOutgoingDep.replace(/\//, "\\");
var newStart = folder + normOutgoingDep;
if (fs.existsSync(newStart)) {
var referencedAST = astutil.buildAST([newStart]);
dependencyGraph = dependencyGraph.concat(makeRequireJsGraph(referencedAST))
}
});
return _.uniq(dependencyGraph, function(edge) {
return edge.toString();
});
}
function Dependency(from, to) {
this.from = from;
this.to = to;
this.toString = function() {
return removeLeadingPointSlash(this.from) + " -> " + removeLeadingPointSlash(this.to);
};
function removeLeadingPointSlash(path) {
return path.replace(/^\.?\//, "");
}
}
exports.makeRequireJsGraph = makeRequireJsGraph;
return exports;
});