request.go 6.37 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
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"

11
	"github.com/jbenet/go-ipfs/commands/files"
12
	"github.com/jbenet/go-ipfs/core"
13
	"github.com/jbenet/go-ipfs/repo/config"
14
	u "github.com/jbenet/go-ipfs/util"
15 16
)

17 18
type optMap map[string]interface{}

19
type Context struct {
20 21 22 23
	// this Context is temporary. Will be replaced soon, as we get
	// rid of this variable entirely.
	Context context.Context

24
	Online     bool
25
	ConfigRoot string
26 27 28 29 30 31 32 33 34 35 36 37 38 39

	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 {
40
			return nil, errors.New("nil LoadConfig function")
41 42 43 44 45 46 47 48 49 50 51 52
		}
		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 {
53
			return nil, errors.New("nil ConstructNode function")
54 55 56 57 58 59 60 61 62 63
		}
		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
64 65
}

Matt Bell's avatar
Matt Bell committed
66
// Request represents a call to a command from a consumer
67 68
type Request interface {
	Path() []string
69 70
	Option(name string) *OptionValue
	Options() optMap
71
	SetOption(name string, val interface{})
Matt Bell's avatar
Matt Bell committed
72
	SetOptions(opts map[string]interface{}) error
73 74
	Arguments() []string
	SetArguments([]string)
75 76
	Files() files.File
	SetFiles(files.File)
77
	Context() *Context
78
	SetContext(Context)
79
	Command() *Command
80

81
	ConvertOptions() error
82 83 84
}

type request struct {
85 86
	path       []string
	options    optMap
87
	arguments  []string
88
	files      files.File
89 90 91
	cmd        *Command
	ctx        Context
	optionDefs map[string]Option
Matt Bell's avatar
Matt Bell committed
92 93
}

94 95
// Path returns the command path of this request
func (r *request) Path() []string {
96 97 98
	return r.path
}

99
// Option returns the value of the option for given name.
100
func (r *request) Option(name string) *OptionValue {
101 102
	// find the option with the specified name
	option, found := r.optionDefs[name]
103 104 105 106 107
	if !found {
		return nil
	}

	// try all the possible names, break if we find a value
108 109
	for _, n := range option.Names() {
		val, found := r.options[n]
110
		if found {
111
			return &OptionValue{val, found, option}
112 113 114
		}
	}

115
	// MAYBE_TODO: use default value instead of nil
116
	return &OptionValue{nil, false, option}
Matt Bell's avatar
Matt Bell committed
117 118
}

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

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

145
	r.options[name] = val
146 147
}

Matt Bell's avatar
Matt Bell committed
148 149 150 151 152 153
// SetOptions sets the option values, unsetting any values that were previously set
func (r *request) SetOptions(opts map[string]interface{}) error {
	r.options = opts
	return r.ConvertOptions()
}

154
// Arguments returns the arguments slice
155
func (r *request) Arguments() []string {
Matt Bell's avatar
Matt Bell committed
156
	return r.arguments
157
}
Matt Bell's avatar
Matt Bell committed
158

159
func (r *request) SetArguments(args []string) {
160 161 162
	r.arguments = args
}

163
func (r *request) Files() files.File {
Matt Bell's avatar
Matt Bell committed
164 165 166
	return r.files
}

167
func (r *request) SetFiles(f files.File) {
168 169 170
	r.files = f
}

171 172 173 174
func (r *request) Context() *Context {
	return &r.ctx
}

175 176 177 178
func (r *request) SetContext(ctx Context) {
	r.ctx = ctx
}

179 180 181 182
func (r *request) Command() *Command {
	return r.cmd
}

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

185
var converters = map[reflect.Kind]converter{
Matt Bell's avatar
Matt Bell committed
186
	Bool: func(v string) (interface{}, error) {
187 188 189 190 191
		if v == "" {
			return true, nil
		}
		return strconv.ParseBool(v)
	},
Matt Bell's avatar
Matt Bell committed
192
	Int: func(v string) (interface{}, error) {
193 194 195 196 197
		val, err := strconv.ParseInt(v, 0, 32)
		if err != nil {
			return nil, err
		}
		return int(val), err
198
	},
Matt Bell's avatar
Matt Bell committed
199
	Uint: func(v string) (interface{}, error) {
200 201 202 203 204
		val, err := strconv.ParseUint(v, 0, 32)
		if err != nil {
			return nil, err
		}
		return int(val), err
205
	},
Matt Bell's avatar
Matt Bell committed
206
	Float: func(v string) (interface{}, error) {
207 208 209 210
		return strconv.ParseFloat(v, 64)
	},
}

211
func (r *request) ConvertOptions() error {
212
	for k, v := range r.options {
213
		opt, ok := r.optionDefs[k]
214
		if !ok {
215
			continue
216 217 218
		}

		kind := reflect.TypeOf(v).Kind()
219
		if kind != opt.Type() {
220
			if kind == String {
221
				convert := converters[opt.Type()]
222 223
				str, ok := v.(string)
				if !ok {
224
					return u.ErrCast()
225 226
				}
				val, err := convert(str)
227
				if err != nil {
228 229 230 231 232
					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')",
233
						value, opt.Type().String(), k)
234
				}
235
				r.options[k] = val
236 237 238

			} else {
				return fmt.Errorf("Option '%s' should be type '%s', but got type '%s'",
239
					k, opt.Type().String(), kind.String())
240 241
			}
		} else {
242
			r.options[k] = v
243 244
		}

245
		for _, name := range opt.Names() {
246 247 248 249 250 251 252 253 254 255
			if _, ok := r.options[name]; name != k && ok {
				return fmt.Errorf("Duplicate command options were provided ('%s' and '%s')",
					k, name)
			}
		}
	}

	return nil
}

256
// NewEmptyRequest initializes an empty request
257
func NewEmptyRequest() (Request, error) {
Matt Bell's avatar
Matt Bell committed
258
	return NewRequest(nil, nil, nil, nil, nil, nil)
Matt Bell's avatar
Matt Bell committed
259 260
}

261
// NewRequest returns a request initialized with given arguments
262
// An non-nil error will be returned if the provided option values are invalid
263
func NewRequest(path []string, opts optMap, args []string, file files.File, cmd *Command, optDefs map[string]Option) (Request, error) {
264
	if path == nil {
Matt Bell's avatar
Matt Bell committed
265
		path = make([]string, 0)
Matt Bell's avatar
Matt Bell committed
266
	}
267 268 269 270
	if opts == nil {
		opts = make(map[string]interface{})
	}
	if args == nil {
271
		args = make([]string, 0)
272
	}
273 274 275
	if optDefs == nil {
		optDefs = make(map[string]Option)
	}
276

277 278
	ctx := Context{Context: context.TODO()}
	req := &request{path, opts, args, file, cmd, ctx, optDefs}
279 280 281 282
	err := req.ConvertOptions()
	if err != nil {
		return nil, err
	}
283

284
	return req, nil
Matt Bell's avatar
Matt Bell committed
285
}