github.com/henvic/wedeploycli@v1.7.6-0.20200319005353-3630f582f284/command/new/service/service.go (about) 1 package service 2 3 import ( 4 "context" 5 "fmt" 6 7 "github.com/henvic/wedeploycli/cmdflagsfromhost" 8 "github.com/henvic/wedeploycli/fancy" 9 10 "github.com/henvic/wedeploycli/color" 11 "github.com/henvic/wedeploycli/command/internal/we" 12 "github.com/henvic/wedeploycli/services" 13 "github.com/spf13/cobra" 14 ) 15 16 var image string 17 18 // Don't use this anywhere but on Cmd.RunE 19 var sh = cmdflagsfromhost.SetupHost{ 20 Pattern: cmdflagsfromhost.FullHostPattern, 21 22 Requires: cmdflagsfromhost.Requires{ 23 Project: true, 24 Auth: true, 25 }, 26 27 PromptMissingProject: true, 28 HideServicesPrompt: true, 29 } 30 31 // Cmd is the command for installing a new service 32 var Cmd = &cobra.Command{ 33 Use: "service", 34 Short: "Install new service", 35 // Don't use other run functions besides RunE here 36 // or fix NewCmd to call it correctly 37 RunE: runE, 38 Args: cobra.NoArgs, 39 } 40 41 func runE(cmd *cobra.Command, args []string) error { 42 if err := sh.Process(context.Background(), we.Context()); err != nil { 43 return err 44 } 45 46 return (&newService{}).run(sh.Project(), sh.Service(), sh.ServiceDomain()) 47 } 48 49 // Run command for creating a service 50 func Run(projectID, serviceID, serviceDomain string) error { 51 return (&newService{}).run(projectID, serviceID, serviceDomain) 52 } 53 54 type newService struct { 55 servicesClient *services.Client 56 } 57 58 func (n *newService) getOrSelectImageType() (string, error) { 59 if image != "" { 60 return image, nil 61 } 62 63 fmt.Println(fancy.Question("Type a service type")) 64 return fancy.Prompt() 65 } 66 67 func (n *newService) run(projectID, serviceID, serviceDomain string) error { 68 wectx := we.Context() 69 n.servicesClient = services.New(wectx) 70 71 var err error 72 73 if serviceID == "" { 74 fmt.Println(fancy.Question("Choose a Service ID") + " " + fancy.Tip("default: random")) 75 serviceID, err = fancy.Prompt() 76 77 if err != nil { 78 return err 79 } 80 } 81 82 fmt.Println("") 83 84 imageType, err := n.getOrSelectImageType() 85 86 if err != nil { 87 return err 88 } 89 90 body := services.CreateBody{ 91 ServiceID: serviceID, 92 Image: imageType, 93 } 94 95 s, err := n.servicesClient.Create(context.Background(), projectID, body) 96 97 if err != nil { 98 return err 99 } 100 101 fmt.Printf(color.Format(color.FgHiBlack, "Service \"")+ 102 "%s-%s.%s"+ 103 color.Format(color.FgHiBlack, "\" created on ")+ 104 wectx.InfrastructureDomain()+ 105 color.Format(color.FgHiBlack, ".")+ 106 "\n", 107 s.ServiceID, 108 projectID, 109 serviceDomain) 110 111 return nil 112 } 113 114 func init() { 115 Cmd.Flags().StringVar(&image, "image", "", "Image type") 116 117 sh.Init(Cmd) 118 }