Skip to content

Commit

Permalink
fix: escape backslashes in JSON formatter output
Browse files Browse the repository at this point in the history
Otherwise, our JSON-formatted ouput is not actually valid JSON when it
is rendered with unescaped backslashes like ".+@.+\..+".

Signed-off-by: Jon Parise <[email protected]>
  • Loading branch information
jparise committed Mar 14, 2024
1 parent 822c0ca commit 8db98b6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion formatters/json_formatter.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class JsonFormatter {
* @returns {string} The formatted output
*/
static formatOutput(output, dryRun) {
return JSON.stringify(output)
return JSON.stringify(output).replace(/\\/g, '\\\\')
}
}

Expand Down
27 changes: 27 additions & 0 deletions tests/formatters/json_formatter_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,32 @@ describe('formatters', () => {
const successResult = jsonFormatter.formatOutput(result, false)
expect(successResult).to.equal(expected)
})
it('escapes backslashes to produce valid JSON', () => {
const jsonFormatter = require('../../formatters/json_formatter')

/** @type {import('../..').LintResult} */
const result = {
passed: true,
errored: false,
results: [
FormatResult.CreateLintOnly(
new RuleInfo('myrule', 'error', [], 'file-existence', {}),
new Result('Escaped: \\', [], true)
)
],
targets: {
language: new Result('No language?', [], false)
},
params: {
targetDir: '.',
filterPaths: [],
ruleset: {}
}
}
const expected =
'{"passed":true,"errored":false,"results":[{"ruleInfo":{"name":"myrule","level":"error","where":[],"ruleType":"file-existence","ruleConfig":{}},"status":"PASSED","lintResult":{"message":"Escaped: \\\\\\\\","targets":[],"passed":true}}],"targets":{"language":{"message":"No language?","targets":[],"passed":false}},"params":{"targetDir":".","filterPaths":[],"ruleset":{}}}'
const successResult = jsonFormatter.formatOutput(result, false)
expect(successResult).to.equal(expected)
})
})
})

0 comments on commit 8db98b6

Please sign in to comment.