cmd.go 1.45 KB
Newer Older
1 2 3 4 5 6 7 8 9
package doc

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

	"github.com/olekukonko/tablewriter"
10
	"github.com/urfave/cli/v2"
Sabnock01's avatar
Sabnock01 committed
11 12

	"github.com/ethereum-optimism/optimism/op-service/metrics"
13 14
)

Sabnock01's avatar
Sabnock01 committed
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
type Metrics interface {
	Document() []metrics.DocumentedMetric
}

func NewSubcommands(m Metrics) cli.Commands {
	return cli.Commands{
		{
			Name:  "metrics",
			Usage: "Dumps a list of supported metrics to stdout",
			Flags: []cli.Flag{
				&cli.StringFlag{
					Name:  "format",
					Value: "markdown",
					Usage: "Output format (json|markdown)",
				},
			},
			Action: func(ctx *cli.Context) error {
				supportedMetrics := m.Document()
				format := ctx.String("format")

				if format != "markdown" && format != "json" {
					return fmt.Errorf("invalid format: %s", format)
				}

				if format == "json" {
					enc := json.NewEncoder(os.Stdout)
					return enc.Encode(supportedMetrics)
				}

				table := tablewriter.NewWriter(os.Stdout)
				table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
				table.SetCenterSeparator("|")
				table.SetAutoWrapText(false)
				table.SetHeader([]string{"Metric", "Description", "Labels", "Type"})
49
				data := make([][]string, 0, len(supportedMetrics))
Sabnock01's avatar
Sabnock01 committed
50 51 52 53 54 55 56
				for _, metric := range supportedMetrics {
					labels := strings.Join(metric.Labels, ",")
					data = append(data, []string{metric.Name, metric.Help, labels, metric.Type})
				}
				table.AppendBulk(data)
				table.Render()
				return nil
57 58
			},
		},
Sabnock01's avatar
Sabnock01 committed
59
	}
60
}