forked from sensu/sensu-go
/
list.go
119 lines (108 loc) · 2.71 KB
/
list.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package entity
import (
"errors"
"io"
"strings"
"github.com/sensu/sensu-go/cli"
"github.com/sensu/sensu-go/cli/commands/flags"
"github.com/sensu/sensu-go/cli/commands/helpers"
"github.com/sensu/sensu-go/cli/commands/timeutil"
"github.com/sensu/sensu-go/cli/elements/table"
"github.com/sensu/sensu-go/types"
"github.com/spf13/cobra"
)
// ListCommand defines new list entity command
func ListCommand(cli *cli.SensuCli) *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "list entities",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 0 {
_ = cmd.Help()
return errors.New("invalid argument(s) received")
}
namespace := cli.Config.Namespace()
if ok, _ := cmd.Flags().GetBool(flags.AllNamespaces); ok {
namespace = types.NamespaceTypeAll
}
opts, err := helpers.ListOptionsFromFlags(cmd.Flags())
if err != nil {
return err
}
// Fetch handlers from API
results, err := cli.Client.ListEntities(namespace, &opts)
if err != nil {
return err
}
// Print the results based on the user preferences
resources := []types.Resource{}
for i := range results {
resources = append(resources, &results[i])
}
return helpers.Print(cmd, cli.Config.Format(), printToTable, resources, results)
},
}
helpers.AddFormatFlag(cmd.Flags())
helpers.AddAllNamespace(cmd.Flags())
helpers.AddFieldSelectorFlag(cmd.Flags())
helpers.AddLabelSelectorFlag(cmd.Flags())
helpers.AddChunkSizeFlag(cmd.Flags())
return cmd
}
func printToTable(results interface{}, writer io.Writer) {
table := table.New([]*table.Column{
{
Title: "ID",
ColumnStyle: table.PrimaryTextStyle,
CellTransformer: func(data interface{}) string {
entity, ok := data.(types.Entity)
if !ok {
return cli.TypeError
}
return entity.Name
},
},
{
Title: "Class",
CellTransformer: func(data interface{}) string {
entity, ok := data.(types.Entity)
if !ok {
return cli.TypeError
}
return entity.EntityClass
},
},
{
Title: "OS",
CellTransformer: func(data interface{}) string {
entity, ok := data.(types.Entity)
if !ok {
return cli.TypeError
}
return entity.System.OS
},
},
{
Title: "Subscriptions",
CellTransformer: func(data interface{}) string {
entity, ok := data.(types.Entity)
if !ok {
return cli.TypeError
}
return strings.Join(entity.Subscriptions, ",")
},
},
{
Title: "Last Seen",
CellTransformer: func(data interface{}) string {
entity, ok := data.(types.Entity)
if !ok {
return cli.TypeError
}
return timeutil.HumanTimestamp(entity.LastSeen)
},
},
})
table.Render(writer, results)
}