Skip to content

Commit

Permalink
(serverv2/cometbft) Commands support both json and yaml output (#20670)
Browse files Browse the repository at this point in the history
  • Loading branch information
hieuvubk authored Jun 17, 2024
1 parent 6ee21af commit 9ab7d39
Showing 1 changed file with 35 additions and 19 deletions.
54 changes: 35 additions & 19 deletions server/v2/cometbft/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,7 @@ func (s *CometBFTServer[T]) StatusCommand() *cobra.Command {
return err
}

cmd.Println(string(output))

// TODO: figure out yaml and json output
return nil
return printOutput(cmd, output)
},
}

Expand Down Expand Up @@ -215,15 +212,12 @@ for. Each module documents its respective events under 'xx_events.md'.
return err
}

// return clientCtx.PrintProto(blocks) // TODO: previously we had this, but I think it can be replaced with a simple json marshal.
// We are missing YAML output tho.
bz, err := protojson.Marshal(blocks)
if err != nil {
return err
}

_, err = cmd.OutOrStdout().Write(bz)
return err
return printOutput(cmd, bz)
},
}

Expand Down Expand Up @@ -282,15 +276,12 @@ $ %s query block --%s=%s <hash>
return fmt.Errorf("no block found with height %s", args[0])
}

// return clientCtx.PrintProto(output)

bz, err := json.Marshal(output)
if err != nil {
return err
}

_, err = cmd.OutOrStdout().Write(bz)
return err
return printOutput(cmd, bz)

case auth.TypeHash:

Expand All @@ -308,14 +299,12 @@ $ %s query block --%s=%s <hash>
return fmt.Errorf("no block found with hash %s", args[0])
}

// return clientCtx.PrintProto(output)
bz, err := json.Marshal(output)
if err != nil {
return err
}

_, err = cmd.OutOrStdout().Write(bz)
return err
return printOutput(cmd, bz)

default:
return fmt.Errorf("unknown --%s value %s", auth.FlagType, typ)
Expand Down Expand Up @@ -371,10 +360,7 @@ func (s *CometBFTServer[T]) QueryBlockResultsCmd() *cobra.Command {
return err
}

cmd.Println(string(blockResStr))

// TODO: figure out yaml and json output
return nil
return printOutput(cmd, blockResStr)
},
}

Expand Down Expand Up @@ -425,3 +411,33 @@ func (s *CometBFTServer[T]) BootstrapStateCmd() *cobra.Command {

return cmd
}

func printOutput(cmd *cobra.Command, out []byte) error {
// Get flags output
outFlag, err := cmd.Flags().GetString(flags.FlagOutput)
if err != nil {
return err
}

if outFlag == "text" {
out, err = yaml.JSONToYAML(out)
if err != nil {
return err
}
}

writer := cmd.OutOrStdout()
_, err = writer.Write(out)
if err != nil {
return err
}

if outFlag != "text" {
// append new-line for formats besides YAML
_, err = writer.Write([]byte("\n"))
if err != nil {
return err
}
}
return nil
}

0 comments on commit 9ab7d39

Please sign in to comment.