index.cjs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. // classic singleton yargs API, to use yargs
  3. // without running as a singleton do:
  4. // require('yargs/yargs')(process.argv.slice(2))
  5. const {Yargs, processArgv} = require('./build/index.cjs');
  6. Argv(processArgv.hideBin(process.argv));
  7. module.exports = Argv;
  8. function Argv(processArgs, cwd) {
  9. const argv = Yargs(processArgs, cwd, require);
  10. singletonify(argv);
  11. // TODO(bcoe): warn if argv.parse() or argv.argv is used directly.
  12. return argv;
  13. }
  14. /* Hack an instance of Argv with process.argv into Argv
  15. so people can do
  16. require('yargs')(['--beeble=1','-z','zizzle']).argv
  17. to parse a list of args and
  18. require('yargs').argv
  19. to get a parsed version of process.argv.
  20. */
  21. function singletonify(inst) {
  22. [
  23. ...Object.keys(inst),
  24. ...Object.getOwnPropertyNames(inst.constructor.prototype),
  25. ].forEach(key => {
  26. if (key === 'argv') {
  27. Argv.__defineGetter__(key, inst.__lookupGetter__(key));
  28. } else if (typeof inst[key] === 'function') {
  29. Argv[key] = inst[key].bind(inst);
  30. } else {
  31. Argv.__defineGetter__('$0', () => {
  32. return inst.$0;
  33. });
  34. Argv.__defineGetter__('parsed', () => {
  35. return inst.parsed;
  36. });
  37. }
  38. });
  39. }