github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/newcmd/account/accountlist.go (about) 1 // Copyright (c) 2019 IoTeX Foundation 2 // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability 3 // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed. 4 // This source code is governed by Apache License 2.0 that can be found in the LICENSE file. 5 6 package account 7 8 import ( 9 "strings" 10 11 "github.com/iotexproject/iotex-address/address" 12 "github.com/pkg/errors" 13 "github.com/spf13/cobra" 14 15 "github.com/iotexproject/iotex-core/ioctl" 16 "github.com/iotexproject/iotex-core/ioctl/config" 17 ) 18 19 // Multi-language support 20 var ( 21 _listCmdShorts = map[config.Language]string{ 22 config.English: "List existing account for ioctl", 23 config.Chinese: "列出ioctl中已存在的账户", 24 } 25 ) 26 27 // NewAccountList represents the account list command 28 func NewAccountList(client ioctl.Client) *cobra.Command { 29 short, _ := client.SelectTranslation(_listCmdShorts) 30 31 return &cobra.Command{ 32 Use: "list", 33 Short: short, 34 Args: cobra.ExactArgs(0), 35 RunE: func(cmd *cobra.Command, args []string) error { 36 cmd.SilenceUsage = true 37 listmessage := listMessage{} 38 aliases := client.AliasMap() 39 40 if client.IsCryptoSm2() { 41 sm2Accounts, err := listSm2Account(client) 42 if err != nil { 43 return errors.Wrap(err, "failed to get sm2 accounts") 44 } 45 for _, addr := range sm2Accounts { 46 listmessage.Accounts = append(listmessage.Accounts, account{ 47 Address: addr, 48 Alias: aliases[addr], 49 }) 50 } 51 } else { 52 ks := client.NewKeyStore() 53 for _, v := range ks.Accounts() { 54 addr, err := address.FromBytes(v.Address.Bytes()) 55 if err != nil { 56 return errors.Wrap(err, "failed to convert bytes into address") 57 } 58 listmessage.Accounts = append(listmessage.Accounts, account{ 59 Address: addr.String(), 60 Alias: aliases[addr.String()], 61 }) 62 } 63 } 64 cmd.Println(listmessage.String()) 65 return nil 66 }, 67 } 68 } 69 70 type listMessage struct { 71 Accounts []account `json:"accounts"` 72 } 73 74 type account struct { 75 Address string `json:"address"` 76 Alias string `json:"alias"` 77 } 78 79 func (m *listMessage) String() string { 80 lines := make([]string, 0) 81 for _, account := range m.Accounts { 82 line := account.Address 83 if account.Alias != "" { 84 line += " - " + account.Alias 85 } 86 lines = append(lines, line) 87 } 88 return strings.Join(lines, "\n") 89 }