argsert.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.argsert = void 0;
  4. const yerror_1 = require("./yerror");
  5. const parse_command_1 = require("./parse-command");
  6. const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
  7. function argsert(arg1, arg2, arg3) {
  8. function parseArgs() {
  9. return typeof arg1 === 'object'
  10. ? [{ demanded: [], optional: [] }, arg1, arg2]
  11. : [parse_command_1.parseCommand(`cmd ${arg1}`), arg2, arg3];
  12. }
  13. // TODO: should this eventually raise an exception.
  14. try {
  15. // preface the argument description with "cmd", so
  16. // that we can run it through yargs' command parser.
  17. let position = 0;
  18. let [parsed, callerArguments, length] = parseArgs();
  19. const args = [].slice.call(callerArguments);
  20. while (args.length && args[args.length - 1] === undefined)
  21. args.pop();
  22. length = length || args.length;
  23. if (length < parsed.demanded.length) {
  24. throw new yerror_1.YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`);
  25. }
  26. const totalCommands = parsed.demanded.length + parsed.optional.length;
  27. if (length > totalCommands) {
  28. throw new yerror_1.YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
  29. }
  30. parsed.demanded.forEach((demanded) => {
  31. const arg = args.shift();
  32. const observedType = guessType(arg);
  33. const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*');
  34. if (matchingTypes.length === 0)
  35. argumentTypeError(observedType, demanded.cmd, position);
  36. position += 1;
  37. });
  38. parsed.optional.forEach((optional) => {
  39. if (args.length === 0)
  40. return;
  41. const arg = args.shift();
  42. const observedType = guessType(arg);
  43. const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*');
  44. if (matchingTypes.length === 0)
  45. argumentTypeError(observedType, optional.cmd, position);
  46. position += 1;
  47. });
  48. }
  49. catch (err) {
  50. console.warn(err.stack);
  51. }
  52. }
  53. exports.argsert = argsert;
  54. function guessType(arg) {
  55. if (Array.isArray(arg)) {
  56. return 'array';
  57. }
  58. else if (arg === null) {
  59. return 'null';
  60. }
  61. return typeof arg;
  62. }
  63. function argumentTypeError(observedType, allowedTypes, position) {
  64. throw new yerror_1.YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`);
  65. }