index.cjs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. function defineGetter(obj, key, getter) {
  15. Object.defineProperty(obj, key, {
  16. configurable: true,
  17. enumerable: true,
  18. get: getter,
  19. });
  20. }
  21. function lookupGetter(obj, key) {
  22. const desc = Object.getOwnPropertyDescriptor(obj, key);
  23. if (typeof desc !== 'undefined') {
  24. return desc.get;
  25. }
  26. }
  27. /* Hack an instance of Argv with process.argv into Argv
  28. so people can do
  29. require('yargs')(['--beeble=1','-z','zizzle']).argv
  30. to parse a list of args and
  31. require('yargs').argv
  32. to get a parsed version of process.argv.
  33. */
  34. function singletonify(inst) {
  35. [
  36. ...Object.keys(inst),
  37. ...Object.getOwnPropertyNames(inst.constructor.prototype),
  38. ].forEach(key => {
  39. if (key === 'argv') {
  40. defineGetter(Argv, key, lookupGetter(inst, key));
  41. } else if (typeof inst[key] === 'function') {
  42. Argv[key] = inst[key].bind(inst);
  43. } else {
  44. defineGetter(Argv, '$0', () => inst.$0);
  45. defineGetter(Argv, 'parsed', () => inst.parsed);
  46. }
  47. });
  48. }