request.go 6.29 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 12
	"github.com/jbenet/go-ipfs/config"
	"github.com/jbenet/go-ipfs/core"
13
	u "github.com/jbenet/go-ipfs/util"
14 15
)

16 17
type optMap map[string]interface{}

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

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

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

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

80
	ConvertOptions() error
81 82 83
}

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

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

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

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

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

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

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

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

Matt Bell's avatar
Matt Bell committed
147 148 149 150 151 152
// 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()
}

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

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

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

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

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

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

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

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

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

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

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

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

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

	return nil
}

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

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

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

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