request.go 4.45 KB
Newer Older
Matt Bell's avatar
Matt Bell committed
1 2
package commands

3
import (
4
	"errors"
5 6 7
	"fmt"
	"reflect"
	"strconv"
8 9 10

	"github.com/jbenet/go-ipfs/config"
	"github.com/jbenet/go-ipfs/core"
11 12
)

13 14
type optMap map[string]interface{}

15 16 17 18 19 20
type Context struct {
	ConfigRoot string
	Config     *config.Config
	Node       *core.IpfsNode
}

Matt Bell's avatar
Matt Bell committed
21
// Request represents a call to a command from a consumer
22 23
type Request interface {
	Path() []string
24 25
	Option(name string) *OptionValue
	Options() optMap
26
	SetOption(name string, val interface{})
27
	Arguments() []interface{} // TODO: make argument value type instead of using interface{}
28
	Context() *Context
29
	SetContext(Context)
30
	Command() *Command
31

32
	ConvertOptions() error
33 34 35
}

type request struct {
36 37 38 39 40 41
	path       []string
	options    optMap
	arguments  []interface{}
	cmd        *Command
	ctx        Context
	optionDefs map[string]Option
Matt Bell's avatar
Matt Bell committed
42 43
}

44 45
// Path returns the command path of this request
func (r *request) Path() []string {
46 47 48
	return r.path
}

49
// Option returns the value of the option for given name.
50
func (r *request) Option(name string) *OptionValue {
51 52
	val, found := r.options[name]
	if found {
53
		return &OptionValue{val, found}
54 55 56 57 58 59
	}

	// if a value isn't defined for that name, we will try to look it up by its aliases

	// find the option with the specified name
	option, found := r.optionDefs[name]
60 61 62 63 64 65 66 67 68
	if !found {
		return nil
	}

	// try all the possible names, break if we find a value
	for _, n := range option.Names {
		val, found = r.options[n]
		if found {
			return &OptionValue{val, found}
69 70 71
		}
	}

72 73
	// MAYBE_TODO: use default value instead of nil
	return &OptionValue{nil, false}
Matt Bell's avatar
Matt Bell committed
74 75
}

76
// Options returns a copy of the option map
77
func (r *request) Options() optMap {
78 79 80 81 82 83 84
	output := make(optMap)
	for k, v := range r.options {
		output[k] = v
	}
	return output
}

85 86
// SetOption sets the value of the option for given name.
func (r *request) SetOption(name string, val interface{}) {
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
	// find the option with the specified name
	option, found := r.optionDefs[name]
	if !found {
		return
	}

	// try all the possible names, if we already have a value then set over it
	for _, n := range option.Names {
		val, found := r.options[n]
		if found {
			r.options[n] = val
			return
		}
	}

102
	r.options[name] = val
103 104
}

105
// Arguments returns the arguments slice
106
func (r *request) Arguments() []interface{} {
Matt Bell's avatar
Matt Bell committed
107
	return r.arguments
108
}
Matt Bell's avatar
Matt Bell committed
109

110 111 112 113
func (r *request) Context() *Context {
	return &r.ctx
}

114 115 116 117
func (r *request) SetContext(ctx Context) {
	r.ctx = ctx
}

118 119 120 121
func (r *request) Command() *Command {
	return r.cmd
}

Matt Bell's avatar
Matt Bell committed
122 123
type converter func(string) (interface{}, error)

124
var converters = map[reflect.Kind]converter{
Matt Bell's avatar
Matt Bell committed
125
	Bool: func(v string) (interface{}, error) {
126 127 128 129 130
		if v == "" {
			return true, nil
		}
		return strconv.ParseBool(v)
	},
Matt Bell's avatar
Matt Bell committed
131
	Int: func(v string) (interface{}, error) {
132 133
		return strconv.ParseInt(v, 0, 32)
	},
Matt Bell's avatar
Matt Bell committed
134
	Uint: func(v string) (interface{}, error) {
135 136
		return strconv.ParseInt(v, 0, 32)
	},
Matt Bell's avatar
Matt Bell committed
137
	Float: func(v string) (interface{}, error) {
138 139 140 141
		return strconv.ParseFloat(v, 64)
	},
}

142
func (r *request) ConvertOptions() error {
143 144 145
	converted := make(map[string]interface{})

	for k, v := range r.options {
146
		opt, ok := r.optionDefs[k]
147
		if !ok {
148
			continue
149 150 151 152 153 154 155 156
		}

		kind := reflect.TypeOf(v).Kind()
		var value interface{}

		if kind != opt.Type {
			if kind == String {
				convert := converters[opt.Type]
157 158 159 160 161
				str, ok := v.(string)
				if !ok {
					return errors.New("cast error")
				}
				val, err := convert(str)
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
				if err != nil {
					return fmt.Errorf("Could not convert string value '%s' to type '%s'",
						v, opt.Type.String())
				}
				value = val

			} else {
				return fmt.Errorf("Option '%s' should be type '%s', but got type '%s'",
					k, opt.Type.String(), kind.String())
			}
		} else {
			value = v
		}

		for _, name := range opt.Names {
			if _, ok := r.options[name]; name != k && ok {
				return fmt.Errorf("Duplicate command options were provided ('%s' and '%s')",
					k, name)
			}

Matt Bell's avatar
Matt Bell committed
182
			converted[name] = value
183 184 185 186 187 188 189
		}
	}

	r.options = converted
	return nil
}

190 191
// NewEmptyRequest initializes an empty request
func NewEmptyRequest() Request {
192
	return NewRequest(nil, nil, nil, nil, nil)
Matt Bell's avatar
Matt Bell committed
193 194
}

195
// NewRequest returns a request initialized with given arguments
196
func NewRequest(path []string, opts optMap, args []interface{}, cmd *Command, optDefs map[string]Option) Request {
197
	if path == nil {
Matt Bell's avatar
Matt Bell committed
198
		path = make([]string, 0)
Matt Bell's avatar
Matt Bell committed
199
	}
200 201 202 203
	if opts == nil {
		opts = make(map[string]interface{})
	}
	if args == nil {
204
		args = make([]interface{}, 0)
205
	}
206 207 208
	if optDefs == nil {
		optDefs = make(map[string]Option)
	}
209 210 211 212 213

	req := &request{path, opts, args, cmd, Context{}, optDefs}
	req.ConvertOptions()

	return req
Matt Bell's avatar
Matt Bell committed
214
}