Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add json output for profile list #5554

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 82 additions & 27 deletions cmd/minikube/cmd/config/profile_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@ limitations under the License.
package config

import (
"encoding/json"
"fmt"
"os"
"strconv"
"strings"

"k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/exit"
Expand All @@ -29,48 +31,101 @@ import (
"github.com/spf13/cobra"
)

var (
output string
)

var profileListCmd = &cobra.Command{
Use: "list",
Short: "Lists all minikube profiles.",
Long: "Lists all valid minikube profiles and detects all possible invalid profiles.",
Run: func(cmd *cobra.Command, args []string) {

var validData [][]string
switch strings.ToLower(output) {
case "json":
printProfilesJSON()
case "table":
printProfilesTable()
default:
exit.WithCodeT(exit.BadUsage, fmt.Sprintf("invalid output format: %s. Valid values: 'table', 'json'", output))
}

},
}

var printProfilesTable = func() {

table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Profile", "VM Driver", "NodeIP", "Node Port", "Kubernetes Version"})
table.SetAutoFormatHeaders(false)
table.SetBorders(tablewriter.Border{Left: true, Top: true, Right: true, Bottom: true})
table.SetCenterSeparator("|")
validProfiles, invalidProfiles, err := config.ListProfiles()
var validData [][]string

if len(validProfiles) == 0 || err != nil {
exit.UsageT("No minikube profile was found. You can create one using `minikube start`.")
}
for _, p := range validProfiles {
validData = append(validData, []string{p.Name, p.Config.MachineConfig.VMDriver, p.Config.KubernetesConfig.NodeIP, strconv.Itoa(p.Config.KubernetesConfig.NodePort), p.Config.KubernetesConfig.KubernetesVersion})
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Profile", "VM Driver", "NodeIP", "Node Port", "Kubernetes Version"})
table.SetAutoFormatHeaders(false)
table.SetBorders(tablewriter.Border{Left: true, Top: true, Right: true, Bottom: true})
table.SetCenterSeparator("|")
validProfiles, invalidProfiles, err := config.ListProfiles()

table.AppendBulk(validData)
table.Render()
if len(validProfiles) == 0 || err != nil {
exit.UsageT("No minikube profile was found. You can create one using `minikube start`.")
}
for _, p := range validProfiles {
validData = append(validData, []string{p.Name, p.Config.MachineConfig.VMDriver, p.Config.KubernetesConfig.NodeIP, strconv.Itoa(p.Config.KubernetesConfig.NodePort), p.Config.KubernetesConfig.KubernetesVersion})
}

if invalidProfiles != nil {
out.T(out.WarningType, "Found {{.number}} invalid profile(s) ! ", out.V{"number": len(invalidProfiles)})
for _, p := range invalidProfiles {
out.T(out.Empty, "\t "+p.Name)
}
out.T(out.Tip, "You can delete them using the following command(s): ")
for _, p := range invalidProfiles {
out.String(fmt.Sprintf("\t $ minikube delete -p %s \n", p.Name))
}
table.AppendBulk(validData)
table.Render()

if invalidProfiles != nil {
out.T(out.WarningType, "Found {{.number}} invalid profile(s) ! ", out.V{"number": len(invalidProfiles)})
for _, p := range invalidProfiles {
out.T(out.Empty, "\t "+p.Name)
}
if err != nil {
exit.WithCodeT(exit.Config, fmt.Sprintf("error loading profiles: %v", err))
out.T(out.Tip, "You can delete them using the following command(s): ")
for _, p := range invalidProfiles {
out.String(fmt.Sprintf("\t $ minikube delete -p %s \n", p.Name))
}
},

}

if err != nil {
exit.WithCodeT(exit.Config, fmt.Sprintf("error loading profiles: %v", err))
}

}

var printProfilesJSON = func() {
validProfiles, invalidProfiles, err := config.ListProfiles()

var valid []*config.Profile
var invalid []*config.Profile

if validProfiles != nil {
valid = validProfiles
} else {
valid = []*config.Profile{}
}

if invalidProfiles != nil {
invalid = invalidProfiles
} else {
invalid = []*config.Profile{}
}

var body = map[string]interface{}{}

if err == nil {
body["valid"] = valid
body["invalid"] = invalid
jsonString, _ := json.Marshal(body)
out.String(string(jsonString))
} else {
body["error"] = err
jsonString, _ := json.Marshal(body)
out.String(string(jsonString))
os.Exit(exit.Failure)
}
}

func init() {
profileListCmd.Flags().StringVarP(&output, "output", "o", "table", "The output format. One of 'json', 'table'")
ProfileCmd.AddCommand(profileListCmd)
}
38 changes: 37 additions & 1 deletion test/integration/functional_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -295,12 +295,48 @@ func validateLogsCmd(ctx context.Context, t *testing.T, profile string) {
}
}

// validateProfileCmd asserts basic "profile" command functionality
// validateProfileCmd asserts "profile" command functionality
func validateProfileCmd(ctx context.Context, t *testing.T, profile string) {
rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list"))
if err != nil {
t.Errorf("%s failed: %v", rr.Args, err)
}

// Table output
listLines := strings.Split(strings.TrimSpace(rr.Stdout.String()), "\n")
profileExists := false
for i := 3; i < (len(listLines) - 1); i++ {
profileLine := listLines[i]
if strings.Contains(profileLine, profile) {
profileExists = true
break
}
}
if !profileExists {
t.Errorf("%s failed: Missing profile '%s'. Got '\n%s\n'", rr.Args, profile, rr.Stdout.String())
}

// Json output
rr, err = Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "--output", "json"))
if err != nil {
t.Errorf("%s failed: %v", rr.Args, err)
}
var jsonObject map[string][]map[string]interface{}
err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
if err != nil {
t.Errorf("%s failed: %v", rr.Args, err)
}
validProfiles := jsonObject["valid"]
profileExists = false
for _, profileObject := range validProfiles {
if profileObject["Name"] == profile {
profileExists = true
break
}
}
if !profileExists {
t.Errorf("%s failed: Missing profile '%s'. Got '\n%s\n'", rr.Args, profile, rr.Stdout.String())
}
}

// validateServiceCmd asserts basic "service" command functionality
Expand Down