feat(autocli): add json file parsing support (#15451)
Co-authored-by: Julien Robert <julien@rbrt.fr>
This commit is contained in:
parent
07415a5d78
commit
b44caab53a
@ -3,6 +3,9 @@ package flag
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"regexp"
|
||||
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
"google.golang.org/protobuf/proto"
|
||||
@ -11,6 +14,8 @@ import (
|
||||
"cosmossdk.io/client/v2/internal/util"
|
||||
)
|
||||
|
||||
var isJSONFileRegex = regexp.MustCompile(`\.json$`)
|
||||
|
||||
type jsonMessageFlagType struct {
|
||||
messageDesc protoreflect.MessageDescriptor
|
||||
}
|
||||
@ -55,7 +60,20 @@ func (j *jsonMessageFlagValue) String() string {
|
||||
|
||||
func (j *jsonMessageFlagValue) Set(s string) error {
|
||||
j.message = j.messageType.New().Interface()
|
||||
return j.jsonUnmarshalOptions.Unmarshal([]byte(s), j.message)
|
||||
var messageBytes []byte
|
||||
if isJSONFileRegex.MatchString(s) {
|
||||
jsonFile, err := os.Open(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
messageBytes, err = io.ReadAll(jsonFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
messageBytes = []byte(s)
|
||||
}
|
||||
return j.jsonUnmarshalOptions.Unmarshal(messageBytes, j.message)
|
||||
}
|
||||
|
||||
func (j *jsonMessageFlagValue) Type() string {
|
||||
|
||||
@ -143,6 +143,25 @@ func TestEverything(t *testing.T) {
|
||||
assert.DeepEqual(t, conn.lastRequest, conn.lastResponse.(*testpb.EchoResponse).Request, protocmp.Transform())
|
||||
}
|
||||
|
||||
func TestJSONParsing(t *testing.T) {
|
||||
conn := testExecCommon(t, buildModuleQueryCommand,
|
||||
"echo",
|
||||
"1", "abc", `{"denom":"foo","amount":"1"}`,
|
||||
"--some-messages", `{"bar":"baz"}`,
|
||||
"-u", "27", // shorthand
|
||||
)
|
||||
assert.DeepEqual(t, conn.lastRequest, conn.lastResponse.(*testpb.EchoResponse).Request, protocmp.Transform())
|
||||
|
||||
conn = testExecCommon(t, buildModuleQueryCommand,
|
||||
"echo",
|
||||
"1", "abc", `{"denom":"foo","amount":"1"}`,
|
||||
"--some-messages", "testdata/some_message.json",
|
||||
"-u", "27", // shorthand
|
||||
)
|
||||
assert.DeepEqual(t, conn.lastRequest, conn.lastResponse.(*testpb.EchoResponse).Request, protocmp.Transform())
|
||||
|
||||
}
|
||||
|
||||
func TestOptions(t *testing.T) {
|
||||
conn := testExecCommon(t, buildModuleQueryCommand,
|
||||
"echo",
|
||||
|
||||
1
client/v2/autocli/testdata/some_message.json
vendored
Normal file
1
client/v2/autocli/testdata/some_message.json
vendored
Normal file
@ -0,0 +1 @@
|
||||
{"bar":"baz"}
|
||||
Loading…
Reference in New Issue
Block a user