normalizeArgs.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. var assert = require('assert');
  3. var map = require('arr-map');
  4. var flatten = require('arr-flatten');
  5. var levenshtein = require('fast-levenshtein');
  6. function normalizeArgs(registry, args) {
  7. function getFunction(task) {
  8. if (typeof task === 'function') {
  9. return task;
  10. }
  11. var fn = registry.get(task);
  12. if (!fn) {
  13. var similar = similarTasks(registry, task);
  14. if (similar.length > 0) {
  15. assert(false, 'Task never defined: ' + task + ' - did you mean? ' + similar.join(', '));
  16. } else {
  17. assert(false, 'Task never defined: ' + task);
  18. }
  19. }
  20. return fn;
  21. }
  22. var flattenArgs = flatten(args);
  23. assert(flattenArgs.length, 'One or more tasks should be combined using series or parallel');
  24. return map(flattenArgs, getFunction);
  25. }
  26. function similarTasks(registry, queryTask) {
  27. if (typeof queryTask !== 'string') {
  28. return [];
  29. }
  30. var tasks = registry.tasks();
  31. var similarTasks = [];
  32. for (var task in tasks) {
  33. if (tasks.hasOwnProperty(task)) {
  34. var distance = levenshtein.get(task, queryTask);
  35. var allowedDistance = Math.floor(0.4 * task.length) + 1;
  36. if (distance < allowedDistance) {
  37. similarTasks.push(task);
  38. }
  39. }
  40. }
  41. return similarTasks;
  42. }
  43. module.exports = normalizeArgs;