base-command.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Base class for npm.commands[cmd]
  2. const usageUtil = require('./utils/usage.js')
  3. const ConfigDefinitions = require('./utils/config/definitions.js')
  4. const getWorkspaces = require('./workspaces/get-workspaces.js')
  5. class BaseCommand {
  6. constructor (npm) {
  7. this.wrapWidth = 80
  8. this.npm = npm
  9. }
  10. get name () {
  11. return this.constructor.name
  12. }
  13. get description () {
  14. return this.constructor.description
  15. }
  16. get usage () {
  17. let usage = `npm ${this.constructor.name}\n\n`
  18. if (this.constructor.description)
  19. usage = `${usage}${this.constructor.description}\n\n`
  20. usage = `${usage}Usage:\n`
  21. if (!this.constructor.usage)
  22. usage = `${usage}npm ${this.constructor.name}`
  23. else
  24. usage = `${usage}${this.constructor.usage.map(u => `npm ${this.constructor.name} ${u}`).join('\n')}`
  25. if (this.constructor.params)
  26. usage = `${usage}\n\nOptions:\n${this.wrappedParams}`
  27. // Mostly this just appends aliases, this could be more clear
  28. usage = usageUtil(this.constructor.name, usage)
  29. usage = `${usage}\n\nRun "npm help ${this.constructor.name}" for more info`
  30. return usage
  31. }
  32. get wrappedParams () {
  33. let results = ''
  34. let line = ''
  35. for (const param of this.constructor.params) {
  36. const usage = `[${ConfigDefinitions[param].usage}]`
  37. if (line.length && (line.length + usage.length) > this.wrapWidth) {
  38. results = [results, line].filter(Boolean).join('\n')
  39. line = ''
  40. }
  41. line = [line, usage].filter(Boolean).join(' ')
  42. }
  43. results = [results, line].filter(Boolean).join('\n')
  44. return results
  45. }
  46. usageError (msg) {
  47. if (!msg) {
  48. return Object.assign(new Error(`\nUsage: ${this.usage}`), {
  49. code: 'EUSAGE',
  50. })
  51. }
  52. return Object.assign(new Error(`\nUsage: ${msg}\n\n${this.usage}`), {
  53. code: 'EUSAGE',
  54. })
  55. }
  56. execWorkspaces (args, filters, cb) {
  57. throw Object.assign(
  58. new Error('This command does not support workspaces.'),
  59. { code: 'ENOWORKSPACES' }
  60. )
  61. }
  62. async setWorkspaces (filters) {
  63. if (this.isArboristCmd)
  64. this.includeWorkspaceRoot = false
  65. const ws = await getWorkspaces(filters, {
  66. path: this.npm.localPrefix,
  67. includeWorkspaceRoot: this.includeWorkspaceRoot,
  68. })
  69. this.workspaces = ws
  70. this.workspaceNames = [...ws.keys()]
  71. this.workspacePaths = [...ws.values()]
  72. }
  73. }
  74. module.exports = BaseCommand