summaryrefslogtreecommitdiffstats
path: root/node_modules/npm-run-all/bin/common/parse-cli-args.js
blob: 7f056fc576f2634f7e0d105b22b7e06c49aa04bf (plain) (blame)
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/**
 * @author Toru Nagashima
 * @copyright 2016 Toru Nagashima. All rights reserved.
 * See LICENSE file in root directory for full license.
 */
"use strict"

/*eslint-disable no-process-env */

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

const OVERWRITE_OPTION = /^--([^:]+?):([^=]+?)(?:=(.+))?$/
const CONFIG_OPTION = /^--([^=]+?)(?:=(.+))$/
const PACKAGE_CONFIG_PATTERN = /^npm_package_config_(.+)$/
const CONCAT_OPTIONS = /^-[clnprs]+$/

/**
 * Overwrites a specified package config.
 *
 * @param {object} config - A config object to be overwritten.
 * @param {string} packageName - A package name to overwrite.
 * @param {string} variable - A variable name to overwrite.
 * @param {string} value - A new value to overwrite.
 * @returns {void}
 */
function overwriteConfig(config, packageName, variable, value) {
    const scope = config[packageName] || (config[packageName] = {})
    scope[variable] = value
}

/**
 * Creates a package config object.
 * This checks `process.env` and creates the default value.
 *
 * @returns {object} Created config object.
 */
function createPackageConfig() {
    const retv = {}
    const packageName = process.env.npm_package_name
    if (!packageName) {
        return retv
    }

    for (const key of Object.keys(process.env)) {
        const m = PACKAGE_CONFIG_PATTERN.exec(key)
        if (m != null) {
            overwriteConfig(retv, packageName, m[1], process.env[key])
        }
    }

    return retv
}

/**
 * Adds a new group into a given list.
 *
 * @param {object[]} groups - A group list to add.
 * @param {object} initialValues - A key-value map for the default of new value.
 * @returns {void}
 */
function addGroup(groups, initialValues) {
    groups.push(Object.assign(
        { parallel: false, patterns: [] },
        initialValues || {}
    ))
}

/**
 * ArgumentSet is values of parsed CLI arguments.
 * This class provides the getter to get the last group.
 */
class ArgumentSet {
    /**
     * @param {object} initialValues - A key-value map for the default of new value.
     * @param {object} options - A key-value map for the options.
     */
    constructor(initialValues, options) {
        this.config = {}
        this.continueOnError = false
        this.groups = []
        this.maxParallel = 0
        this.npmPath = null
        this.packageConfig = createPackageConfig()
        this.printLabel = false
        this.printName = false
        this.race = false
        this.rest = []
        this.silent = process.env.npm_config_loglevel === "silent"
        this.singleMode = Boolean(options && options.singleMode)

        addGroup(this.groups, initialValues)
    }

    /**
     * Gets the last group.
     */
    get lastGroup() {
        return this.groups[this.groups.length - 1]
    }

    /**
     * Gets "parallel" flag.
     */
    get parallel() {
        return this.groups.some(g => g.parallel)
    }
}

/**
 * Parses CLI arguments.
 *
 * @param {ArgumentSet} set - The parsed CLI arguments.
 * @param {string[]} args - CLI arguments.
 * @returns {ArgumentSet} set itself.
 */
function parseCLIArgsCore(set, args) {    // eslint-disable-line complexity
    LOOP:
    for (let i = 0; i < args.length; ++i) {
        const arg = args[i]

        switch (arg) {
            case "--":
                set.rest = args.slice(1 + i)
                break LOOP

            case "--color":
            case "--no-color":
                // do nothing.
                break

            case "-c":
            case "--continue-on-error":
                set.continueOnError = true
                break

            case "-l":
            case "--print-label":
                set.printLabel = true
                break

            case "-n":
            case "--print-name":
                set.printName = true
                break

            case "-r":
            case "--race":
                set.race = true
                break

            case "--silent":
                set.silent = true
                break

            case "--max-parallel":
                set.maxParallel = parseInt(args[++i], 10)
                if (!Number.isFinite(set.maxParallel) || set.maxParallel <= 0) {
                    throw new Error(`Invalid Option: --max-parallel ${args[i]}`)
                }
                break

            case "-s":
            case "--sequential":
            case "--serial":
                if (set.singleMode && arg === "-s") {
                    set.silent = true
                    break
                }
                if (set.singleMode) {
                    throw new Error(`Invalid Option: ${arg}`)
                }
                addGroup(set.groups)
                break

            case "--aggregate-output":
                set.aggregateOutput = true
                break

            case "-p":
            case "--parallel":
                if (set.singleMode) {
                    throw new Error(`Invalid Option: ${arg}`)
                }
                addGroup(set.groups, { parallel: true })
                break

            case "--npm-path":
                set.npmPath = args[++i] || null
                break

            default: {
                let matched = null
                if ((matched = OVERWRITE_OPTION.exec(arg))) {
                    overwriteConfig(
                        set.packageConfig,
                        matched[1],
                        matched[2],
                        matched[3] || args[++i]
                    )
                }
                else if ((matched = CONFIG_OPTION.exec(arg))) {
                    set.config[matched[1]] = matched[2]
                }
                else if (CONCAT_OPTIONS.test(arg)) {
                    parseCLIArgsCore(
                        set,
                        arg.slice(1).split("").map(c => `-${c}`)
                    )
                }
                else if (arg[0] === "-") {
                    throw new Error(`Invalid Option: ${arg}`)
                }
                else {
                    set.lastGroup.patterns.push(arg)
                }

                break
            }
        }
    }

    if (!set.parallel && set.aggregateOutput) {
        throw new Error("Invalid Option: --aggregate-output (without parallel)")
    }
    if (!set.parallel && set.race) {
        const race = args.indexOf("--race") !== -1 ? "--race" : "-r"
        throw new Error(`Invalid Option: ${race} (without parallel)`)
    }
    if (!set.parallel && set.maxParallel !== 0) {
        throw new Error("Invalid Option: --max-parallel (without parallel)")
    }

    return set
}

/**
 * Parses CLI arguments.
 *
 * @param {string[]} args - CLI arguments.
 * @param {object} initialValues - A key-value map for the default of new value.
 * @param {object} options - A key-value map for the options.
 * @param {boolean} options.singleMode - The flag to be single group mode.
 * @returns {ArgumentSet} The parsed CLI arguments.
 */
module.exports = function parseCLIArgs(args, initialValues, options) {
    return parseCLIArgsCore(new ArgumentSet(initialValues, options), args)
}

/*eslint-enable */