Skip to content

Commit 1c063e8

Browse files
committed
fix: inline color selector in libnpmdiff
Eventually we'll use npm to do this so we don't have to check if color is enabled
1 parent f703100 commit 1c063e8

File tree

2 files changed

+33
-9
lines changed

2 files changed

+33
-9
lines changed

workspaces/libnpmdiff/lib/format-diff.js

+28-4
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,24 @@
1-
const colorizeDiff = require('@npmcli/disparity-colors')
21
const jsDiff = require('diff')
32

43
const shouldPrintPatch = require('./should-print-patch.js')
54

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+
622
const formatDiff = ({ files, opts = {}, refs, versions }) => {
723
let res = ''
824
const srcPrefix = opts.diffNoPrefix ? '' : opts.diffSrcPrefix || 'a/'
@@ -83,9 +99,17 @@ const formatDiff = ({ files, opts = {}, refs, versions }) => {
8399
header(`+++ ${names.b}`)
84100
}
85101

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+
}
89113
}
90114

91115
return res.trim()

workspaces/libnpmdiff/tap-snapshots/test/format-diff.js.test.cjs

+5-5
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,11 @@ index v1.0.0..v2.0.0
3333
`
3434

3535
exports[`test/format-diff.js TAP colored output > should output expected colored diff result 1`] = `
36-
[33mdiff --git a/foo.js b/foo.js[39m
37-
[33mindex v1.0.0..v2.0.0 100644[39m
38-
[33m--- a/foo.js[39m
39-
[33m+++ b/foo.js[39m
40-
[35m@@ -1,2 +1,2 @@[39m
36+
[34mdiff --git a/foo.js b/foo.js[39m
37+
[34mindex v1.0.0..v2.0.0 100644[39m
38+
[34m--- a/foo.js[39m
39+
[34m+++ b/foo.js[39m
40+
[36m@@ -1,2 +1,2 @@[39m
4141
"use strict"
4242
-module.exports = "foo"
4343
+module.exports = "foobar"

0 commit comments

Comments
 (0)