• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// npm edit <pkg>
2// open the package folder in the $EDITOR
3
4const { resolve } = require('path')
5const fs = require('graceful-fs')
6const cp = require('child_process')
7const completion = require('../utils/completion/installed-shallow.js')
8const BaseCommand = require('../base-command.js')
9
10const splitPackageNames = (path) => {
11  return path.split('/')
12    // combine scoped parts
13    .reduce((parts, part) => {
14      if (parts.length === 0) {
15        return [part]
16      }
17
18      const lastPart = parts[parts.length - 1]
19      // check if previous part is the first part of a scoped package
20      if (lastPart[0] === '@' && !lastPart.includes('/')) {
21        parts[parts.length - 1] += '/' + part
22      } else {
23        parts.push(part)
24      }
25
26      return parts
27    }, [])
28    .join('/node_modules/')
29    .replace(/(\/node_modules)+/, '/node_modules')
30}
31
32class Edit extends BaseCommand {
33  static description = 'Edit an installed package'
34  static name = 'edit'
35  static usage = ['<pkg>[/<subpkg>...]']
36  static params = ['editor']
37  static ignoreImplicitWorkspace = false
38
39  // TODO
40  /* istanbul ignore next */
41  static async completion (opts, npm) {
42    return completion(npm, opts)
43  }
44
45  async exec (args) {
46    if (args.length !== 1) {
47      throw this.usageError()
48    }
49
50    const path = splitPackageNames(args[0])
51    const dir = resolve(this.npm.dir, path)
52
53    // graceful-fs does not promisify
54    await new Promise((res, rej) => {
55      fs.lstat(dir, (err) => {
56        if (err) {
57          return rej(err)
58        }
59        const [bin, ...spawnArgs] = this.npm.config.get('editor').split(/\s+/)
60        const editor = cp.spawn(bin, [...spawnArgs, dir], { stdio: 'inherit' })
61        editor.on('exit', async (code) => {
62          if (code) {
63            return rej(new Error(`editor process exited with code: ${code}`))
64          }
65          try {
66            await this.npm.exec('rebuild', [dir])
67          } catch (execErr) {
68            rej(execErr)
69          }
70          res()
71        })
72      })
73    })
74  }
75}
76module.exports = Edit
77