Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80684 views
1
// info about each config option.
2
3
var debug = process.env.DEBUG_NOPT || process.env.NOPT_DEBUG
4
? function () { console.error.apply(console, arguments) }
5
: function () {}
6
7
var url = require("url")
8
, path = require("path")
9
, Stream = require("stream").Stream
10
, abbrev = require("abbrev")
11
12
module.exports = exports = nopt
13
exports.clean = clean
14
15
exports.typeDefs =
16
{ String : { type: String, validate: validateString }
17
, Boolean : { type: Boolean, validate: validateBoolean }
18
, url : { type: url, validate: validateUrl }
19
, Number : { type: Number, validate: validateNumber }
20
, path : { type: path, validate: validatePath }
21
, Stream : { type: Stream, validate: validateStream }
22
, Date : { type: Date, validate: validateDate }
23
}
24
25
function nopt (types, shorthands, args, slice) {
26
args = args || process.argv
27
types = types || {}
28
shorthands = shorthands || {}
29
if (typeof slice !== "number") slice = 2
30
31
debug(types, shorthands, args, slice)
32
33
args = args.slice(slice)
34
var data = {}
35
, key
36
, remain = []
37
, cooked = args
38
, original = args.slice(0)
39
40
parse(args, data, remain, types, shorthands)
41
// now data is full
42
clean(data, types, exports.typeDefs)
43
data.argv = {remain:remain,cooked:cooked,original:original}
44
Object.defineProperty(data.argv, 'toString', { value: function () {
45
return this.original.map(JSON.stringify).join(" ")
46
}, enumerable: false })
47
return data
48
}
49
50
function clean (data, types, typeDefs) {
51
typeDefs = typeDefs || exports.typeDefs
52
var remove = {}
53
, typeDefault = [false, true, null, String, Array]
54
55
Object.keys(data).forEach(function (k) {
56
if (k === "argv") return
57
var val = data[k]
58
, isArray = Array.isArray(val)
59
, type = types[k]
60
if (!isArray) val = [val]
61
if (!type) type = typeDefault
62
if (type === Array) type = typeDefault.concat(Array)
63
if (!Array.isArray(type)) type = [type]
64
65
debug("val=%j", val)
66
debug("types=", type)
67
val = val.map(function (val) {
68
// if it's an unknown value, then parse false/true/null/numbers/dates
69
if (typeof val === "string") {
70
debug("string %j", val)
71
val = val.trim()
72
if ((val === "null" && ~type.indexOf(null))
73
|| (val === "true" &&
74
(~type.indexOf(true) || ~type.indexOf(Boolean)))
75
|| (val === "false" &&
76
(~type.indexOf(false) || ~type.indexOf(Boolean)))) {
77
val = JSON.parse(val)
78
debug("jsonable %j", val)
79
} else if (~type.indexOf(Number) && !isNaN(val)) {
80
debug("convert to number", val)
81
val = +val
82
} else if (~type.indexOf(Date) && !isNaN(Date.parse(val))) {
83
debug("convert to date", val)
84
val = new Date(val)
85
}
86
}
87
88
if (!types.hasOwnProperty(k)) {
89
return val
90
}
91
92
// allow `--no-blah` to set 'blah' to null if null is allowed
93
if (val === false && ~type.indexOf(null) &&
94
!(~type.indexOf(false) || ~type.indexOf(Boolean))) {
95
val = null
96
}
97
98
var d = {}
99
d[k] = val
100
debug("prevalidated val", d, val, types[k])
101
if (!validate(d, k, val, types[k], typeDefs)) {
102
if (exports.invalidHandler) {
103
exports.invalidHandler(k, val, types[k], data)
104
} else if (exports.invalidHandler !== false) {
105
debug("invalid: "+k+"="+val, types[k])
106
}
107
return remove
108
}
109
debug("validated val", d, val, types[k])
110
return d[k]
111
}).filter(function (val) { return val !== remove })
112
113
if (!val.length) delete data[k]
114
else if (isArray) {
115
debug(isArray, data[k], val)
116
data[k] = val
117
} else data[k] = val[0]
118
119
debug("k=%s val=%j", k, val, data[k])
120
})
121
}
122
123
function validateString (data, k, val) {
124
data[k] = String(val)
125
}
126
127
function validatePath (data, k, val) {
128
if (val === true) return false
129
if (val === null) return true
130
131
val = String(val)
132
var homePattern = process.platform === 'win32' ? /^~(\/|\\)/ : /^~\//
133
if (val.match(homePattern) && process.env.HOME) {
134
val = path.resolve(process.env.HOME, val.substr(2))
135
}
136
data[k] = path.resolve(String(val))
137
return true
138
}
139
140
function validateNumber (data, k, val) {
141
debug("validate Number %j %j %j", k, val, isNaN(val))
142
if (isNaN(val)) return false
143
data[k] = +val
144
}
145
146
function validateDate (data, k, val) {
147
debug("validate Date %j %j %j", k, val, Date.parse(val))
148
var s = Date.parse(val)
149
if (isNaN(s)) return false
150
data[k] = new Date(val)
151
}
152
153
function validateBoolean (data, k, val) {
154
if (val instanceof Boolean) val = val.valueOf()
155
else if (typeof val === "string") {
156
if (!isNaN(val)) val = !!(+val)
157
else if (val === "null" || val === "false") val = false
158
else val = true
159
} else val = !!val
160
data[k] = val
161
}
162
163
function validateUrl (data, k, val) {
164
val = url.parse(String(val))
165
if (!val.host) return false
166
data[k] = val.href
167
}
168
169
function validateStream (data, k, val) {
170
if (!(val instanceof Stream)) return false
171
data[k] = val
172
}
173
174
function validate (data, k, val, type, typeDefs) {
175
// arrays are lists of types.
176
if (Array.isArray(type)) {
177
for (var i = 0, l = type.length; i < l; i ++) {
178
if (type[i] === Array) continue
179
if (validate(data, k, val, type[i], typeDefs)) return true
180
}
181
delete data[k]
182
return false
183
}
184
185
// an array of anything?
186
if (type === Array) return true
187
188
// NaN is poisonous. Means that something is not allowed.
189
if (type !== type) {
190
debug("Poison NaN", k, val, type)
191
delete data[k]
192
return false
193
}
194
195
// explicit list of values
196
if (val === type) {
197
debug("Explicitly allowed %j", val)
198
// if (isArray) (data[k] = data[k] || []).push(val)
199
// else data[k] = val
200
data[k] = val
201
return true
202
}
203
204
// now go through the list of typeDefs, validate against each one.
205
var ok = false
206
, types = Object.keys(typeDefs)
207
for (var i = 0, l = types.length; i < l; i ++) {
208
debug("test type %j %j %j", k, val, types[i])
209
var t = typeDefs[types[i]]
210
if (t && type === t.type) {
211
var d = {}
212
ok = false !== t.validate(d, k, val)
213
val = d[k]
214
if (ok) {
215
// if (isArray) (data[k] = data[k] || []).push(val)
216
// else data[k] = val
217
data[k] = val
218
break
219
}
220
}
221
}
222
debug("OK? %j (%j %j %j)", ok, k, val, types[i])
223
224
if (!ok) delete data[k]
225
return ok
226
}
227
228
function parse (args, data, remain, types, shorthands) {
229
debug("parse", args, data, remain)
230
231
var key = null
232
, abbrevs = abbrev(Object.keys(types))
233
, shortAbbr = abbrev(Object.keys(shorthands))
234
235
for (var i = 0; i < args.length; i ++) {
236
var arg = args[i]
237
debug("arg", arg)
238
239
if (arg.match(/^-{2,}$/)) {
240
// done with keys.
241
// the rest are args.
242
remain.push.apply(remain, args.slice(i + 1))
243
args[i] = "--"
244
break
245
}
246
var hadEq = false
247
if (arg.charAt(0) === "-" && arg.length > 1) {
248
if (arg.indexOf("=") !== -1) {
249
hadEq = true
250
var v = arg.split("=")
251
arg = v.shift()
252
v = v.join("=")
253
args.splice.apply(args, [i, 1].concat([arg, v]))
254
}
255
256
// see if it's a shorthand
257
// if so, splice and back up to re-parse it.
258
var shRes = resolveShort(arg, shorthands, shortAbbr, abbrevs)
259
debug("arg=%j shRes=%j", arg, shRes)
260
if (shRes) {
261
debug(arg, shRes)
262
args.splice.apply(args, [i, 1].concat(shRes))
263
if (arg !== shRes[0]) {
264
i --
265
continue
266
}
267
}
268
arg = arg.replace(/^-+/, "")
269
var no = null
270
while (arg.toLowerCase().indexOf("no-") === 0) {
271
no = !no
272
arg = arg.substr(3)
273
}
274
275
if (abbrevs[arg]) arg = abbrevs[arg]
276
277
var isArray = types[arg] === Array ||
278
Array.isArray(types[arg]) && types[arg].indexOf(Array) !== -1
279
280
// allow unknown things to be arrays if specified multiple times.
281
if (!types.hasOwnProperty(arg) && data.hasOwnProperty(arg)) {
282
if (!Array.isArray(data[arg]))
283
data[arg] = [data[arg]]
284
isArray = true
285
}
286
287
var val
288
, la = args[i + 1]
289
290
var isBool = typeof no === 'boolean' ||
291
types[arg] === Boolean ||
292
Array.isArray(types[arg]) && types[arg].indexOf(Boolean) !== -1 ||
293
(typeof types[arg] === 'undefined' && !hadEq) ||
294
(la === "false" &&
295
(types[arg] === null ||
296
Array.isArray(types[arg]) && ~types[arg].indexOf(null)))
297
298
if (isBool) {
299
// just set and move along
300
val = !no
301
// however, also support --bool true or --bool false
302
if (la === "true" || la === "false") {
303
val = JSON.parse(la)
304
la = null
305
if (no) val = !val
306
i ++
307
}
308
309
// also support "foo":[Boolean, "bar"] and "--foo bar"
310
if (Array.isArray(types[arg]) && la) {
311
if (~types[arg].indexOf(la)) {
312
// an explicit type
313
val = la
314
i ++
315
} else if ( la === "null" && ~types[arg].indexOf(null) ) {
316
// null allowed
317
val = null
318
i ++
319
} else if ( !la.match(/^-{2,}[^-]/) &&
320
!isNaN(la) &&
321
~types[arg].indexOf(Number) ) {
322
// number
323
val = +la
324
i ++
325
} else if ( !la.match(/^-[^-]/) && ~types[arg].indexOf(String) ) {
326
// string
327
val = la
328
i ++
329
}
330
}
331
332
if (isArray) (data[arg] = data[arg] || []).push(val)
333
else data[arg] = val
334
335
continue
336
}
337
338
if (types[arg] === String && la === undefined)
339
la = ""
340
341
if (la && la.match(/^-{2,}$/)) {
342
la = undefined
343
i --
344
}
345
346
val = la === undefined ? true : la
347
if (isArray) (data[arg] = data[arg] || []).push(val)
348
else data[arg] = val
349
350
i ++
351
continue
352
}
353
remain.push(arg)
354
}
355
}
356
357
function resolveShort (arg, shorthands, shortAbbr, abbrevs) {
358
// handle single-char shorthands glommed together, like
359
// npm ls -glp, but only if there is one dash, and only if
360
// all of the chars are single-char shorthands, and it's
361
// not a match to some other abbrev.
362
arg = arg.replace(/^-+/, '')
363
364
// if it's an exact known option, then don't go any further
365
if (abbrevs[arg] === arg)
366
return null
367
368
// if it's an exact known shortopt, same deal
369
if (shorthands[arg]) {
370
// make it an array, if it's a list of words
371
if (shorthands[arg] && !Array.isArray(shorthands[arg]))
372
shorthands[arg] = shorthands[arg].split(/\s+/)
373
374
return shorthands[arg]
375
}
376
377
// first check to see if this arg is a set of single-char shorthands
378
var singles = shorthands.___singles
379
if (!singles) {
380
singles = Object.keys(shorthands).filter(function (s) {
381
return s.length === 1
382
}).reduce(function (l,r) {
383
l[r] = true
384
return l
385
}, {})
386
shorthands.___singles = singles
387
debug('shorthand singles', singles)
388
}
389
390
var chrs = arg.split("").filter(function (c) {
391
return singles[c]
392
})
393
394
if (chrs.join("") === arg) return chrs.map(function (c) {
395
return shorthands[c]
396
}).reduce(function (l, r) {
397
return l.concat(r)
398
}, [])
399
400
401
// if it's an arg abbrev, and not a literal shorthand, then prefer the arg
402
if (abbrevs[arg] && !shorthands[arg])
403
return null
404
405
// if it's an abbr for a shorthand, then use that
406
if (shortAbbr[arg])
407
arg = shortAbbr[arg]
408
409
// make it an array, if it's a list of words
410
if (shorthands[arg] && !Array.isArray(shorthands[arg]))
411
shorthands[arg] = shorthands[arg].split(/\s+/)
412
413
return shorthands[arg]
414
}
415
416