const fs = require('fs');
const path = require('path');
/**
* Monitors CLI arguments against a configuration file.
*
* @param {string[]} args - The CLI arguments passed to the script.
* @param {string} configPath - Path to the configuration file (JSON).
* @returns {Promise<object | null>} - A promise resolving to the validated arguments object, or null if validation fails.
*/
async function validateArgs(args, configPath) {
try {
// Read the configuration file
const configContent = fs.readFileSync(configPath, 'utf8');
const config = JSON.parse(configContent);
// Validate arguments against the configuration
const validatedArgs = {};
let validationSuccessful = true;
for (const argName in config.arguments) {
const expectedType = config.arguments[argName].type;
const argValue = args.find(a => a.startsWith(argName + '=')); //Find argument value
if (!argValue) {
console.error(`Missing argument: ${argName}`);
validationSuccessful = false;
continue; //Skip to the next argument if one is missing
}
let parsedValue;
try {
if (expectedType === 'string') {
parsedValue = argValue.slice(argName.length).trim();
if(parsedValue.startsWith('"') && parsedValue.endsWith('"')){
parsedValue = parsedValue.slice(1, -1); //remove quotes
}
} else if (expectedType === 'number') {
parsedValue = Number(argValue.slice(argName.length).trim());
} else if (expectedType === 'boolean') {
parsedValue = argValue.slice(argName.length).trim().toLowerCase() === 'true';
} else if (expectedType === 'array') {
const arrayValues = argValue.slice(argName.length).trim().split(',');
parsedValue = arrayValues.map(item => item.trim());
}
else {
console.error(`Unsupported argument type: ${expectedType} for argument ${argName}`);
validationSuccessful = false;
continue;
}
} catch (error) {
console.error(`Invalid value for argument ${argName}: ${argValue.slice(argName.length).trim()}. Expected ${expectedType}. Error: ${error.message}`);
validationSuccessful = false;
continue;
}
validatedArgs[argName] = parsedValue;
}
if (!validationSuccessful) {
return null; // Validation failed
}
return validatedArgs;
} catch (error) {
console.error(`Error reading or parsing config file: ${error.message}`);
return null; // Error reading configuration
}
}
module.exports = validateArgs;
Add your comment