1. /**
  2. * Parses log stream arguments with sanity checks.
  3. *
  4. * @param {string[]} args Array of command-line arguments.
  5. * @returns {object} An object containing parsed arguments and error information.
  6. */
  7. function parseLogStreamArgs(args) {
  8. const parsedArgs = {};
  9. let errors = [];
  10. // Basic argument parsing with type validation
  11. if (args.length < 2) {
  12. errors.push("Missing required arguments: <log_file> <level>");
  13. return { parsedArgs: null, errors };
  14. }
  15. const logFile = args[0];
  16. const level = args[1];
  17. let format = "default";
  18. // Validate log file
  19. if (!logFile || typeof logFile !== 'string') {
  20. errors.push("Invalid log file path.");
  21. return { parsedArgs: null, errors };
  22. }
  23. // Validate log level
  24. const validLevels = ["debug", "info", "warn", "error", "critical"];
  25. if (!validLevels.includes(level.toLowerCase())) {
  26. errors.push(`Invalid log level. Valid levels are: ${validLevels.join(", ")}`);
  27. return { parsedArgs: null, errors };
  28. }
  29. parsedArgs.logFile = logFile;
  30. parsedArgs.level = level.toLowerCase();
  31. //Optional format argument
  32. if(args.length > 2){
  33. format = args[2];
  34. if(format !== "json" && format !== "text"){
  35. errors.push("Invalid format. Valid formats are 'json' and 'text'.");
  36. return {parsedArgs: null, errors};
  37. }
  38. parsedArgs.format = format;
  39. }
  40. return { parsedArgs, errors };
  41. }

Add your comment