parse.go 10.9 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
	"path/filepath"
9
	"runtime"
Jeromy's avatar
Jeromy committed
10
	"sort"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11
	"strings"
12

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18 19
// Parse parses the input commandline string (cmd, flags, and args).
// returns the corresponding command Request object.
20
func Parse(input []string, stdin *os.File, root *cmds.Command) (cmds.Request, *cmds.Command, []string, error) {
Etienne Laurin's avatar
Etienne Laurin committed
21
	path, opts, stringVals, cmd, err := parseOpts(input, root)
22
	if err != nil {
Etienne Laurin's avatar
Etienne Laurin committed
23
		return nil, nil, path, err
24 25
	}

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

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

36 37 38 39 40 41 42
	// 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 {
43
			return req, nil, nil, u.ErrCast()
44
		}
45
	}
46

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

53 54 55 56
	if len(fileArgs) > 0 {
		file := files.NewSliceFile("", "", fileArgs)
		req.SetFiles(file)
	}
57 58 59

	err = cmd.CheckArguments(req)
	if err != nil {
60
		return req, cmd, path, err
61 62
	}

63
	return req, cmd, path, nil
64 65
}

Etienne Laurin's avatar
Etienne Laurin committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
// 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)
		}
86

Etienne Laurin's avatar
Etienne Laurin committed
87 88 89 90
		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
91
		}
92 93 94 95 96 97
		// mustUse implies that you must use the argument given after the '='
		// eg. -r=true means you must take true into consideration
		//		mustUse == true in the above case
		// eg. ipfs -r <file> means disregard <file> since there is no '='
		//		mustUse == false in the above situation
		//arg == nil implies the flag was specified without an argument
Etienne Laurin's avatar
Etienne Laurin committed
98
		if optDef.Type() == cmds.Bool {
99 100 101 102 103 104 105 106 107 108 109 110 111 112
			if arg == nil || !mustUse {
				opts[name] = true
				return false, nil
			}
			argVal := strings.ToLower(*arg)
			switch argVal {
			case "true":
				opts[name] = true
				return true, nil
			case "false":
				opts[name] = false
				return true, nil
			default:
				return true, fmt.Errorf("Option '%s' takes true/false arguments, but was passed '%s'", name, argVal)
Etienne Laurin's avatar
Etienne Laurin committed
113 114 115 116 117 118 119
			}
		} 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
120 121
		}
	}
122

Etienne Laurin's avatar
Etienne Laurin committed
123 124 125 126
	optDefs, err = root.GetOptions(path)
	if err != nil {
		return
	}
127

Etienne Laurin's avatar
Etienne Laurin committed
128 129 130 131 132 133 134
	consumed := false
	for i, arg := range args {
		switch {
		case consumed:
			// arg was already consumed by the preceding flag
			consumed = false
			continue
135

Etienne Laurin's avatar
Etienne Laurin committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
		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
158
			}
Etienne Laurin's avatar
Etienne Laurin committed
159 160 161
			consumed, err = parseFlag(arg[2:], next, len(split) == 2)
			if err != nil {
				return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162
			}
Etienne Laurin's avatar
Etienne Laurin committed
163 164
			if !slurped {
				consumed = false
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
165
			}
166

Etienne Laurin's avatar
Etienne Laurin committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
		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
rht's avatar
rht committed
191
				end, err = parseFlag(arg[:1], rest, mustUse)
Etienne Laurin's avatar
Etienne Laurin committed
192 193 194 195 196 197 198 199
				if err != nil {
					return
				}
				if end {
					consumed = slurped
					break
				}
			}
200

Etienne Laurin's avatar
Etienne Laurin committed
201 202 203 204 205 206 207 208 209 210
		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
				}
211 212 213 214 215 216 217

				// If we've come across an external binary call, pass all the remaining
				// arguments on to it
				if cmd.External {
					stringVals = append(stringVals, args[i+1:]...)
					return
				}
Etienne Laurin's avatar
Etienne Laurin committed
218 219 220
			} else {
				stringVals = append(stringVals, arg)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221 222
		}
	}
Etienne Laurin's avatar
Etienne Laurin committed
223
	return
224
}
225

226
func parseArgs(inputs []string, stdin *os.File, argDefs []cmds.Argument, recursive bool, root *cmds.Command) ([]string, []files.File, error) {
227 228 229 230 231
	// ignore stdin on Windows
	if runtime.GOOS == "windows" {
		stdin = nil
	}

232 233
	// check if stdin is coming from terminal or is being piped in
	if stdin != nil {
234
		if term, err := isTerminal(stdin); err != nil {
235
			return nil, nil, err
236 237
		} else if term {
			stdin = nil // set to nil so we ignore it
238 239 240
		}
	}

241
	// count required argument definitions
242
	numRequired := 0
243
	for _, argDef := range argDefs {
244
		if argDef.Required {
245
			numRequired++
246
		}
247
	}
248

249 250 251
	// 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.
252
	numInputs := len(inputs)
253
	if len(argDefs) > 0 && argDefs[len(argDefs)-1].SupportsStdin && stdin != nil {
254
		numInputs += 1
255 256
	}

257 258 259
	// 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
260
	if notVariadic && len(inputs) > len(argDefs) {
261 262 263 264 265 266 267 268 269
		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])
		}
