request.go 5.86 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
	u "github.com/jbenet/go-ipfs/util"
12 13
)

14 15
type optMap map[string]interface{}

16 17
type Context struct {
	ConfigRoot string
18 19 20 21 22 23 24 25 26 27 28 29 30 31

	config     *config.Config
	LoadConfig func(path string) (*config.Config, error)

	node          *core.IpfsNode
	ConstructNode func() (*core.IpfsNode, error)
}

// GetConfig returns the config of the current Command exection
// context. It may load it with the providied function.
func (c *Context) GetConfig() (*config.Config, error) {
	var err error
	if c.config == nil {
		if c.LoadConfig == nil {
32
			return nil, errors.New("nil LoadConfig function")
33 34 35 36 37 38 39 40 41 42 43 44
		}
		c.config, err = c.LoadConfig(c.ConfigRoot)
	}
	return c.config, err
}

// GetNode returns the node of the current Command exection
// context. It may construct it with the providied function.
func (c *Context) GetNode() (*core.IpfsNode, error) {
	var err error
	if c.node == nil {
		if c.ConstructNode == nil {
45
			return nil, errors.New("nil ConstructNode function")
46 47 48 49 50 51 52 53 54 55
		}
		c.node, err = c.ConstructNode()
	}
	return c.node, err
}

// NodeWithoutConstructing returns the underlying node variable
// so that clients may close it.
func (c *Context) NodeWithoutConstructing() *core.IpfsNode {
	return c.node
56 57
}

Matt Bell's avatar
Matt Bell committed
58
// Request represents a call to a command from a consumer
59 60
type Request interface {
	Path() []string
61 62
	Option(name string) *OptionValue
	Options() optMap
63
	SetOption(name string, val interface{})
Matt Bell's avatar
Matt Bell committed
64 65
	Arguments() []interface{}
	Files() File
66
	Context() *Context
67
	SetContext(Context)
68
	Command() *Command
69
	Cleanup() error
70

71
	ConvertOptions() error
72 73 74
}

type request struct {
75 76 77
	path       []string
	options    optMap
	arguments  []interface{}
Matt Bell's avatar
Matt Bell committed
78
	files      File
79 80 81
	cmd        *Command
	ctx        Context
	optionDefs map[string]Option
Matt Bell's avatar
Matt Bell committed
82 83
}

84 85
// Path returns the command path of this request
func (r *request) Path() []string {
86 87 88
	return r.path
}

89
// Option returns the value of the option for given name.
90
func (r *request) Option(name string) *OptionValue {
91 92
	val, found := r.options[name]
	if found {
93
		return &OptionValue{val, found}
94 95 96 97 98 99
	}

	// 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]
100 101 102 103 104 105 106 107 108
	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}
109 110 111
		}
	}

112 113
	// MAYBE_TODO: use default value instead of nil
	return &OptionValue{nil, false}
Matt Bell's avatar
Matt Bell committed
114 115
}

116
// Options returns a copy of the option map
117
func (r *request) Options() optMap {
118 119 120 121 122 123 124
	output := make(optMap)
	for k, v := range r.options {
		output[k] = v
	}
	return output
}

125 126
// SetOption sets the value of the option for given name.
func (r *request) SetOption(name string, val interface{}) {
127 128 129 130 131 132 133 134
	// 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 {
135
		_, found := r.options[n]
136 137 138 139 140 141
		if found {
			r.options[n] = val
			return
		}
	}

142
	r.options[name] = val
143 144
}

145
// Arguments returns the arguments slice
146
func (r *request) Arguments() []interface{} {
Matt Bell's avatar
Matt Bell committed
147
	return r.arguments
148
}
Matt Bell's avatar
Matt Bell committed
149

Matt Bell's avatar
Matt Bell committed
150 151 152 153
func (r *request) Files() File {
	return r.files
}

154 155 156 157
func (r *request) Context() *Context {
	return &r.ctx
}

158 159 160 161
func (r *request) SetContext(ctx Context) {
	r.ctx = ctx
}

162 163 164 165
func (r *request) Command() *Command {
	return r.cmd
}

166
func (r *request) Cleanup() error {
Matt Bell's avatar
Matt Bell committed
167
	// TODO
168 169 170
	return nil
}

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

173
var converters = map[reflect.Kind]converter{
Matt Bell's avatar
Matt Bell committed
174
	Bool: func(v string) (interface{}, error) {
175 176 177 178 179
		if v == "" {
			return true, nil
		}
		return strconv.ParseBool(v)
	},
Matt Bell's avatar
Matt Bell committed
180
	Int: func(v string) (interface{}, error) {
181 182 183 184 185
		val, err := strconv.ParseInt(v, 0, 32)
		if err != nil {
			return nil, err
		}
		return int(val), err
186
	},
Matt Bell's avatar
Matt Bell committed
187
	Uint: func(v string) (interface{}, error) {
188 189 190 191 192
		val, err := strconv.ParseUint(v, 0, 32)
		if err != nil {
			return nil, err
		}
		return int(val), err
193
	},
Matt Bell's avatar
Matt Bell committed
194
	Float: func(v string) (interface{}, error) {
195 196 197 198
		return strconv.ParseFloat(v, 64)
	},
}

199
func (r *request) ConvertOptions() error {
200
	for k, v := range r.options {
201
		opt, ok := r.optionDefs[k]
202
		if !ok {
203
			continue
204 205 206 207 208 209
		}

		kind := reflect.TypeOf(v).Kind()
		if kind != opt.Type {
			if kind == String {
				convert := converters[opt.Type]
210 211
				str, ok := v.(string)
				if !ok {
212
					return u.ErrCast()
213 214
				}
				val, err := convert(str)
215
				if err != nil {
216 217 218 219 220 221
					value := fmt.Sprintf("value '%v'", v)
					if len(str) == 0 {
						value = "empty value"
					}
					return fmt.Errorf("Could not convert %s to type '%s' (for option '-%s')",
						value, opt.Type.String(), k)
222
				}
223
				r.options[k] = val
224 225 226 227 228 229

			} else {
				return fmt.Errorf("Option '%s' should be type '%s', but got type '%s'",
					k, opt.Type.String(), kind.String())
			}
		} else {
230
			r.options[k] = v
231 232 233 234 235 236 237 238 239 240 241 242 243
		}

		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
}

244
// NewEmptyRequest initializes an empty request
245
func NewEmptyRequest() (Request, error) {
Matt Bell's avatar
Matt Bell committed
246
	return NewRequest(nil, nil, nil, nil, nil, nil)
Matt Bell's avatar
Matt Bell committed
247 248
}

249
// NewRequest returns a request initialized with given arguments
250
// An non-nil error will be returned if the provided option values are invalid
Matt Bell's avatar
Matt Bell committed
251
func NewRequest(path []string, opts optMap, args []interface{}, file File, cmd *Command, optDefs map[string]Option) (Request, error) {
252
	if path == nil {
Matt Bell's avatar
Matt Bell committed
253
		path = make([]string, 0)
Matt Bell's avatar
Matt Bell committed
254
	}
255 256 257 258
	if opts == nil {
		opts = make(map[string]interface{})
	}
	if args == nil {
259
		args = make([]interface{}, 0)
260
	}
261 262 263
	if optDefs == nil {
		optDefs = make(map[string]Option)
	}
264

Matt Bell's avatar
Matt Bell committed
265
	req := &request{path, opts, args, file, cmd, Context{}, optDefs}
266 267 268 269
	err := req.ConvertOptions()
	if err != nil {
		return nil, err
	}
270

271
	return req, nil
Matt Bell's avatar
Matt Bell committed
272
}