forked from cypress-io/cypress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
args.js
430 lines (358 loc) · 10.6 KB
/
args.js
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
const _ = require('lodash')
const la = require('lazy-ass')
const is = require('check-more-types')
const path = require('path')
const debug = require('debug')('cypress:server:args')
const minimist = require('minimist')
const { getPublicConfigKeys } = require('@packages/config')
const ig = require('is-glob')
const glob = require('glob')
const coerceUtil = require('./coerce')
const proxyUtil = require('./proxy')
const errors = require('../errors')
const nestedObjectsInCurlyBracesRe = /\{(.+?)\}/g
const nestedArraysInSquareBracketsRe = /\[(.+?)\]/g
const everythingAfterFirstEqualRe = /=(.*)/
const allowList = [
'apiKey',
'appPath',
'browser',
'ci',
'ciBuildId',
'clearLogs',
'userNodePath',
'userNodeVersion',
'config',
'configFile',
'cwd',
'env',
'execPath',
'exit',
'exitWithCode',
'group',
'headed',
'inspectBrk',
'key',
'logs',
'mode',
'outputPath',
'parallel',
'ping',
'port',
'project',
'proxySource',
'quiet',
'record',
'reporter',
'reporterOptions',
'returnPkg',
'runMode',
'runProject',
'smokeTest',
'spec',
'tag',
'testingType',
'updating',
'version',
]
// returns true if the given string has double quote character "
// only at the last position.
const hasStrayEndQuote = (s) => {
const quoteAt = s.indexOf('"')
return quoteAt === (s.length - 1)
}
const removeLastCharacter = (s) => {
return s.substr(0, s.length - 1)
}
const normalizeBackslash = (s) => {
if (hasStrayEndQuote(s)) {
return removeLastCharacter(s)
}
return s
}
/**
* remove stray double quote from runProject and other path properties
* due to bug in NPM passing arguments with backslash at the end
* @see https://github.com/cypress-io/cypress/issues/535
*
*/
const normalizeBackslashes = (options) => {
// these properties are paths and likely to have backslash on Windows
const pathProperties = ['runProject', 'project', 'appPath', 'execPath', 'configFile']
pathProperties.forEach((property) => {
// sometimes a string parameter might get parsed into a boolean
// for example "--project ''" will be transformed in "project: true"
// which we should treat as undefined
if (typeof options[property] === 'string') {
options[property] = normalizeBackslash(options[property])
} else {
// configFile is a special case that can be set to false
if (property !== 'configFile') {
delete options[property]
}
}
})
return options
}
const stringify = (val) => {
if (_.isObject(val)) {
return JSON.stringify(val)
}
return val
}
const strToArray = (str) => {
const parsed = tryJSONParse(str)
if (parsed) {
return parsed
}
return [].concat(str.split(','))
}
// swap out comma's for bars
const commasToPipes = (match) => {
return match.split(',').join('|')
}
// convert foo=bar|version=1.2.3 to
// foo=bar,version=1.2.3
const pipesToCommas = (str) => {
return str.split('|').join(',')
}
const tryJSONParse = (str) => {
try {
// https://github.com/cypress-io/cypress/issues/6891
return JSON.parse(str) === Infinity ? null : JSON.parse(str)
} catch (err) {
return null
}
}
const JSONOrCoerce = (str) => {
// valid JSON? horray
const parsed = tryJSONParse(str)
if (parsed) {
return parsed
}
// convert bars back to commas
str = pipesToCommas(str)
// try to parse again?
const parsed2 = tryJSONParse(str)
if (parsed2) {
return parsed2
}
// nupe :-(
return coerceUtil.coerce(str)
}
const sanitizeAndConvertNestedArgs = (str, argname) => {
la(is.unemptyString(argname), 'missing config argname to be parsed')
try {
if (typeof str === 'object') {
return str
}
// if this is valid JSON then just
// parse it and call it a day
const parsed = tryJSONParse(str)
if (parsed) {
return parsed
}
// invalid JSON, so assume mixed usage
// first find foo={a:b,b:c} and bar=[1,2,3]
// syntax and turn those into
// foo: a:b|b:c
// bar: 1|2|3
return _
.chain(str)
.replace(nestedObjectsInCurlyBracesRe, commasToPipes)
.replace(nestedArraysInSquareBracketsRe, commasToPipes)
.split(',')
.map((pair) => {
return pair.split(everythingAfterFirstEqualRe)
})
.fromPairs()
.mapValues(JSONOrCoerce)
.value()
} catch (err) {
debug('could not pass config %s value %s', argname, str)
debug('error %o', err)
return errors.throw('COULD_NOT_PARSE_ARGUMENTS', argname, str, err.message)
}
}
const parseSpecArgvAsGlob = (spec, cwd) => {
return {
isGlob: ig(spec),
setGlob: (pattern) => {
const globbed = glob.sync(path.resolve(cwd, pattern))
// This is needed to output the glob pattern on error.
return globbed.length ? globbed : [spec]
},
}
}
module.exports = {
normalizeBackslashes,
toObject (argv) {
debug('argv array: %o', argv)
const alias = {
'api-key': 'apiKey',
'app-path': 'appPath',
'ci-build-id': 'ciBuildId',
'clear-logs': 'clearLogs',
'config-file': 'configFile',
'exec-path': 'execPath',
'exit-with-code': 'exitWithCode',
'inspect-brk': 'inspectBrk',
'output-path': 'outputPath',
'proxy-source': 'proxySource',
'reporter-options': 'reporterOptions',
'return-pkg': 'returnPkg',
'run-mode': 'isTextTerminal',
'run-project': 'runProject',
'smoke-test': 'smokeTest',
'testing-type': 'testingType',
}
// takes an array of args and converts
// to an object
let options = minimist(argv, {
alias,
// never cast the following CLI arguments
string: ['ci-build-id'],
})
debug('parsed argv options %o', { options })
const allowed = _.pick(argv, allowList)
// were we invoked from the CLI or directly?
const invokedFromCli = Boolean(options.cwd)
options = _
.chain(options)
.defaults(allowed)
.omit(_.keys(alias)) // remove aliases
.extend({ invokedFromCli })
.defaults({
// set in case we
// bypassed the cli
cwd: process.cwd(),
testingType: 'e2e',
})
.mapValues(coerceUtil.coerce)
.value()
debug('argv parsed: %o', options)
// throw new Error()
// if we are updating we may have to pluck out the
// appPath + execPath from the options._ because
// in previous versions up until 0.14.0 these args
// were not passed as dashes and instead were just
// regular arguments
if (options.updating && !options.appPath) {
// take the last two arguments that were unknown
// and apply them to both appPath + execPath
[options.appPath, options.execPath] = options._.slice(-2)
}
let { spec } = options
const { env, config, reporterOptions, outputPath, tag } = options
let project = options.project || options.runProject
// only accept project if it is a string
if (typeof project !== 'string') {
project = undefined
}
// if non-string key has been passed, set it to undefined
// https://github.com/cypress-io/cypress/issues/14571
if (typeof options.key !== 'string') {
delete options.key
}
if (spec) {
try {
const resolvePath = (p) => {
return path.resolve(options.cwd, p)
}
// https://github.com/cypress-io/cypress/issues/8818
// Sometimes spec is parsed to array. Because of that, we need check.
if (typeof spec === 'string') {
// clean up single quotes wrapping the spec for Windows users
// https://github.com/cypress-io/cypress/issues/2298
if (spec[0] === '\'' && spec[spec.length - 1] === '\'') {
spec = spec.substring(1, spec.length - 1)
}
// Before blindly parsing to an array of path, check if spec is not
// a glob pattern with commas.
const { isGlob, setGlob } = parseSpecArgvAsGlob(spec, options.cwd)
if (isGlob) {
options.spec = setGlob(spec)
} else {
options.spec = strToArray(spec).map(resolvePath)
}
} else {
const stringifiedArg = spec.join()
const { isGlob, setGlob } = parseSpecArgvAsGlob(stringifiedArg, options.cwd)
if (isGlob) {
options.spec = setGlob(stringifiedArg)
} else {
options.spec = spec.map(resolvePath)
}
}
} catch (err) {
debug('could not parse config spec value %s', spec)
debug('error %o', err)
return errors.throw('COULD_NOT_PARSE_ARGUMENTS', 'spec', spec, 'spec must be a string or comma-separated list')
}
}
if (tag) {
options.tag = typeof tag === 'string' ? strToArray(tag) : tag
}
if (env) {
options.env = sanitizeAndConvertNestedArgs(env, 'env')
}
const proxySource = proxyUtil.loadSystemProxySettings()
if (process.env.HTTP_PROXY) {
if (proxySource) {
options.proxySource = proxySource
}
options.proxyServer = process.env.HTTP_PROXY
options.proxyBypassList = process.env.NO_PROXY
}
if (reporterOptions) {
options.reporterOptions = sanitizeAndConvertNestedArgs(reporterOptions, 'reporterOptions')
}
if (config) {
// convert config to an object
// and store the config
options.config = sanitizeAndConvertNestedArgs(config, 'config')
}
// get a list of the available config keys
const configKeys = getPublicConfigKeys()
// and if any of our options match this
const configValues = _.pick(options, configKeys)
// then set them on config
// this solves situations where we accept
// root level arguments which also can
// be set in configuration
if (options.config == null) {
options.config = {}
}
_.extend(options.config, configValues)
// remove them from the root options object
options = _.omit(options, configKeys)
options = normalizeBackslashes(options)
debug('options %o', options)
// normalize project to projectRoot
if (project) {
options.projectRoot = path.resolve(options.cwd, project)
}
// normalize output path from previous current working directory
if (outputPath) {
options.outputPath = path.resolve(options.cwd, outputPath)
}
if (options.smokeTest) {
options.pong = options.ping
}
debug('argv options: %o', options)
return options
},
toArray (obj = {}) {
// goes in reverse, takes an object
// and converts to an array by picking
// only the allowed properties and
// mapping them to include the argument
return _
.chain(obj)
.pick(...allowList)
.mapValues((val, key) => {
return `--${key}=${stringify(val)}`
}).values()
.value()
},
}