Skip to content

Commit

Permalink
Fix conflicts
Browse files Browse the repository at this point in the history
Signed-off-by: Rohit Nayak <rohit@planetscale.com>
  • Loading branch information
rohit-nayak-ps committed Jun 21, 2024
1 parent 741a026 commit 5ccd402
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 4 deletions.
2 changes: 1 addition & 1 deletion go/cmd/vtctldclient/command/routing_rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func commandApplyRoutingRules(cmd *cobra.Command, args []string) error {
}

rr := &vschemapb.RoutingRules{}
if err := json2.Unmarshal(rulesBytes, &rr); err != nil {
if err := json2.UnmarshalPB(rulesBytes, rr); err != nil {
return err
}

Expand Down
2 changes: 1 addition & 1 deletion go/cmd/vtctldclient/command/shard_routing_rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func commandApplyShardRoutingRules(cmd *cobra.Command, args []string) error {
}

srr := &vschemapb.ShardRoutingRules{}
if err := json2.Unmarshal(rulesBytes, &srr); err != nil {
if err := json2.UnmarshalPB(rulesBytes, srr); err != nil {
return err
}
// Round-trip so when we display the result it's readable.
Expand Down
9 changes: 7 additions & 2 deletions go/json2/unmarshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@ var carriageReturn = []byte("\n")
// efficient and should not be used for high QPS operations.
func Unmarshal(data []byte, v any) error {
if pb, ok := v.(proto.Message); ok {
opts := protojson.UnmarshalOptions{DiscardUnknown: true}
return annotate(data, opts.Unmarshal(data, pb))
return UnmarshalPB(data, pb)
}
return annotate(data, json.Unmarshal(data, v))
}
Expand All @@ -53,3 +52,9 @@ func annotate(data []byte, err error) error {

return fmt.Errorf("line: %d, position %d: %v", line, pos, err)
}

// UnmarshalPB is similar to Unmarshal but specifically for proto.Message to add type safety.
func UnmarshalPB(data []byte, pb proto.Message) error {
opts := protojson.UnmarshalOptions{DiscardUnknown: true}
return annotate(data, opts.Unmarshal(data, pb))
}
11 changes: 11 additions & 0 deletions go/json2/unmarshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,14 @@ func TestAnnotate(t *testing.T) {
require.Equal(t, tcase.err, err, "annotate(%s, %v) error", string(tcase.data), tcase.err)
}
}

func TestUnmarshalPB(t *testing.T) {
want := &emptypb.Empty{}
json, err := protojson.Marshal(want)
require.NoError(t, err)

var got emptypb.Empty
err = UnmarshalPB(json, &got)
require.NoError(t, err)
require.Equal(t, want, &got)
}

0 comments on commit 5ccd402

Please sign in to comment.