2025-02-28 20:25:44 -08:00
|
|
|
// @ts-check
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Result of a call to parseConfiguration.
|
|
|
|
*
|
|
|
|
* @typedef {Object} ParseConfigurationResult
|
|
|
|
* @property {Object | null} config Configuration object if successful.
|
2025-03-01 18:23:48 -08:00
|
|
|
* @property {string | null} message Error message if an error occurred.
|
2025-02-28 20:25:44 -08:00
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Parse the content of a configuration file.
|
|
|
|
*
|
|
|
|
* @param {string} name Name of the configuration file.
|
|
|
|
* @param {string} content Configuration content.
|
|
|
|
* @param {import("./markdownlint.mjs").ConfigurationParser[]} [parsers] Parsing function(s).
|
|
|
|
* @returns {ParseConfigurationResult} Parse configuration result.
|
|
|
|
*/
|
|
|
|
export default function parseConfiguration(name, content, parsers) {
|
|
|
|
let config = null;
|
2025-03-01 18:23:48 -08:00
|
|
|
let message = null;
|
2025-02-28 20:25:44 -08:00
|
|
|
const errors = [];
|
|
|
|
let index = 0;
|
|
|
|
// Try each parser
|
2025-03-01 18:23:48 -08:00
|
|
|
const failed = (parsers || [ JSON.parse ]).every((parser) => {
|
2025-02-28 20:25:44 -08:00
|
|
|
try {
|
2025-03-01 18:23:48 -08:00
|
|
|
const result = parser(content);
|
|
|
|
config = (result && (typeof result === "object") && !Array.isArray(result)) ? result : {};
|
|
|
|
// Succeeded
|
|
|
|
return false;
|
2025-02-28 20:25:44 -08:00
|
|
|
} catch (error) {
|
|
|
|
errors.push(`Parser ${index++}: ${error.message}`);
|
|
|
|
}
|
2025-03-01 18:23:48 -08:00
|
|
|
// Failed, try the next parser
|
|
|
|
return true;
|
2025-02-28 20:25:44 -08:00
|
|
|
});
|
|
|
|
// Message if unable to parse
|
2025-03-01 18:23:48 -08:00
|
|
|
if (failed) {
|
2025-02-28 20:25:44 -08:00
|
|
|
errors.unshift(`Unable to parse '${name}'`);
|
|
|
|
message = errors.join("; ");
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
config,
|
|
|
|
message
|
|
|
|
};
|
|
|
|
}
|