request.go 6.55 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
	Values() map[string]interface{}
81

82
	ConvertOptions() error
83 84 85
}

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

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

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

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

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

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

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

147
	r.options[name] = val
148 149
}

Matt Bell's avatar
Matt Bell committed
150 151 152 153 154 155
// 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()
}

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

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

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

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

173 174 175 176
func (r *request) Context() *Context {
	return &r.ctx
}

177 178 179 180
func (r *request) SetContext(ctx Context) {
	r.ctx = ctx
}

181 182 183 184
func (r *request) Command() *Command {
	return r.cmd
}

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

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

213 214 215 216
func (r *request) Values() map[string]interface{} {
	return r.values
}

217
func (r *request) ConvertOptions() error {
218
	for k, v := range r.options {
219
		opt, ok := r.optionDefs[k]
220
		if !ok {
221
			continue
222 223 224
		}

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

			} else {
				return fmt.Errorf("Option '%s' should be type '%s', but got type '%s'",
245
					k, opt.Type().String(), kind.String())
246 247
			}
		} else {
248
			r.options[k] = v
249 250
		}

251
		for _, name := range opt.Names() {
252 253 254 255 256 257 258 259 260 261
			if _, ok := r.options[name]; name != k && ok {
				return fmt.Errorf("Duplicate command options were provided ('%s' and '%s')",
					k, name)
			}
		}
	}

	return nil
}

262
// NewEmptyRequest initializes an empty request
263
func NewEmptyRequest() (Request, error) {
Matt Bell's avatar
Matt Bell committed
264
	return NewRequest(nil, nil, nil, nil, nil, nil)
Matt Bell's avatar
Matt Bell committed
265 266
}

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

283
	ctx := Context{Context: context.TODO()}
284 285
	values := make(map[string]interface{})
	req := &request{path, opts, args, file, cmd, ctx, optDefs, values}
286 287 288 289
	err := req.ConvertOptions()
	if err != nil {
		return nil, err
	}
290

291
	return req, nil
Matt Bell's avatar
Matt Bell committed
292
}