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

     1  package libraryPrompts
     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  	libraryI18n "github.com/taubyte/tau-cli/i18n/library"
    11  	libraryLib "github.com/taubyte/tau-cli/lib/library"
    12  	"github.com/taubyte/tau-cli/prompts"
    13  
    14  	"github.com/urfave/cli/v2"
    15  )
    16  
    17  /*
    18  GetOrSelect will try to get the library 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.Library, error) {
    22  	name := ctx.String(flags.Name.Name)
    23  
    24  	resources, err := libraryLib.ListResources()
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  
    29  	// Try to select a library
    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, libraryI18n.SelectPromptFailed(err)
    39  		}
    40  	}
    41  
    42  	if len(name) != 0 {
    43  		LName := strings.ToLower(name)
    44  		for _, library := range resources {
    45  			if LName == strings.ToLower(library.Name) {
    46  				return library, nil
    47  			}
    48  		}
    49  
    50  		return nil, fmt.Errorf(NotFound, name)
    51  	}
    52  
    53  	return nil, errors.New(NoneFound)
    54  }