1const { resolve } = require('path')
2const pkgJson = require('@npmcli/package-json')
3
4const reifyFinish = require('../utils/reify-finish.js')
5const completion = require('../utils/completion/installed-shallow.js')
6
7const ArboristWorkspaceCmd = require('../arborist-cmd.js')
8class Uninstall extends ArboristWorkspaceCmd {
9  static description = 'Remove a package'
10  static name = 'uninstall'
11  static params = ['save', 'global', ...super.params]
12  static usage = ['[<@scope>/]<pkg>...']
13  static ignoreImplicitWorkspace = false
14
15  // TODO
16  /* istanbul ignore next */
17  static async completion (opts, npm) {
18    return completion(npm, opts)
19  }
20
21  async exec (args) {
22    if (!args.length) {
23      if (!this.npm.global) {
24        throw new Error('Must provide a package name to remove')
25      } else {
26        try {
27          const { content: pkg } = await pkgJson.normalize(this.npm.localPrefix)
28          args.push(pkg.name)
29        } catch (er) {
30          if (er.code !== 'ENOENT' && er.code !== 'ENOTDIR') {
31            throw er
32          } else {
33            throw this.usageError()
34          }
35        }
36      }
37    }
38
39    // the /path/to/node_modules/..
40    const path = this.npm.global
41      ? resolve(this.npm.globalDir, '..')
42      : this.npm.localPrefix
43
44    const Arborist = require('@npmcli/arborist')
45    const opts = {
46      ...this.npm.flatOptions,
47      path,
48      rm: args,
49      workspaces: this.workspaceNames,
50    }
51    const arb = new Arborist(opts)
52    await arb.reify(opts)
53    await reifyFinish(this.npm, arb)
54  }
55}
56module.exports = Uninstall
57