2
0

target.go 6.0 KB

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