cli.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Separated out for easier unit testing
  2. module.exports = async (process) => {
  3. // set it here so that regardless of what happens later, we don't
  4. // leak any private CLI configs to other programs
  5. process.title = 'npm'
  6. const {
  7. checkForBrokenNode,
  8. checkForUnsupportedNode,
  9. } = require('../lib/utils/unsupported.js')
  10. checkForBrokenNode()
  11. const log = require('npmlog')
  12. // pause it here so it can unpause when we've loaded the configs
  13. // and know what loglevel we should be printing.
  14. log.pause()
  15. checkForUnsupportedNode()
  16. const npm = require('../lib/npm.js')
  17. const exitHandler = require('../lib/utils/exit-handler.js')
  18. exitHandler.setNpm(npm)
  19. // if npm is called as "npmg" or "npm_g", then
  20. // run in global mode.
  21. if (process.argv[1][process.argv[1].length - 1] === 'g')
  22. process.argv.splice(1, 1, 'npm', '-g')
  23. const replaceInfo = require('../lib/utils/replace-info.js')
  24. log.verbose('cli', replaceInfo(process.argv))
  25. log.info('using', 'npm@%s', npm.version)
  26. log.info('using', 'node@%s', process.version)
  27. process.on('uncaughtException', exitHandler)
  28. process.on('unhandledRejection', exitHandler)
  29. const updateNotifier = require('../lib/utils/update-notifier.js')
  30. // now actually fire up npm and run the command.
  31. // this is how to use npm programmatically:
  32. try {
  33. await npm.load()
  34. if (npm.config.get('version', 'cli')) {
  35. npm.output(npm.version)
  36. return exitHandler()
  37. }
  38. // npm --versions=cli
  39. if (npm.config.get('versions', 'cli')) {
  40. npm.argv = ['version']
  41. npm.config.set('usage', false, 'cli')
  42. }
  43. updateNotifier(npm)
  44. const cmd = npm.argv.shift()
  45. if (!cmd) {
  46. npm.output(npm.usage)
  47. process.exitCode = 1
  48. return exitHandler()
  49. }
  50. const impl = npm.commands[cmd]
  51. if (!impl) {
  52. const didYouMean = require('./utils/did-you-mean.js')
  53. const suggestions = await didYouMean(npm, npm.localPrefix, cmd)
  54. npm.output(`Unknown command: "${cmd}"${suggestions}\n\nTo see a list of supported npm commands, run:\n npm help`)
  55. process.exitCode = 1
  56. return exitHandler()
  57. }
  58. impl(npm.argv, exitHandler)
  59. } catch (err) {
  60. return exitHandler(err)
  61. }
  62. }