Skip to content

Commit

Permalink
Fix to show vfile message causes nicely
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Apr 7, 2024
1 parent 1e8c62f commit 1a23c67
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 8 deletions.
36 changes: 28 additions & 8 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -236,10 +236,11 @@ function createByline(state, stats) {
* Info passed around.
* @param {unknown} cause
* Cause.
* @returns {Array<string>}
* @returns {Array<Array<string> | string>}
* Lines.
*/
function createCauseLines(state, cause) {
/** @type {Array<Array<string> | string>} */
const lines = [' ' + state.bold + '[cause]' + state.normalIntensity + ':']
let foundReasonableCause = false

Expand All @@ -250,15 +251,34 @@ function createCauseLines(state, cause) {

if (typeof stackValue === 'string') {
foundReasonableCause = true
/** @type {Array<Array<string> | string>} */
let causeLines

// Looks like a message.
if ('file' in cause && 'fatal' in cause) {
causeLines = createMessageLine(
state,
/** @type {VFileMessage} */ (cause)
)
}
// Regular error.
else {
causeLines = stackValue.split(eol)

const stackLines = stackValue.split(eol)
stackLines[0] = ' ' + stackLines[0]

lines.push(...stackLines)
// Recurse.
if ('cause' in cause && cause.cause) {
causeLines.push(...createCauseLines(state, cause.cause))
}
}

if ('cause' in cause && cause.cause) {
lines.push(...createCauseLines(state, cause.cause))
const head = causeLines[0]
if (typeof head === 'string') {
causeLines[0] = ' ' + head
} else {
head[0] = ' ' + head[0]
}

lines.push(...causeLines)
}
}

Expand Down Expand Up @@ -345,7 +365,7 @@ function createMessageLine(state, message) {
let reason = message.stack || message.message

const match = eol.exec(reason)
/** @type {Array<string>} */
/** @type {Array<Array<string> | string>} */
let rest = []

if (match) {
Expand Down
19 changes: 19 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import assert from 'node:assert/strict'
import test from 'node:test'
import strip from 'strip-ansi'
import {VFile} from 'vfile'
import {VFileMessage} from 'vfile-message'
import {reporter} from 'vfile-reporter'

/* eslint-disable no-undef */
Expand Down Expand Up @@ -441,6 +442,24 @@ test('reporter', async function () {
'should support a `message.cause`, w/ another cause'
)

file = new VFile()

file.message('Something failed terribly', {
cause: new VFileMessage('Boom!', {ruleId: 'foo', source: 'bar'})
})

assert.equal(
strip(reporter(file)),
[
' warning Something failed terribly',
' [cause]:',
' info Boom! foo bar',
'',
'⚠ 1 warning'
].join('\n'),
'should support a `message.cause` w/ a message'
)

file = new VFile()
let message = file.message('Something failed terribly')
message.cause = 'Boom!'
Expand Down

0 comments on commit 1a23c67

Please sign in to comment.