github.com/taubyte/tau-cli@v0.1.13-0.20240326000942-487f0d57edfc/cli/commands/resources/common/new.go (about)

     1  package resources
     2  
     3  import (
     4  	structureSpec "github.com/taubyte/go-specs/structure"
     5  	"github.com/taubyte/tau-cli/cli/common"
     6  	"github.com/taubyte/tau-cli/flags"
     7  	projectLib "github.com/taubyte/tau-cli/lib/project"
     8  	"github.com/urfave/cli/v2"
     9  )
    10  
    11  type New[T structureSpec.Structure] struct {
    12  	PromptsNew        func(ctx *cli.Context) (T, error)
    13  	TableConfirm      func(ctx *cli.Context, service T, prompt string) bool
    14  	PromptsCreateThis string
    15  	LibNew            func(service T) error
    16  	I18nCreated       func(name string)
    17  
    18  	UniqueFlags []cli.Flag
    19  }
    20  
    21  func (h *New[T]) Default() common.Command {
    22  	return common.Create(
    23  		&cli.Command{
    24  			Flags:  h.BasicFlags(),
    25  			Action: h.Action(),
    26  		},
    27  	)
    28  }
    29  
    30  func (h *New[T]) BasicFlags() []cli.Flag {
    31  	return append(append([]cli.Flag{
    32  		flags.Description,
    33  		flags.Tags,
    34  	},
    35  		// Insert unique flags between basic and Yes
    36  		h.UniqueFlags...),
    37  
    38  		flags.Yes,
    39  	)
    40  }
    41  
    42  func (h *New[T]) Action() func(ctx *cli.Context) error {
    43  	PanicIfMissingValue(h)
    44  
    45  	return func(ctx *cli.Context) error {
    46  		err := projectLib.ConfirmSelectedProject()
    47  		if err != nil {
    48  			return err
    49  		}
    50  
    51  		// Prompts.New will prompt for relative values for a new resource
    52  		resource, err := h.PromptsNew(ctx)
    53  		if err != nil {
    54  			return err
    55  		}
    56  
    57  		// Table.Confirm will display a table and wait for a confirmation based on the
    58  		// flag provided to `tau new -y` or offer a y\n selection
    59  		confirm := h.TableConfirm(ctx, resource, h.PromptsCreateThis)
    60  		if confirm {
    61  
    62  			// Lib.New handles the seer creation and id generation on selected project/application
    63  			err := h.LibNew(resource)
    64  			if err != nil {
    65  				return err
    66  			}
    67  
    68  			// I18n.Created will display a message that the resource of name has been created
    69  			h.I18nCreated(resource.GetName())
    70  
    71  			return nil
    72  		}
    73  
    74  		return nil
    75  	}
    76  }