@cryptotaxi247 / kubo / commits / 1b3561582

commands: Made Command#GetOption method, for getting all options for a given command path

Matt Bell committed Oct 14, 2014 at 14:27 UTC 1b3561582450084313482b8db6c2b7e4a662ab4d
1 file changed +35 -24
commands/command.go
+35 -24
@@ -38,35 +38,17 @@ func (c *Command) Register(id string, sub *Command) error {
38
39 // Call invokes the command at the given subcommand path
40 func (c *Command) Call(path []string, req *Request) *Response {
41 - options := make([]Option, len(c.Options))
42 - copy(options, c.Options)
43 - options = append(options, globalOptions...)
41 cmd := c
42 res := &Response{req: req}
43
47 - if path != nil {
48 - for i, id := range path {
49 - cmd = c.Sub(id)
50 -
51 - if cmd == nil {
52 - pathS := strings.Join(path[0:i], "/")
53 - res.SetError(fmt.Errorf("Undefined command: '%s'", pathS), Client)
54 - return res
55 - }
56 -
57 - options = append(options, cmd.Options...)
58 - }
59 - }
60 -
61 - optionsMap := make(map[string]Option)
62 - for _, opt := range options {
63 - for _, name := range opt.Names {
64 - optionsMap[name] = opt
65 - }
66 - }
44 + options, err := cmd.GetOptions(path)
45 + if err != nil {
46 + res.SetError(err, Client)
47 + return res
48 + }
49
50 for k, v := range req.options {
69 - opt, ok := optionsMap[k]
51 + opt, ok := options[k]
52
53 if !ok {
54 res.SetError(fmt.Errorf("Unrecognized command option: '%s'", k), Client)
@@ -94,6 +76,35 @@ func (c *Command) Call(path []string, req *Request) *Response {
76 return res
77 }
78
79 +// GetOptions gets the options in the given path of commands
80 +func (c *Command) GetOptions(path []string) (map[string]Option, error) {
81 + options := make([]Option, len(c.Options))
82 + copy(options, c.Options)
83 + options = append(options, globalOptions...)
84 +
85 + if path != nil {
86 + for i, id := range path {
87 + cmd := c.Sub(id)
88 +
89 + if cmd == nil {
90 + pathS := strings.Join(path[0:i], "/")
91 + return nil, fmt.Errorf("Undefined command: '%s'", pathS)
92 + }
93 +
94 + options = append(options, cmd.Options...)
95 + }
96 + }
97 +
98 + optionsMap := make(map[string]Option)
99 + for _, opt := range options {
100 + for _, name := range opt.Names {
101 + optionsMap[name] = opt
102 + }
103 + }
104 +
105 + return optionsMap, nil
106 +}
107 +
108 // Sub returns the subcommand with the given id
109 func (c *Command) Sub(id string) *Command {
110 return c.subcommands[id]