1
0
Fork 0
mirror of https://github.com/moby/moby.git synced 2022-11-09 12:21:53 -05:00
moby--moby/api/client/container/top.go
Yong Tang 0f38669267 Use spf13/cobra for docker top
This fix is part of the effort to convert commands to spf13/cobra #23211.

Thif fix coverted command `docker top` to use spf13/cobra

Signed-off-by: Yong Tang <yong.tang.github@outlook.com>
2016-06-06 06:38:43 -07:00

59 lines
1.2 KiB
Go

package container
import (
"fmt"
"strings"
"text/tabwriter"
"golang.org/x/net/context"
"github.com/docker/docker/api/client"
"github.com/docker/docker/cli"
"github.com/spf13/cobra"
)
type topOptions struct {
container string
args []string
}
// NewTopCommand creats a new cobra.Command for `docker top`
func NewTopCommand(dockerCli *client.DockerCli) *cobra.Command {
var opts topOptions
cmd := &cobra.Command{
Use: "top CONTAINER [ps OPTIONS]",
Short: "Display the running processes of a container",
Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.container = args[0]
opts.args = args[1:]
return runTop(dockerCli, &opts)
},
}
cmd.SetFlagErrorFunc(flagErrorFunc)
flags := cmd.Flags()
flags.SetInterspersed(false)
return cmd
}
func runTop(dockerCli *client.DockerCli, opts *topOptions) error {
ctx := context.Background()
procList, err := dockerCli.Client().ContainerTop(ctx, opts.container, opts.args)
if err != nil {
return err
}
w := tabwriter.NewWriter(dockerCli.Out(), 20, 1, 3, ' ', 0)
fmt.Fprintln(w, strings.Join(procList.Titles, "\t"))
for _, proc := range procList.Processes {
fmt.Fprintln(w, strings.Join(proc, "\t"))
}
w.Flush()
return nil
}