-
Notifications
You must be signed in to change notification settings - Fork 2
/
astdiff.js
78 lines (66 loc) · 1.82 KB
/
astdiff.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'use strict';
var esprima = require('esprima'),
escodegen = require('escodegen'),
jsdiff = require('diff'),
astraverse = require('./astraverse');
function getTree(sourceCode) {
var tree;
try {
tree = esprima.parse(sourceCode);
} catch (e) {
throw 'unable to parse ' + sourceCode;
}
return tree;
}
function getDiff(file1, file2) {
var ast1,
ast2,
format1,
format2,
diff,
patch;
ast1 = getTree(file1);
ast2 = getTree(file2);
format1 = escodegen.generate(ast1);
format2 = escodegen.generate(ast2);
diff = jsdiff.diffLines(format2, format1);
patch = jsdiff.createPatch(undefined, format1, format2);
return patch;
}
function applyPatch(file1, diff) {
var format1,
ast1,
patched;
ast1 = getTree(file1);
format1 = escodegen.generate(ast1);
patched = jsdiff.applyPatch(format1, diff);
return patched + '\n';
}
function applyPatchPreserve(sourceCode, diff) {
var astOfOriginalFile,
regeneratedOriginalFile,
patched,
astOfPatchedFile;
function createAstWithSourceMap(source) {
return esprima.parse(source, {
loc: true,
source: source.toString()
});
}
astOfOriginalFile = createAstWithSourceMap(sourceCode);
regeneratedOriginalFile = escodegen.generate(astOfOriginalFile, {
sourceMapWithCode: true,
sourceContent: sourceCode.toString()
});
patched = jsdiff.applyPatch(regeneratedOriginalFile.code, diff);
astOfPatchedFile = esprima.parse(patched, {
loc: true,
source: patched
});
return astraverse.equalizeTrees(astOfPatchedFile, sourceCode, createAstWithSourceMap);
}
module.exports = {
diff: getDiff,
patch: applyPatch,
patchPreserve: applyPatchPreserve
};