table

package
v6.10.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 21, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package table provides a unified Table abstraction for formatting CLI output.

It replaces the scattered jsontabwriter + tabheaders + jsonpaths + resource2table packages with a single, cohesive API. Column definitions carry their own JSON extraction paths, default visibility, and optional format functions, eliminating the need for separate "preconverted" output paths.

Basic usage:

var datacenterCols = []table.Column{
    {Name: "DatacenterId", JSONPath: "id", Default: true},
    {Name: "Name", JSONPath: "properties.name", Default: true},
    {Name: "State", JSONPath: "metadata.state", Default: true},
    {Name: "Description", JSONPath: "properties.description"},
}

// In command execution:
cols, _ := c.Command.Command.Flags().GetStringSlice(constants.ArgCols)
return c.Out(table.Sprint(datacenterCols, dc, cols))

For resources with computed columns (replaces resource2table converters):

var clusterCols = []table.Column{
    {Name: "ClusterId", JSONPath: "id", Default: true},
    {Name: "MaintenanceWindow", Default: true, Format: func(item map[string]any) any {
        mw := table.Navigate(item, "properties.maintenanceWindow")
        if mw == nil { return "" }
        m := mw.(map[string]any)
        return fmt.Sprintf("%s %s", m["dayOfTheWeek"], m["time"])
    }},
}

For more control (editing cells, re-rendering with fresh data):

t := table.New(datacenterCols)
t.Extract(dc)
t.SetCell(0, "State", "AVAILABLE")
return c.Out(t.Render(table.ResolveCols(datacenterCols, userCols)))

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllCols

func AllCols(columns []Column) []string

AllCols returns the names of all defined columns.

func ColsMessage

func ColsMessage(columns []Column) string

ColsMessage generates help text for the --cols flag.

func DefaultCols

func DefaultCols(columns []Column) []string

DefaultCols returns the names of columns marked as Default.

func Navigate(m map[string]any, path string) any

Navigate extracts a nested value from a map using a dot-separated path. Useful inside FormatFunc implementations.

mw := table.Navigate(item, "properties.maintenanceWindow")

func ResolveCols

func ResolveCols(columns []Column, userCols []string) []string

ResolveCols resolves user-specified column names against defined columns. Handles the "all" keyword, case-insensitive matching, and falls back to defaults.

func Sprint

func Sprint(columns []Column, sourceData any, userCols []string, opts ...Option) (string, error)

Sprint is the single convenience entry point: Extract + Render → string.

cols, _ := c.Command.Command.Flags().GetStringSlice(constants.ArgCols)
return c.Out(table.Sprint(serverCols, data, cols, table.WithPrefix("items")))

Types

type BeforeRenderFunc

type BeforeRenderFunc func(t *Table, visibleCols []string) bool

BeforeRenderFunc is a hook called before rendering. If it returns false, rendering is suppressed (returns "", nil). This is used by the --wait flag to defer output until the resource reaches a terminal state.

var BeforeRender BeforeRenderFunc

BeforeRender is a package-level hook that, if set, is called before each Render invocation. Set this in init() or early startup to integrate with features like global --wait.

type Column

type Column struct {
	Name     string     // Display name / header (e.g., "ServerId", "Name", "State")
	JSONPath string     // Extraction path (e.g., "id", "properties.name", "metadata.state")
	Default  bool       // Show in default output (when user doesn't specify --cols)
	Format   FormatFunc // Optional: custom value transformer (overrides JSONPath extraction)
}

Column defines a single column in a table.

type FormatFunc

type FormatFunc func(item map[string]any) any

FormatFunc transforms a value for text display. It receives the full raw JSON item as a map, allowing access to any field. This enables computed columns like combining maintenance window day + time. Return nil or "" to indicate no value (column will be empty for this row).

type Option

type Option func(*Table)

Option configures Table creation.

func WithPrefix

func WithPrefix(prefix string) Option

WithPrefix sets the JSONPath prefix for navigating to the data array root. For example, "items" navigates into the "items" array of a list response.

type Table

type Table struct {
	// contains filtered or unexported fields
}

Table holds column definitions, extracted row data, and original source data. Create with New, populate with Extract, format with Render.

func New

func New(columns []Column, opts ...Option) *Table

New creates a Table with the given column definitions and options.

func (*Table) Extract

func (t *Table) Extract(sourceData any) error

Extract populates the table rows from source data (SDK struct, slice, or map). It stores the raw data for JSON output and extracts formatted rows for text output. Can be called multiple times to replace data (e.g., after re-fetching for --wait).

func (*Table) Raw

func (t *Table) Raw() any

Raw returns the original source data.

func (*Table) Render

func (t *Table) Render(visibleCols []string) (string, error)

Render produces the final formatted output string. It respects --output, --quiet, --query, and --no-headers flags. visibleCols specifies which columns to display; use ResolveCols to compute this from user-supplied --cols values.

If the package-level BeforeRender hook is set and returns false, output is suppressed (returns "", nil).

func (*Table) Rows

func (t *Table) Rows() []map[string]any

Rows returns the extracted row data. Each map represents a row with column names as keys.

func (*Table) SetCell

func (t *Table) SetCell(row int, col string, value any)

SetCell sets a value for a specific column in a specific row. Useful for post-extraction adjustments.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL