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

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

7
	cmds "github.com/jbenet/go-ipfs/commands"
8 9
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10 11
// Parse parses the input commandline string (cmd, flags, and args).
// returns the corresponding command Request object.
12 13
func Parse(input []string, root *cmds.Command) (cmds.Request, error) {
	path, input, cmd := parsePath(input, root)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
14 15
	opts, args, err := parseOptions(input)
	if err != nil {
16
		return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17
	}
18

19 20 21 22
	// TODO: figure out how to know when to read given file(s) as an input stream
	// (instead of filename arg string)

	return cmds.NewRequest(path, opts, args, nil, cmd), nil
23 24
}

25
// parsePath gets the command path from the command line input
26
func parsePath(input []string, root *cmds.Command) ([]string, []string, *cmds.Command) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27 28
	cmd := root
	i := 0
29

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30 31 32 33
	for _, blob := range input {
		if strings.HasPrefix(blob, "-") {
			break
		}
34

35 36
		sub := cmd.Subcommand(blob)
		if sub == nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
37 38
			break
		}
39
		cmd = sub
40

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41 42
		i++
	}
43

44
	return input[:i], input[i:], cmd
45 46
}

47
// parseOptions parses the raw string values of the given options
48
// returns the parsed options as strings, along with the CLI args
49
func parseOptions(input []string) (map[string]interface{}, []string, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
50 51
	opts := make(map[string]interface{})
	args := []string{}
52

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
56 57 58
		if strings.HasPrefix(blob, "-") {
			name := blob[1:]
			value := ""
59

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60 61 62 63
			// support single and double dash
			if strings.HasPrefix(name, "-") {
				name = name[1:]
			}
64

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65 66 67 68 69
			if strings.Contains(name, "=") {
				split := strings.SplitN(name, "=", 2)
				name = split[0]
				value = split[1]
			}
70

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
75
			opts[name] = value
76

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77 78 79 80
		} else {
			args = append(args, blob)
		}
	}
81

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
82
	return opts, args, nil
83
}