Add comprehensive tests for parseConfiguration function, handle non-object parser results consistently (fixes #1523).

This commit is contained in:
David Anson 2025-03-01 18:23:48 -08:00
parent 1f237e6c54
commit 63147ee1eb
4 changed files with 97 additions and 11 deletions

View file

@ -1183,6 +1183,7 @@ export function readConfigSync(file, parsers, fs) {
// Try to parse file
const { config, message } = parseConfiguration(file, content, parsers);
if (!config) {
// @ts-ignore
throw new Error(message);
}
// Extend configuration

View file

@ -5,7 +5,7 @@
*
* @typedef {Object} ParseConfigurationResult
* @property {Object | null} config Configuration object if successful.
* @property {string} message Error message if an error occurred.
* @property {string | null} message Error message if an error occurred.
*/
/**
@ -18,20 +18,24 @@
*/
export default function parseConfiguration(name, content, parsers) {
let config = null;
let message = "";
let message = null;
const errors = [];
let index = 0;
// Try each parser
(parsers || [ JSON.parse ]).every((parser) => {
const failed = (parsers || [ JSON.parse ]).every((parser) => {
try {
config = parser(content);
const result = parser(content);
config = (result && (typeof result === "object") && !Array.isArray(result)) ? result : {};
// Succeeded
return false;
} catch (error) {
errors.push(`Parser ${index++}: ${error.message}`);
}
return !config;
// Failed, try the next parser
return true;
});
// Message if unable to parse
if (!config) {
if (failed) {
errors.unshift(`Unable to parse '${name}'`);
message = errors.join("; ");
}