gogo-cobra

Kubectl like output format for my cobra project


I am trying to develop a command line tool using cobra. I would like to provide flags like kubectl offers to its users. As a first step I would like to implement kubectl standard format like this:

kubectl get pods -n mpo
NAME                                                    READY   STATUS      RESTARTS   AGE
my-deployment-5588bf7844-n2nw7                        1/1     Running     0          3d
my-deployment-5588bf7844-qcpsl                        1/1     Running     0          3d

How do I implement an output format like this?


Solution

  • You can format strings in Go with padding on either side. See this post for example.

    Below, I format all strings with right padding. The first column gets 40 char padding as the pod name might be long. The other columns get only 10 chars padding.

    fmt.Printf("%-40s %-10s %-10s\n", "NAME", "READY", "STATUS")
    fmt.Printf("%-40s %-10s %-10s\n", "my-deployment-5588bf7844-n2nw7", " 1/1", "Running")
    fmt.Printf("%-40s %-10s %-10s\n", "my-deployment-5588bf7844-n2nw7", " 1/1", "Running")
    }
    

    https://play.golang.com/p/8ZZH5XmqTpR

    That said, using tabwriter, may be another, potentially even better option.

    // io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint
    w := tabwriter.NewWriter(os.Stdout, 10, 1, 5, ' ', 0)
    fmt.Fprintln(w, "NAME\tREADY\tSTATUS")
    fmt.Fprintln(w, "my-deployment-5588bf7844-n2nw7\t1/1\tRunning")
    fmt.Fprintln(w, "my-deployment-5588bf7844-n2nw7\t1/1\tRunning")
    w.Flush()
    

    https://play.golang.com/p/QS01cuR34Jx