1 | 'use strict'
|
2 | const arrayify = require('array-back')
|
3 | const option = require('./option')
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | class Argv extends Array {
|
13 | load (argv) {
|
14 | if (argv) {
|
15 | argv = arrayify(argv)
|
16 | } else {
|
17 |
|
18 | argv = process.argv.slice(0)
|
19 | argv.splice(0, 2)
|
20 | }
|
21 | argv.forEach(arg => this.push(arg))
|
22 | }
|
23 |
|
24 | clear () {
|
25 | this.length = 0
|
26 | }
|
27 |
|
28 | |
29 |
|
30 |
|
31 | expandOptionEqualsNotation () {
|
32 | const optEquals = option.optEquals
|
33 | if (this.some(optEquals.test.bind(optEquals))) {
|
34 | const expandedArgs = []
|
35 | this.forEach(arg => {
|
36 | const matches = arg.match(optEquals)
|
37 | if (matches) {
|
38 | expandedArgs.push(matches[1], option.VALUE_MARKER + matches[2])
|
39 | } else {
|
40 | expandedArgs.push(arg)
|
41 | }
|
42 | })
|
43 | this.clear()
|
44 | this.load(expandedArgs)
|
45 | }
|
46 | }
|
47 |
|
48 | |
49 |
|
50 |
|
51 | expandGetoptNotation () {
|
52 | const findReplace = require('find-replace')
|
53 | const combinedArg = option.combined
|
54 | const hasGetopt = this.some(combinedArg.test.bind(combinedArg))
|
55 | if (hasGetopt) {
|
56 | findReplace(this, combinedArg, arg => {
|
57 | arg = arg.slice(1)
|
58 | return arg.split('').map(letter => '-' + letter)
|
59 | })
|
60 | }
|
61 | }
|
62 |
|
63 | |
64 |
|
65 |
|
66 |
|
67 | validate (definitions, options) {
|
68 | options = options || {}
|
69 | let invalidOption
|
70 |
|
71 | if (!options.partial) {
|
72 | const optionWithoutDefinition = this
|
73 | .filter(arg => option.isOption(arg))
|
74 | .some(arg => {
|
75 | if (definitions.get(arg) === undefined) {
|
76 | invalidOption = arg
|
77 | return true
|
78 | }
|
79 | })
|
80 | if (optionWithoutDefinition) {
|
81 | halt(
|
82 | 'UNKNOWN_OPTION',
|
83 | 'Unknown option: ' + invalidOption
|
84 | )
|
85 | }
|
86 | }
|
87 | }
|
88 | }
|
89 |
|
90 | function halt (name, message) {
|
91 | const err = new Error(message)
|
92 | err.name = name
|
93 | throw err
|
94 | }
|
95 |
|
96 | module.exports = Argv
|