target.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. package commands
  2. import (
  3. "bufio"
  4. "context"
  5. "fmt"
  6. "os"
  7. "sort"
  8. "strings"
  9. "text/tabwriter"
  10. "github.com/fatih/color"
  11. "github.com/google/uuid"
  12. api "github.com/porter-dev/porter/api/client"
  13. "github.com/porter-dev/porter/api/types"
  14. "github.com/porter-dev/porter/cli/cmd/config"
  15. "github.com/spf13/cobra"
  16. )
  17. func registerCommand_Target(cliConf config.CLIConfig) *cobra.Command {
  18. targetCmd := &cobra.Command{
  19. Use: "target",
  20. Aliases: []string{"targets"},
  21. Short: "Commands that control Porter target settings",
  22. }
  23. createTargetCmd := &cobra.Command{
  24. Use: "create --name [name]",
  25. Short: "Creates a deployment target",
  26. Run: func(cmd *cobra.Command, args []string) {
  27. err := checkLoginAndRunWithConfig(cmd, cliConf, args, createTarget)
  28. if err != nil {
  29. os.Exit(1)
  30. }
  31. },
  32. }
  33. var targetName string
  34. createTargetCmd.Flags().StringVar(&targetName, "name", "", "Name of deployment target")
  35. targetCmd.AddCommand(createTargetCmd)
  36. listTargetCmd := &cobra.Command{
  37. Use: "list",
  38. Short: "Lists the deployment targets for the logged in user",
  39. Long: `Lists the deployment targets in the project
  40. The following columns are returned:
  41. * ID: id of the deployment target
  42. * NAME: name of the deployment target
  43. * CLUSTER-ID: id of the cluster associated with the deployment target
  44. * DEFAULT: whether the deployment target is the default target for the cluster
  45. If the --preview flag is set, only deployment targets for preview environments will be returned.
  46. `,
  47. Run: func(cmd *cobra.Command, args []string) {
  48. err := checkLoginAndRunWithConfig(cmd, cliConf, args, listTargets)
  49. if err != nil {
  50. os.Exit(1)
  51. }
  52. },
  53. }
  54. var includePreviews bool
  55. listTargetCmd.Flags().BoolVar(&includePreviews, "preview", false, "List preview environments")
  56. targetCmd.AddCommand(listTargetCmd)
  57. deleteTargetCmd := &cobra.Command{
  58. Use: "delete",
  59. Short: "Deletes a deployment target",
  60. Long: `Deletes a deployment target in the project. Currently, this command only supports the deletion of preview environments.`,
  61. Run: func(cmd *cobra.Command, args []string) {
  62. err := checkLoginAndRunWithConfig(cmd, cliConf, args, deleteTarget)
  63. if err != nil {
  64. os.Exit(1)
  65. }
  66. },
  67. }
  68. deleteTargetCmd.Flags().StringVar(&targetName, "name", "", "Name of deployment target")
  69. deleteTargetCmd.Flags().BoolP("force", "f", false, "Force deletion without confirmation")
  70. deleteTargetCmd.MarkFlagRequired("name") // nolint:errcheck,gosec
  71. targetCmd.AddCommand(deleteTargetCmd)
  72. return targetCmd
  73. }
  74. func createTarget(ctx context.Context, _ *types.GetAuthenticatedUserResponse, client api.Client, cliConf config.CLIConfig, featureFlags config.FeatureFlags, cmd *cobra.Command, args []string) error {
  75. targetName, err := cmd.Flags().GetString("name")
  76. if err != nil {
  77. return fmt.Errorf("error finding name flag: %w", err)
  78. }
  79. resp, err := client.CreateDeploymentTarget(ctx, cliConf.Project, &types.CreateDeploymentTargetRequest{
  80. Name: targetName,
  81. ClusterId: cliConf.Cluster,
  82. })
  83. if err != nil {
  84. return err
  85. }
  86. _, _ = color.New(color.FgGreen).Printf("Created target with name %s and id %s\n", targetName, resp.DeploymentTargetID)
  87. return nil
  88. }
  89. func listTargets(ctx context.Context, user *types.GetAuthenticatedUserResponse, client api.Client, cliConf config.CLIConfig, featureFlags config.FeatureFlags, cmd *cobra.Command, args []string) error {
  90. includePreviews, err := cmd.Flags().GetBool("preview")
  91. if err != nil {
  92. return fmt.Errorf("error finding preview flag: %w", err)
  93. }
  94. resp, err := client.ListDeploymentTargets(ctx, cliConf.Project, includePreviews)
  95. if err != nil {
  96. return err
  97. }
  98. if resp == nil {
  99. return nil
  100. }
  101. targets := *resp
  102. sort.Slice(targets.DeploymentTargets, func(i, j int) bool {
  103. if targets.DeploymentTargets[i].ClusterID != targets.DeploymentTargets[j].ClusterID {
  104. return targets.DeploymentTargets[i].ClusterID < targets.DeploymentTargets[j].ClusterID
  105. }
  106. return targets.DeploymentTargets[i].Name < targets.DeploymentTargets[j].Name
  107. })
  108. w := new(tabwriter.Writer)
  109. w.Init(os.Stdout, 3, 8, 0, '\t', tabwriter.AlignRight)
  110. if includePreviews {
  111. fmt.Fprintf(w, "%s\t%s\t%s\n", "ID", "NAME", "CLUSTER-ID")
  112. for _, target := range targets.DeploymentTargets {
  113. fmt.Fprintf(w, "%s\t%s\t%d\n", target.ID, target.Name, target.ClusterID)
  114. }
  115. } else {
  116. fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", "ID", "NAME", "CLUSTER-ID", "DEFAULT")
  117. for _, target := range targets.DeploymentTargets {
  118. fmt.Fprintf(w, "%s\t%s\t%d\t%s\n", target.ID, target.Name, target.ClusterID, checkmark(target.IsDefault))
  119. }
  120. }
  121. _ = w.Flush()
  122. return nil
  123. }
  124. func deleteTarget(ctx context.Context, _ *types.GetAuthenticatedUserResponse, client api.Client, cliConf config.CLIConfig, featureFlags config.FeatureFlags, cmd *cobra.Command, args []string) error {
  125. name, err := cmd.Flags().GetString("name")
  126. if err != nil {
  127. return fmt.Errorf("error finding name flag: %w", err)
  128. }
  129. if name == "" {
  130. return fmt.Errorf("name flag must be set")
  131. }
  132. force, err := cmd.Flags().GetBool("force")
  133. if err != nil {
  134. return fmt.Errorf("error finding force flag: %w", err)
  135. }
  136. var confirmed bool
  137. if !force {
  138. confirmed, err = confirmAction(fmt.Sprintf("Are you sure you want to delete target '%s'?", name))
  139. if err != nil {
  140. return fmt.Errorf("error confirming action: %w", err)
  141. }
  142. }
  143. if !confirmed && !force {
  144. color.New(color.FgYellow).Println("Deletion aborted") // nolint:errcheck,gosec
  145. return nil
  146. }
  147. // assume deletion will be for preview environments only for now
  148. dts, err := client.ListDeploymentTargets(ctx, cliConf.Project, true)
  149. if err != nil {
  150. return fmt.Errorf("error listing targets: %w", err)
  151. }
  152. var targetID uuid.UUID
  153. for _, dt := range dts.DeploymentTargets {
  154. if dt.Name == name {
  155. targetID = dt.ID
  156. break
  157. }
  158. }
  159. if targetID == uuid.Nil {
  160. return fmt.Errorf("target '%s' not found", name)
  161. }
  162. err = client.DeleteDeploymentTarget(ctx, cliConf.Project, targetID)
  163. if err != nil {
  164. return fmt.Errorf("error deleting target: %w", err)
  165. }
  166. color.New(color.FgGreen).Printf("Deleted target '%s'\n", name) // nolint:errcheck,gosec
  167. return nil
  168. }
  169. func confirmAction(prompt string) (bool, error) {
  170. reader := bufio.NewReader(os.Stdin)
  171. fmt.Printf("%s [Y/n]: ", prompt)
  172. response, err := reader.ReadString('\n')
  173. if err != nil {
  174. return false, fmt.Errorf("error reading input: %w", err)
  175. }
  176. response = strings.TrimSpace(response)
  177. confirmed := strings.ToLower(response) == "y" || response == ""
  178. return confirmed, nil
  179. }
  180. func checkmark(b bool) string {
  181. if b {
  182. return "✓"
  183. }
  184. return ""
  185. }