edit.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // npm edit <pkg>
  2. // open the package folder in the $EDITOR
  3. const { resolve } = require('path')
  4. const fs = require('graceful-fs')
  5. const { spawn } = require('child_process')
  6. const splitPackageNames = require('./utils/split-package-names.js')
  7. const completion = require('./utils/completion/installed-shallow.js')
  8. const BaseCommand = require('./base-command.js')
  9. class Edit extends BaseCommand {
  10. static get description () {
  11. return 'Edit an installed package'
  12. }
  13. /* istanbul ignore next - see test/lib/load-all-commands.js */
  14. static get name () {
  15. return 'edit'
  16. }
  17. /* istanbul ignore next - see test/lib/load-all-commands.js */
  18. static get usage () {
  19. return ['<pkg>[/<subpkg>...]']
  20. }
  21. /* istanbul ignore next - see test/lib/load-all-commands.js */
  22. static get params () {
  23. return ['editor']
  24. }
  25. /* istanbul ignore next - see test/lib/load-all-commands.js */
  26. async completion (opts) {
  27. return completion(this.npm, opts)
  28. }
  29. exec (args, cb) {
  30. this.edit(args).then(() => cb()).catch(cb)
  31. }
  32. async edit (args) {
  33. if (args.length !== 1)
  34. throw new Error(this.usage)
  35. const path = splitPackageNames(args[0])
  36. const dir = resolve(this.npm.dir, path)
  37. // graceful-fs does not promisify
  38. await new Promise((resolve, reject) => {
  39. fs.lstat(dir, (err) => {
  40. if (err)
  41. return reject(err)
  42. const [bin, ...args] = this.npm.config.get('editor').split(/\s+/)
  43. const editor = spawn(bin, [...args, dir], { stdio: 'inherit' })
  44. editor.on('exit', (code) => {
  45. if (code)
  46. return reject(new Error(`editor process exited with code: ${code}`))
  47. this.npm.commands.rebuild([dir], (err) => {
  48. if (err)
  49. return reject(err)
  50. resolve()
  51. })
  52. })
  53. })
  54. })
  55. }
  56. }
  57. module.exports = Edit