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

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

11
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
12
	"github.com/jbenet/go-ipfs/commands/files"
13
	"github.com/jbenet/go-ipfs/core"
14
	"github.com/jbenet/go-ipfs/repo/config"
15
	u "github.com/jbenet/go-ipfs/util"
16 17
)

18 19
type optMap map[string]interface{}

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

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

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

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

84
	ConvertOptions() error
85 86 87
}

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

99 100
// Path returns the command path of this request
func (r *request) Path() []string {
101 102 103
	return r.path
}

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

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

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

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

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

150
	r.options[name] = val
151 152
}

Matt Bell's avatar
Matt Bell committed
153 154 155 156 157 158
// 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()
}

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

164
func (r *request) SetArguments(args []string) {
165 166 167
	r.arguments = args
}

168
func (r *request) Files() files.File {
Matt Bell's avatar
Matt Bell committed
169 170 171
	return r.files
}

172
func (r *request) SetFiles(f files.File) {
173 174 175
	r.files = f
}

176 177 178 179
func (r *request) Context() *Context {
	return &r.ctx
}

180 181 182 183
func (r *request) SetContext(ctx Context) {
	r.ctx = ctx
}

184 185 186 187
func (r *request) Command() *Command {
	return r.cmd
}

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

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

216 217 218 219
func (r *request) Values() map[string]interface{} {
	return r.values
}

220 221 222 223
func (r *request) Stdin() io.Reader {
	return r.stdin
}

224
func (r *request) ConvertOptions() error {
225
	for k, v := range r.options {
226
		opt, ok := r.optionDefs[k]
227
		if !ok {
228
			continue
229 230 231
		}

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

			} else {
				return fmt.Errorf("Option '%s' should be type '%s', but got type '%s'",
252
					k, opt.Type().String(), kind.String())
253 254
			}
		} else {
255
			r.options[k] = v
256 257
		}

258
		for _, name := range opt.Names() {
259 260 261 262 263 264 265 266 267 268
			if _, ok := r.options[name]; name != k && ok {
				return fmt.Errorf("Duplicate command options were provided ('%s' and '%s')",
					k, name)
			}
		}
	}

	return nil
}

269
// NewEmptyRequest initializes an empty request
270
func NewEmptyRequest() (Request, error) {
Matt Bell's avatar
Matt Bell committed
271
	return NewRequest(nil, nil, nil, nil, nil, nil)
Matt Bell's avatar
Matt Bell committed
272 273
}

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

290
	ctx := Context{Context: context.TODO()}
291
	values := make(map[string]interface{})
292
	req := &request{path, opts, args, file, cmd, ctx, optDefs, values, os.Stdin}
293 294 295 296
	err := req.ConvertOptions()
	if err != nil {
		return nil, err
	}
297

298
	return req, nil
Matt Bell's avatar
Matt Bell committed
299
}