فهرست منبع

added colored output

Alexander Belanger 5 سال پیش
والد
کامیت
44ccf0b38f
11فایلهای تغییر یافته به همراه126 افزوده شده و 109 حذف شده
  1. 15 30
      cli/cmd/auth.go
  2. 8 7
      cli/cmd/config.go
  3. 11 11
      cli/cmd/connect.go
  4. 9 9
      cli/cmd/connect/kubeconfig.go
  5. 0 4
      cli/cmd/docker/agent.go
  6. 0 6
      cli/cmd/docker/porter.go
  7. 53 0
      cli/cmd/errors.go
  8. 9 27
      cli/cmd/project.go
  9. 4 4
      cli/cmd/root.go
  10. 13 8
      cli/cmd/server.go
  11. 4 3
      cli/cmd/utils/close.go

+ 15 - 30
cli/cmd/auth.go

@@ -4,7 +4,6 @@ import (
 	"context"
 	"fmt"
 	"os"
-	"strings"
 
 	"github.com/fatih/color"
 
@@ -25,7 +24,7 @@ var loginCmd = &cobra.Command{
 		err := login()
 
 		if err != nil {
-			fmt.Println("Error logging in:", err.Error())
+			color.Red("Error logging in:", err.Error())
 			os.Exit(1)
 		}
 	},
@@ -38,7 +37,7 @@ var registerCmd = &cobra.Command{
 		err := register()
 
 		if err != nil {
-			fmt.Println("Error registering:", err.Error())
+			color.Red("Error registering:", err.Error())
 			os.Exit(1)
 		}
 	},
@@ -48,10 +47,9 @@ var logoutCmd = &cobra.Command{
 	Use:   "logout",
 	Short: "Logs a user out of a given Porter server",
 	Run: func(cmd *cobra.Command, args []string) {
-		err := logout()
+		err := checkLoginAndRun(args, logout)
 
 		if err != nil {
-			fmt.Println("Error logging out:", err.Error())
 			os.Exit(1)
 		}
 	},
@@ -73,7 +71,14 @@ func init() {
 }
 
 func login() error {
-	host := getHost()
+	client := api.NewClient(getHost()+"/api", "cookie.json")
+	user, _ := client.AuthCheck(context.Background())
+
+	if user != nil {
+		color.Yellow("You are already logged in. If you'd like to log out, run \"porter auth logout\".")
+		return nil
+	}
+
 	var username, pw string
 
 	fmt.Println("Please log in with an email and password:")
@@ -90,8 +95,6 @@ func login() error {
 		return err
 	}
 
-	client := api.NewClient(host+"/api", "cookie.json")
-
 	_, err = client.Login(context.Background(), &api.LoginRequest{
 		Email:    username,
 		Password: pw,
@@ -101,25 +104,11 @@ func login() error {
 		return err
 	}
 
-	fmt.Println("Successfully logged in!")
+	color.New(color.FgGreen).Println("Successfully logged in!")
 
 	return nil
 }
 
-func check(client *api.Client) (*api.AuthCheckResponse, error) {
-	user, err := client.AuthCheck(context.Background())
-
-	if err != nil {
-		if strings.Contains(err.Error(), "403") {
-			color.Red("You are not logged in. Log in using \"porter auth login\"")
-		}
-
-		return nil, err
-	}
-
-	return user, nil
-}
-
 func register() error {
 	host := getHost()
 
@@ -148,23 +137,19 @@ func register() error {
 		return err
 	}
 
-	fmt.Printf("Created user with email %s and id %d\n", username, resp.ID)
+	color.New(color.FgGreen).Printf("Created user with email %s and id %d\n", username, resp.ID)
 
 	return nil
 }
 
-func logout() error {
-	host := getHost()
-
-	client := api.NewClient(host+"/api", "cookie.json")
-
+func logout(user *api.AuthCheckResponse, client *api.Client, args []string) error {
 	err := client.Logout(context.Background())
 
 	if err != nil {
 		return err
 	}
 
-	fmt.Println("Successfully logged out")
+	color.Green("Successfully logged out")
 
 	return nil
 }

+ 8 - 7
cli/cmd/config.go

@@ -1,10 +1,10 @@
 package cmd
 
 import (
-	"fmt"
 	"os"
 	"strconv"
 
+	"github.com/fatih/color"
 	"github.com/spf13/cobra"
 	"github.com/spf13/viper"
 )
@@ -28,14 +28,14 @@ var setProjectCmd = &cobra.Command{
 		projID, err := strconv.ParseUint(args[0], 10, 64)
 
 		if err != nil {
-			fmt.Printf("An error occurred: %v\n", err)
+			color.New(color.FgRed).Printf("An error occurred: %v\n", err)
 			os.Exit(1)
 		}
 
 		err = setProject(uint(projID))
 
 		if err != nil {
-			fmt.Printf("An error occurred: %v\n", err)
+			color.New(color.FgRed).Printf("An error occurred: %v\n", err)
 			os.Exit(1)
 		}
 	},
@@ -49,7 +49,7 @@ var setHostCmd = &cobra.Command{
 		err := setHost(args[0])
 
 		if err != nil {
-			fmt.Printf("An error occurred: %v\n", err)
+			color.New(color.FgRed).Printf("An error occurred: %v\n", err)
 			os.Exit(1)
 		}
 	},
@@ -64,14 +64,15 @@ func init() {
 
 func setProject(id uint) error {
 	viper.Set("project", id)
-	fmt.Printf("Set the current project id as %d\n", id)
+	color.New(color.FgGreen).Printf("Set the current project id as %d\n", id)
 	return viper.WriteConfig()
 }
 
 func setHost(host string) error {
 	viper.Set("host", host)
-	fmt.Printf("Set the current host as %s\n", host)
-	return viper.WriteConfig()
+	err := viper.WriteConfig()
+	color.New(color.FgGreen).Printf("Set the current host as %s\n", host)
+	return err
 }
 
 func getHost() string {

+ 11 - 11
cli/cmd/connect.go

@@ -1,9 +1,9 @@
 package cmd
 
 import (
-	"fmt"
 	"os"
 
+	"github.com/porter-dev/porter/cli/cmd/api"
 	"github.com/porter-dev/porter/cli/cmd/connect"
 	"github.com/spf13/cobra"
 )
@@ -23,18 +23,9 @@ var connectKubeconfigCmd = &cobra.Command{
 	Use:   "kubeconfig",
 	Short: "Uses the local kubeconfig to connect to a cluster",
 	Run: func(cmd *cobra.Command, args []string) {
-		host := getHost()
-		projectID := getProjectID()
-
-		err := connect.Kubeconfig(
-			kubeconfigPath,
-			*contexts,
-			host,
-			projectID,
-		)
+		err := checkLoginAndRun(args, runConnect)
 
 		if err != nil {
-			fmt.Printf("Error occurred: %v\n", err)
 			os.Exit(1)
 		}
 	},
@@ -73,3 +64,12 @@ func init() {
 		"the list of contexts to connect (defaults to the current context)",
 	)
 }
+
+func runConnect(_ *api.AuthCheckResponse, client *api.Client, _ []string) error {
+	return connect.Kubeconfig(
+		client,
+		kubeconfigPath,
+		*contexts,
+		getProjectID(),
+	)
+}

+ 9 - 9
cli/cmd/connect/kubeconfig.go

@@ -9,6 +9,7 @@ import (
 	"os"
 	"strings"
 
+	"github.com/fatih/color"
 	"github.com/porter-dev/porter/cli/cmd/utils"
 	"github.com/porter-dev/porter/internal/kubernetes/local"
 	gcpLocal "github.com/porter-dev/porter/internal/providers/gcp/local"
@@ -20,9 +21,9 @@ import (
 // Kubeconfig creates a service account for a project by parsing the local
 // kubeconfig and resolving actions that must be performed.
 func Kubeconfig(
+	client *api.Client,
 	kubeconfigPath string,
 	contexts []string,
-	host string,
 	projectID uint,
 ) error {
 	// if project ID is 0, ask the user to set the project ID or create a project
@@ -38,8 +39,6 @@ func Kubeconfig(
 	}
 
 	// send kubeconfig to client
-	client := api.NewClient(host+"/api", "cookie.json")
-
 	saCandidates, err := client.CreateProjectCandidates(
 		context.Background(),
 		projectID,
@@ -124,7 +123,7 @@ func Kubeconfig(
 		}
 
 		for _, cluster := range sa.Clusters {
-			fmt.Printf("created service account for cluster %s with id %d\n", cluster.Name, sa.ID)
+			color.New(color.FgGreen).Printf("created service account for cluster %s with id %d\n", cluster.Name, sa.ID)
 
 			// sanity check to ensure it's working
 			// namespaces, err := client.GetK8sNamespaces(
@@ -233,9 +232,10 @@ func resolveGCPKeyAction(endpoint string, clusterName string) (*models.ServiceAc
 		fmt.Sprintf(
 			`Detected GKE cluster in kubeconfig for the endpoint %s (%s). 
 Porter can set up a service account in your GCP project to connect to this cluster automatically.
-Would you like to proceed? [y/n] `,
-			endpoint,
+Would you like to proceed? %s `,
+			color.New(color.FgCyan).Sprintf("%s", endpoint),
 			clusterName,
+			color.New(color.FgCyan).Sprintf("[y/n]"),
 		),
 	)
 
@@ -259,7 +259,7 @@ Would you like to proceed? [y/n] `,
 		resp, err := agent.CreateServiceAccount(name)
 
 		if err != nil {
-			fmt.Println("Automatic creation failed.")
+			color.New(color.FgRed).Println("Automatic creation failed, manual input required.")
 			return resolveGCPKeyActionManual(endpoint, clusterName)
 		}
 
@@ -286,8 +286,8 @@ Would you like to proceed? [y/n] `,
 }
 
 func resolveGCPKeyActionManual(endpoint string, clusterName string) (*models.ServiceAccountAllActions, error) {
-	keyFileLocation, err := utils.PromptPlaintext(`Please provide the full path to a service account key file.
-Key file location: `)
+	keyFileLocation, err := utils.PromptPlaintext(fmt.Sprintf(`Please provide the full path to a service account key file.
+Key file location: `))
 
 	if err != nil {
 		return nil, err

+ 0 - 4
cli/cmd/docker/agent.go

@@ -147,8 +147,6 @@ type PullImageEvent struct {
 
 // PullImage pulls an image specified by the image string
 func (a *Agent) PullImage(image string) error {
-	fmt.Println("Pulling image:", image)
-
 	// pull the specified image
 	out, err := a.client.ImagePull(a.ctx, image, types.ImagePullOptions{})
 
@@ -170,8 +168,6 @@ func (a *Agent) PullImage(image string) error {
 		}
 	}
 
-	fmt.Println("Finished pulling image:", image)
-
 	return nil
 }
 

+ 0 - 6
cli/cmd/docker/porter.go

@@ -116,7 +116,6 @@ func StartPorter(opts *PorterStartOpts) (agent *Agent, id string, err error) {
 			return nil, "", err
 		}
 
-		fmt.Println("Waiting for postgres:latest to be healthy...")
 		err = agent.WaitForContainerHealthy(pgID, 10)
 
 		if err != nil {
@@ -151,7 +150,6 @@ func StartPorter(opts *PorterStartOpts) (agent *Agent, id string, err error) {
 		return nil, "", err
 	}
 
-	fmt.Println("Waiting for porter to be healthy...")
 	err = agent.WaitForContainerHealthy(id, 10)
 
 	if err != nil {
@@ -385,8 +383,6 @@ func (a *Agent) startPostgresContainer(id string) error {
 // StopPorterContainers finds all containers that were started via the CLI and stops them
 // -- removes the container if remove is set to true
 func (a *Agent) StopPorterContainers(remove bool) error {
-	fmt.Println("Stopping containers...")
-
 	containers, err := a.getContainersCreatedByStart()
 
 	if err != nil {
@@ -419,8 +415,6 @@ func (a *Agent) StopPorterContainers(remove bool) error {
 // and have a given process id and stops them -- removes the container if remove is set
 // to true
 func (a *Agent) StopPorterContainersWithProcessID(processID string, remove bool) error {
-	fmt.Println("Stopping containers...")
-
 	containers, err := a.getContainersCreatedByStart()
 
 	if err != nil {

+ 53 - 0
cli/cmd/errors.go

@@ -0,0 +1,53 @@
+package cmd
+
+import (
+	"context"
+	"strings"
+
+	"github.com/fatih/color"
+	"github.com/porter-dev/porter/cli/cmd/api"
+)
+
+func checkLoginAndRun(args []string, runner func(user *api.AuthCheckResponse, client *api.Client, args []string) error) error {
+	client := api.NewClient(getHost()+"/api", "cookie.json")
+
+	user, err := client.AuthCheck(context.Background())
+
+	if err != nil {
+		red := color.New(color.FgRed)
+
+		if strings.Contains(err.Error(), "403") {
+			red.Print("You are not logged in. Log in using \"porter auth login\"\n")
+			return nil
+		} else if strings.Contains(err.Error(), "connection refused") {
+			red.Printf("Unable to connect to the Porter server at %s\n", getHost())
+			red.Print("To set a different host, run \"porter config set-host [HOST]\"\n")
+			red.Print("To start a local server, run \"porter server start\"\n")
+			return nil
+		}
+
+		red.Printf("Error: %v\n", err.Error())
+		return err
+	}
+
+	err = runner(user, client, args)
+
+	if err != nil {
+		red := color.New(color.FgRed)
+
+		if strings.Contains(err.Error(), "403") {
+			red.Print("You do not have the necessary permissions to view this resource")
+			return nil
+		} else if strings.Contains(err.Error(), "connection refused") {
+			red.Printf("Unable to connect to the Porter server at %s\n", getHost())
+			red.Print("To set a different host, run \"porter config set-host [HOST]\"")
+			red.Print("To start a local server, run \"porter server start\"")
+			return nil
+		}
+
+		red.Printf("Error: %v\n", err.Error())
+		return err
+	}
+
+	return nil
+}

+ 9 - 27
cli/cmd/project.go

@@ -23,7 +23,7 @@ var createProjectCmd = &cobra.Command{
 	Args:  cobra.ExactArgs(1),
 	Short: "Creates a project with the authorized user as admin",
 	Run: func(cmd *cobra.Command, args []string) {
-		err := createProject(getHost(), args[0])
+		err := checkLoginAndRun(args, createProject)
 
 		if err != nil {
 			os.Exit(1)
@@ -35,7 +35,7 @@ var listProjectCmd = &cobra.Command{
 	Use:   "list",
 	Short: "Lists the projects for the logged in user",
 	Run: func(cmd *cobra.Command, args []string) {
-		err := listProjects(getHost())
+		err := checkLoginAndRun(args, listProjects)
 
 		if err != nil {
 			os.Exit(1)
@@ -47,7 +47,7 @@ var listProjectClustersCmd = &cobra.Command{
 	Use:   "clusters list",
 	Short: "Lists the linked clusters for a project",
 	Run: func(cmd *cobra.Command, args []string) {
-		err := listProjectClusters(getHost(), getProjectID())
+		err := checkLoginAndRun(args, listProjectClusters)
 
 		if err != nil {
 			os.Exit(1)
@@ -72,31 +72,21 @@ func init() {
 	projectCmd.AddCommand(listProjectClustersCmd)
 }
 
-func createProject(host string, name string) error {
-	client := api.NewClient(host+"/api", "cookie.json")
-
+func createProject(_ *api.AuthCheckResponse, client *api.Client, args []string) error {
 	resp, err := client.CreateProject(context.Background(), &api.CreateProjectRequest{
-		Name: name,
+		Name: args[0],
 	})
 
 	if err != nil {
 		return err
 	}
 
-	fmt.Printf("Created project with name %s and id %d\n", name, resp.ID)
+	color.New(color.FgGreen).Printf("Created project with name %s and id %d\n", args[0], resp.ID)
 
 	return setProject(resp.ID)
 }
 
-func listProjects(host string) error {
-	client := api.NewClient(host+"/api", "cookie.json")
-
-	user, err := check(client)
-
-	if err != nil {
-		return err
-	}
-
+func listProjects(user *api.AuthCheckResponse, client *api.Client, args []string) error {
 	projects, err := client.ListUserProjects(context.Background(), user.ID)
 
 	if err != nil {
@@ -123,16 +113,8 @@ func listProjects(host string) error {
 	return nil
 }
 
-func listProjectClusters(host string, projectID uint) error {
-	client := api.NewClient(host+"/api", "cookie.json")
-
-	_, err := check(client)
-
-	if err != nil {
-		return err
-	}
-
-	clusters, err := client.ListProjectClusters(context.Background(), projectID)
+func listProjectClusters(user *api.AuthCheckResponse, client *api.Client, args []string) error {
+	clusters, err := client.ListProjectClusters(context.Background(), getProjectID())
 
 	if err != nil {
 		return err

+ 4 - 4
cli/cmd/root.go

@@ -1,11 +1,11 @@
 package cmd
 
 import (
-	"fmt"
 	"io/ioutil"
 	"os"
 	"path/filepath"
 
+	"github.com/fatih/color"
 	"github.com/spf13/cobra"
 	"github.com/spf13/viper"
 	"k8s.io/client-go/util/homedir"
@@ -35,18 +35,18 @@ func Execute() {
 			err := ioutil.WriteFile(filepath.Join(home, ".porter", "porter.yaml"), []byte{}, 0644)
 
 			if err != nil {
-				fmt.Printf("%v\n", err)
+				color.New(color.FgRed).Printf("%v\n", err)
 				os.Exit(1)
 			}
 		} else {
 			// Config file was found but another error was produced
-			fmt.Printf("%v\n", err)
+			color.New(color.FgRed).Printf("%v\n", err)
 			os.Exit(1)
 		}
 	}
 
 	if err := rootCmd.Execute(); err != nil {
-		fmt.Println(err)
+		color.New(color.FgRed).Println(err)
 		os.Exit(1)
 	}
 }

+ 13 - 8
cli/cmd/server.go

@@ -4,6 +4,7 @@ import (
 	"fmt"
 	"os"
 
+	"github.com/fatih/color"
 	"github.com/porter-dev/porter/cli/cmd/docker"
 
 	"github.com/spf13/cobra"
@@ -34,13 +35,14 @@ var startCmd = &cobra.Command{
 		)
 
 		if err != nil {
-			fmt.Println("Error running start:", err.Error())
-			fmt.Println("Shutting down...")
+			red := color.New(color.FgRed)
+			red.Println("Error running start:", err.Error())
+			red.Println("Shutting down...")
 
 			err = stop()
 
 			if err != nil {
-				fmt.Println("Shutdown unsuccessful:", err.Error())
+				red.Println("Shutdown unsuccessful:", err.Error())
 			}
 
 			os.Exit(1)
@@ -53,7 +55,7 @@ var stopCmd = &cobra.Command{
 	Short: "Stops a Porter instance running on the Docker engine",
 	Run: func(cmd *cobra.Command, args []string) {
 		if err := stop(); err != nil {
-			fmt.Println("Shutdown unsuccessful:", err.Error())
+			color.New(color.FgRed).Println("Shutdown unsuccessful:", err.Error())
 			os.Exit(1)
 		}
 	},
@@ -116,10 +118,9 @@ func start(
 		return err
 	}
 
-	// fmt.Println("Spinning up the server...")
-	// time.Sleep(7 * time.Second)
-	// openBrowser(fmt.Sprintf("http://localhost:%d/login?email=%s", port, username))
-	fmt.Printf("Server ready: listening on localhost:%d\n", port)
+	green := color.New(color.FgGreen)
+
+	green.Printf("Server ready: listening on localhost:%d\n", port)
 
 	return setHost(fmt.Sprintf("http://localhost:%d", port))
 }
@@ -137,5 +138,9 @@ func stop() error {
 		return err
 	}
 
+	green := color.New(color.FgGreen)
+
+	green.Println("Successfully stopped the Porter server.")
+
 	return nil
 }

+ 4 - 3
cli/cmd/utils/close.go

@@ -1,10 +1,11 @@
 package utils
 
 import (
-	"fmt"
 	"os"
 	"os/signal"
 	"syscall"
+
+	"github.com/fatih/color"
 )
 
 func closeHandler(closer func() error) {
@@ -15,11 +16,11 @@ func closeHandler(closer func() error) {
 		err := closer()
 
 		if err == nil {
-			fmt.Println("shutdown successful")
+			color.New(color.FgRed).Println("shutdown successful")
 			os.Exit(0)
 		}
 
-		fmt.Printf("shutdown unsuccessful: %s\n", err.Error())
+		color.New(color.FgRed).Printf("shutdown unsuccessful: %s\n", err.Error())
 		os.Exit(1)
 	}()
 }