-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
args.js
333 lines (270 loc) · 8.49 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
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 coerceUtil = require('./coerce')
const configUtil = require('../config')
const proxyUtil = require('./proxy')
const errors = require('../errors')
const nestedObjectsInCurlyBracesRe = /\{(.+?)\}/g
const nestedArraysInSquareBracketsRe = /\[(.+?)\]/g
const everythingAfterFirstEqualRe = /=(.*)/
const whitelist = 'appPath apiKey browser ci ciBuildId clearLogs config configFile cwd env execPath exit exitWithCode generateKey getKey group headed inspectBrk key logs mode outputPath parallel ping port project proxySource quiet record reporter reporterOptions returnPkg runMode runProject smokeTest spec tag updating version'.split(' ')
// 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 {
return 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(str)
}
const sanitizeAndConvertNestedArgs = (str, argname) => {
la(is.unemptyString(argname), 'missing config argname to be parsed')
try {
// 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)
}
}
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',
'get-key': 'getKey',
'new-key': 'generateKey',
'output-path': 'outputPath',
'proxy-source': 'proxySource',
'reporter-options': 'reporterOptions',
'return-pkg': 'returnPkg',
'run-mode': 'isTextTerminal',
'run-project': 'runProject',
'smoke-test': 'smokeTest',
}
// takes an array of args and converts
// to an object
let options = minimist(argv, {
alias,
})
const whitelisted = _.pick(argv, whitelist)
// were we invoked from the CLI or directly?
const invokedFromCli = Boolean(options.cwd)
options = _
.chain(options)
.defaults(whitelisted)
.omit(_.keys(alias)) // remove aliases
.extend({ invokedFromCli })
.defaults({
// set in case we
// bypassed the cli
cwd: process.cwd(),
})
.mapValues(coerceUtil)
.value()
debug('argv parsed: %o', options)
// 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 (spec) {
const resolvePath = (p) => {
return path.resolve(options.cwd, p)
}
// 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)
}
options.spec = strToArray(spec).map(resolvePath)
}
if (tag) {
options.tag = strToArray(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 = configUtil.getConfigKeys()
// 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.runProject) {
options.run = true
}
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 whitelisted properties and
// mapping them to include the argument
return _
.chain(obj)
.pick(...whitelist)
.mapValues((val, key) => {
return `--${key}=${stringify(val)}`
}).values()
.value()
},
}