crowdsec/cmd/crowdsec-cli/climetrics/list.go
mmetc 8d96ddd48e
refact cscli metrics: fix lines between tables, skip wrapper api (#3137)
* fix empty line between metrics tables

* refact metrics tables: use go-pretty api directly

* lint
2024-07-17 12:30:52 +02:00

95 lines
2.2 KiB
Go

package climetrics
import (
"encoding/json"
"fmt"
"io"
"github.com/fatih/color"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/jedib0t/go-pretty/v6/text"
"github.com/spf13/cobra"
"github.com/crowdsecurity/go-cs-lib/maptools"
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/cstable"
)
func (cli *cliMetrics) list() error {
type metricType struct {
Type string `json:"type" yaml:"type"`
Title string `json:"title" yaml:"title"`
Description string `json:"description" yaml:"description"`
}
var allMetrics []metricType
ms := NewMetricStore()
for _, section := range maptools.SortedKeys(ms) {
title, description := ms[section].Description()
allMetrics = append(allMetrics, metricType{
Type: section,
Title: title,
Description: description,
})
}
outputFormat := cli.cfg().Cscli.Output
switch outputFormat {
case "human":
out := color.Output
t := cstable.New(out, cli.cfg().Cscli.Color).Writer
t.AppendHeader(table.Row{"Type", "Title", "Description"})
t.SetColumnConfigs([]table.ColumnConfig{
{
Name: "Type",
AlignHeader: text.AlignCenter,
},
{
Name: "Title",
AlignHeader: text.AlignCenter,
},
{
Name: "Description",
AlignHeader: text.AlignCenter,
WidthMax: 60,
WidthMaxEnforcer: text.WrapSoft,
},
})
t.Style().Options.SeparateRows = true
for _, metric := range allMetrics {
t.AppendRow(table.Row{metric.Type, metric.Title, metric.Description})
}
io.WriteString(out, t.Render() + "\n")
case "json":
x, err := json.MarshalIndent(allMetrics, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal metric types: %w", err)
}
fmt.Println(string(x))
default:
return fmt.Errorf("output format '%s' not supported for this command", outputFormat)
}
return nil
}
func (cli *cliMetrics) newListCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "List available types of metrics.",
Long: `List available types of metrics.`,
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.list()
},
}
return cmd
}