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

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

11 12 13
	cmds "github.com/ipfs/go-ipfs/commands"
	files "github.com/ipfs/go-ipfs/commands/files"
	u "github.com/ipfs/go-ipfs/util"
14 15
)

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
func Parse(input []string, stdin *os.File, root *cmds.Command) (cmds.Request, *cmds.Command, []string, error) {
Etienne Laurin's avatar
Etienne Laurin committed
19
	path, opts, stringVals, cmd, err := parseOpts(input, root)
20
	if err != nil {
Etienne Laurin's avatar
Etienne Laurin committed
21
		return nil, nil, path, err
22 23
	}

24 25
	optDefs, err := root.GetOptions(path)
	if err != nil {
26
		return nil, cmd, path, err
27 28
	}

29 30 31 32
	req, err := cmds.NewRequest(path, opts, nil, nil, cmd, optDefs)
	if err != nil {
		return nil, cmd, path, err
	}
33

34 35 36 37 38 39 40
	// if -r is provided, and it is associated with the package builtin
	// recursive path option, allow recursive file paths
	recursiveOpt := req.Option(cmds.RecShort)
	recursive := false
	if recursiveOpt != nil && recursiveOpt.Definition() == cmds.OptionRecursivePath {
		recursive, _, err = recursiveOpt.Bool()
		if err != nil {
41
			return req, nil, nil, u.ErrCast()
42
		}
43
	}
44

45
	stringArgs, fileArgs, err := parseArgs(stringVals, stdin, cmd.Arguments, recursive, root)
46
	if err != nil {
47
		return req, cmd, path, err
48
	}
49 50
	req.SetArguments(stringArgs)

51
	file := files.NewSliceFile("", "", fileArgs)
52
	req.SetFiles(file)
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
}

