github.com/openshift/installer@v1.4.17/pkg/asset/installconfig/ibmcloud/ibmcloud.go (about)

     1  package ibmcloud
     2  
     3  import (
     4  	"fmt"
     5  	"sort"
     6  	"strings"
     7  
     8  	survey "github.com/AlecAivazis/survey/v2"
     9  	"github.com/AlecAivazis/survey/v2/core"
    10  	"github.com/pkg/errors"
    11  
    12  	"github.com/openshift/installer/pkg/types/ibmcloud"
    13  	"github.com/openshift/installer/pkg/types/ibmcloud/validation"
    14  )
    15  
    16  const (
    17  	createNew = "<create new>"
    18  )
    19  
    20  // Platform collects IBM Cloud-specific configuration.
    21  func Platform() (*ibmcloud.Platform, error) {
    22  	region, err := selectRegion()
    23  	if err != nil {
    24  		return nil, err
    25  	}
    26  
    27  	return &ibmcloud.Platform{
    28  		Region: region,
    29  	}, nil
    30  }
    31  
    32  func selectRegion() (string, error) {
    33  	longRegions := make([]string, 0, len(validation.Regions))
    34  	shortRegions := make([]string, 0, len(validation.Regions))
    35  	for id, location := range validation.Regions {
    36  		longRegions = append(longRegions, fmt.Sprintf("%s (%s)", id, location))
    37  		shortRegions = append(shortRegions, id)
    38  	}
    39  	var regionTransform survey.Transformer = func(ans interface{}) interface{} {
    40  		switch v := ans.(type) {
    41  		case core.OptionAnswer:
    42  			return core.OptionAnswer{Value: strings.SplitN(v.Value, " ", 2)[0], Index: v.Index}
    43  		case string:
    44  			return strings.SplitN(v, " ", 2)[0]
    45  		}
    46  		return ""
    47  	}
    48  
    49  	sort.Strings(longRegions)
    50  	sort.Strings(shortRegions)
    51  
    52  	defaultRegion := longRegions[0]
    53  
    54  	var selectedRegion string
    55  	err := survey.Ask([]*survey.Question{
    56  		{
    57  			Prompt: &survey.Select{
    58  				Message: "Region",
    59  				Help:    "The IBM Cloud region to be used for installation.",
    60  				Default: fmt.Sprintf("%s (%s)", defaultRegion, validation.Regions[defaultRegion]),
    61  				Options: longRegions,
    62  			},
    63  			Validate: survey.ComposeValidators(survey.Required, func(ans interface{}) error {
    64  				choice := regionTransform(ans).(core.OptionAnswer).Value
    65  				i := sort.SearchStrings(shortRegions, choice)
    66  				if i == len(shortRegions) || shortRegions[i] != choice {
    67  					return errors.Errorf("invalid region %q", choice)
    68  				}
    69  				return nil
    70  			}),
    71  			Transform: regionTransform,
    72  		},
    73  	}, &selectedRegion)
    74  	if err != nil {
    75  		return "", err
    76  	}
    77  	return selectedRegion, nil
    78  }