Skip to content

Commit

Permalink
fix: inline color selector in libnpmdiff
Browse files Browse the repository at this point in the history
Eventually we'll use npm to do this so we don't have to check if color
is enabled
  • Loading branch information
wraithgar committed Apr 23, 2024
1 parent b0ca163 commit 03958c3
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
32 changes: 28 additions & 4 deletions workspaces/libnpmdiff/lib/format-diff.js
Original file line number Diff line number Diff line change
@@ -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/'
Expand Down Expand Up @@ -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()
Expand Down
10 changes: 5 additions & 5 deletions workspaces/libnpmdiff/tap-snapshots/test/format-diff.js.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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`] = `
[33mdiff --git a/foo.js b/foo.js[39m
[33mindex v1.0.0..v2.0.0 100644[39m
[33m--- a/foo.js[39m
[33m+++ b/foo.js[39m
[35m@@ -1,2 +1,2 @@[39m
[34mdiff --git a/foo.js b/foo.js[39m
[34mindex v1.0.0..v2.0.0 100644[39m
[34m--- a/foo.js[39m
[34m+++ b/foo.js[39m
[36m@@ -1,2 +1,2 @@[39m
"use strict"
-module.exports = "foo"
+module.exports = "foobar"
Expand Down

0 comments on commit 03958c3

Please sign in to comment.