Skip to content

Commit

Permalink
json reporter: resolve relative paths and ensure parent folders exist
Browse files Browse the repository at this point in the history
  • Loading branch information
dwightjack committed May 25, 2021
1 parent 1d7010b commit d7a2632
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions lib/reporters/json.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,32 @@
'use strict';

const fs = require('fs');
const {resolve, isAbsolute, dirname} = require('path');

function writeReport(fileName, data) {
try {
const dirPath = dirname(fileName);
if (!(fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory())) {
fs.mkdirSync(dirPath, {recursive: true});
}
fs.writeFileSync(fileName, data);
return true;
} catch (error) {
console.error(`Unable to write ${fileName}`);
console.error(error);
return false;
}
}

function resolveFile(fileName) {
if (typeof fileName !== 'string') {
return null;
}
return isAbsolute(fileName) ? fileName : resolve(process.cwd(), fileName);
}

module.exports = function jsonReporter(options = {}) {
const fileName = resolveFile(options.fileName);
return {
afterAll(report) {
const jsonString = JSON.stringify(report, (key, value) => {
Expand All @@ -15,8 +39,8 @@ module.exports = function jsonReporter(options = {}) {
// If reporter options specify an output file, write to file.
// Otherwise, write to console for backwards compatibility with
// previous --json CLI option.
if (options.fileName) {
fs.writeFileSync(options.fileName, jsonString);
if (fileName) {
writeReport(fileName, jsonString);
} else {
console.log(jsonString);
}
Expand Down

0 comments on commit d7a2632

Please sign in to comment.