1. #!/usr/bin/env node
  2. const { program } = require('commander');
  3. const { exec } = require('child_process');
  4. const CLI_ARGUMENTS = {
  5. 'command1': {
  6. command: 'my-command1',
  7. retryInterval: 2000, // 2 seconds
  8. retries: 3,
  9. },
  10. 'command2': {
  11. command: 'my-command2',
  12. retryInterval: 1000, // 1 second
  13. retries: 5,
  14. },
  15. // Add more commands here
  16. };
  17. program.on('command', (command) => {
  18. const commandDetails = CLI_ARGUMENTS[command];
  19. if (!commandDetails) {
  20. console.error(`Command "${command}" not found.`);
  21. process.exit(1);
  22. }
  23. let retryCount = 0;
  24. const executeCommand = () => {
  25. exec(commandDetails.command, (error, stdout, stderr) => {
  26. if (error) {
  27. retryCount++;
  28. if (retryCount <= commandDetails.retries) {
  29. console.error(`Command "${commandDetails.command}" failed. Retrying (${retryCount}/${commandDetails.retries})...`);
  30. setTimeout(executeCommand, commandDetails.retryInterval);
  31. } else {
  32. console.error(`Command "${commandDetails.command}" failed after ${commandDetails.retries} retries.`);
  33. process.exit(1);
  34. }
  35. } else if (stderr) {
  36. console.error(`Command "${commandDetails.command}" stderr: ${stderr}`);
  37. retryCount++;
  38. if (retryCount <= commandDetails.retries) {
  39. console.error(`Command "${commandDetails.command}" failed. Retrying (${retryCount}/${commandDetails.retries})...`);
  40. setTimeout(executeCommand, commandDetails.retryInterval);
  41. } else {
  42. console.error(`Command "${commandDetails.command}" failed after ${commandDetails.retries} retries.`);
  43. process.exit(1);
  44. }
  45. } else {
  46. console.log(stdout);
  47. }
  48. });
  49. };
  50. executeCommand();
  51. });
  52. program.parse(process.argv);

Add your comment