format

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2025 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package format provides centralized CLI output formatting for agentic-memorizer.

The package implements a three-tier architecture:

  1. Builders - Construct structured output (Section, Table, List, Progress, Status, Error)
  2. Formatters - Render builders to specific formats (Text, JSON, YAML, Markdown, XML)
  3. Writers - Handle buffered I/O with error handling

Basic Usage

Create a section with key-value pairs:

section := format.NewSection("Daemon Status")
section.AddKeyValue("Status", "Running")
section.AddKeyValue("PID", "12345")

formatter := format.GetFormatter("text")
output, _ := formatter.Format(section)
fmt.Print(output)

Multi-Format Support

Commands can support multiple output formats:

cmd.Flags().String("format", "text", "Output format (text|json|yaml)")

formatStr, _ := cmd.Flags().GetString("format")
formatter, _ := format.GetFormatter(formatStr)
output, _ := formatter.Format(section)
fmt.Print(output)

Builder Types

  • Section: Hierarchical key-value pairs with headers and subsections
  • Table: Columnar data with headers, alignment, and compact mode
  • List: Ordered/unordered lists with nesting support
  • Progress: Progress bars, spinners, and percentage indicators
  • Status: Status messages with severity levels and symbols
  • Error: Structured error formatting with suggestions

Shared Utilities

The package provides common formatting utilities:

  • FormatBytes(int64) - Human-readable byte sizes (1.5 MB, 2.3 GB)
  • FormatNumber(int64) - Numbers with thousands separators (1,234,567)
  • FormatDuration(time.Duration) - Human-readable durations
  • GetStatusSymbol(StatusSeverity) - Consistent status symbols (✓, ✗, ○, ⚠)

Thread Safety

The formatter registry is thread-safe and can be accessed concurrently. Individual builders and formatters are not thread-safe and should be used from a single goroutine.

Testing

When testing commands with formatted output:

  1. Use golden files for complex output verification
  2. Test each supported format separately
  3. Verify E2E tests pass after refactoring

See internal/format/README.md for comprehensive documentation.

Index

Constants

View Source
const (
	SymbolSuccess = "✓"
	SymbolError   = "✗"
	SymbolWarning = "⚠"
	SymbolInfo    = "○"
	SymbolRunning = "▸"
	SymbolStopped = "■"
)

Status symbols

View Source
const MaxListDepth = 5

MaxListDepth is the maximum allowed nesting depth for lists

View Source
const MaxSectionDepth = 5

MaxSectionDepth is the maximum allowed nesting depth for sections

Variables

This section is empty.

Functions

func AlignText

func AlignText(text string, width int, align Alignment) string

AlignText aligns text within a given width

func Blue

func Blue(text string) string

Blue wraps text in blue color codes

func Bold

func Bold(text string) string

Bold wraps text in bold formatting codes

func FormatBytes

func FormatBytes(bytes int64) string

FormatBytes formats bytes into human-readable format (B, KB, MB, GB, TB, PB, EB)

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration formats a duration into human-readable format

func FormatNumber

func FormatNumber(n int64) string

FormatNumber formats a number with thousands separators

func GetStatusSymbol

func GetStatusSymbol(severity StatusSeverity) string

GetStatusSymbol returns the appropriate symbol for a status severity

func Green

func Green(text string) string

Green wraps text in green color codes

func ListFormatters

func ListFormatters() []string

ListFormatters returns all registered formatter names

func Red

func Red(text string) string

Red wraps text in red color codes

func RegisterFormatter

func RegisterFormatter(name string, formatter Formatter)

RegisterFormatter adds a formatter to the default registry

func StripANSI

func StripANSI(s string) string

StripANSI removes ANSI escape codes from a string

func TruncateString

func TruncateString(s string, maxLen int) string

TruncateString truncates a string to maxLen characters, adding "..." if truncated

func Yellow

func Yellow(text string) string

Yellow wraps text in yellow color codes

Types

type Alignment

type Alignment string

Alignment represents text alignment in table columns

const (
	// AlignLeft aligns text to the left
	AlignLeft Alignment = "left"

	// AlignRight aligns text to the right
	AlignRight Alignment = "right"

	// AlignCenter centers text
	AlignCenter Alignment = "center"
)