270 271
	}

272
	stringArgs := make([]string, 0, numInputs)
273

Jeromy's avatar
Jeromy committed
274
	fileArgs := make(map[string]files.File)
275
	argDefIndex := 0 // the index of the current argument definition
276
	for i := 0; i < numInputs; i++ {
277
		argDef := getArgDef(argDefIndex, argDefs)
278

279
		// skip optional argument definitions if there aren't sufficient remaining inputs
280 281 282 283 284
		for numInputs-i <= numRequired && !argDef.Required {
			argDefIndex++
			argDef = getArgDef(argDefIndex, argDefs)
		}
		if argDef.Required {
285
			numRequired--
286
		}
287

288
		var err error
289
		if argDef.Type == cmds.ArgString {
290
			if stdin == nil || !argDef.SupportsStdin {
291
				// add string values
292
				stringArgs, inputs = appendString(stringArgs, inputs)
293

294
			} else {
295 296 297 298 299 300 301 302 303
				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
					}
304 305
				}
			}
306
		} else if argDef.Type == cmds.ArgFile {
307
			if stdin == nil || !argDef.SupportsStdin {
308
				// treat stringArg values as file paths
Jeromy's avatar
Jeromy committed
309 310 311
				fpath := inputs[0]
				inputs = inputs[1:]
				file, err := appendFile(fpath, argDef, recursive)
312 313 314 315
				if err != nil {
					return nil, nil, err
				}

Jeromy's avatar
Jeromy committed
316
				fileArgs[fpath] = file
317
			} else {
318 319 320 321 322
				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
Jeromy's avatar
Jeromy committed
323
					fileArgs[""] = files.NewReaderFile("", "", stdin, nil)
324
				}
325 326
			}
		}
327 328

		argDefIndex++
329 330
	}

331
	// check to make sure we didn't miss any required arguments
332 333 334 335 336
	if len(argDefs) > argDefIndex {
		for _, argDef := range argDefs[argDefIndex:] {
			if argDef.Required {
				return nil, nil, fmt.Errorf("Argument '%s' is required", argDef.Name)
			}
337 338 339
		}
	}

Jeromy's avatar
Jeromy committed
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
	return stringArgs, filesMapToSortedArr(fileArgs), nil
}

func filesMapToSortedArr(fs map[string]files.File) []files.File {
	var names []string
	for name, _ := range fs {
		names = append(names, name)
	}

	sort.Strings(names)

	var out []files.File
	for _, f := range names {
		out = append(out, fs[f])
	}

	return out
357
}
358

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
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) {
378
	buf := new(bytes.Buffer)
379 380 381 382 383 384

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

385 386
	input := strings.TrimSpace(buf.String())
	return append(args, strings.Split(input, "\n")...), nil, nil
387 388
}

Jeromy's avatar
Jeromy committed
389 390 391 392 393
const notRecursiveFmtStr = "'%s' is a directory, use the '-%s' flag to specify directories"
const dirNotSupportedFmtStr = "Invalid path '%s', argument '%s' does not support directories"

func appendFile(fpath string, argDef *cmds.Argument, recursive bool) (files.File, error) {
	fpath = filepath.ToSlash(filepath.Clean(fpath))
394

395 396 397
	if fpath == "." {
		cwd, err := os.Getwd()
		if err != nil {
Jeromy's avatar
Jeromy committed
398
			return nil, err
399 400 401
		}
		fpath = cwd
	}
Jeromy's avatar
Jeromy committed
402

Jeromy's avatar
Jeromy committed
403
	stat, err := os.Lstat(fpath)
404
	if err != nil {
Jeromy's avatar
Jeromy committed
405
		return nil, err
406 407 408 409
	}

	if stat.IsDir() {
		if !argDef.Recursive {
Jeromy's avatar
Jeromy committed
410
			return nil, fmt.Errorf(dirNotSupportedFmtStr, fpath, argDef.Name)
411 412
		}
		if !recursive {
Jeromy's avatar
Jeromy committed
413
			return nil, fmt.Errorf(notRecursiveFmtStr, fpath, cmds.RecShort)
414 415 416
		}
	}

Jeromy's avatar
Jeromy committed
417
	return files.NewSerialFile(path.Base(fpath), fpath, stat)
418 419 420 421 422 423 424 425 426 427 428 429 430 431
}

// 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
}