Skip to content

Commit 89a72c8

Browse files
authored
add output json format to keys add command (#29)
1 parent fd8a58c commit 89a72c8

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

cmd/opinitd/key.go

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package main
1818

1919
import (
2020
"bufio"
21+
"encoding/json"
2122
"fmt"
2223
"io"
2324
"os"
@@ -37,8 +38,16 @@ const (
3738
flagRecover = "recover"
3839
flagMnemonicSrc = "source"
3940
flagBech32Prefix = "bech32"
41+
flagOutput = "output"
4042
)
4143

44+
type keyJsonOutput map[string]keyJsonOutputElem
45+
46+
type keyJsonOutputElem struct {
47+
Address string `json:"address"`
48+
Mnemonic string `json:"mnemonic"`
49+
}
50+
4251
// keysCmd represents the keys command
4352
func keysCmd(ctx *cmdContext) *cobra.Command {
4453
cmd := &cobra.Command{
@@ -69,7 +78,8 @@ func keysAddCmd(ctx *cmdContext) *cobra.Command {
6978
$ keys add localnet key1
7079
$ keys add l2 key2 --bech32 celestia
7180
$ keys add l2 key2 --recover
72-
$ keys add l2 key2 --recover --source mnemonic.txt`),
81+
$ keys add l2 key2 --recover --source mnemonic.txt
82+
$ keys add l2 key2 --output json`),
7383
RunE: func(cmd *cobra.Command, args []string) error {
7484
chainId := args[0]
7585
keyName := args[1]
@@ -138,13 +148,32 @@ $ keys add l2 key2 --recover --source mnemonic.txt`),
138148
return err
139149
}
140150

141-
fmt.Fprintf(cmd.OutOrStdout(), "%s: %s\n%s\n", account.Name, addrString, mnemonic)
151+
outputFormat, _ := cmd.Flags().GetString(flagOutput)
152+
var output string
153+
switch outputFormat {
154+
case "json":
155+
jsonOutput := make(keyJsonOutput)
156+
jsonOutput[account.Name] = keyJsonOutputElem{
157+
Address: addrString,
158+
Mnemonic: mnemonic,
159+
}
160+
outputBytes, err := json.Marshal(&jsonOutput)
161+
if err != nil {
162+
return err
163+
}
164+
output = string(outputBytes)
165+
default:
166+
output = fmt.Sprintf("%s: %s\n%s", account.Name, addrString, mnemonic)
167+
}
168+
169+
fmt.Fprintln(cmd.OutOrStdout(), output)
142170
return nil
143171
},
144172
}
145173
cmd.Flags().Bool(flagRecover, false, "Provide seed phrase to recover existing key instead of creating")
146174
cmd.Flags().String(flagMnemonicSrc, "", "Import mnemonic from a file")
147175
cmd.Flags().String(flagBech32Prefix, "init", "Bech32 prefix")
176+
cmd.Flags().String(flagOutput, "plain", "Output format (plain|json)")
148177
return cmd
149178
}
150179

0 commit comments

Comments
 (0)