request.go 6.04 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
type Context struct {
17
	Online     bool
18
	ConfigRoot string
19 20 21 22 23 24 25 26 27 28 29 30 31 32

	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 {
33
			return nil, errors.New("nil LoadConfig function")
34 35 36 37 38 39 40 41 42 43 44 45
		}
		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 {
46
			return nil, errors.New("nil ConstructNode function")
47 48 49 50 51 52 53 54 55 56
		}
		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
57 58
}

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

74
	ConvertOptions() error
75 76 77
}

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

87 88
// Path returns the command path of this request
func (r *request) Path() []string {
89 90 91
	return r.path
}

92
// Option returns the value of the option for given name.
93
func (r *request) Option(name string) *OptionValue {
94 95
	// find the option with the specified name
	option, found := r.optionDefs[name]
96 97 98 99 100
	if !found {
		return nil
	}

	// try all the possible names, break if we find a value
101 102
	for _, n := range option.Names() {
		val, found := r.options[n]
103
		if found {
104
			return &OptionValue{val, found, option}
105 106 107
		}
	}

108
	// MAYBE_TODO: use default value instead of nil
109
	return &OptionValue{nil, false, option}
Matt Bell's avatar
Matt Bell committed
110 111
}

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

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

138
	r.options[name] = val
139 140
}

Matt Bell's avatar
Matt Bell committed
141 142 143 144 145 146
// 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()
}

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

152
func (r *request) SetArguments(args []string) {
153 154 155
	r.arguments = args
}

Matt Bell's avatar
Matt Bell committed
156 157 158 159
func (r *request) Files() File {
	return r.files
}

160 161 162 163
func (r *request) SetFiles(f File) {
	r.files = f
}

164 165 166 167
func (r *request) Context() *Context {
	return &r.ctx
}

168 169 170 171
func (r *request) SetContext(ctx Context) {
	r.ctx = ctx
}

172 173 174 175
func (r *request) Command() *Command {
	return r.cmd
}

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

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

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

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

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

238
		for _, name := range opt.Names() {
239 240 241 242 243 244 245 246 247 248
			if _, ok := r.options[name]; name != k && ok {
				return fmt.Errorf("Duplicate command options were provided ('%s' and '%s')",
					k, name)
			}
		}
	}

	return nil
}

249
// NewEmptyRequest initializes an empty request
250
func NewEmptyRequest() (Request, error) {
Matt Bell's avatar
Matt Bell committed
251
	return NewRequest(nil, nil, nil, nil, nil, nil)
Matt Bell's avatar
Matt Bell committed
252 253
}

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

Matt Bell's avatar
Matt Bell committed
270
	req := &request{path, opts, args, file, cmd, Context{}, optDefs}
271 272 273 274
	err := req.ConvertOptions()
	if err != nil {
		return nil, err
	}
275

276
	return req, nil
Matt Bell's avatar
Matt Bell committed
277
}