Option.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { removeBrackets, camelcaseOptionName } from "./utils.ts";
  2. interface OptionConfig {
  3. default?: any;
  4. type?: any[];
  5. }
  6. export default class Option {
  7. /** Option name */
  8. name: string;
  9. /** Option name and aliases */
  10. names: string[];
  11. isBoolean?: boolean; // `required` will be a boolean for options with brackets
  12. required?: boolean;
  13. config: OptionConfig;
  14. negated: boolean;
  15. constructor(public rawName: string, public description: string, config?: OptionConfig) {
  16. this.config = Object.assign({}, config); // You may use cli.option('--env.* [value]', 'desc') to denote a dot-nested option
  17. rawName = rawName.replace(/\.\*/g, '');
  18. this.negated = false;
  19. this.names = removeBrackets(rawName).split(',').map((v: string) => {
  20. let name = v.trim().replace(/^-{1,2}/, '');
  21. if (name.startsWith('no-')) {
  22. this.negated = true;
  23. name = name.replace(/^no-/, '');
  24. }
  25. return camelcaseOptionName(name);
  26. }).sort((a, b) => a.length > b.length ? 1 : -1); // Sort names
  27. // Use the longest name (last one) as actual option name
  28. this.name = this.names[this.names.length - 1];
  29. if (this.negated && this.config.default == null) {
  30. this.config.default = true;
  31. }
  32. if (rawName.includes('<')) {
  33. this.required = true;
  34. } else if (rawName.includes('[')) {
  35. this.required = false;
  36. } else {
  37. // No arg needed, it's boolean flag
  38. this.isBoolean = true;
  39. }
  40. }
  41. }
  42. export type { OptionConfig };