commands: Ensure command output is correct type (if cmd.Type is set), resolves #321
Matt Bell committed
Nov 13, 2014 at 01:09 UTC
3b407c705d5626e012f463f67683f68aec36b53d
1 file changed
+14
commands/command.go
+14
@@ -4,6 +4,7 @@ import (
4
"errors"
5
"fmt"
6
"io"
7
+ "reflect"
8
"strings"
9
10
u "github.com/jbenet/go-ipfs/util"
@@ -64,6 +65,8 @@ var ErrNotCallable = errors.New("This command can't be called directly. Try one
65
66
var ErrNoFormatter = errors.New("This command cannot be formatted to plain text")
67
68
+var ErrIncorrectType = errors.New("The command returned a value with a different type than expected")
69
+
70
// Call invokes the command for the given Request
71
func (c *Command) Call(req Request) Response {
72
res := NewResponse(req)
@@ -106,6 +109,17 @@ func (c *Command) Call(req Request) Response {
109
return res
110
}
111
112
+ // If the command specified an output type, ensure the actual value returned is of that type
113
+ if cmd.Type != nil {
114
+ definedType := reflect.ValueOf(cmd.Type).Type()
115
+ actualType := reflect.ValueOf(output).Type()
116
+
117
+ if definedType != actualType {
118
+ res.SetError(ErrIncorrectType, ErrNormal)
119
+ return res
120
+ }
121
+ }
122
+
123
// clean up the request (close the readers, e.g. fileargs)
124
// NOTE: this means commands can't expect to keep reading after cmd.Run returns (in a goroutine)
125
err = req.Cleanup()