output

package
v0.0.0-...-0bc6d30 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2025 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package output provides output formatting for CLI command responses.

The output package supports multiple format types including JSON, YAML, tables, CSV, and custom templates with Go template expressions. Formatters can be configured through OpenAPI x-cli-output extensions or runtime flags.

Key Features

  • Multiple output formats (JSON, YAML, table, CSV, template)
  • Pretty-printing and colored output support
  • Data transformation via JQ-like expressions
  • Field selection and column configuration
  • Template-based custom formatting

Example Usage

manager := output.NewManager()
err := manager.Format(os.Stdout, data, "json")

OpenAPI Integration

Output behavior can be controlled via x-cli-output extensions:

x-cli-output:
  format: table
  fields: [id, name, status]
  transform: .results[]

Index

Constants

This section is empty.

Variables

View Source
var DefaultManager = NewManager()

DefaultManager is the global default output manager.

View Source
var DefaultTemplates = func() *TemplateLibrary {
	lib := NewTemplateLibrary()

	lib.Add(NewMessageTemplate(
		"created",
		"{resource_type} '{name}' created successfully",
		"Resource creation success message",
	))

	lib.Add(NewMessageTemplate(
		"updated",
		"{resource_type} '{name}' updated successfully",
		"Resource update success message",
	))

	lib.Add(NewMessageTemplate(
		"deleted",
		"{resource_type} '{name}' deleted successfully",
		"Resource deletion success message",
	))

	lib.Add(NewMessageTemplate(
		"not_found",
		"{resource_type} '{name}' not found",
		"Resource not found error message",
	))

	lib.Add(NewMessageTemplate(
		"operation_pending",
		"{operation} is in progress for '{name}'",
		"Async operation pending message",
	))

	lib.Add(NewMessageTemplate(
		"operation_complete",
		"{operation} completed successfully for '{name}'",
		"Async operation complete message",
	))

	lib.Add(NewMessageTemplate(
		"operation_failed",
		"{operation} failed for '{name}': {error}",
		"Async operation failed message",
	))

	return lib
}()

DefaultTemplates provides commonly used message templates.

Functions

func Format

func Format(w io.Writer, data interface{}, format string) error

Format formats data using the default manager.

func FormatResult

func FormatResult(w io.Writer, result *Result, format string) error

FormatResult formats a Result using the default manager.

func Print

func Print(data interface{}, format string) error

Print formats and prints data to stdout using the default manager.

func PrintError

func PrintError(err error, format string) error

PrintError formats and prints an error to stderr using the default manager.

func PrintResult

func PrintResult(result *Result, format string) error

PrintResult formats and prints a Result to stdout using the default manager.

func PrintSuccess

func PrintSuccess(message string, data interface{}, format string) error

PrintSuccess formats and prints a success message to stdout using the default manager.

func RenderCreated

func RenderCreated(resourceType, name string) string

RenderCreated renders a resource creation message.

func RenderDeleted

func RenderDeleted(resourceType, name string) string

RenderDeleted renders a resource deletion message.

func RenderNotFound

func RenderNotFound(resourceType, name string) string

RenderNotFound renders a resource not found message.

func RenderUpdated

func RenderUpdated(resourceType, name string) string

RenderUpdated renders a resource update message.

Types

type FormatConfig

type FormatConfig struct {
	// Output configuration from OpenAPI spec
	OutputConfig *openapi.CLIOutput

	// Pretty enables pretty-printing (for JSON/YAML)
	Pretty bool

	// Colors enables colored output
	Colors bool

	// Compact reduces whitespace in output
	Compact bool

	// ShowHeaders controls header display (for tables)
	ShowHeaders bool

	// SortBy specifies the field to sort by (for tables)
	SortBy string

	// SortAsc controls sort direction
	SortAsc bool

	// MaxWidth is the maximum width for output (for tables)
	MaxWidth int

	// AdditionalData contains extra data for template interpolation
	AdditionalData map[string]interface{}
}

FormatConfig contains configuration options for formatting output.

func NewFormatConfig

func NewFormatConfig() *FormatConfig

NewFormatConfig creates a new FormatConfig with sensible defaults.

func (*FormatConfig) WithColors

func (c *FormatConfig) WithColors(colors bool) *FormatConfig

WithColors sets the colors option.

func (*FormatConfig) WithCompact

func (c *FormatConfig) WithCompact(compact bool) *FormatConfig