type BufferedWriter

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

BufferedWriter implements Writer with buffered I/O

func NewBufferedWriter

func NewBufferedWriter(w io.Writer) *BufferedWriter

NewBufferedWriter creates a new buffered writer

func NewFileWriter

func NewFileWriter(path string) (*BufferedWriter, error)

NewFileWriter creates a buffered writer for a file

func NewStdoutWriter

func NewStdoutWriter() *BufferedWriter

NewStdoutWriter creates a buffered writer for stdout

func (*BufferedWriter) Close

func (w *BufferedWriter) Close() error

Close flushes and closes the writer

func (*BufferedWriter) Flush

func (w *BufferedWriter) Flush() error

Flush flushes any buffered data

func (*BufferedWriter) Write

func (w *BufferedWriter) Write(content string) error

Write writes content without a newline

func (*BufferedWriter) WriteLine

func (w *BufferedWriter) WriteLine(content string) error

WriteLine writes content with a newline

type Buildable

type Buildable interface {
	// Type returns the builder type
	Type() BuilderType

	// Validate checks if the builder is correctly constructed
	Validate() error
}

Buildable represents any structure that can be formatted

type BuilderType

type BuilderType string

BuilderType represents the type of output structure being built

const (
	// BuilderTypeSection represents hierarchical key-value pairs
	BuilderTypeSection BuilderType = "section"

	// BuilderTypeTable represents columnar data
	BuilderTypeTable BuilderType = "table"

	// BuilderTypeList represents ordered or unordered lists
	BuilderTypeList BuilderType = "list"

	// BuilderTypeProgress represents progress indicators
	BuilderTypeProgress BuilderType = "progress"

	// BuilderTypeStatus represents status messages
	BuilderTypeStatus BuilderType = "status"

	// BuilderTypeError represents structured error messages
	BuilderTypeError BuilderType = "error"

	// BuilderTypeGraph represents graph index data
	BuilderTypeGraph BuilderType = "graph"
)

func (BuilderType) String

func (bt BuilderType) String() string

String returns the string representation of the builder type

type Error

type Error struct {
	ErrorType  ErrorType
	Message    string
	Field      string   // Optional field name (for validation errors)
	Value      any      // Optional value that caused the error
	Details    []string // Additional details
	Suggestion string   // Optional suggestion for resolution
}

Error represents structured error messages with suggestions

func NewError

func NewError(errorType ErrorType, message string) *Error

NewError creates a new error message

func (*Error) AddDetail

func (e *Error) AddDetail(detail string) *Error

AddDetail adds a detail line to the error

func (*Error) SetField

func (e *Error) SetField(field string) *Error

SetField sets the field name (for validation errors)

func (*Error) SetValue

func (e *Error) SetValue(value any) *Error

SetValue sets the value that caused the error

func (*Error) Type

func (e *Error) Type() BuilderType

Type returns the builder type

func (*Error) Validate

func (e *Error) Validate() error

Validate checks if the error is correctly constructed

func (*Error) WithSuggestion

func (e *Error) WithSuggestion(suggestion string) *Error

WithSuggestion sets a suggestion for resolving the error

type ErrorType

type ErrorType string

ErrorType represents the type of error

const (
	// ErrorTypeValidation represents validation errors
	ErrorTypeValidation ErrorType = "validation"

	// ErrorTypeRuntime represents runtime errors
	ErrorTypeRuntime ErrorType = "runtime"

	// ErrorTypeInput represents user input errors
	ErrorTypeInput ErrorType = "input"
)

type Formatter

type Formatter interface {
	// Format renders a single buildable structure
	Format(b Buildable) (string, error)

	// FormatMultiple renders multiple buildable structures
	FormatMultiple(builders []Buildable) (string, error)

	// Name returns the formatter name (e.g., "text", "json")
	Name() string

	// SupportsColors returns true if the formatter supports color output
	SupportsColors() bool
}

Formatter renders Buildable structures to specific output formats

func GetFormatter

func GetFormatter(name string) (Formatter, error)

GetFormatter retrieves a formatter from the default registry

type GraphContent

type GraphContent struct {
	Index *types.GraphIndex
}

