Skip to content

Commit

Permalink
remove tip when null
Browse files Browse the repository at this point in the history
  • Loading branch information
giunatale committed Apr 25, 2024
1 parent 9140f02 commit 85a2263
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
1 change: 1 addition & 0 deletions build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
go build -C cmd/cosmos-signer -o ../../build/cosmos-signer
61 changes: 60 additions & 1 deletion cmd/cosmos-signer/cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cmd

import (
"encoding/json"
"io"
"os"
"strings"

Expand Down Expand Up @@ -33,6 +35,59 @@ const (
flagPrefixPublic = "prefix-pub"
)

// FilterNullValJSON implements the io.Writer interface
type FilterNullValJSON struct {
Output io.Writer
NullKeys []string
}

func (w *FilterNullValJSON) Write(p []byte) (n int, err error) {
var data interface{}
if err := json.Unmarshal(p, &data); err != nil {
return 0, err
}
filteredData := filterNullValues(data, w.NullKeys)
filteredBytes, err := json.Marshal(filteredData)
if err != nil {
return 0, err
}
return w.Output.Write(filteredBytes)
}

// filterNullValues recursively filters out null values from JSON for specified keys
func filterNullValues(data interface{}, nullKeys []string) interface{} {
switch v := data.(type) {
case map[string]interface{}:
for key, val := range v {
if shouldCheckKey(key, nullKeys) {
if val == nil {
delete(v, key) // Delete key with null value if shouldPrint is true
} else {
v[key] = filterNullValues(val, nullKeys)
}
}
}
return v
case []interface{}:
for i := range v {
v[i] = filterNullValues(v[i], nullKeys)
}
return v
default:
return v
}
}

// shouldCheckKey checks if the key is one of the specified keys to check
func shouldCheckKey(key string, nullKeys []string) bool {
for _, k := range nullKeys {
if key == k {
return true
}
}
return false
}

// NewRootCmd creates a new root command for cosmos-signer. It is called once in the main function.
func NewRootCmd() *cobra.Command {

Expand All @@ -49,7 +104,11 @@ func NewRootCmd() *cobra.Command {
SilenceErrors: true,
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
// set the default command outputs
cmd.SetOut(cmd.OutOrStdout())
w := &FilterNullValJSON{
Output: cmd.OutOrStdout(),
NullKeys: []string{"tips"},
}
cmd.SetOut(w)
cmd.SetErr(cmd.ErrOrStderr())

clientCtx = clientCtx.WithCmdContext(cmd.Context())
Expand Down

0 comments on commit 85a2263

Please sign in to comment.