feat(autocli): add json file parsing support (#15451)

Co-authored-by: Julien Robert <julien@rbrt.fr>
This commit is contained in:
Jeancarlo Barrios 2023-03-23 15:43:46 -05:00 committed by GitHub
parent 07415a5d78
commit b44caab53a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 39 additions and 1 deletions

View File

@ -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 {

View File

@ -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",

View File

@ -0,0 +1 @@
{"bar":"baz"}