github.com/verrazzano/verrazzano@v1.7.1/tools/charts-manager/vcm/cmd/helpers/command.go (about)

     1  // Copyright (c) 2023, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  
     4  package helpers
     5  
     6  import (
     7  	"fmt"
     8  	"strings"
     9  
    10  	"github.com/spf13/cobra"
    11  )
    12  
    13  const (
    14  	// ErrFormatMustSpecifyFlag format of error message when flag is supplied without a value.
    15  	ErrFormatMustSpecifyFlag = "must specify %s using --%s or -%s"
    16  	// ErrFormatNotEmpty format of error message when flag is supplied with empty value.
    17  	ErrFormatNotEmpty = "%s can not be empty"
    18  )
    19  
    20  // GetMandatoryStringFlagValueOrError returns a non empty value of a flag or an error if the flag is not declared or
    21  // the value is empty or nil.
    22  func GetMandatoryStringFlagValueOrError(cmd *cobra.Command, flagName string, flagShorthand string) (string, error) {
    23  	flagValue, err := cmd.PersistentFlags().GetString(flagName)
    24  	if err != nil {
    25  		return "", err
    26  	}
    27  
    28  	if flagValue == "" {
    29  		return "", fmt.Errorf(ErrFormatMustSpecifyFlag, flagName, flagName, flagShorthand)
    30  	}
    31  
    32  	if len(strings.TrimSpace(flagValue)) == 0 {
    33  		return "", fmt.Errorf(ErrFormatNotEmpty, flagName)
    34  	}
    35  
    36  	return flagValue, nil
    37  }