lib/runs/echo.js

const path = require('node:path');

/**
 * @module pete/lib/runs/echo
 */
module.exports = createRunEcho;

/**
 * This run simply imports reports from JSON file and re-reports them again.
 * It can be used to quickly convert JSON-stored results in a different format.
 *
 * @alias module:pete/lib/runs/echo
 * @param {string}   filePath                  to import
 * @param {object}   options
 * @param {boolean}  [options.renameReports]   to add source file name to reports names
 * @param {object}   state
 * @return {module:pete/lib/runner~run}
 */
function createRunEcho (filePath, options, state) {
	if (!filePath) {
		state.error = new Error('When using `echo`, `filePath` pointing to a JSON file with previously repeported results is required');
		return null;
	}

	const fileName = path.basename(filePath || '', '.json');
	const renameReports = options.renameReports === true;

	/**
	 * @private
	 * @param {module:pete/lib/createReport~Report} data     to report
	 * @param {module:pete/lib/getReporters~report} report   function
	 */
	function echo (data, report) {
		let err = null;

		if (data.error) {
			err = new Error(data.report.error.replace('Error: ', ''));
			err.stack = data.error.replace('\\n', '\n');
		}

		if (data && data.report && renameReports) {
			data.report.name = `${data.report.name || 'unnamed'} (${fileName})`;
		}

		report(err, data && data.report);
	}

	return function runEcho (report) {
		try {
			const reportedData = require(path.join(path.isAbsolute(filePath) ? '' : process.cwd(), filePath)); // eslint-disable-line global-require
			reportedData.forEach(r => echo(r, report));
		}
		catch (e) {
			report(e);
		}

		report();
	};
}