Repositorio del curso CCOM4030 el semestre B91 del proyecto kilometro0

nopt.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. , osenv = require("osenv")
  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 (!val.length) delete data[k]
  102. else if (isArray) {
  103. debug(isArray, data[k], val)
  104. data[k] = val
  105. } else data[k] = val[0]
  106. debug("k=%s val=%j", k, val, data[k])
  107. })
  108. }
  109. function validateString (data, k, val) {
  110. data[k] = String(val)
  111. }
  112. function validatePath (data, k, val) {
  113. if (val === true) return false
  114. if (val === null) return true
  115. val = String(val)
  116. var isWin = process.platform === 'win32'
  117. , homePattern = isWin ? /^~(\/|\\)/ : /^~\//
  118. , home = osenv.home()
  119. if (home && val.match(homePattern)) {
  120. data[k] = path.resolve(home, val.substr(2))
  121. } else {
  122. data[k] = path.resolve(val)
  123. }
  124. return true
  125. }
  126. function validateNumber (data, k, val) {
  127. debug("validate Number %j %j %j", k, val, isNaN(val))
  128. if (isNaN(val)) return false
  129. data[k] = +val
  130. }
  131. function validateDate (data, k, val) {
  132. var s = Date.parse(val)
  133. debug("validate Date %j %j %j", k, val, s)
  134. if (isNaN(s)) return false
  135. data[k] = new Date(val)
  136. }
  137. function validateBoolean (data, k, val) {
  138. if (val instanceof Boolean) val = val.valueOf()
  139. else if (typeof val === "string") {
  140. if (!isNaN(val)) val = !!(+val)
  141. else if (val === "null" || val === "false") val = false
  142. else val = true
  143. } else val = !!val
  144. data[k] = val
  145. }
  146. function validateUrl (data, k, val) {
  147. val = url.parse(String(val))
  148. if (!val.host) return false
  149. data[k] = val.href
  150. }
  151. function validateStream (data, k, val) {
  152. if (!(val instanceof Stream)) return false
  153. data[k] = val
  154. }
  155. function validate (data, k, val, type, typeDefs) {
  156. // arrays are lists of types.
  157. if (Array.isArray(type)) {
  158. for (var i = 0, l = type.length; i < l; i ++) {
  159. if (type[i] === Array) continue
  160. if (validate(data, k, val, type[i], typeDefs)) return true
  161. }
  162. delete data[k]
  163. return false
  164. }
  165. // an array of anything?
  166. if (type === Array) return true
  167. // NaN is poisonous. Means that something is not allowed.
  168. if (type !== type) {
  169. debug("Poison NaN", k, val, type)
  170. delete data[k]
  171. return false
  172. }
  173. // explicit list of values
  174. if (val === type) {
  175. debug("Explicitly allowed %j", val)
  176. // if (isArray) (data[k] = data[k] || []).push(val)
  177. // else data[k] = val
  178. data[k] = val
  179. return true
  180. }
  181. // now go through the list of typeDefs, validate against each one.
  182. var ok = false
  183. , types = Object.keys(typeDefs)
  184. for (var i = 0, l = types.length; i < l; i ++) {
  185. debug("test type %j %j %j", k, val, types[i])
  186. var t = typeDefs[types[i]]
  187. if (t &&
  188. ((type && type.name && t.type && t.type.name) ? (type.name === t.type.name) : (type === t.type))) {
  189. var d = {}
  190. ok = false !== t.validate(d, k, val)
  191. val = d[k]
  192. if (ok) {
  193. // if (isArray) (data[k] = data[k] || []).push(val)
  194. // else data[k] = val
  195. data[k] = val
  196. break
  197. }
  198. }
  199. }
  200. debug("OK? %j (%j %j %j)", ok, k, val, types[i])
  201. if (!ok) delete data[k]
  202. return ok
  203. }
  204. function parse (args, data, remain, types, shorthands) {
  205. debug("parse", args, data, remain)
  206. var key = null
  207. , abbrevs = abbrev(Object.keys(types))
  208. , shortAbbr = abbrev(Object.keys(shorthands))
  209. for (var i = 0; i < args.length; i ++) {
  210. var arg = args[i]
  211. debug("arg", arg)
  212. if (arg.match(/^-{2,}$/)) {
  213. // done with keys.
  214. // the rest are args.
  215. remain.push.apply(remain, args.slice(i + 1))
  216. args[i] = "--"
  217. break
  218. }
  219. var hadEq = false
  220. if (arg.charAt(0) === "-" && arg.length > 1) {
  221. var at = arg.indexOf('=')
  222. if (at > -1) {
  223. hadEq = true
  224. var v = arg.substr(at + 1)
  225. arg = arg.substr(0, at)
  226. args.splice(i, 1, arg, v)
  227. }
  228. // see if it's a shorthand
  229. // if so, splice and back up to re-parse it.
  230. var shRes = resolveShort(arg, shorthands, shortAbbr, abbrevs)
  231. debug("arg=%j shRes=%j", arg, shRes)
  232. if (shRes) {
  233. debug(arg, shRes)
  234. args.splice.apply(args, [i, 1].concat(shRes))
  235. if (arg !== shRes[0]) {
  236. i --
  237. continue
  238. }
  239. }
  240. arg = arg.replace(/^-+/, "")
  241. var no = null
  242. while (arg.toLowerCase().indexOf("no-") === 0) {
  243. no = !no
  244. arg = arg.substr(3)
  245. }
  246. if (abbrevs[arg]) arg = abbrevs[arg]
  247. var argType = types[arg]
  248. var isTypeArray = Array.isArray(argType)
  249. if (isTypeArray && argType.length === 1) {
  250. isTypeArray = false
  251. argType = argType[0]
  252. }
  253. var isArray = argType === Array ||
  254. isTypeArray && argType.indexOf(Array) !== -1
  255. // allow unknown things to be arrays if specified multiple times.
  256. if (!types.hasOwnProperty(arg) && data.hasOwnProperty(arg)) {
  257. if (!Array.isArray(data[arg]))
  258. data[arg] = [data[arg]]
  259. isArray = true
  260. }
  261. var val
  262. , la = args[i + 1]
  263. var isBool = typeof no === 'boolean' ||
  264. argType === Boolean ||
  265. isTypeArray && argType.indexOf(Boolean) !== -1 ||
  266. (typeof argType === 'undefined' && !hadEq) ||
  267. (la === "false" &&
  268. (argType === null ||
  269. isTypeArray && ~argType.indexOf(null)))
  270. if (isBool) {
  271. // just set and move along
  272. val = !no
  273. // however, also support --bool true or --bool false
  274. if (la === "true" || la === "false") {
  275. val = JSON.parse(la)
  276. la = null
  277. if (no) val = !val
  278. i ++
  279. }
  280. // also support "foo":[Boolean, "bar"] and "--foo bar"
  281. if (isTypeArray && la) {
  282. if (~argType.indexOf(la)) {
  283. // an explicit type
  284. val = la
  285. i ++
  286. } else if ( la === "null" && ~argType.indexOf(null) ) {
  287. // null allowed
  288. val = null
  289. i ++
  290. } else if ( !la.match(/^-{2,}[^-]/) &&
  291. !isNaN(la) &&
  292. ~argType.indexOf(Number) ) {
  293. // number
  294. val = +la
  295. i ++
  296. } else if ( !la.match(/^-[^-]/) && ~argType.indexOf(String) ) {
  297. // string
  298. val = la
  299. i ++
  300. }
  301. }
  302. if (isArray) (data[arg] = data[arg] || []).push(val)
  303. else data[arg] = val
  304. continue
  305. }
  306. if (argType === String) {
  307. if (la === undefined) {
  308. la = ""
  309. } else if (la.match(/^-{1,2}[^-]+/)) {
  310. la = ""
  311. i --
  312. }
  313. }
  314. if (la && la.match(/^-{2,}$/)) {
  315. la = undefined
  316. i --
  317. }
  318. val = la === undefined ? true : la
  319. if (isArray) (data[arg] = data[arg] || []).push(val)
  320. else data[arg] = val
  321. i ++
  322. continue
  323. }
  324. remain.push(arg)
  325. }
  326. }
  327. function resolveShort (arg, shorthands, shortAbbr, abbrevs) {
  328. // handle single-char shorthands glommed together, like
  329. // npm ls -glp, but only if there is one dash, and only if
  330. // all of the chars are single-char shorthands, and it's
  331. // not a match to some other abbrev.
  332. arg = arg.replace(/^-+/, '')
  333. // if it's an exact known option, then don't go any further
  334. if (abbrevs[arg] === arg)
  335. return null
  336. // if it's an exact known shortopt, same deal
  337. if (shorthands[arg]) {
  338. // make it an array, if it's a list of words
  339. if (shorthands[arg] && !Array.isArray(shorthands[arg]))
  340. shorthands[arg] = shorthands[arg].split(/\s+/)
  341. return shorthands[arg]
  342. }
  343. // first check to see if this arg is a set of single-char shorthands
  344. var singles = shorthands.___singles
  345. if (!singles) {
  346. singles = Object.keys(shorthands).filter(function (s) {
  347. return s.length === 1
  348. }).reduce(function (l,r) {
  349. l[r] = true
  350. return l
  351. }, {})
  352. shorthands.___singles = singles
  353. debug('shorthand singles', singles)
  354. }
  355. var chrs = arg.split("").filter(function (c) {
  356. return singles[c]
  357. })
  358. if (chrs.join("") === arg) return chrs.map(function (c) {
  359. return shorthands[c]
  360. }).reduce(function (l, r) {
  361. return l.concat(r)
  362. }, [])
  363. // if it's an arg abbrev, and not a literal shorthand, then prefer the arg
  364. if (abbrevs[arg] && !shorthands[arg])
  365. return null
  366. // if it's an abbr for a shorthand, then use that
  367. if (shortAbbr[arg])
  368. arg = shortAbbr[arg]
  369. // make it an array, if it's a list of words
  370. if (shorthands[arg] && !Array.isArray(shorthands[arg]))
  371. shorthands[arg] = shorthands[arg].split(/\s+/)
  372. return shorthands[arg]
  373. }