nopt.js 12 KB

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