(expected: string, actual: string, diffLineContextRange = 10)
| 14 | * colored diff string. |
| 15 | */ |
| 16 | export function diffText(expected: string, actual: string, diffLineContextRange = 10): string { |
| 17 | const redColorCode = chalk.red('ɵɵ').split('ɵɵ')[0]; |
| 18 | const greenColorCode = chalk.green('ɵɵ').split('ɵɵ')[0]; |
| 19 | const goldenDiff = diff.diffChars(actual, expected); |
| 20 | let fullResult = ''; |
| 21 | |
| 22 | for (const part of goldenDiff) { |
| 23 | // whitespace cannot be highlighted, so we use a tiny indicator character. |
| 24 | const valueForColor = part.value.replace(/[ \t]/g, '·'); |
| 25 | // green for additions, red for deletions |
| 26 | const text = part.added |
| 27 | ? chalk.green(valueForColor) |
| 28 | : part.removed |
| 29 | ? chalk.red(valueForColor) |
| 30 | : chalk.reset(part.value); |
| 31 | |
| 32 | fullResult += text; |
| 33 | } |
| 34 | |
| 35 | const lines = fullResult.split(/\n/g); |
| 36 | const linesToRender = new Set<number>(); |
| 37 | |
| 38 | // Find lines with diff, and include context lines around them. |
| 39 | for (const [index, l] of lines.entries()) { |
| 40 | if (l.includes(redColorCode) || l.includes(greenColorCode)) { |
| 41 | const contextBottom = index - diffLineContextRange; |
| 42 | const contextTop = index + diffLineContextRange; |
| 43 | |
| 44 | numbersFromTo(Math.max(0, contextBottom), index).forEach((lineNum) => |
| 45 | linesToRender.add(lineNum), |
| 46 | ); |
| 47 | numbersFromTo(index, Math.min(contextTop, lines.length - 1)).forEach((lineNum) => |
| 48 | linesToRender.add(lineNum), |
| 49 | ); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | let result = ''; |
| 54 | let previous = -1; |
| 55 | |
| 56 | // Compute full diff text. Add markers if lines were skipped. |
| 57 | for (const lineIndex of Array.from(linesToRender).sort((a, b) => a - b)) { |
| 58 | if (lineIndex - 1 !== previous) { |
| 59 | result += `${chalk.grey('... (lines above) ...')}\n`; |
| 60 | } |
| 61 | result += `${lines[lineIndex]}\n`; |
| 62 | previous = lineIndex; |
| 63 | } |
| 64 | |
| 65 | if (previous < lines.length - 1) { |
| 66 | result += `${chalk.grey('... (lines below) ...\n')}`; |
| 67 | } |
| 68 | |
| 69 | return result; |
| 70 | } |
| 71 | |
| 72 | function numbersFromTo(start: number, end: number): number[] { |
| 73 | const list: number[] = []; |
searching dependent graphs…