did-you-mean.js 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. const Npm = require('../npm')
  2. const { distance } = require('fastest-levenshtein')
  3. const { commands } = require('./cmd-list.js')
  4. const runScripts = ['stop', 'start', 'test', 'restart']
  5. const isClose = (scmd, cmd) => distance(scmd, cmd) < scmd.length * 0.4
  6. const didYouMean = (pkg, scmd) => {
  7. const { scripts = {}, bin = {} } = pkg || {}
  8. const best = [
  9. ...commands
  10. .filter(cmd => isClose(scmd, cmd) && scmd !== cmd)
  11. .map(str => [str, Npm.cmd(str).description]),
  12. ...Object.keys(scripts)
  13. // We would already be suggesting this in `npm x` so omit them here
  14. .filter(cmd => isClose(scmd, cmd) && !runScripts.includes(cmd))
  15. .map(str => [`run ${str}`, `run the "${str}" package script`]),
  16. ...Object.keys(bin)
  17. .filter(cmd => isClose(scmd, cmd))
  18. .map(str => [`exec ${str}`, `run the "${str}" command from either this or a remote npm package`]),
  19. ]
  20. if (best.length === 0) {
  21. return ''
  22. }
  23. return `\n\nDid you mean ${best.length === 1 ? 'this' : 'one of these'}?\n` +
  24. best.slice(0, 3).map(([msg, comment]) => ` npm ${msg} # ${comment}`).join('\n')
  25. }
  26. module.exports = didYouMean