github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/cmd/alias/aliasexport.go (about) 1 // Copyright (c) 202 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 alias 7 8 import ( 9 "encoding/json" 10 "fmt" 11 12 "github.com/spf13/cobra" 13 "gopkg.in/yaml.v2" 14 15 "github.com/iotexproject/iotex-core/ioctl/config" 16 ) 17 18 // _aliasExportCmd doesn't support global flag "output-format", use `ioctl alias list -o [FORMAT]` instead 19 20 // Multi-language support 21 var ( 22 _exportCmd = map[config.Language]string{ 23 config.English: "Export aliases to either json or yaml format", 24 config.Chinese: "以json或yaml格式导出别名", 25 } 26 _flagExportFormatUsages = map[config.Language]string{ 27 config.English: "set format: json/yaml", 28 config.Chinese: "设置格式:json / yaml", 29 } 30 ) 31 32 // _aliasExportCmd represents the alias export command 33 var _aliasExportCmd = &cobra.Command{ 34 Use: "export", 35 Short: config.TranslateInLang(_exportCmd, config.UILanguage), 36 Args: cobra.ExactArgs(0), 37 RunE: func(cmd *cobra.Command, args []string) error { 38 cmd.SilenceUsage = true 39 output, err := aliasExport(cmd) 40 if err == nil { 41 println(output) 42 } 43 return err 44 }, 45 } 46 47 func init() { 48 _aliasExportCmd.Flags().StringVarP(&_format, 49 "format", "f", "json", config.TranslateInLang(_flagExportFormatUsages, config.UILanguage)) 50 } 51 52 func aliasExport(cmd *cobra.Command) (string, error) { 53 exportAliases := aliases{} 54 for name, address := range config.ReadConfig.Aliases { 55 exportAliases.Aliases = append(exportAliases.Aliases, alias{Name: name, Address: address}) 56 } 57 switch _format { 58 default: 59 cmd.SilenceUsage = false 60 return "", fmt.Errorf("invalid flag %s", _format) 61 case "json": 62 output, err := json.Marshal(exportAliases) 63 if err != nil { 64 return "", nil 65 } 66 return string(output), nil 67 case "yaml": 68 output, err := yaml.Marshal(exportAliases) 69 if err != nil { 70 return "", nil 71 } 72 return string(output), nil 73 } 74 }