parse.go 4.09 KB
Newer Older
1 2 3
package cli

import (
4
	"errors"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5
	"fmt"
6
	"os"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7
	"strings"
8

9
	cmds "github.com/jbenet/go-ipfs/commands"
10 11
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12 13 14
// ErrInvalidSubcmd signals when the parse error is not found
var ErrInvalidSubcmd = errors.New("subcommand not found")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15 16
// Parse parses the input commandline string (cmd, flags, and args).
// returns the corresponding command Request object.
17
// Parse will search each root to find the one that best matches the requested subcommand.
18
func Parse(input []string, root *cmds.Command) (cmds.Request, *cmds.Command, []string, error) {
19
	// use the root that matches the longest path (most accurately matches request)
20 21 22
	path, input, cmd := parsePath(input, root)
	opts, stringArgs, err := parseOptions(input)
	if err != nil {
23
		return nil, cmd, path, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
24
	}
25

26
	if len(path) == 0 {
27
		return nil, nil, path, ErrInvalidSubcmd
28 29
	}

30
	args, err := parseArgs(stringArgs, cmd.Arguments)
31
	if err != nil {
32
		return nil, cmd, path, err
33 34
	}

35 36
	optDefs, err := root.GetOptions(path)
	if err != nil {
37
		return nil, cmd, path, err
38 39
	}

40 41 42 43 44 45 46 47
	// check to make sure there aren't any undefined options
	for k := range opts {
		if _, found := optDefs[k]; !found {
			err = fmt.Errorf("Unrecognized option: -%s", k)
			return nil, cmd, path, err
		}
	}

48
	req := cmds.NewRequest(path, opts, args, cmd, optDefs)
49 50 51

	err = cmd.CheckArguments(req)
	if err != nil {
52
		return req, cmd, path, err
53 54
	}

55
	return req, cmd, path, nil
56 57
}

58 59
// parsePath separates the command path and the opts and args from a command string
// returns command path slice, rest slice, and the corresponding *cmd.Command
60
func parsePath(input []string, root *cmds.Command) ([]string, []string, *cmds.Command) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
61 62
	cmd := root
	i := 0
63

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
64 65 66 67
	for _, blob := range input {
		if strings.HasPrefix(blob, "-") {
			break
		}
68

69 70
		sub := cmd.Subcommand(blob)
		if sub == nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
71 72
			break
		}
73
		cmd = sub
74

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
75 76
		i++
	}
77

78
	return input[:i], input[i:], cmd
79 80
}

81
// parseOptions parses the raw string values of the given options
82
// returns the parsed options as strings, along with the CLI args
83
func parseOptions(input []string) (map[string]interface{}, []string, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84
	opts := make(map[string]interface{})
85
	args := []string{}
86

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
87 88
	for i := 0; i < len(input); i++ {
		blob := input[i]
89

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90 91 92
		if strings.HasPrefix(blob, "-") {
			name := blob[1:]
			value := ""
93

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
94 95 96 97
			// support single and double dash
			if strings.HasPrefix(name, "-") {
				name = name[1:]
			}
98

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
99 100 101 102 103
			if strings.Contains(name, "=") {
				split := strings.SplitN(name, "=", 2)
				name = split[0]
				value = split[1]
			}
104

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
105 106 107
			if _, ok := opts[name]; ok {
				return nil, nil, fmt.Errorf("Duplicate values for option '%s'", name)
			}
108

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109
			opts[name] = value
110

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
111 112 113 114
		} else {
			args = append(args, blob)
		}
	}
115

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
116
	return opts, args, nil
117
}
118

119
func parseArgs(stringArgs []string, arguments []cmds.Argument) ([]interface{}, error) {
120 121
	// count required argument definitions
	lenRequired := 0
122
	for _, argDef := range arguments {
123 124
		if argDef.Required {
			lenRequired++
125
		}
126
	}
127

128 129
	args := make([]interface{}, len(stringArgs))

130
	valueIndex := 0 // the index of the current stringArgs value
131
	for _, argDef := range arguments {
132
		// skip optional argument definitions if there aren't sufficient remaining values
133
		if len(stringArgs)-valueIndex <= lenRequired && !argDef.Required {
134
			continue
135 136
		} else if argDef.Required {
			lenRequired--
137
		}
138

139
		if valueIndex >= len(stringArgs) {
140 141 142 143
			break
		}

		if argDef.Variadic {
144
			for _, arg := range stringArgs[valueIndex:] {
145
				value, err := argValue(argDef, arg)
146 147 148
				if err != nil {
					return nil, err
				}
149
				args[valueIndex] = value
150
				valueIndex++
151
			}
152
		} else {
153
			var err error
154
			value, err := argValue(argDef, stringArgs[valueIndex])
155 156 157
			if err != nil {
				return nil, err
			}
158
			args[valueIndex] = value
159
			valueIndex++
160 161 162 163 164
		}
	}

	return args, nil
}
165

166
func argValue(argDef cmds.Argument, value string) (interface{}, error) {
167
	if argDef.Type == cmds.ArgString {
168
		return value, nil
169 170

	} else {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
171 172 173 174
		// NB At the time of this commit, file cleanup is performed when
		// Requests are cleaned up. TODO try to perform open and close at the
		// same level of abstraction (or at least in the same package!)
		in, err := os.Open(value)
175 176 177
		if err != nil {
			return nil, err
		}
178
		return in, nil
179 180
	}
}