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

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

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

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

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

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

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

41 42 43 44 45 46 47 48
	// 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
		}
	}

49 50 51 52
	req, err := cmds.NewRequest(path, opts, args, cmd, optDefs)
	if err != nil {
		return nil, cmd, path, err
	}
53 54 55

	err = cmd.CheckArguments(req)
	if err != nil {
56
		return req, cmd, path, err
57 58
	}

59
	return req, cmd, path, nil
60 61
}

62 63
// 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
64
func parsePath(input []string, root *cmds.Command) ([]string, []string, *cmds.Command) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65 66
	cmd := root
	i := 0
67

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68 69 70 71
	for _, blob := range input {
		if strings.HasPrefix(blob, "-") {
			break
		}
72

73 74
		sub := cmd.Subcommand(blob)
		if sub == nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
75 76
			break
		}
77
		cmd = sub
78

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
79 80
		i++
	}
81

82
	return input[:i], input[i:], cmd
83 84
}

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
94 95 96
		if strings.HasPrefix(blob, "-") {
			name := blob[1:]
			value := ""
97

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
98 99 100 101
			// support single and double dash
			if strings.HasPrefix(name, "-") {
				name = name[1:]
			}
102

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103 104 105 106 107
			if strings.Contains(name, "=") {
				split := strings.SplitN(name, "=", 2)
				name = split[0]
				value = split[1]
			}
108

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
113
			opts[name] = value
114

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
115 116 117 118
		} else {
			args = append(args, blob)
		}
	}
119

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
120
	return opts, args, nil
121
}
122

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
func parseArgs(stringArgs []string, stdin *os.File, arguments []cmds.Argument) ([]interface{}, error) {
	// check if stdin is coming from terminal or is being piped in
	if stdin != nil {
		stat, err := stdin.Stat()
		if err != nil {
			return nil, err
		}

		// if stdin isn't a CharDevice, set it to nil
		// (this means it is coming from terminal and we want to ignore it)
		if (stat.Mode() & os.ModeCharDevice) != 0 {
			stdin = nil
		}
	}

138 139
	// count required argument definitions
	lenRequired := 0
140
	for _, argDef := range arguments {
141 142
		if argDef.Required {
			lenRequired++
143
		}
144
	}
145

146 147 148 149 150 151 152 153 154 155 156 157 158 159
	valCount := len(stringArgs)
	if stdin != nil {
		valCount += 1
	}

	args := make([]interface{}, 0, valCount)

	argDefIndex := 0 // the index of the current argument definition
	for i := 0; i < valCount; i++ {
		// get the argument definiton (should be arguments[argDefIndex],
		// but if argDefIndex > len(arguments) we use the last argument definition)
		var argDef cmds.Argument
		if argDefIndex < len(arguments) {
			argDef = arguments[argDefIndex]
160
		} else if len(arguments) > 0 {
161 162
			argDef = arguments[len(arguments)-1]
		}
163

164
		// skip optional argument definitions if there aren't sufficient remaining values
165
		if valCount-i <= lenRequired && !argDef.Required {
166
			continue
167 168
		} else if argDef.Required {
			lenRequired--
169
		}
170

171 172 173 174 175
		if argDef.Type == cmds.ArgString {
			if stdin == nil {
				// add string values
				args = append(args, stringArgs[0])
				stringArgs = stringArgs[1:]
176

177
			} else if argDef.SupportsStdin {
178 179 180
				// if we have a stdin, read it in and use the data as a string value
				var buf bytes.Buffer
				_, err := buf.ReadFrom(stdin)
181 182 183
				if err != nil {
					return nil, err
				}
184 185
				args = append(args, buf.String())
				stdin = nil
186
			}
187 188 189 190 191 192 193 194 195 196 197

		} else if argDef.Type == cmds.ArgFile {
			if stdin == nil {
				// treat stringArg values as file paths
				file, err := os.Open(stringArgs[0])
				if err != nil {
					return nil, err
				}
				args = append(args, file)
				stringArgs = stringArgs[1:]

198
			} else if argDef.SupportsStdin {
199 200 201
				// if we have a stdin, use that as a reader
				args = append(args, stdin)
				stdin = nil
202 203
			}
		}
204 205

		argDefIndex++
206 207 208 209
	}

	return args, nil
}