WithCompact sets the compact option.

func (*FormatConfig) WithData

func (c *FormatConfig) WithData(key string, value interface{}) *FormatConfig

WithData adds additional data for template interpolation.

func (*FormatConfig) WithMaxWidth

func (c *FormatConfig) WithMaxWidth(width int) *FormatConfig

WithMaxWidth sets the maximum width for output.

func (*FormatConfig) WithOutputConfig

func (c *FormatConfig) WithOutputConfig(cfg *openapi.CLIOutput) *FormatConfig

WithOutputConfig sets the OpenAPI output configuration.

func (*FormatConfig) WithPretty

func (c *FormatConfig) WithPretty(pretty bool) *FormatConfig

WithPretty sets the pretty-printing option.

func (*FormatConfig) WithSorting

func (c *FormatConfig) WithSorting(field string, asc bool) *FormatConfig

WithSorting sets the sorting options.

type Formatter

type Formatter interface {
	// Format formats the given data according to the formatter's rules
	// and writes the output to the provided writer.
	Format(w io.Writer, data interface{}, config *FormatConfig) error

	// Name returns the name of the formatter (e.g., "json", "yaml", "table").
	Name() string

	// Supports returns true if the formatter can handle the given data type.
	Supports(data interface{}) bool
}

Formatter is the interface that all output formatters must implement. It provides a unified way to format and display CLI command output in various formats.

type JSONFormatter

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

JSONFormatter formats output as JSON with optional pretty printing.

func NewJSONFormatter

func NewJSONFormatter() *JSONFormatter

NewJSONFormatter creates a new JSON formatter.

func (*JSONFormatter) Format

func (f *JSONFormatter) Format(w io.Writer, data interface{}, config *FormatConfig) error

Format formats the data as JSON and writes it to the writer.

func (*JSONFormatter) FormatEmpty

func (f *JSONFormatter) FormatEmpty(w io.Writer, message string, config *FormatConfig) error

FormatEmpty formats an empty result as JSON.

func (*JSONFormatter) FormatError

func (f *JSONFormatter) FormatError(w io.Writer, err error, config *FormatConfig) error

FormatError formats an error as JSON.

func (*JSONFormatter) FormatResult

func (f *JSONFormatter) FormatResult(w io.Writer, result *Result, config *FormatConfig) error

FormatResult formats a Result object as JSON.

func (*JSONFormatter) Name

func (f *JSONFormatter) Name() string

Name returns the formatter name.

func (*JSONFormatter) SetIndent

func (f *JSONFormatter) SetIndent(indent string) *JSONFormatter

SetIndent sets the indentation string for pretty printing.

func (*JSONFormatter) Supports

func (f *JSONFormatter) Supports(data interface{}) bool

Supports returns true if the formatter can handle the given data type. JSON formatter can handle any data type.

type Manager

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

Manager manages output formatting and provides high-level formatting methods.

func NewManager

func NewManager() *Manager

NewManager creates a new output manager with default formatters.

func (*Manager) ApplyOutputRules

func (m *Manager) ApplyOutputRules(config *openapi.CLIOutput) *FormatConfig

ApplyOutputRules applies output configuration rules from OpenAPI spec.

func (*Manager) Format

func (m *Manager) Format(w io.Writer, data interface{}, format string) error

Format formats data using the specified format.

func (*Manager) FormatEmpty

func (m *Manager) FormatEmpty(w io.Writer, message string, format string) error

FormatEmpty formats an empty result with an optional message.

func (*Manager) FormatError

func (m *Manager) FormatError(w io.Writer, err error, format string) error

FormatError formats an error.

func (*Manager) FormatResult

func (m *Manager) FormatResult(w io.Writer, result *Result, format string) error

FormatResult formats a Result object.

func (*Manager) FormatSuccess

func (m *Manager) FormatSuccess(w io.Writer, message string, data interface{}, format string) error

FormatSuccess formats a success message with optional data.

func (*Manager) FormatWithConfig

func (m *Manager) FormatWithConfig(w io.Writer, data interface{}, format string, config *FormatConfig) error

FormatWithConfig formats data using the specified format and config.

func (*Manager) FormatWithTemplate

func (m *Manager) FormatWithTemplate(w io.Writer, data interface{}, messageTemplate string, templateData map[string]interface{}, format string) error

FormatWithTemplate formats data and includes a rendered message template.

