|
1 |
| -const colorizeDiff = require('@npmcli/disparity-colors') |
2 | 1 | const jsDiff = require('diff')
|
3 | 2 |
|
4 | 3 | const shouldPrintPatch = require('./should-print-patch.js')
|
5 | 4 |
|
| 5 | +const colors = { |
| 6 | + // red |
| 7 | + removed: { open: '\x1B[31m', close: '\x1B[39m' }, |
| 8 | + // green |
| 9 | + added: { open: '\x1B[32m', close: '\x1B[39m' }, |
| 10 | + // blue |
| 11 | + header: { open: '\x1B[34m', close: '\x1B[39m' }, |
| 12 | + // cyan |
| 13 | + section: { open: '\x1B[36m', close: '\x1B[39m' }, |
| 14 | +} |
| 15 | + |
| 16 | +const color = (colorStr, colorId) => { |
| 17 | + const { open, close } = colors[colorId] |
| 18 | + // avoid highlighting the "\n" (would highlight till the end of the line) |
| 19 | + return colorStr.replace(/[^\n\r]+/g, open + '$&' + close) |
| 20 | +} |
| 21 | + |
6 | 22 | const formatDiff = ({ files, opts = {}, refs, versions }) => {
|
7 | 23 | let res = ''
|
8 | 24 | const srcPrefix = opts.diffNoPrefix ? '' : opts.diffSrcPrefix || 'a/'
|
@@ -83,9 +99,17 @@ const formatDiff = ({ files, opts = {}, refs, versions }) => {
|
83 | 99 | header(`+++ ${names.b}`)
|
84 | 100 | }
|
85 | 101 |
|
86 |
| - res += (opts.color |
87 |
| - ? colorizeDiff(patch, { headerLength }) |
88 |
| - : patch) |
| 102 | + if (opts.color) { |
| 103 | + // this RegExp will include all the `\n` chars into the lines, easier to join |
| 104 | + const lines = patch.split(/^/m) |
| 105 | + res += color(lines.slice(0, headerLength).join(''), 'header') |
| 106 | + res += lines.slice(headerLength).join('') |
| 107 | + .replace(/^-.*/gm, color('$&', 'removed')) |
| 108 | + .replace(/^\+.*/gm, color('$&', 'added')) |
| 109 | + .replace(/^@@.+@@/gm, color('$&', 'section')) |
| 110 | + } else { |
| 111 | + res += patch |
| 112 | + } |
89 | 113 | }
|
90 | 114 |
|
91 | 115 | return res.trim()
|
|
0 commit comments