Open History to see the last commit
1import ansis from 'ansis'
2import { diffWords } from 'diff'
3β
4export function logDiff(oldStr: string, newStr: string) {
5 const differences = diffWords(oldStr, newStr)
6β
7 let output = ''
8 let unchangedLines = ''
9β
10 function processUnchangedLines(lines: string): string {
11 const lineArray = lines.split('\n')
12 if (lineArray.length > 4) {
13 return [
14 ansis.dim(lineArray[0]),
15 ansis.dim(lineArray[1]),
16 '',
17 ansis.dim.bold(`... (${lineArray.length - 4} lines) ...`),
18 '',
19 ansis.dim(lineArray[lineArray.length - 2]),
20 ansis.dim(lineArray[lineArray.length - 1]),
21 ].join('\n')
22 }
23 return ansis.dim(lines)
24 }
25β
26 differences.forEach((part, index) => {
27 const nextPart = differences[index + 1]
28β
29 if (part.added) {
30 if (unchangedLines) {
31 output += processUnchangedLines(unchangedLines)
32 unchangedLines = ''
33 }
34 output += ansis.green.bold(part.value)
35 if (nextPart?.removed) output += ' '
36 } else if (part.removed) {
37 if (unchangedLines) {
38 output += processUnchangedLines(unchangedLines)
39 unchangedLines = ''
40 }
41 output += ansis.red.bold(part.value)
42 if (nextPart?.added) output += ' '
43 } else {
44 unchangedLines += part.value
45 }
46 })
47β
48 // Process any remaining unchanged lines at the end
49 if (unchangedLines) {
50 output += processUnchangedLines(unchangedLines)
51 }
52β
53 if (output) {
54 console.log('\nDiff:')
55 console.log(output + '\n\n')
56 } else {
57 console.log('No changes')
58 }
59}