Welcome to mirror list, hosted at ThFree Co, Russian Federation.

set-script.js « lib « npm « deps - github.com/nodejs/node.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7bac6eca50604eb985f01692639010c37f4795e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const log = require('npmlog')
const usageUtil = require('./utils/usage.js')
const { localPrefix } = require('./npm.js')
const fs = require('fs')
const usage = usageUtil('set-script', 'npm set-script [<script>] [<command>]')
const parseJSON = require('json-parse-even-better-errors')
const rpj = require('read-package-json-fast')

const cmd = (args, cb) => set(args).then(() => cb()).catch(cb)

const set = async function (args) {
  if (process.env.npm_lifecycle_event === 'postinstall')
    throw new Error('Scripts can’t set from the postinstall script')

  // Parse arguments
  if (args.length !== 2)
    throw new Error(`Expected 2 arguments: got ${args.length}`)

  // Set the script
  let manifest
  let warn = false
  try {
    manifest = fs.readFileSync(localPrefix + '/package.json', 'utf-8')
  } catch (error) {
    throw new Error('package.json not found')
  }
  try {
    manifest = parseJSON(manifest)
  } catch (error) {
    throw new Error(`Invalid package.json: ${error}`)
  }
  if (!manifest.scripts)
    manifest.scripts = {}
  if (manifest.scripts[args[0]] && manifest.scripts[args[0]] !== args[1])
    warn = true
  manifest.scripts[args[0]] = args[1]
  // format content
  const packageJsonInfo = await rpj(localPrefix + '/package.json')
  const {
    [Symbol.for('indent')]: indent,
    [Symbol.for('newline')]: newline,
  } = packageJsonInfo
  const format = indent === undefined ? '  ' : indent
  const eol = newline === undefined ? '\n' : newline
  const content = (JSON.stringify(manifest, null, format) + '\n')
    .replace(/\n/g, eol)
  fs.writeFileSync(localPrefix + '/package.json', content)
  if (warn)
    log.warn('set-script', `Script "${args[0]}" was overwritten`)
}

module.exports = Object.assign(cmd, { usage })