xref: /expo/tools/src/Diff.ts (revision f194f574)
1import chalk from 'chalk';
2import { diffLines } from 'diff';
3
4const CONTEXT_SIZE = 5;
5
6export function printDiff(before: string, after: string): void {
7  const diff = diffLines(before, after);
8  diff.forEach((part, index) => {
9    const isContextEnd = index > 0 && (diff[index - 1].added || diff[index - 1].removed);
10    const isContextStart =
11      index < diff.length - 1 && (diff[index + 1].added || diff[index + 1].removed);
12    let result = '';
13    if (part.added) {
14      result = chalk.green(part.value);
15    } else if (part.removed) {
16      result = chalk.red(part.value);
17    } else if (isContextEnd && isContextStart) {
18      const split = part.value.split('\n');
19      if (split.length - 1 > 2 * CONTEXT_SIZE) {
20        result = [
21          split.slice(0, CONTEXT_SIZE).join('\n'),
22          '...',
23          split.slice(-CONTEXT_SIZE - 1).join('\n'),
24        ].join('\n');
25      } else {
26        result = part.value;
27      }
28    } else if (isContextEnd) {
29      result = part.value
30        .split('\n')
31        .slice(0, CONTEXT_SIZE + 1)
32        .join('\n');
33    } else if (isContextStart) {
34      result = part.value
35        .split('\n')
36        .slice(-CONTEXT_SIZE - 1)
37        .join('\n');
38    }
39    process.stdout.write(result);
40  });
41  console.log();
42}
43