github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/newcmd/config/config_set.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 config
     7  
     8  import (
     9  	"fmt"
    10  	"strings"
    11  
    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  var (
    20  	_configSetUse = map[config.Language]string{
    21  		config.English: "set VARIABLE VALUE",
    22  		config.Chinese: "set 变量 值",
    23  	}
    24  	_configSetUseCmdShorts = map[config.Language]string{
    25  		config.English: "Set config fields for ioctl",
    26  		config.Chinese: "为 ioctl 设置配置字段",
    27  	}
    28  	_configSetUseCmdLong = map[config.Language]string{
    29  		config.English: "Set config fields for ioctl\nValid Variables: [" + strings.Join(_validArgs, ", ") + "]",
    30  		config.Chinese: "为 ioctl 设置配置字段\n有效变量: [" + strings.Join(_validArgs, ", ") + "]",
    31  	}
    32  )
    33  
    34  // NewConfigSetCmd is a command to set config fields from iotcl.
    35  func NewConfigSetCmd(client ioctl.Client) *cobra.Command {
    36  	use, _ := client.SelectTranslation(_configSetUse)
    37  	short, _ := client.SelectTranslation(_configSetUseCmdShorts)
    38  	long, _ := client.SelectTranslation(_configSetUseCmdLong)
    39  
    40  	cmd := &cobra.Command{
    41  		Use:       use,
    42  		Short:     short,
    43  		Long:      long,
    44  		ValidArgs: _validArgs,
    45  		Args: func(cmd *cobra.Command, args []string) error {
    46  			if len(args) != 2 {
    47  				return fmt.Errorf("accepts 2 arg(s), received %d\n"+
    48  					"Valid arg(s): %s", len(args), _validArgs)
    49  			}
    50  			return cobra.OnlyValidArgs(cmd, args[:1])
    51  		},
    52  		RunE: func(cmd *cobra.Command, args []string) error {
    53  			cmd.SilenceUsage = true
    54  			result, err := newInfo(client.Config(), client.ConfigFilePath()).set(args, client.Insecure(), client)
    55  			if err != nil {
    56  				return errors.Wrap(err, fmt.Sprintf("problem setting config fields %+v", args))
    57  			}
    58  			cmd.Println(result)
    59  			return nil
    60  		},
    61  	}
    62  
    63  	client.SetInsecureWithFlag(cmd.PersistentFlags().BoolVar)
    64  	return cmd
    65  }