request.go 6.2 KB
Newer Older
Matt Bell's avatar
Matt Bell committed
1 2
package commands

3
import (
4
	"errors"
5
	"fmt"
6
	"io"
7 8
	"reflect"
	"strconv"
9 10 11

	"github.com/jbenet/go-ipfs/config"
	"github.com/jbenet/go-ipfs/core"
12
	u "github.com/jbenet/go-ipfs/util"
13 14
)

15 16
type optMap map[string]interface{}

17 18
type Context struct {
	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{})
Brian Tiger Chow's avatar
Brian Tiger Chow committed
65 66 67 68 69 70

	// Arguments() returns user provided arguments as declared on the Command.
	//
	// NB: `io.Reader`s returned by Arguments() are owned by the library.
	// Readers are not guaranteed to remain open after the Command's Run
	// function returns.
71
	Arguments() []interface{} // TODO: make argument value type instead of using interface{}
72
	Context() *Context
73
	SetContext(Context)
74
	Command() *Command
75
	Cleanup() error
76

77
	ConvertOptions() error
78 79 80
}

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

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

94
// Option returns the value of the option for given name.
95
func (r *request) Option(name string) *OptionValue {
96 97
	val, found := r.options[name]
	if found {
98
		return &OptionValue{val, found}
99 100 101 102 103 104
	}

	// 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]
105 106 107 108 109 110 111 112 113
	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}
114 115 116
		}
	}

117 118
	// MAYBE_TODO: use default value instead of nil
	return &OptionValue{nil, false}
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 139
	// 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 {
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
}

150
// Arguments returns the arguments slice
151
func (r *request) Arguments() []interface{} {
Matt Bell's avatar
Matt Bell committed
152
	return r.arguments
153
}
Matt Bell's avatar
Matt Bell committed
154

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

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

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

167 168 169 170 171 172 173 174 175 176 177 178 179 180
func (r *request) Cleanup() error {
	for _, arg := range r.arguments {
		closer, ok := arg.(io.Closer)
		if ok {
			err := closer.Close()
			if err != nil {
				return err
			}
		}
	}

	return nil
}

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

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

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

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

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

		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
}

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

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

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

281
	return req, nil
Matt Bell's avatar
Matt Bell committed
282
}