github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/cmd/alias/aliasimport.go (about)

     1  // Copyright (c) 2022 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  	"os"
    12  
    13  	"github.com/spf13/cobra"
    14  	yaml "gopkg.in/yaml.v2"
    15  
    16  	"github.com/iotexproject/iotex-core/ioctl/config"
    17  	"github.com/iotexproject/iotex-core/ioctl/output"
    18  )
    19  
    20  // Multi-language support
    21  var (
    22  	_importCmdShorts = map[config.Language]string{
    23  		config.English: "Import aliases",
    24  		config.Chinese: "导入别名",
    25  	}
    26  	_importCmdUses = map[config.Language]string{
    27  		config.English: "import 'DATA'",
    28  		config.Chinese: "import '数据'",
    29  	}
    30  	_flagImportFormatUsages = map[config.Language]string{
    31  		config.English: "set format: json/yaml",
    32  		config.Chinese: "设置格式:json / yaml",
    33  	}
    34  	_flagForceImportUsages = map[config.Language]string{
    35  		config.English: "override existing aliases",
    36  		config.Chinese: "覆盖现有别名",
    37  	}
    38  )
    39  
    40  // _aliasImportCmd represents the alias import command
    41  var _aliasImportCmd = &cobra.Command{
    42  	Use:   config.TranslateInLang(_importCmdUses, config.UILanguage),
    43  	Short: config.TranslateInLang(_importCmdShorts, config.UILanguage),
    44  	Args:  cobra.ExactArgs(1),
    45  	RunE: func(cmd *cobra.Command, args []string) error {
    46  		cmd.SilenceUsage = true
    47  		err := aliasImport(cmd, args)
    48  		return output.PrintError(err)
    49  	},
    50  }
    51  
    52  type importMessage struct {
    53  	ImportedNumber int     `json:"importedNumber"`
    54  	TotalNumber    int     `json:"totalNumber"`
    55  	Imported       []alias `json:"imported"`
    56  	Unimported     []alias `json:"unimported"`
    57  }
    58  
    59  func init() {
    60  	_aliasImportCmd.Flags().StringVarP(&_format,
    61  		"format=", "f", "json", config.TranslateInLang(_flagImportFormatUsages, config.UILanguage))
    62  	_aliasImportCmd.Flags().BoolVarP(&_forceImport,
    63  		"force-import", "F", false, config.TranslateInLang(_flagForceImportUsages, config.UILanguage))
    64  }
    65  
    66  func aliasImport(cmd *cobra.Command, args []string) error {
    67  	var importedAliases aliases
    68  	switch _format {
    69  	default:
    70  		return output.NewError(output.FlagError, fmt.Sprintf("invalid format flag %s", _format), nil)
    71  	case "json":
    72  		if err := json.Unmarshal([]byte(args[0]), &importedAliases); err != nil {
    73  			return output.NewError(output.SerializationError, "failed to unmarshal imported aliases", err)
    74  		}
    75  	case "yaml":
    76  		if err := yaml.Unmarshal([]byte(args[0]), &importedAliases); err != nil {
    77  			return output.NewError(output.SerializationError, "failed to unmarshal imported aliases", err)
    78  		}
    79  	}
    80  	aliases := GetAliasMap()
    81  	message := importMessage{TotalNumber: len(importedAliases.Aliases), ImportedNumber: 0}
    82  	for _, importedAlias := range importedAliases.Aliases {
    83  		if !_forceImport && config.ReadConfig.Aliases[importedAlias.Name] != "" {
    84  			message.Unimported = append(message.Unimported, importedAlias)
    85  			continue
    86  		}
    87  		for aliases[importedAlias.Address] != "" {
    88  			delete(config.ReadConfig.Aliases, aliases[importedAlias.Address])
    89  			aliases = GetAliasMap()
    90  		}
    91  		config.ReadConfig.Aliases[importedAlias.Name] = importedAlias.Address
    92  		message.Imported = append(message.Imported, importedAlias)
    93  		message.ImportedNumber++
    94  	}
    95  	out, err := yaml.Marshal(&config.ReadConfig)
    96  	if err != nil {
    97  		return output.NewError(output.SerializationError, "failed to marshal config", err)
    98  	}
    99  	if err := os.WriteFile(config.DefaultConfigFile, out, 0600); err != nil {
   100  		return output.NewError(output.WriteFileError,
   101  			fmt.Sprintf("failed to write to config file %s", config.DefaultConfigFile), err)
   102  	}
   103  	fmt.Println(message.String())
   104  	return nil
   105  }
   106  
   107  func (m *importMessage) String() string {
   108  	if output.Format == "" {
   109  		line := fmt.Sprintf("%d/%d aliases imported\nExisted aliases:", m.ImportedNumber, m.TotalNumber)
   110  		for _, alias := range m.Unimported {
   111  			line += fmt.Sprint(" " + alias.Name)
   112  		}
   113  		return line
   114  	}
   115  	return output.FormatString(output.Result, m)
   116  }