validation.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. const objFilter = require('./obj-filter')
  2. // validation-type-stuff, missing params,
  3. // bad implications, custom checks.
  4. module.exports = function (yargs, usage, y18n) {
  5. const __ = y18n.__
  6. const __n = y18n.__n
  7. const self = {}
  8. // validate appropriate # of non-option
  9. // arguments were provided, i.e., '_'.
  10. self.nonOptionCount = function (argv) {
  11. const demanded = yargs.getDemanded()
  12. const _s = argv._.length
  13. if (demanded._ && (_s < demanded._.count || _s > demanded._.max)) {
  14. if (demanded._.msg !== undefined) {
  15. usage.fail(demanded._.msg)
  16. } else if (_s < demanded._.count) {
  17. usage.fail(
  18. __('Not enough non-option arguments: got %s, need at least %s', argv._.length, demanded._.count)
  19. )
  20. } else {
  21. usage.fail(
  22. __('Too many non-option arguments: got %s, maximum of %s', argv._.length, demanded._.max)
  23. )
  24. }
  25. }
  26. }
  27. // validate the appropriate # of <required>
  28. // positional arguments were provided:
  29. self.positionalCount = function (required, observed) {
  30. if (observed < required) {
  31. usage.fail(
  32. __('Not enough non-option arguments: got %s, need at least %s', observed, required)
  33. )
  34. }
  35. }
  36. // make sure that any args that require an
  37. // value (--foo=bar), have a value.
  38. self.missingArgumentValue = function (argv) {
  39. const defaultValues = [true, false, '']
  40. const options = yargs.getOptions()
  41. if (options.requiresArg.length > 0) {
  42. const missingRequiredArgs = []
  43. options.requiresArg.forEach(function (key) {
  44. const value = argv[key]
  45. // if a value is explicitly requested,
  46. // flag argument as missing if it does not
  47. // look like foo=bar was entered.
  48. if (~defaultValues.indexOf(value) ||
  49. (Array.isArray(value) && !value.length)) {
  50. missingRequiredArgs.push(key)
  51. }
  52. })
  53. if (missingRequiredArgs.length > 0) {
  54. usage.fail(__n(
  55. 'Missing argument value: %s',
  56. 'Missing argument values: %s',
  57. missingRequiredArgs.length,
  58. missingRequiredArgs.join(', ')
  59. ))
  60. }
  61. }
  62. }
  63. // make sure all the required arguments are present.
  64. self.requiredArguments = function (argv) {
  65. const demanded = yargs.getDemanded()
  66. var missing = null
  67. Object.keys(demanded).forEach(function (key) {
  68. if (!argv.hasOwnProperty(key)) {
  69. missing = missing || {}
  70. missing[key] = demanded[key]
  71. }
  72. })
  73. if (missing) {
  74. const customMsgs = []
  75. Object.keys(missing).forEach(function (key) {
  76. const msg = missing[key].msg
  77. if (msg && customMsgs.indexOf(msg) < 0) {
  78. customMsgs.push(msg)
  79. }
  80. })
  81. const customMsg = customMsgs.length ? '\n' + customMsgs.join('\n') : ''
  82. usage.fail(__n(
  83. 'Missing required argument: %s',
  84. 'Missing required arguments: %s',
  85. Object.keys(missing).length,
  86. Object.keys(missing).join(', ') + customMsg
  87. ))
  88. }
  89. }
  90. // check for unknown arguments (strict-mode).
  91. self.unknownArguments = function (argv, aliases) {
  92. const aliasLookup = {}
  93. const descriptions = usage.getDescriptions()
  94. const demanded = yargs.getDemanded()
  95. const commandKeys = yargs.getCommandInstance().getCommands()
  96. const unknown = []
  97. const currentContext = yargs.getContext()
  98. Object.keys(aliases).forEach(function (key) {
  99. aliases[key].forEach(function (alias) {
  100. aliasLookup[alias] = key
  101. })
  102. })
  103. Object.keys(argv).forEach(function (key) {
  104. if (key !== '$0' && key !== '_' &&
  105. !descriptions.hasOwnProperty(key) &&
  106. !demanded.hasOwnProperty(key) &&
  107. !aliasLookup.hasOwnProperty(key)) {
  108. unknown.push(key)
  109. }
  110. })
  111. if (commandKeys.length > 0) {
  112. argv._.slice(currentContext.commands.length).forEach(function (key) {
  113. if (commandKeys.indexOf(key) === -1) {
  114. unknown.push(key)
  115. }
  116. })
  117. }
  118. if (unknown.length > 0) {
  119. usage.fail(__n(
  120. 'Unknown argument: %s',
  121. 'Unknown arguments: %s',
  122. unknown.length,
  123. unknown.join(', ')
  124. ))
  125. }
  126. }
  127. // validate arguments limited to enumerated choices
  128. self.limitedChoices = function (argv) {
  129. const options = yargs.getOptions()
  130. const invalid = {}
  131. if (!Object.keys(options.choices).length) return
  132. Object.keys(argv).forEach(function (key) {
  133. if (key !== '$0' && key !== '_' &&
  134. options.choices.hasOwnProperty(key)) {
  135. [].concat(argv[key]).forEach(function (value) {
  136. // TODO case-insensitive configurability
  137. if (options.choices[key].indexOf(value) === -1) {
  138. invalid[key] = (invalid[key] || []).concat(value)
  139. }
  140. })
  141. }
  142. })
  143. const invalidKeys = Object.keys(invalid)
  144. if (!invalidKeys.length) return
  145. var msg = __('Invalid values:')
  146. invalidKeys.forEach(function (key) {
  147. msg += '\n ' + __(
  148. 'Argument: %s, Given: %s, Choices: %s',
  149. key,
  150. usage.stringifiedValues(invalid[key]),
  151. usage.stringifiedValues(options.choices[key])
  152. )
  153. })
  154. usage.fail(msg)
  155. }
  156. // custom checks, added using the `check` option on yargs.
  157. var checks = []
  158. self.check = function (f) {
  159. checks.push(f)
  160. }
  161. self.customChecks = function (argv, aliases) {
  162. checks.forEach(function (f) {
  163. try {
  164. const result = f(argv, aliases)
  165. if (!result) {
  166. usage.fail(__('Argument check failed: %s', f.toString()))
  167. } else if (typeof result === 'string') {
  168. usage.fail(result)
  169. }
  170. } catch (err) {
  171. usage.fail(err.message ? err.message : err, err)
  172. }
  173. })
  174. }
  175. // check implications, argument foo implies => argument bar.
  176. var implied = {}
  177. self.implies = function (key, value) {
  178. if (typeof key === 'object') {
  179. Object.keys(key).forEach(function (k) {
  180. self.implies(k, key[k])
  181. })
  182. } else {
  183. implied[key] = value
  184. }
  185. }
  186. self.getImplied = function () {
  187. return implied
  188. }
  189. self.implications = function (argv) {
  190. const implyFail = []
  191. Object.keys(implied).forEach(function (key) {
  192. var booleanNegation
  193. if (yargs.getOptions().configuration['boolean-negation'] === false) {
  194. booleanNegation = false
  195. } else {
  196. booleanNegation = true
  197. }
  198. var num
  199. const origKey = key
  200. var value = implied[key]
  201. // convert string '1' to number 1
  202. num = Number(key)
  203. key = isNaN(num) ? key : num
  204. if (typeof key === 'number') {
  205. // check length of argv._
  206. key = argv._.length >= key
  207. } else if (key.match(/^--no-.+/) && booleanNegation) {
  208. // check if key doesn't exist
  209. key = key.match(/^--no-(.+)/)[1]
  210. key = !argv[key]
  211. } else {
  212. // check if key exists
  213. key = argv[key]
  214. }
  215. num = Number(value)
  216. value = isNaN(num) ? value : num
  217. if (typeof value === 'number') {
  218. value = argv._.length >= value
  219. } else if (value.match(/^--no-.+/) && booleanNegation) {
  220. value = value.match(/^--no-(.+)/)[1]
  221. value = !argv[value]
  222. } else {
  223. value = argv[value]
  224. }
  225. if (key && !value) {
  226. implyFail.push(origKey)
  227. }
  228. })
  229. if (implyFail.length) {
  230. var msg = __('Implications failed:') + '\n'
  231. implyFail.forEach(function (key) {
  232. msg += (' ' + key + ' -> ' + implied[key])
  233. })
  234. usage.fail(msg)
  235. }
  236. }
  237. self.reset = function (globalLookup) {
  238. implied = objFilter(implied, function (k, v) {
  239. return globalLookup[k]
  240. })
  241. checks = []
  242. return self
  243. }
  244. return self
  245. }