commands/cli: Added CLI option parsing
Matt Bell committed
Oct 13, 2014 at 19:10 UTC
bf328181cd7d8dacc2b15f537530956161b4dde3
1 file changed
+92
commands/cli/parse.go
new
+92
@@ -0,0 +1,92 @@
1
+package cli
2
+
3
+import (
4
+ "strings"
5
+ "fmt"
6
+
7
+ "github.com/jbenet/go-ipfs/commands"
8
+)
9
+
10
+func Parse(input []string, root *commands.Command) ([]string, []string, map[string]string, error) {
11
+ opts, input, err := options(input, root)
12
+ if err != nil {
13
+ return nil, nil, nil, err
14
+ }
15
+
16
+ return nil, nil, opts, nil
17
+}
18
+
19
+// options parses the raw string values of the given options
20
+// returns the parsed options as strings, along with the CLI input minus option blobs
21
+func options(input []string, root *commands.Command) (map[string]string, []string, error) {
22
+ opts := make(map[string]string)
23
+ cleanInput := make([]string, 0)
24
+
25
+ // TODO: error if one option is defined multiple times
26
+
27
+ for i := 0; i < len(input); i++ {
28
+ blob := input[i]
29
+
30
+ if strings.HasPrefix(blob, "--") {
31
+ name := blob[2:]
32
+ value := ""
33
+
34
+ if strings.Contains(name, "=") {
35
+ split := strings.SplitN(name, "=", 2)
36
+ name = split[0]
37
+ value = split[1]
38
+ }
39
+
40
+ if strings.Contains(name, "-") {
41
+ return nil, nil, fmt.Errorf("Invalid option blob: '%s' (Shouldn't contain '-')", input[i])
42
+ }
43
+
44
+ if value != "" && strings.Contains(value, "\"") {
45
+ // TODO: ignore escaped quotations (--foo="\"")
46
+ if !strings.HasPrefix(value, "\"") {
47
+ return nil, nil, fmt.Errorf("Invalid option blob: '%s' (Quotation wasn't at the start of value)", input[i])
48
+ }
49
+
50
+ value = value[1:]
51
+
52
+ for {
53
+ if strings.HasSuffix(value, "\"") {
54
+ value = value[:len(value)-1]
55
+ break
56
+ }
57
+
58
+ i++
59
+ if i >= len(input) {
60
+ return nil, nil, fmt.Errorf("Unterminated string: '%s'", value)
61
+ }
62
+
63
+ value += " " + input[i]
64
+ }
65
+
66
+ if strings.Contains(value, "\"") {
67
+ return nil, nil, fmt.Errorf("Invalid option blob: '%s' (Value contains unescaped quotation)", value)
68
+ }
69
+ }
70
+
71
+ opts[name] = value
72
+
73
+ } else if strings.HasPrefix(blob, "-") {
74
+ blob = blob[1:]
75
+
76
+ if strings.ContainsAny(blob, "-=\"") {
77
+ return nil, nil, fmt.Errorf("Invalid option blob: '%s'", input[i])
78
+ }
79
+
80
+ for _, name := range blob {
81
+ opts[string(name)] = ""
82
+ }
83
+
84
+ // TODO: interpret next blob as value if the last option isn't a bool
85
+
86
+ } else {
87
+ cleanInput = append(cleanInput, blob)
88
+ }
89
+ }
90
+
91
+ return opts, cleanInput, nil
92
+}