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

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

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

14 15
type optMap map[string]interface{}

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

Matt Bell's avatar
Matt Bell committed
22
// Request represents a call to a command from a consumer
23 24
type Request interface {
	Path() []string
25 26
	Option(name string) *OptionValue
	Options() optMap
27
	SetOption(name string, val interface{})
Brian Tiger Chow's avatar
Brian Tiger Chow committed
28 29 30 31 32 33

	// Arguments() returns user provided arguments as declared on the Command.
	//
	// NB: `io.Reader`s returned by Arguments() are owned by the library.
	// Readers are not guaranteed to remain open after the Command's Run
	// function returns.
34
	Arguments() []interface{} // TODO: make argument value type instead of using interface{}
35
	Context() *Context
36
	SetContext(Context)
37
	Command() *Command
38
	Cleanup() error
39

40
	ConvertOptions() error
41 42 43
}

type request struct {
44 45 46 47 48 49
	path       []string
	options    optMap
	arguments  []interface{}
	cmd        *Command
	ctx        Context
	optionDefs map[string]Option
Matt Bell's avatar
Matt Bell committed
50 51
}

52 53
// Path returns the command path of this request
func (r *request) Path() []string {
54 55 56
	return r.path
}

57
// Option returns the value of the option for given name.
58
func (r *request) Option(name string) *OptionValue {
59 60
	val, found := r.options[name]
	if found {
61
		return &OptionValue{val, found}
62 63 64 65 66 67
	}

	// 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]
68 69 70 71 72 73 74 75 76
	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}
77 78 79
		}
	}

80 81
	// MAYBE_TODO: use default value instead of nil
	return &OptionValue{nil, false}
Matt Bell's avatar
Matt Bell committed
82 83
}

84
// Options returns a copy of the option map
85
func (r *request) Options() optMap {
86 87 88 89 90 91 92
	output := make(optMap)
	for k, v := range r.options {
		output[k] = v
	}
	return output
}

93 94
// SetOption sets the value of the option for given name.
func (r *request) SetOption(name string, val interface{}) {
95 96 97 98 99 100 101 102
	// 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 {
103
		_, found := r.options[n]
104 105 106 107 108 109
		if found {
			r.options[n] = val
			return
		}
	}

110
	r.options[name] = val
111 112
}

113
// Arguments returns the arguments slice
114
func (r *request) Arguments() []interface{} {
Matt Bell's avatar
Matt Bell committed
115
	return r.arguments
116
}
Matt Bell's avatar
Matt Bell committed
117

118 119 120 121
func (r *request) Context() *Context {
	return &r.ctx
}

122 123 124 125
func (r *request) SetContext(ctx Context) {
	r.ctx = ctx
}

126 127 128 129
func (r *request) Command() *Command {
	return r.cmd
}

130 131 132 133 134 135 136 137 138 139 140 141 142 143
func (r *request) Cleanup() error {
	for _, arg := range r.arguments {
		closer, ok := arg.(io.Closer)
		if ok {
			err := closer.Close()
			if err != nil {
				return err
			}
		}
	}

	return nil
}

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

146
var converters = map[reflect.Kind]converter{
Matt Bell's avatar
Matt Bell committed
147
	Bool: func(v string) (interface{}, error) {
148 149 150 151 152
		if v == "" {
			return true, nil
		}
		return strconv.ParseBool(v)
	},
Matt Bell's avatar
Matt Bell committed
153
	Int: func(v string) (interface{}, error) {
154 155 156 157 158
		val, err := strconv.ParseInt(v, 0, 32)
		if err != nil {
			return nil, err
		}
		return int(val), err
159
	},
Matt Bell's avatar
Matt Bell committed
160
	Uint: func(v string) (interface{}, error) {
161 162 163 164 165
		val, err := strconv.ParseUint(v, 0, 32)
		if err != nil {
			return nil, err
		}
		return int(val), err
166
	},
Matt Bell's avatar
Matt Bell committed
167
	Float: func(v string) (interface{}, error) {
168 169 170 171
		return strconv.ParseFloat(v, 64)
	},
}

172
func (r *request) ConvertOptions() error {
173
	for k, v := range r.options {
174
		opt, ok := r.optionDefs[k]
175
		if !ok {
176
			continue
177 178 179 180 181 182
		}

		kind := reflect.TypeOf(v).Kind()
		if kind != opt.Type {
			if kind == String {
				convert := converters[opt.Type]
183 184
				str, ok := v.(string)
				if !ok {
185
					return u.ErrCast()
186 187
				}
				val, err := convert(str)
188 189 190 191
				if err != nil {
					return fmt.Errorf("Could not convert string value '%s' to type '%s'",
						v, opt.Type.String())
				}
192
				r.options[k] = val
193 194 195 196 197 198

			} else {
				return fmt.Errorf("Option '%s' should be type '%s', but got type '%s'",
					k, opt.Type.String(), kind.String())
			}
		} else {
199
			r.options[k] = v
200 201 202 203 204 205 206 207 208 209 210 211 212
		}

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

	return nil
}

213 214
// NewEmptyRequest initializes an empty request
func NewEmptyRequest() Request {
215
	return NewRequest(nil, nil, nil, nil, nil)
Matt Bell's avatar
Matt Bell committed
216 217
}

218
// NewRequest returns a request initialized with given arguments
219
func NewRequest(path []string, opts optMap, args []interface{}, cmd *Command, optDefs map[string]Option) Request {
220
	if path == nil {
Matt Bell's avatar
Matt Bell committed
221
		path = make([]string, 0)
Matt Bell's avatar
Matt Bell committed
222
	}
223 224 225 226
	if opts == nil {
		opts = make(map[string]interface{})
	}
	if args == nil {
227
		args = make([]interface{}, 0)
228
	}
229 230 231
	if optDefs == nil {
		optDefs = make(map[string]Option)
	}
232 233 234 235 236

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

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