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