GraphContent wraps a GraphIndex for formatting through the format package. It implements the Buildable interface to integrate with the format system.

func NewGraphContent

func NewGraphContent(index *types.GraphIndex) *GraphContent

NewGraphContent creates a new GraphContent builder.

func (*GraphContent) Type

func (g *GraphContent) Type() BuilderType

Type returns the builder type.

func (*GraphContent) Validate

func (g *GraphContent) Validate() error

Validate checks if the GraphContent is valid.

type List

type List struct {
	ListType  ListType
	Items     []ListItem
	IsCompact bool // Compact mode uses less spacing
}

List represents ordered or unordered lists with nesting

func NewList

func NewList(listType ListType) *List

NewList creates a new list of the specified type

func (*List) AddItem

func (l *List) AddItem(content string) *List

AddItem adds a simple item to the list

func (*List) AddItemf

func (l *List) AddItemf(format string, args ...any) *List

AddItemf adds a formatted item to the list

func (*List) AddNested

func (l *List) AddNested(content string, nested *List) *List

AddNested adds an item with a nested list

func (*List) Compact

func (l *List) Compact() *List

Compact enables compact mode (less spacing between items)

func (*List) Type

func (l *List) Type() BuilderType

Type returns the builder type

func (*List) Validate

func (l *List) Validate() error

Validate checks if the list is correctly constructed

type ListItem

type ListItem struct {
	Content string
	Nested  *List // Optional nested list
}

ListItem represents an item in a list

type ListType

type ListType string

ListType represents the type of list

const (
	// ListTypeUnordered represents bullet lists
	ListTypeUnordered ListType = "unordered"

	// ListTypeOrdered represents numbered lists
	ListTypeOrdered ListType = "ordered"
)

type Progress

type Progress struct {
	ProgressType ProgressType
	Current      int
	Total        int
	Message      string
	BarWidth     int // Width of progress bar (default: 40)
}

Progress represents progress indicators

func NewProgress

func NewProgress(progressType ProgressType, current, total int) *Progress

NewProgress creates a new progress indicator

func (*Progress) Percentage

func (p *Progress) Percentage() float64

Percentage returns the completion percentage (0-100)

func (*Progress) SetCurrent

func (p *Progress) SetCurrent(current int) *Progress

SetCurrent updates the current progress value

func (*Progress) SetMessage

func (p *Progress) SetMessage(msg string) *Progress

SetMessage sets the progress message

func (*Progress) ShowBar

func (p *Progress) ShowBar(width int) *Progress

ShowBar enables progress bar display with the specified width

func (*Progress) ShowPercentage

func (p *Progress) ShowPercentage() *Progress

ShowPercentage enables percentage display

func (*Progress) Type

func (p *Progress) Type() BuilderType

Type returns the builder type

func (*Progress) Validate

func (p *Progress) Validate() error

Validate checks if the progress indicator is correctly constructed

type ProgressType

type ProgressType string

ProgressType represents the type of progress indicator

const (
	// ProgressTypeBar represents a progress bar
	ProgressTypeBar ProgressType = "bar"

	// ProgressTypeSpinner represents a spinner
	ProgressTypeSpinner ProgressType = "spinner"

	// ProgressTypePercentage represents a percentage
	ProgressTypePercentage ProgressType = "percentage"
)

type Registry

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

Registry manages registered formatters

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new formatter registry

func (*Registry) Get

func (r *Registry) Get(name string) (Formatter, error)

Get retrieves a formatter by name

func (*Registry) List

func (r *Registry) List() []string

List returns all registered formatter names

func (*Registry) Register

func (r *Registry) Register(name string, formatter Formatter)

Register adds a formatter to the registry

type Section

type Section struct {
	Title       string
	Level       int  // 0 = main section, 1 = subsection, etc.
	WithDivider bool // Whether to show a divider line under title
	Items       []SectionItem
}

Section represents hierarchical key-value pairs with headers

func NewSection

func NewSection(title string) *Section

NewSection creates a new section with the given title

func (*Section) AddDivider

func (s *Section) AddDivider() *Section

WithDivider adds a divider line under the section title

func (*Section) AddKeyValue

func (s *Section) AddKeyValue(key, value string) *Section

