b2362b15af1958ed602d2bacfd9283115e53d773.svn-base
2.38 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
78
79
80
81
82
83
84
85
86
87
88
89
90
'use strict'
var fs = require('fs')
var path = require('path')
var highlighter = require('..')
var colors = require('ansicolors')
var diffFile = path.join(__dirname, 'git-diff.txt')
var diff = fs.readFileSync(diffFile, 'utf-8')
// @@ is not a valid js token, so when we see it, we can be sure that we are dealing with a git or svn diff
var diffRegex = /^@@[^@]+@@$/m
var diffIndRegex = /^(@@[^@]+@@)(.*)$/
var addRemRegex = /^[+-]/
var lines = diff.split('\n')
function isDiff(lines) {
return !!lines
.filter(function(line) {
return diffRegex.test(line)
})
.length
}
diff = isDiff(lines)
function tryHighlight(code) {
// TODO: need to remove symbols added to get valid code
// this should be done by getting the splits instead of the actual code from the highlighter
// now we can remove first / last one after highlighting completed
function tryAppending(appended, tryNext) {
try {
return highlighter.highlight(code + appended)
} catch (e) {
return tryNext(code)
}
}
function tryRemoveLeadingComma(tryNext) {
var success
try {
success = highlighter.highlight(code.replace(/^( +),(.+)$/, '$1 $2'))
return success
} catch (e) {
return tryNext(code)
}
}
function tryPlain() {
try {
return highlighter.highlight(code)
} catch (e) {
return tryCloseMustache()
}
}
function tryCloseMustache() { return tryAppending('}', tryCloseParen) }
function tryCloseParen() { return tryAppending('\\)', tryCloseMustacheParen) }
function tryCloseMustacheParen() { return tryAppending('})', tryRemovingCommas) }
function tryRemovingCommas() { return tryRemoveLeadingComma(giveUp) }
function giveUp() { return code }
return tryPlain()
}
function highlightDiffInd(line, matches) {
var highlighted = colors.brightBlue(matches[1])
var code = matches[2]
return code ? highlighted + tryHighlight(code) : highlighted
}
function colorsAddRemove(c) {
return addRemRegex.test(c) ? colors.yellow(c) : c
}
function highlightDiff(line) {
var diffIndMatches = diffIndRegex.exec(line)
return diffIndMatches
? highlightDiffInd(line, diffIndMatches)
: colorsAddRemove(line[0]) + tryHighlight(line.slice(1))
}
var highlightFn = diff ? highlightDiff : tryHighlight
var highlightedLines = lines.map(highlightFn)
console.log(highlightedLines.join('\n'))