nopt.js 11 KB

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