You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.3 KiB

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