github.com/Azure/draft-classic@v0.16.0/cmd/draft/config_set.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"strings"
     7  
     8  	"github.com/spf13/cobra"
     9  )
    10  
    11  type configSetCmd struct {
    12  	out   io.Writer
    13  	args  []string
    14  	key   string
    15  	value string
    16  }
    17  
    18  func newConfigSetCmd(out io.Writer) *cobra.Command {
    19  	ccmd := &configSetCmd{
    20  		out:  out,
    21  		args: []string{"key", "value"},
    22  	}
    23  	cmd := &cobra.Command{
    24  		Use:   "set",
    25  		Short: "set global Draft configuration stored in $DRAFT_HOME/config.toml",
    26  		PreRunE: func(cmd *cobra.Command, args []string) error {
    27  			return ccmd.complete(args)
    28  		},
    29  		RunE: func(cmd *cobra.Command, args []string) error {
    30  			return ccmd.run()
    31  		},
    32  	}
    33  	return cmd
    34  }
    35  
    36  func (ccmd *configSetCmd) complete(args []string) error {
    37  	if err := validateConfigSetArgs(args, ccmd.args); err != nil {
    38  		return err
    39  	}
    40  	ccmd.key = args[0]
    41  	ccmd.value = args[1]
    42  	return nil
    43  }
    44  
    45  func (ccmd *configSetCmd) run() error {
    46  	if globalConfig == nil {
    47  		return fmt.Errorf("Draft configuration in $DRAFT_HOME/config.toml has not been initialized. Run draft init to get started.")
    48  	}
    49  	globalConfig[ccmd.key] = ccmd.value
    50  	return SaveConfig(globalConfig)
    51  }
    52  
    53  func validateConfigSetArgs(args, expectedArgs []string) error {
    54  	if len(args) == 1 {
    55  		for _, k := range configKeys {
    56  			if k.name == args[0] {
    57  				return fmt.Errorf("This command needs a value: %v", k.description)
    58  			}
    59  		}
    60  		return fmt.Errorf("This command needs a value. No help available for key '%v'", args[0])
    61  	}
    62  	if len(args) != len(expectedArgs) {
    63  		keys := []string{}
    64  		for _, k := range configKeys {
    65  			keys = append(keys, "  "+k.name+": "+k.description)
    66  		}
    67  		return fmt.Errorf("This command needs a key and a value to set it to. Supported keys:\n%v", strings.Join(keys, "\n"))
    68  	}
    69  	return nil
    70  }