* Get the options. * @param {Array. } args An array, like ['-x', 'hello'] * @param {Object} [defaults={}] An optional collection of default values. * @returns {Object} The keys will be the longNames, or the shortName if no longName is defined for * that option. The values
(args, defaults)
| 223 | * that option. The values will be the values provided, or `true` if the option accepts no value. |
| 224 | */ |
| 225 | parse(args, defaults) { |
| 226 | let arg; |
| 227 | let next; |
| 228 | let option; |
| 229 | const result = ( defaults && _.defaults({}, defaults) ) || {}; |
| 230 | let shortName; |
| 231 | let longName; |
| 232 | let name; |
| 233 | let value; |
| 234 | |
| 235 | result._ = []; |
| 236 | for (let i = 0, l = args.length; i < l; i++) { |
| 237 | arg = String(args[i]); |
| 238 | next = (i < l - 1) ? String(args[i + 1]) : null; |
| 239 | shortName = null; |
| 240 | value = null; |
| 241 | |
| 242 | // like -t |
| 243 | if (arg.charAt(0) === '-') { |
| 244 | // like --template |
| 245 | if (arg.charAt(1) === '-') { |
| 246 | name = longName = arg.slice(2); |
| 247 | option = this._getOptionByLongName(longName); |
| 248 | } |
| 249 | else { |
| 250 | name = shortName = arg.slice(1); |
| 251 | option = this._getOptionByShortName(shortName); |
| 252 | } |
| 253 | |
| 254 | if (option === null) { |
| 255 | throw new Error( util.format('Unknown command-line option "%s".', name) ); |
| 256 | } |
| 257 | |
| 258 | if (option.hasValue) { |
| 259 | value = next; |
| 260 | i++; |
| 261 | |
| 262 | if (value === null || value.charAt(0) === '-') { |
| 263 | throw new Error( util.format('The command-line option "%s" requires a value.', name) ); |
| 264 | } |
| 265 | } |
| 266 | else { |
| 267 | value = true; |
| 268 | } |
| 269 | |
| 270 | // skip ignored options now that we've consumed the option text |
| 271 | if (option.ignore) { |
| 272 | continue; |
| 273 | } |
| 274 | |
| 275 | if (option.longName && shortName) { |
| 276 | name = option.longName; |
| 277 | } |
| 278 | |
| 279 | if (typeof option.coercer === 'function') { |
| 280 | value = option.coercer(value); |
| 281 | } |
| 282 |
no test coverage detected