search.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. const Pipeline = require('minipass-pipeline')
  2. const libSearch = require('libnpmsearch')
  3. const { log, output } = require('proc-log')
  4. const formatSearchStream = require('../utils/format-search-stream.js')
  5. const BaseCommand = require('../base-cmd.js')
  6. class Search extends BaseCommand {
  7. static description = 'Search for packages'
  8. static name = 'search'
  9. static params = [
  10. 'json',
  11. 'color',
  12. 'parseable',
  13. 'description',
  14. 'searchlimit',
  15. 'searchopts',
  16. 'searchexclude',
  17. 'registry',
  18. 'prefer-online',
  19. 'prefer-offline',
  20. 'offline',
  21. ]
  22. static usage = ['<search term> [<search term> ...]']
  23. async exec (args) {
  24. const opts = {
  25. ...this.npm.flatOptions,
  26. ...this.npm.flatOptions.search,
  27. include: args.map(s => s.toLowerCase()).filter(Boolean),
  28. exclude: this.npm.flatOptions.search.exclude.split(/\s+/),
  29. }
  30. if (opts.include.length === 0) {
  31. throw new Error('search must be called with arguments')
  32. }
  33. // Used later to figure out whether we had any packages go out
  34. let anyOutput = false
  35. // Grab a configured output stream that will spit out packages in the desired format.
  36. const outputStream = formatSearchStream({
  37. args, // --searchinclude options are not highlighted
  38. ...opts,
  39. npm: this.npm,
  40. })
  41. log.silly('search', 'searching packages')
  42. const p = new Pipeline(
  43. libSearch.stream(opts.include, opts),
  44. outputStream
  45. )
  46. p.on('data', chunk => {
  47. if (!anyOutput) {
  48. anyOutput = true
  49. }
  50. output.standard(chunk.toString('utf8'))
  51. })
  52. await p.promise()
  53. if (!anyOutput && !this.npm.config.get('json') && !this.npm.config.get('parseable')) {
  54. output.standard('No matches found for ' + (args.map(JSON.stringify).join(' ')))
  55. }
  56. log.silly('search', 'search completed')
  57. }
  58. }
  59. module.exports = Search