github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/cmd/alias/aliasset.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  	"fmt"
    10  	"os"
    11  
    12  	"github.com/spf13/cobra"
    13  	yaml "gopkg.in/yaml.v2"
    14  
    15  	"github.com/iotexproject/iotex-core/ioctl/config"
    16  	"github.com/iotexproject/iotex-core/ioctl/output"
    17  	"github.com/iotexproject/iotex-core/ioctl/validator"
    18  )
    19  
    20  // Multi-language support
    21  var (
    22  	_setCmdShorts = map[config.Language]string{
    23  		config.English: "Set alias for address",
    24  		config.Chinese: "设定地址的别名",
    25  	}
    26  	_setCmdUses = map[config.Language]string{
    27  		config.English: "set ALIAS ADDRESS",
    28  		config.Chinese: "set 别名 地址",
    29  	}
    30  )
    31  
    32  // _aliasSetCmd represents the alias set command
    33  var _aliasSetCmd = &cobra.Command{
    34  	Use:   config.TranslateInLang(_setCmdUses, config.UILanguage),
    35  	Short: config.TranslateInLang(_setCmdShorts, config.UILanguage),
    36  	Args:  cobra.ExactArgs(2),
    37  	RunE: func(cmd *cobra.Command, args []string) error {
    38  		cmd.SilenceUsage = true
    39  		err := set(args)
    40  		return output.PrintError(err)
    41  	},
    42  }
    43  
    44  // set sets alias
    45  func set(args []string) error {
    46  	if err := validator.ValidateAlias(args[0]); err != nil {
    47  		return output.NewError(output.ValidationError, "invalid alias", err)
    48  	}
    49  	alias := args[0]
    50  	if err := validator.ValidateAddress(args[1]); err != nil {
    51  		return output.NewError(output.ValidationError, "invalid address", err)
    52  	}
    53  	addr := args[1]
    54  	aliases := GetAliasMap()
    55  	for aliases[addr] != "" {
    56  		delete(config.ReadConfig.Aliases, aliases[addr])
    57  		aliases = GetAliasMap()
    58  	}
    59  	config.ReadConfig.Aliases[alias] = addr
    60  	out, err := yaml.Marshal(&config.ReadConfig)
    61  	if err != nil {
    62  		return output.NewError(output.SerializationError, "failed to marshal config", err)
    63  	}
    64  	if err := os.WriteFile(config.DefaultConfigFile, out, 0600); err != nil {
    65  		return output.NewError(output.WriteFileError,
    66  			fmt.Sprintf("failed to write to config file %s", config.DefaultConfigFile), err)
    67  	}
    68  	output.PrintResult(args[0] + " has been set!")
    69  	return nil
    70  }