func (*Manager) GetConfig

func (m *Manager) GetConfig() *FormatConfig

GetConfig returns the current format configuration.

func (*Manager) GetFormatter

func (m *Manager) GetFormatter(name string) (Formatter, error)

GetFormatter returns a formatter by name.

func (*Manager) GetSupportedFormats

func (m *Manager) GetSupportedFormats() []string

GetSupportedFormats returns a list of all supported format names.

func (*Manager) IsFormatSupported

func (m *Manager) IsFormatSupported(format string) bool

IsFormatSupported checks if a format is supported.

func (*Manager) Print

func (m *Manager) Print(data interface{}, format string) error

Print is a convenience method to format and print to stdout.

func (*Manager) PrintError

func (m *Manager) PrintError(err error, format string) error

PrintError is a convenience method to format and print an error to stderr.

func (*Manager) PrintResult

func (m *Manager) PrintResult(result *Result, format string) error

PrintResult is a convenience method to format and print a Result to stdout.

func (*Manager) PrintSuccess

func (m *Manager) PrintSuccess(message string, data interface{}, format string) error

PrintSuccess is a convenience method to format and print a success message to stdout.

func (*Manager) RegisterFormatter

func (m *Manager) RegisterFormatter(formatter Formatter)

RegisterFormatter registers a new formatter.

func (*Manager) RenderErrorMessage

func (m *Manager) RenderErrorMessage(outputConfig *openapi.CLIOutput, data map[string]interface{}) (string, error)

RenderErrorMessage renders an error message from output config.

func (*Manager) RenderMessage

func (m *Manager) RenderMessage(template string, data map[string]interface{}) (string, error)

RenderMessage renders a message template with the given data.

func (*Manager) RenderSuccessMessage

func (m *Manager) RenderSuccessMessage(outputConfig *openapi.CLIOutput, data map[string]interface{}) (string, error)

RenderSuccessMessage renders a success message from output config.

func (*Manager) SelectFormat

func (m *Manager) SelectFormat(explicitFormat string, outputConfig *openapi.CLIOutput, globalConfig *openapi.OutputSettings) string

SelectFormat selects the appropriate format based on configuration and flags. Priority: explicit format > output config > global config > default

func (*Manager) SetConfig

func (m *Manager) SetConfig(config *FormatConfig)

SetConfig sets the format configuration.

func (*Manager) SetDefaultFormat

func (m *Manager) SetDefaultFormat(format string)

SetDefaultFormat sets the default output format.

func (*Manager) ValidateFormat

func (m *Manager) ValidateFormat(format string, data interface{}) error

ValidateFormat validates if the format is supported and can handle the data.

type MessageTemplate

type MessageTemplate struct {
	Name        string
	Template    string
	Description string
	// contains filtered or unexported fields
}

MessageTemplate represents a reusable message template.

func NewMessageTemplate

func NewMessageTemplate(name, template, description string) *MessageTemplate

NewMessageTemplate creates a new message template.

func (*MessageTemplate) Precompile

func (m *MessageTemplate) Precompile(env map[string]interface{}) error

Precompile precompiles the template expressions.

func (*MessageTemplate) Render

func (m *MessageTemplate) Render(data map[string]interface{}) (string, error)

Render renders the template with the given data.

type Result

type Result struct {
	// Success indicates whether the operation was successful
	Success bool

	// Data is the actual result data
	Data interface{}

	// Error is the error message if Success is false
	Error string

	// Message is an optional message to display
	Message string

	// Metadata contains additional information about the result
	Metadata map[string]interface{}
}

Result represents a formatted output result with success/error information.

func NewErrorResult

func NewErrorResult(err error) *Result

NewErrorResult creates an error result.

func NewResult

func NewResult(data interface{}) *Result

NewResult creates a successful result.

func (*Result) WithMessage

func (r *Result) WithMessage(msg string) *Result

WithMessage sets the result message.

func (*Result) WithMetadata

func (r *Result) WithMetadata(key string, value interface{}) *Result

WithMetadata adds metadata to the result.

type TableFormatter

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

TableFormatter formats output as a table using pterm.

func NewTableFormatter

func NewTableFormatter() *TableFormatter

NewTableFormatter creates a new table formatter.

func (*TableFormatter) Format

func (f *TableFormatter) Format(w io.Writer, data interface{}, config *FormatConfig) error

Format formats the data as a table and writes it to the writer.

