Skip to content

Commit

Permalink
add output json format to keys add command (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
sh-cha authored Oct 5, 2024
1 parent fd8a58c commit 89a72c8
Showing 1 changed file with 31 additions and 2 deletions.
33 changes: 31 additions & 2 deletions cmd/opinitd/key.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package main

import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
Expand All @@ -37,8 +38,16 @@ const (
flagRecover = "recover"
flagMnemonicSrc = "source"
flagBech32Prefix = "bech32"
flagOutput = "output"
)

type keyJsonOutput map[string]keyJsonOutputElem

type keyJsonOutputElem struct {
Address string `json:"address"`
Mnemonic string `json:"mnemonic"`
}

// keysCmd represents the keys command
func keysCmd(ctx *cmdContext) *cobra.Command {
cmd := &cobra.Command{
Expand Down Expand Up @@ -69,7 +78,8 @@ func keysAddCmd(ctx *cmdContext) *cobra.Command {
$ keys add localnet key1
$ keys add l2 key2 --bech32 celestia
$ keys add l2 key2 --recover
$ keys add l2 key2 --recover --source mnemonic.txt`),
$ keys add l2 key2 --recover --source mnemonic.txt
$ keys add l2 key2 --output json`),
RunE: func(cmd *cobra.Command, args []string) error {
chainId := args[0]
keyName := args[1]
Expand Down Expand Up @@ -138,13 +148,32 @@ $ keys add l2 key2 --recover --source mnemonic.txt`),
return err
}

fmt.Fprintf(cmd.OutOrStdout(), "%s: %s\n%s\n", account.Name, addrString, mnemonic)
outputFormat, _ := cmd.Flags().GetString(flagOutput)
var output string
switch outputFormat {
case "json":
jsonOutput := make(keyJsonOutput)
jsonOutput[account.Name] = keyJsonOutputElem{
Address: addrString,
Mnemonic: mnemonic,
}
outputBytes, err := json.Marshal(&jsonOutput)
if err != nil {
return err
}
output = string(outputBytes)
default:
output = fmt.Sprintf("%s: %s\n%s", account.Name, addrString, mnemonic)
}

fmt.Fprintln(cmd.OutOrStdout(), output)
return nil
},
}
cmd.Flags().Bool(flagRecover, false, "Provide seed phrase to recover existing key instead of creating")
cmd.Flags().String(flagMnemonicSrc, "", "Import mnemonic from a file")
cmd.Flags().String(flagBech32Prefix, "init", "Bech32 prefix")
cmd.Flags().String(flagOutput, "plain", "Output format (plain|json)")
return cmd
}

Expand Down

0 comments on commit 89a72c8

Please sign in to comment.