diff --git a/workspaces/libnpmdiff/lib/format-diff.js b/workspaces/libnpmdiff/lib/format-diff.js index 8db110fbea186..a6606d94b8b30 100644 --- a/workspaces/libnpmdiff/lib/format-diff.js +++ b/workspaces/libnpmdiff/lib/format-diff.js @@ -1,8 +1,24 @@ -const colorizeDiff = require('@npmcli/disparity-colors') const jsDiff = require('diff') const shouldPrintPatch = require('./should-print-patch.js') +const colors = { + // red + removed: { open: '\x1B[31m', close: '\x1B[39m' }, + // green + added: { open: '\x1B[32m', close: '\x1B[39m' }, + // blue + header: { open: '\x1B[34m', close: '\x1B[39m' }, + // cyan + section: { open: '\x1B[36m', close: '\x1B[39m' }, +} + +const color = (colorStr, colorId) => { + const { open, close } = colors[colorId] + // avoid highlighting the "\n" (would highlight till the end of the line) + return colorStr.replace(/[^\n\r]+/g, open + '$&' + close) +} + const formatDiff = ({ files, opts = {}, refs, versions }) => { let res = '' const srcPrefix = opts.diffNoPrefix ? '' : opts.diffSrcPrefix || 'a/' @@ -83,9 +99,17 @@ const formatDiff = ({ files, opts = {}, refs, versions }) => { header(`+++ ${names.b}`) } - res += (opts.color - ? colorizeDiff(patch, { headerLength }) - : patch) + if (opts.color) { + // this RegExp will include all the `\n` chars into the lines, easier to join + const lines = patch.split(/^/m) + res += color(lines.slice(0, headerLength).join(''), 'header') + res += lines.slice(headerLength).join('') + .replace(/^-.*/gm, color('$&', 'removed')) + .replace(/^\+.*/gm, color('$&', 'added')) + .replace(/^@@.+@@/gm, color('$&', 'section')) + } else { + res += patch + } } return res.trim() diff --git a/workspaces/libnpmdiff/tap-snapshots/test/format-diff.js.test.cjs b/workspaces/libnpmdiff/tap-snapshots/test/format-diff.js.test.cjs index f735d8925820a..a35d1f1ce55a8 100644 --- a/workspaces/libnpmdiff/tap-snapshots/test/format-diff.js.test.cjs +++ b/workspaces/libnpmdiff/tap-snapshots/test/format-diff.js.test.cjs @@ -33,11 +33,11 @@ index v1.0.0..v2.0.0 ` exports[`test/format-diff.js TAP colored output > should output expected colored diff result 1`] = ` -diff --git a/foo.js b/foo.js -index v1.0.0..v2.0.0 100644 ---- a/foo.js -+++ b/foo.js -@@ -1,2 +1,2 @@ +diff --git a/foo.js b/foo.js +index v1.0.0..v2.0.0 100644 +--- a/foo.js ++++ b/foo.js +@@ -1,2 +1,2 @@ "use strict" -module.exports = "foo" +module.exports = "foobar"