npm-usage.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. const { dirname } = require('path')
  2. const { cmdList } = require('./cmd-list')
  3. const localeCompare = require('@isaacs/string-locale-compare')('en')
  4. module.exports = (npm) => {
  5. const usesBrowser = npm.config.get('viewer') === 'browser'
  6. ? ' (in a browser)' : ''
  7. return `npm <command>
  8. Usage:
  9. npm install install all the dependencies in your project
  10. npm install <foo> add the <foo> dependency to your project
  11. npm test run this project's tests
  12. npm run <foo> run the script named <foo>
  13. npm <command> -h quick help on <command>
  14. npm -l display usage info for all commands
  15. npm help <term> search for help on <term>${usesBrowser}
  16. npm help npm more involved overview${usesBrowser}
  17. All commands:
  18. ${allCommands(npm)}
  19. Specify configs in the ini-formatted file:
  20. ${npm.config.get('userconfig')}
  21. or on the command line via: npm <command> --key=value
  22. More configuration info: npm help config
  23. Configuration fields: npm help 7 config
  24. npm@${npm.version} ${dirname(dirname(__dirname))}`
  25. }
  26. const allCommands = (npm) => {
  27. if (npm.config.get('long'))
  28. return usages(npm)
  29. return ('\n ' + wrap(cmdList))
  30. }
  31. const wrap = (arr) => {
  32. const out = ['']
  33. const line = !process.stdout.columns ? 60
  34. : Math.min(60, Math.max(process.stdout.columns - 16, 24))
  35. let l = 0
  36. for (const c of arr.sort((a, b) => a < b ? -1 : 1)) {
  37. if (out[l].length + c.length + 2 < line)
  38. out[l] += ', ' + c
  39. else {
  40. out[l++] += ','
  41. out[l] = c
  42. }
  43. }
  44. return out.join('\n ').substr(2)
  45. }
  46. const usages = (npm) => {
  47. // return a string of <command>: <usage>
  48. let maxLen = 0
  49. return cmdList.reduce((set, c) => {
  50. set.push([c, npm.commands[c].usage])
  51. maxLen = Math.max(maxLen, c.length)
  52. return set
  53. }, [])
  54. .sort(([a], [b]) => localeCompare(a, b))
  55. .map(([c, usage]) => `\n ${c}${' '.repeat(maxLen - c.length + 1)}${
  56. (usage.split('\n').join('\n' + ' '.repeat(maxLen + 5)))}`)
  57. .join('\n')
  58. }