1. const fs = require('fs');
  2. const path = require('path');
  3. /**
  4. * Monitors CLI arguments against a configuration file.
  5. *
  6. * @param {string[]} args - The CLI arguments passed to the script.
  7. * @param {string} configPath - Path to the configuration file (JSON).
  8. * @returns {Promise<object | null>} - A promise resolving to the validated arguments object, or null if validation fails.
  9. */
  10. async function validateArgs(args, configPath) {
  11. try {
  12. // Read the configuration file
  13. const configContent = fs.readFileSync(configPath, 'utf8');
  14. const config = JSON.parse(configContent);
  15. // Validate arguments against the configuration
  16. const validatedArgs = {};
  17. let validationSuccessful = true;
  18. for (const argName in config.arguments) {
  19. const expectedType = config.arguments[argName].type;
  20. const argValue = args.find(a => a.startsWith(argName + '=')); //Find argument value
  21. if (!argValue) {
  22. console.error(`Missing argument: ${argName}`);
  23. validationSuccessful = false;
  24. continue; //Skip to the next argument if one is missing
  25. }
  26. let parsedValue;
  27. try {
  28. if (expectedType === 'string') {
  29. parsedValue = argValue.slice(argName.length).trim();
  30. if(parsedValue.startsWith('"') && parsedValue.endsWith('"')){
  31. parsedValue = parsedValue.slice(1, -1); //remove quotes
  32. }
  33. } else if (expectedType === 'number') {
  34. parsedValue = Number(argValue.slice(argName.length).trim());
  35. } else if (expectedType === 'boolean') {
  36. parsedValue = argValue.slice(argName.length).trim().toLowerCase() === 'true';
  37. } else if (expectedType === 'array') {
  38. const arrayValues = argValue.slice(argName.length).trim().split(',');
  39. parsedValue = arrayValues.map(item => item.trim());
  40. }
  41. else {
  42. console.error(`Unsupported argument type: ${expectedType} for argument ${argName}`);
  43. validationSuccessful = false;
  44. continue;
  45. }
  46. } catch (error) {
  47. console.error(`Invalid value for argument ${argName}: ${argValue.slice(argName.length).trim()}. Expected ${expectedType}. Error: ${error.message}`);
  48. validationSuccessful = false;
  49. continue;
  50. }
  51. validatedArgs[argName] = parsedValue;
  52. }
  53. if (!validationSuccessful) {
  54. return null; // Validation failed
  55. }
  56. return validatedArgs;
  57. } catch (error) {
  58. console.error(`Error reading or parsing config file: ${error.message}`);
  59. return null; // Error reading configuration
  60. }
  61. }
  62. module.exports = validateArgs;

Add your comment