command-registry.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. import { Command } from 'commander';
  2. import { CliCommandDefinition } from './cli-command-definition';
  3. export function registerCommands(program: Command, commands: CliCommandDefinition[]): void {
  4. commands.forEach(commandDef => {
  5. const command = program
  6. .command(commandDef.name)
  7. .description(commandDef.description)
  8. .action(async options => {
  9. await commandDef.action(options);
  10. });
  11. // Add options if they exist
  12. if (commandDef.options) {
  13. commandDef.options.forEach(option => {
  14. const parts: string[] = [];
  15. if (option.short) {
  16. parts.push(option.short);
  17. }
  18. parts.push(option.long);
  19. let optionString = parts.join(', ');
  20. // Handle optional options which expect a value by converting <value> to [value]
  21. if (!option.required) {
  22. optionString = optionString.replace(/<([^>]+)>/g, '[$1]');
  23. }
  24. command.option(optionString, option.description, option.defaultValue);
  25. });
  26. }
  27. });
  28. }