forked from vitest-dev/vitest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
diff.ts
51 lines (41 loc) · 1.13 KB
/
diff.ts
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
import { getColors } from './colors'
import { diffDescriptors, getConcordanceTheme } from './descriptors'
export interface DiffOptions {
showLegend?: boolean
}
/**
* Returns unified diff between two strings with coloured ANSI output.
*
* @private
* @param {String} actual
* @param {String} expected
* @return {string} The diff.
*/
export function unifiedDiff(actual: unknown, expected: unknown, options: DiffOptions = {}) {
const theme = getConcordanceTheme()
const diff = diffDescriptors(actual, expected, { theme })
const { showLegend = true } = options
const counts = {
'+': 0,
'-': 0,
}
const c = getColors()
const plus = theme.diffGutters.actual
const minus = ` ${c.green('+')}`
const lines = diff.split(/\r?\n/g)
lines.forEach((line) => {
if (line.startsWith(plus))
counts['+']++
else if (line.startsWith(minus))
counts['-']++
})
if (counts['+'] === 0 && counts['-'] === 0)
return ''
let legend = ''
if (showLegend) {
legend = ` ${c.green(`- Expected - ${counts['-']}`)}
${c.red(`+ Received + ${counts['+']}`)}
`
}
return legend + diff.replace(/␊\s*$/mg, '')
}