AddKeyValue adds a key-value pair to the section

func (*Section) AddKeyValuef

func (s *Section) AddKeyValuef(key, format string, args ...any) *Section

AddKeyValuef adds a formatted key-value pair to the section

func (*Section) AddSubsection

func (s *Section) AddSubsection(sub *Section) *Section

AddSubsection adds a nested subsection

func (*Section) AddTextLine

func (s *Section) AddTextLine(text string) *Section

AddTextLine adds a plain text line to the section

func (*Section) SetLevel

func (s *Section) SetLevel(level int) *Section

SetLevel sets the section level (0 = top level, 1 = subsection, etc.)

func (*Section) Type

func (s *Section) Type() BuilderType

Type returns the builder type

func (*Section) Validate

func (s *Section) Validate() error

Validate checks if the section is correctly constructed

type SectionItem

type SectionItem struct {
	Type       SectionItemType
	Key        string
	Value      string
	Text       string // For SectionItemText type
	Subsection *Section
}

SectionItem represents an item in a section

type SectionItemType

type SectionItemType string

SectionItemType represents the type of item in a section

const (
	// SectionItemKeyValue represents a key-value pair
	SectionItemKeyValue SectionItemType = "key_value"

	// SectionItemSubsection represents a nested subsection
	SectionItemSubsection SectionItemType = "subsection"

	// SectionItemText represents a plain text line
	SectionItemText SectionItemType = "text"
)

type Status

type Status struct {
	Severity     StatusSeverity
	Message      string
	Details      []string
	CustomSymbol string // Optional custom symbol override
}

Status represents status messages with severity and symbols

func NewStatus

func NewStatus(severity StatusSeverity, message string) *Status

NewStatus creates a new status message

func (*Status) AddDetail

func (s *Status) AddDetail(detail string) *Status

AddDetail adds a detail line to the status

func (*Status) Type

func (s *Status) Type() BuilderType

Type returns the builder type

func (*Status) Validate

func (s *Status) Validate() error

Validate checks if the status is correctly constructed

func (*Status) WithSymbol

func (s *Status) WithSymbol(symbol string) *Status

WithSymbol sets a custom symbol override

type StatusSeverity

type StatusSeverity string

StatusSeverity represents the severity level of a status message

const (
	// StatusSuccess represents successful completion
	StatusSuccess StatusSeverity = "success"

	// StatusInfo represents informational messages
	StatusInfo StatusSeverity = "info"

	// StatusWarning represents warnings
	StatusWarning StatusSeverity = "warning"

	// StatusError represents errors
	StatusError StatusSeverity = "error"

	// StatusRunning represents running/active state
	StatusRunning StatusSeverity = "running"

	// StatusStopped represents stopped/inactive state
	StatusStopped StatusSeverity = "stopped"
)

type Table

type Table struct {
	Headers     []string
	Rows        [][]string
	Alignments  []Alignment
	HideHeaders bool
	IsCompact   bool // Compact mode uses less spacing
}

Table represents columnar data with headers and alignment

func NewTable

func NewTable(headers ...string) *Table

NewTable creates a new table with the given headers

func (*Table) AddRow

func (t *Table) AddRow(cells ...string) *Table

AddRow adds a data row to the table

func (*Table) AddRowf

func (t *Table) AddRowf(formats []string, values [][]any) *Table

AddRowf adds a formatted row to the table

func (*Table) Compact

func (t *Table) Compact() *Table

Compact enables compact mode (less spacing)

func (*Table) HideHeader

func (t *Table) HideHeader() *Table

HideHeader hides the table header row

func (*Table) SetAlignments

func (t *Table) SetAlignments(alignments ...Alignment) *Table

SetAlignments sets the column alignments

func (*Table) Type

func (t *Table) Type() BuilderType

Type returns the builder type

func (*Table) Validate

func (t *Table) Validate() error

Validate checks if the table is correctly constructed

type Writer

type Writer interface {
	// Write writes content without a newline
	Write(content string) error

	// WriteLine writes content with a newline
	WriteLine(content string) error

	// Flush flushes any buffered data
	Flush() error

	// Close flushes and closes the writer
	Close() error
}

Writer provides buffered output with error handling

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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