Etienne Laurin's avatar
Etienne Laurin committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
// Parse a command line made up of sub-commands, short arguments, long arguments and positional arguments
func parseOpts(args []string, root *cmds.Command) (
	path []string,
	opts map[string]interface{},
	stringVals []string,
	cmd *cmds.Command,
	err error,
) {
	path = make([]string, 0, len(args))
	stringVals = make([]string, 0, len(args))
	optDefs := map[string]cmds.Option{}
	opts = map[string]interface{}{}
	cmd = root

	// parseFlag checks that a flag is valid and saves it into opts
	// Returns true if the optional second argument is used
	parseFlag := func(name string, arg *string, mustUse bool) (bool, error) {
		if _, ok := opts[name]; ok {
			return false, fmt.Errorf("Duplicate values for option '%s'", name)
		}
82

Etienne Laurin's avatar
Etienne Laurin committed
83 84 85 86
		optDef, found := optDefs[name]
		if !found {
			err = fmt.Errorf("Unrecognized option '%s'", name)
			return false, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
87
		}
88

Etienne Laurin's avatar
Etienne Laurin committed
89 90 91 92 93 94 95 96 97 98 99 100
		if optDef.Type() == cmds.Bool {
			if mustUse {
				return false, fmt.Errorf("Option '%s' takes no arguments, but was passed '%s'", name, *arg)
			}
			opts[name] = ""
			return false, nil
		} else {
			if arg == nil {
				return true, fmt.Errorf("Missing argument for option '%s'", name)
			}
			opts[name] = *arg
			return true, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101 102
		}
	}
103

Etienne Laurin's avatar
Etienne Laurin committed
104 105 106 107
	optDefs, err = root.GetOptions(path)
	if err != nil {
		return
	}
108

Etienne Laurin's avatar
Etienne Laurin committed
109 110 111 112 113 114 115
	consumed := false
	for i, arg := range args {
		switch {
		case consumed:
			// arg was already consumed by the preceding flag
			consumed = false
			continue
116

Etienne Laurin's avatar
Etienne Laurin committed
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
		case arg == "--":
			// treat all remaining arguments as positional arguments
			stringVals = append(stringVals, args[i+1:]...)
			return

		case strings.HasPrefix(arg, "--"):
			// arg is a long flag, with an optional argument specified
			// using `=' or in args[i+1]
			var slurped bool
			var next *string
			split := strings.SplitN(arg, "=", 2)
			if len(split) == 2 {
				slurped = false
				arg = split[0]
				next = &split[1]
			} else {
				slurped = true
				if i+1 < len(args) {
					next = &args[i+1]
				} else {
					next = nil
				}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139
			}
Etienne Laurin's avatar
Etienne Laurin committed
140 141 142
			consumed, err = parseFlag(arg[2:], next, len(split) == 2)
			if err != nil {
				return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143
			}
Etienne Laurin's avatar
Etienne Laurin committed
144 145
			if !slurped {
				consumed = false
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146
			}
147

Etienne Laurin's avatar
Etienne Laurin committed
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
		case strings.HasPrefix(arg, "-") && arg != "-":
			// args is one or more flags in short form, followed by an optional argument
			// all flags except the last one have type bool
			for arg = arg[1:]; len(arg) != 0; arg = arg[1:] {
				var rest *string
				var slurped bool
				mustUse := false
				if len(arg) > 1 {
					slurped = false
					str := arg[1:]
					if len(str) > 0 && str[0] == '=' {
						str = str[1:]
						mustUse = true
					}
					rest = &str
				} else {
					slurped = true
					if i+1 < len(args) {
						rest = &args[i+1]
					} else {
						rest = nil
					}
				}
				var end bool
				end, err = parseFlag(arg[0:1], rest, mustUse)
				if err != nil {
					return
				}
				if end {
					consumed = slurped
					break
				}
			}
181

Etienne Laurin's avatar
Etienne Laurin committed
182 183 184 185 186 187 188 189 190 191 192 193 194
		default:
			// arg is a sub-command or a positional argument
			sub := cmd.Subcommand(arg)
			if sub != nil {
				cmd = sub
				path = append(path, arg)
				optDefs, err = root.GetOptions(path)
				if err != nil {
					return
				}
			} else {
				stringVals = append(stringVals, arg)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
195 196
		}
	}
Etienne Laurin's avatar
Etienne Laurin committed
197
	return
198
}
199

200
func parseArgs(inputs []string, stdin *os.File, argDefs []cmds.Argument, recursive bool, root *cmds.Command) ([]string, []files.File, error) {
201 202 203 204 205
	// ignore stdin on Windows
	if runtime.GOOS == "windows" {
		stdin = nil
	}

206 207
	// check if stdin is coming from terminal or is being piped in
	if stdin != nil {
208
		if term, err := isTerminal(stdin); err != nil {
209
			return nil, nil, err
210 211
		} else if term {
			stdin = nil // set to nil so we ignore it
212 213 214
		}
	}

215
	// count required argument definitions
216
	numRequired := 0
217
	for _, argDef := range argDefs {
218
		if argDef.Required {
219
			numRequired++
220
		}
221
	}
222

223 224 225
	// count number of values provided by user.
	// if there is at least one ArgDef, we can safely trigger the inputs loop
	// below to parse stdin.
226
	numInputs := len(inputs)
227
	if len(argDefs) > 0 && argDefs[len(argDefs)-1].SupportsStdin && stdin != nil {
228
		numInputs += 1
229 230
	}

231 232 233
	// if we have more arg values provided than argument definitions,
	// and the last arg definition is not variadic (or there are no definitions), return an error
	notVariadic := len(argDefs) == 0 || !argDefs[len(argDefs)-1].Variadic
Christian Couder's avatar
Christian Couder committed
234
	if notVariadic && len(inputs) > len(argDefs) {
235 236 237 238 239 240 241 242 243
		suggestions := suggestUnknownCmd(inputs, root)

		if len(suggestions) > 1 {
			return nil, nil, fmt.Errorf("Unknown Command \"%s\"\n\nDid you mean any of these?\n\n\t%s", inputs[0], strings.Join(suggestions, "\n\t"))
		} else if len(suggestions) > 0 {
			return nil, nil, fmt.Errorf("Unknown Command \"%s\"\n\nDid you mean this?\n\n\t%s", inputs[0], suggestions[0])
		} else {
			return nil, nil, fmt.Errorf("Unknown Command \"%s\"\n", inputs[0])
		}
244 245
	}

246
	stringArgs := make([]string, 0, numInputs)
247
	fileArgs := make([]files.File, 0, numInputs)
248 249

	argDefIndex := 0 // the index of the current argument definition
250
	for i := 0; i < numInputs; i++ {
251
		argDef := getArgDef(argDefIndex, argDefs)
252

253
		// skip optional argument definitions if there aren't sufficient remaining inputs
254 255 256 257 258
		for numInputs-i <= numRequired && !argDef.Required {
			argDefIndex++
			argDef = getArgDef(argDefIndex, argDefs)
		}
		if argDef.Required {
259
			numRequired--
260
		}
261

262
		var err error
263
		if argDef.Type == cmds.ArgString {
264
			if stdin == nil || !argDef.SupportsStdin {
265
				// add string values
266
				stringArgs, inputs = appendString(stringArgs, inputs)
267

268
			} else {
269 270 271 272 273 274 275 276 277
				if len(inputs) > 0 {
					// don't use stdin if we have inputs
					stdin = nil
				} else {
					// if we have a stdin, read it in and use the data as a string value
					stringArgs, stdin, err = appendStdinAsString(stringArgs, stdin)
					if err != nil {
						return nil, nil, err
					}
278 279
				}
			}
280
		} else if argDef.Type == cmds.ArgFile {
281
			if stdin == nil || !argDef.SupportsStdin {
282
				// treat stringArg values as file paths
283
				fileArgs, inputs, err = appendFile(fileArgs, inputs, argDef, recursive)
284 285 286 287
				if err != nil {
					return nil, nil, err
				}

288
			} else {
289 290 291 292 293 294 295
				if len(inputs) > 0 {
					// don't use stdin if we have inputs
					stdin = nil
				} else {
					// if we have a stdin, create a file from it
					fileArgs, stdin = appendStdinAsFile(fileArgs, stdin)
				}
296 297
			}
		}
298 299

		argDefIndex++
300 301
	}

302
	// check to make sure we didn't miss any required arguments
303 304 305 306 307
	if len(argDefs) > argDefIndex {
		for _, argDef := range argDefs[argDefIndex:] {
			if argDef.Required {
				return nil, nil, fmt.Errorf("Argument '%s' is required", argDef.Name)
			}
308 309 310
		}
	}

311
	return stringArgs, fileArgs, nil
312
}
313

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
func getArgDef(i int, argDefs []cmds.Argument) *cmds.Argument {
	if i < len(argDefs) {
		// get the argument definition (usually just argDefs[i])
		return &argDefs[i]

	} else if len(argDefs) > 0 {
		// but if i > len(argDefs) we use the last argument definition)
		return &argDefs[len(argDefs)-1]
	}

	// only happens if there aren't any definitions
	return nil
}

func appendString(args, inputs []string) ([]string, []string) {
	return append(args, inputs[0]), inputs[1:]
}

func appendStdinAsString(args []string, stdin *os.File) ([]string, *os.File, error) {
333
	buf := new(bytes.Buffer)
334 335 336 337 338 339

	_, err := buf.ReadFrom(stdin)
	if err != nil {
		return nil, nil, err
	}

340 341
	input := strings.TrimSpace(buf.String())
	return append(args, strings.Split(input, "\n")...), nil, nil
342 343
}

344
func appendFile(args []files.File, inputs []string, argDef *cmds.Argument, recursive bool) ([]files.File, []string, error) {
345
	fpath := inputs[0]
346

347 348 349 350 351 352 353
	if fpath == "." {
		cwd, err := os.Getwd()
		if err != nil {
			return nil, nil, err
		}
		fpath = cwd
	}
Jeromy's avatar
Jeromy committed
354
	stat, err := os.Lstat(fpath)
355 356 357 358 359 360 361
	if err != nil {
		return nil, nil, err
	}

	if stat.IsDir() {
		if !argDef.Recursive {
			err = fmt.Errorf("Invalid path '%s', argument '%s' does not support directories",
362
				fpath, argDef.Name)
363 364 365 366
			return nil, nil, err
		}
		if !recursive {
			err = fmt.Errorf("'%s' is a directory, use the '-%s' flag to specify directories",
367
				fpath, cmds.RecShort)
368 369 370 371
			return nil, nil, err
		}
	}

372
	arg, err := files.NewSerialFile(path.Base(fpath), fpath, stat)
373 374 375 376 377 378
	if err != nil {
		return nil, nil, err
	}
	return append(args, arg), inputs[1:], nil
}

379
func appendStdinAsFile(args []files.File, stdin *os.File) ([]files.File, *os.File) {
380
	arg := files.NewReaderFile("", "", stdin, nil)
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
	return append(args, arg), nil
}

// isTerminal returns true if stdin is a Stdin pipe (e.g. `cat file | ipfs`),
// and false otherwise (e.g. nothing is being piped in, so stdin is
// coming from the terminal)
func isTerminal(stdin *os.File) (bool, error) {
	stat, err := stdin.Stat()
	if err != nil {
		return false, err
	}

	// if stdin is a CharDevice, return true
	return ((stat.Mode() & os.ModeCharDevice) != 0), nil
}