No Description
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.

validation.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. import { argsert } from './argsert.js';
  2. import { assertNotStrictEqual, } from './typings/common-types.js';
  3. import { levenshtein as distance } from './utils/levenshtein.js';
  4. import { objFilter } from './utils/obj-filter.js';
  5. const specialKeys = ['$0', '--', '_'];
  6. export function validation(yargs, usage, y18n, shim) {
  7. const __ = y18n.__;
  8. const __n = y18n.__n;
  9. const self = {};
  10. self.nonOptionCount = function nonOptionCount(argv) {
  11. const demandedCommands = yargs.getDemandedCommands();
  12. const positionalCount = argv._.length + (argv['--'] ? argv['--'].length : 0);
  13. const _s = positionalCount - yargs.getContext().commands.length;
  14. if (demandedCommands._ &&
  15. (_s < demandedCommands._.min || _s > demandedCommands._.max)) {
  16. if (_s < demandedCommands._.min) {
  17. if (demandedCommands._.minMsg !== undefined) {
  18. usage.fail(demandedCommands._.minMsg
  19. ? demandedCommands._.minMsg
  20. .replace(/\$0/g, _s.toString())
  21. .replace(/\$1/, demandedCommands._.min.toString())
  22. : null);
  23. }
  24. else {
  25. usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s.toString(), demandedCommands._.min.toString()));
  26. }
  27. }
  28. else if (_s > demandedCommands._.max) {
  29. if (demandedCommands._.maxMsg !== undefined) {
  30. usage.fail(demandedCommands._.maxMsg
  31. ? demandedCommands._.maxMsg
  32. .replace(/\$0/g, _s.toString())
  33. .replace(/\$1/, demandedCommands._.max.toString())
  34. : null);
  35. }
  36. else {
  37. usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s.toString(), demandedCommands._.max.toString()));
  38. }
  39. }
  40. }
  41. };
  42. self.positionalCount = function positionalCount(required, observed) {
  43. if (observed < required) {
  44. usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed + '', required + ''));
  45. }
  46. };
  47. self.requiredArguments = function requiredArguments(argv) {
  48. const demandedOptions = yargs.getDemandedOptions();
  49. let missing = null;
  50. for (const key of Object.keys(demandedOptions)) {
  51. if (!Object.prototype.hasOwnProperty.call(argv, key) ||
  52. typeof argv[key] === 'undefined') {
  53. missing = missing || {};
  54. missing[key] = demandedOptions[key];
  55. }
  56. }
  57. if (missing) {
  58. const customMsgs = [];
  59. for (const key of Object.keys(missing)) {
  60. const msg = missing[key];
  61. if (msg && customMsgs.indexOf(msg) < 0) {
  62. customMsgs.push(msg);
  63. }
  64. }
  65. const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : '';
  66. usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg));
  67. }
  68. };
  69. self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) {
  70. const commandKeys = yargs.getCommandInstance().getCommands();
  71. const unknown = [];
  72. const currentContext = yargs.getContext();
  73. Object.keys(argv).forEach(key => {
  74. if (specialKeys.indexOf(key) === -1 &&
  75. !Object.prototype.hasOwnProperty.call(positionalMap, key) &&
  76. !Object.prototype.hasOwnProperty.call(yargs._getParseContext(), key) &&
  77. !self.isValidAndSomeAliasIsNotNew(key, aliases)) {
  78. unknown.push(key);
  79. }
  80. });
  81. if (checkPositionals &&
  82. (currentContext.commands.length > 0 ||
  83. commandKeys.length > 0 ||
  84. isDefaultCommand)) {
  85. argv._.slice(currentContext.commands.length).forEach(key => {
  86. if (commandKeys.indexOf('' + key) === -1) {
  87. unknown.push('' + key);
  88. }
  89. });
  90. }
  91. if (unknown.length > 0) {
  92. usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.join(', ')));
  93. }
  94. };
  95. self.unknownCommands = function unknownCommands(argv) {
  96. const commandKeys = yargs.getCommandInstance().getCommands();
  97. const unknown = [];
  98. const currentContext = yargs.getContext();
  99. if (currentContext.commands.length > 0 || commandKeys.length > 0) {
  100. argv._.slice(currentContext.commands.length).forEach(key => {
  101. if (commandKeys.indexOf('' + key) === -1) {
  102. unknown.push('' + key);
  103. }
  104. });
  105. }
  106. if (unknown.length > 0) {
  107. usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', ')));
  108. return true;
  109. }
  110. else {
  111. return false;
  112. }
  113. };
  114. self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) {
  115. if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
  116. return false;
  117. }
  118. const newAliases = yargs.parsed.newAliases;
  119. for (const a of [key, ...aliases[key]]) {
  120. if (!Object.prototype.hasOwnProperty.call(newAliases, a) ||
  121. !newAliases[key]) {
  122. return true;
  123. }
  124. }
  125. return false;
  126. };
  127. self.limitedChoices = function limitedChoices(argv) {
  128. const options = yargs.getOptions();
  129. const invalid = {};
  130. if (!Object.keys(options.choices).length)
  131. return;
  132. Object.keys(argv).forEach(key => {
  133. if (specialKeys.indexOf(key) === -1 &&
  134. Object.prototype.hasOwnProperty.call(options.choices, key)) {
  135. [].concat(argv[key]).forEach(value => {
  136. if (options.choices[key].indexOf(value) === -1 &&
  137. value !== undefined) {
  138. invalid[key] = (invalid[key] || []).concat(value);
  139. }
  140. });
  141. }
  142. });
  143. const invalidKeys = Object.keys(invalid);
  144. if (!invalidKeys.length)
  145. return;
  146. let msg = __('Invalid values:');
  147. invalidKeys.forEach(key => {
  148. msg += `\n ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`;
  149. });
  150. usage.fail(msg);
  151. };
  152. let checks = [];
  153. self.check = function check(f, global) {
  154. checks.push({
  155. func: f,
  156. global,
  157. });
  158. };
  159. self.customChecks = function customChecks(argv, aliases) {
  160. for (let i = 0, f; (f = checks[i]) !== undefined; i++) {
  161. const func = f.func;
  162. let result = null;
  163. try {
  164. result = func(argv, aliases);
  165. }
  166. catch (err) {
  167. usage.fail(err.message ? err.message : err, err);
  168. continue;
  169. }
  170. if (!result) {
  171. usage.fail(__('Argument check failed: %s', func.toString()));
  172. }
  173. else if (typeof result === 'string' || result instanceof Error) {
  174. usage.fail(result.toString(), result);
  175. }
  176. }
  177. };
  178. let implied = {};
  179. self.implies = function implies(key, value) {
  180. argsert('<string|object> [array|number|string]', [key, value], arguments.length);
  181. if (typeof key === 'object') {
  182. Object.keys(key).forEach(k => {
  183. self.implies(k, key[k]);
  184. });
  185. }
  186. else {
  187. yargs.global(key);
  188. if (!implied[key]) {
  189. implied[key] = [];
  190. }
  191. if (Array.isArray(value)) {
  192. value.forEach(i => self.implies(key, i));
  193. }
  194. else {
  195. assertNotStrictEqual(value, undefined, shim);
  196. implied[key].push(value);
  197. }
  198. }
  199. };
  200. self.getImplied = function getImplied() {
  201. return implied;
  202. };
  203. function keyExists(argv, val) {
  204. const num = Number(val);
  205. val = isNaN(num) ? val : num;
  206. if (typeof val === 'number') {
  207. val = argv._.length >= val;
  208. }
  209. else if (val.match(/^--no-.+/)) {
  210. val = val.match(/^--no-(.+)/)[1];
  211. val = !argv[val];
  212. }
  213. else {
  214. val = argv[val];
  215. }
  216. return val;
  217. }
  218. self.implications = function implications(argv) {
  219. const implyFail = [];
  220. Object.keys(implied).forEach(key => {
  221. const origKey = key;
  222. (implied[key] || []).forEach(value => {
  223. let key = origKey;
  224. const origValue = value;
  225. key = keyExists(argv, key);
  226. value = keyExists(argv, value);
  227. if (key && !value) {
  228. implyFail.push(` ${origKey} -> ${origValue}`);
  229. }
  230. });
  231. });
  232. if (implyFail.length) {
  233. let msg = `${__('Implications failed:')}\n`;
  234. implyFail.forEach(value => {
  235. msg += value;
  236. });
  237. usage.fail(msg);
  238. }
  239. };
  240. let conflicting = {};
  241. self.conflicts = function conflicts(key, value) {
  242. argsert('<string|object> [array|string]', [key, value], arguments.length);
  243. if (typeof key === 'object') {
  244. Object.keys(key).forEach(k => {
  245. self.conflicts(k, key[k]);
  246. });
  247. }
  248. else {
  249. yargs.global(key);
  250. if (!conflicting[key]) {
  251. conflicting[key] = [];
  252. }
  253. if (Array.isArray(value)) {
  254. value.forEach(i => self.conflicts(key, i));
  255. }
  256. else {
  257. conflicting[key].push(value);
  258. }
  259. }
  260. };
  261. self.getConflicting = () => conflicting;
  262. self.conflicting = function conflictingFn(argv) {
  263. Object.keys(argv).forEach(key => {
  264. if (conflicting[key]) {
  265. conflicting[key].forEach(value => {
  266. if (value && argv[key] !== undefined && argv[value] !== undefined) {
  267. usage.fail(__('Arguments %s and %s are mutually exclusive', key, value));
  268. }
  269. });
  270. }
  271. });
  272. };
  273. self.recommendCommands = function recommendCommands(cmd, potentialCommands) {
  274. const threshold = 3;
  275. potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
  276. let recommended = null;
  277. let bestDistance = Infinity;
  278. for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) {
  279. const d = distance(cmd, candidate);
  280. if (d <= threshold && d < bestDistance) {
  281. bestDistance = d;
  282. recommended = candidate;
  283. }
  284. }
  285. if (recommended)
  286. usage.fail(__('Did you mean %s?', recommended));
  287. };
  288. self.reset = function reset(localLookup) {
  289. implied = objFilter(implied, k => !localLookup[k]);
  290. conflicting = objFilter(conflicting, k => !localLookup[k]);
  291. checks = checks.filter(c => c.global);
  292. return self;
  293. };
  294. const frozens = [];
  295. self.freeze = function freeze() {
  296. frozens.push({
  297. implied,
  298. checks,
  299. conflicting,
  300. });
  301. };
  302. self.unfreeze = function unfreeze() {
  303. const frozen = frozens.pop();
  304. assertNotStrictEqual(frozen, undefined, shim);
  305. ({ implied, checks, conflicting } = frozen);
  306. };
  307. return self;
  308. }