github.com/saucelabs/saucectl@v0.175.1/internal/cmd/apit/setvariable.go (about)

     1  package apit
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  
     8  	"github.com/saucelabs/saucectl/internal/apitest"
     9  	cmds "github.com/saucelabs/saucectl/internal/cmd"
    10  	"github.com/saucelabs/saucectl/internal/http"
    11  	"github.com/saucelabs/saucectl/internal/segment"
    12  	"github.com/saucelabs/saucectl/internal/usage"
    13  	"github.com/spf13/cobra"
    14  	"golang.org/x/text/cases"
    15  	"golang.org/x/text/language"
    16  )
    17  
    18  func SetVariableCommand() *cobra.Command {
    19  	cmd := &cobra.Command{
    20  		Use:   "set-variable NAME VALUE [--project PROJECT_NAME]",
    21  		Short: "Set a vault variable",
    22  		Long: `Set/update a variable in a project's vault. If a variable NAME is already in the vault,
    23  the value will be updated, otherwise a new variable will be added. 
    24  
    25  Use [--project] to specify a project by its name or run without [--project] to choose from a list of projects.
    26  `,
    27  		SilenceUsage: true,
    28  		Args: func(cmd *cobra.Command, args []string) error {
    29  			if len(args) == 0 || args[0] == "" {
    30  				return errors.New("no variable name specified")
    31  			}
    32  			if len(args) == 1 || args[1] == "" {
    33  				return errors.New("no variable value specified")
    34  			}
    35  			return nil
    36  		},
    37  		PreRunE: func(cmd *cobra.Command, args []string) error {
    38  			err := http.CheckProxy()
    39  			if err != nil {
    40  				return fmt.Errorf("invalid HTTP_PROXY value")
    41  			}
    42  
    43  			tracker := segment.DefaultTracker
    44  
    45  			go func() {
    46  				tracker.Collect(
    47  					cases.Title(language.English).String(cmds.FullName(cmd)),
    48  					usage.Properties{}.SetFlags(cmd.Flags()),
    49  				)
    50  				_ = tracker.Close()
    51  			}()
    52  			return nil
    53  		},
    54  		RunE: func(cmd *cobra.Command, args []string) error {
    55  			name := args[0]
    56  			val := args[1]
    57  			updateVault := apitest.Vault{
    58  				Variables: []apitest.VaultVariable{
    59  					{
    60  						Name:  name,
    61  						Value: val,
    62  						Type:  "variable",
    63  					},
    64  				},
    65  				Snippets: map[string]string{},
    66  			}
    67  
    68  			err := apitesterClient.PutVault(context.Background(), selectedProject.Hooks[0].Identifier, updateVault)
    69  			if err != nil {
    70  				return err
    71  			}
    72  			return nil
    73  		},
    74  	}
    75  
    76  	return cmd
    77  }