github.com/taubyte/tau-cli@v0.1.13-0.20240326000942-487f0d57edfc/prompts/service/select.go (about)

     1  package servicePrompts
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"strings"
     7  
     8  	structureSpec "github.com/taubyte/go-specs/structure"
     9  	"github.com/taubyte/tau-cli/flags"
    10  	serviceI18n "github.com/taubyte/tau-cli/i18n/service"
    11  	serviceLib "github.com/taubyte/tau-cli/lib/service"
    12  	"github.com/taubyte/tau-cli/prompts"
    13  
    14  	"github.com/urfave/cli/v2"
    15  )
    16  
    17  /*
    18  GetOrSelect will try to get the service from a name flag
    19  if it is not set in the flag it will offer a selection menu
    20  */
    21  func GetOrSelect(ctx *cli.Context) (*structureSpec.Service, error) {
    22  	name := ctx.String(flags.Name.Name)
    23  
    24  	resources, err := serviceLib.ListResources()
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  
    29  	// Try to select a service
    30  	if len(name) == 0 && len(resources) > 0 {
    31  		options := make([]string, len(resources))
    32  		for idx, p := range resources {
    33  			options[idx] = p.Name
    34  		}
    35  
    36  		name, err = prompts.SelectInterface(options, SelectPrompt, options[0])
    37  		if err != nil {
    38  			return nil, serviceI18n.SelectPromptFailed(err)
    39  		}
    40  	}
    41  
    42  	if len(name) != 0 {
    43  		nameLC := strings.ToLower(name)
    44  
    45  		for _, service := range resources {
    46  			if nameLC == strings.ToLower(service.Name) {
    47  				return service, nil
    48  			}
    49  		}
    50  
    51  		return nil, fmt.Errorf(NotFound, name)
    52  	}
    53  
    54  	return nil, errors.New(NoneFound)
    55  }