Skip to content

Commit

Permalink
reporter: escape ANSI escape codes in diffs
Browse files Browse the repository at this point in the history
Fix: #962
  • Loading branch information
isaacs committed Oct 18, 2023
1 parent f29b997 commit a5f209e
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 9 deletions.
19 changes: 11 additions & 8 deletions src/reporter/src/diff.tsx
Expand Up @@ -84,14 +84,17 @@ export const Diff: FC<{ diff: string }> = ({ diff = '' }) => {

let width = 0
const maxLen = Math.max(columns - 5, 0)
const lines = sd.split('\n').filter(line => {
if (stringLength(line) > width) {
width = Math.min(maxLen, stringLength(line))
}
return (
line !== '\\ No newline at end of file' && !/^\=+$/.test(line)
)
})
const lines = sd
.replace(/\x1b/g, '\\' + 'x1b')
.split('\n')
.filter(line => {
if (line.length > width) {
width = Math.min(maxLen, line.length)
}
return (
line !== '\\ No newline at end of file' && !/^\=+$/.test(line)
)
})
return (
<Box flexDirection="column">
{lines
Expand Down
11 changes: 11 additions & 0 deletions src/reporter/tap-snapshots/test/diff.tsx.test.cjs
Expand Up @@ -5,6 +5,17 @@
* Make sure to inspect the output below. Do not ignore changes!
*/
'use strict'
exports[`test/diff.tsx > TAP > ansi escape codes > must match snapshot 1`] = `
--- expected 
+++ actual 
@@ -1,3 +1,3 @@ 
-Error: Oh \\x1b[1mdeary \\x1b[2mdeary \\x1b[0mdear. { 
- "cause": "foo", 
+Error: Oh deary deary dear. { 
+ "cause": "bar", 
 } 
`

exports[`test/diff.tsx > TAP > diff some stuff > must match snapshot 1`] = `
--- expected 
+++ actual 
Expand Down
25 changes: 24 additions & 1 deletion src/reporter/test/diff.tsx
@@ -1,9 +1,10 @@
import './fixtures/chalk.js'
import { createTwoFilesPatch } from 'diff'
import { render } from 'ink-testing-library'
import React from 'react'
import t from 'tap'
import { format } from 'tcompare'
import { Diff } from '../dist/esm/diff.js'
import './fixtures/chalk.js'

t.test('diff some stuff', async t => {
const found = {
Expand Down Expand Up @@ -119,3 +120,25 @@ I am a sojourner in civilized life again.`
)
t.matchSnapshot(app.lastFrame())
})

t.test('ansi escape codes', async t => {
const expected = new Error(
`Oh \x1b[1mdeary \x1b[2mdeary \x1b[0mdear.`,
{
cause: 'foo',
}
)
const actual = new Error(`Oh deary deary dear.`, { cause: 'bar' })

const app = render(
<Diff
diff={createTwoFilesPatch(
'expected',
'actual',
format(expected),
format(actual)
)}
/>
)
t.matchSnapshot(app.lastFrame())
})

0 comments on commit a5f209e

Please sign in to comment.