index.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import process from 'node:process';
  2. import { y as yargsParser, t as trimNewlines, r as redent, n as normalizePackageData, c as camelcaseKeys } from './dependencies.js';
  3. import { buildOptions } from './options.js';
  4. import { buildParserOptions } from './parser.js';
  5. import { checkUnknownFlags, validate, checkMissingRequiredFlags } from './validate.js';
  6. const buildResult = (options, parserOptions) => {
  7. const {pkg: package_} = options;
  8. const argv = yargsParser(options.argv, parserOptions);
  9. let help = '';
  10. if (options.help) {
  11. help = trimNewlines((options.help || '').replace(/\t+\n*$/, ''));
  12. if (help.includes('\n')) {
  13. help = redent(help, options.helpIndent);
  14. }
  15. help = `\n${help}`;
  16. }
  17. normalizePackageData(package_);
  18. let {description} = options;
  19. if (!description && description !== false) {
  20. ({description} = package_);
  21. }
  22. description &&= help ? redent(`\n${description}\n`, options.helpIndent) : `\n${description}`;
  23. help = `${description || ''}${help}\n`;
  24. const showHelp = code => {
  25. console.log(help);
  26. process.exit(typeof code === 'number' ? code : 2);
  27. };
  28. const showVersion = () => {
  29. console.log(typeof options.version === 'string' ? options.version : package_.version);
  30. process.exit(0);
  31. };
  32. if (argv._.length === 0 && options.argv.length === 1) {
  33. if (argv.version === true && options.autoVersion) {
  34. showVersion();
  35. } else if (argv.help === true && options.autoHelp) {
  36. showHelp(0);
  37. }
  38. }
  39. const input = argv._;
  40. delete argv._;
  41. if (!options.allowUnknownFlags) {
  42. checkUnknownFlags(input);
  43. }
  44. const flags = camelcaseKeys(argv, {exclude: ['--', /^\w$/]});
  45. const unnormalizedFlags = {...flags};
  46. validate(flags, options);
  47. for (const flagValue of Object.values(options.flags)) {
  48. if (Array.isArray(flagValue.aliases)) {
  49. for (const alias of flagValue.aliases) {
  50. delete flags[alias];
  51. }
  52. }
  53. delete flags[flagValue.shortFlag];
  54. }
  55. checkMissingRequiredFlags(options.flags, flags, input);
  56. return {
  57. input,
  58. flags,
  59. unnormalizedFlags,
  60. pkg: package_,
  61. help,
  62. showHelp,
  63. showVersion,
  64. };
  65. };
  66. const meow = (helpText, options = {}) => {
  67. const parsedOptions = buildOptions(helpText, options);
  68. const parserOptions = buildParserOptions(parsedOptions);
  69. const result = buildResult(parsedOptions, parserOptions);
  70. process.title = result.pkg.bin ? Object.keys(result.pkg.bin).at(0) : result.pkg.name;
  71. return result;
  72. };
  73. export { meow as default };