nopt.js 13 KB

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