npm-usage.js 2.0 KB

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