func (*TableFormatter) FormatEmpty

func (f *TableFormatter) FormatEmpty(w io.Writer, message string, config *FormatConfig) error

FormatEmpty formats an empty result message.

func (*TableFormatter) FormatError

func (f *TableFormatter) FormatError(w io.Writer, err error, config *FormatConfig) error

FormatError formats an error as a table.

func (*TableFormatter) FormatResult

func (f *TableFormatter) FormatResult(w io.Writer, result *Result, config *FormatConfig) error

FormatResult formats a Result object as a table.

func (*TableFormatter) Name

func (f *TableFormatter) Name() string

Name returns the formatter name.

func (*TableFormatter) Supports

func (f *TableFormatter) Supports(data interface{}) bool

Supports returns true if the formatter can handle the given data type. Table formatter supports slices, arrays, and maps.

type TemplateEngine

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

TemplateEngine provides message template rendering with variable interpolation. It supports both simple variable substitution (e.g., {name}) and expr expressions.

func NewTemplateEngine

func NewTemplateEngine() *TemplateEngine

NewTemplateEngine creates a new template engine.

func (*TemplateEngine) ClearCache

func (t *TemplateEngine) ClearCache()

ClearCache clears the compiled expression cache.

func (*TemplateEngine) PrecompileTemplate

func (t *TemplateEngine) PrecompileTemplate(template string, env map[string]interface{}) error

PrecompileTemplate precompiles a template's expr expressions.

func (*TemplateEngine) Render

func (t *TemplateEngine) Render(template string, data map[string]interface{}) (string, error)

Render renders a template string with the given data. Supports two template syntaxes:

  1. Simple variables: {variable_name} or {object.field}
  2. Expr expressions: {{expression}}

func (*TemplateEngine) RenderError

func (t *TemplateEngine) RenderError(template string, data map[string]interface{}) (string, error)

RenderError renders an error message template.

func (*TemplateEngine) RenderSuccess

func (t *TemplateEngine) RenderSuccess(template string, data map[string]interface{}) (string, error)

RenderSuccess renders a success message template.

type TemplateLibrary

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

TemplateLibrary manages a collection of message templates.

func NewTemplateLibrary

func NewTemplateLibrary() *TemplateLibrary

NewTemplateLibrary creates a new template library.

func (*TemplateLibrary) Add

func (l *TemplateLibrary) Add(template *MessageTemplate)

Add adds a template to the library.

func (*TemplateLibrary) Get

func (l *TemplateLibrary) Get(name string) (*MessageTemplate, error)

Get retrieves a template by name.

func (*TemplateLibrary) List

func (l *TemplateLibrary) List() []string

List returns all template names.

func (*TemplateLibrary) Render

func (l *TemplateLibrary) Render(name string, data map[string]interface{}) (string, error)

Render renders a template by name with the given data.

type YAMLFormatter

type YAMLFormatter struct{}

YAMLFormatter formats output as YAML.

func NewYAMLFormatter

func NewYAMLFormatter() *YAMLFormatter

NewYAMLFormatter creates a new YAML formatter.

func (*YAMLFormatter) Format

func (f *YAMLFormatter) Format(w io.Writer, data interface{}, _ *FormatConfig) error

Format formats the data as YAML and writes it to the writer.

func (*YAMLFormatter) FormatCompact

func (f *YAMLFormatter) FormatCompact(w io.Writer, data interface{}) error

FormatCompact formats data as compact YAML (flow style).

func (*YAMLFormatter) FormatEmpty

func (f *YAMLFormatter) FormatEmpty(w io.Writer, message string, config *FormatConfig) error

FormatEmpty formats an empty result as YAML.

func (*YAMLFormatter) FormatError

func (f *YAMLFormatter) FormatError(w io.Writer, err error, config *FormatConfig) error

FormatError formats an error as YAML.

func (*YAMLFormatter) FormatResult

func (f *YAMLFormatter) FormatResult(w io.Writer, result *Result, config *FormatConfig) error

FormatResult formats a Result object as YAML.

func (*YAMLFormatter) Name

func (f *YAMLFormatter) Name() string

Name returns the formatter name.

func (*YAMLFormatter) Supports

func (f *YAMLFormatter) Supports(data interface{}) bool

Supports returns true if the formatter can handle the given data type. YAML formatter can handle any data type.

Jump to

Keyboard shortcuts

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