Documentation
¶
Overview ¶
Package format provides centralized CLI output formatting for agentic-memorizer.
The package implements a three-tier architecture:
- Builders - Construct structured output (Section, Table, List, Progress, Status, Error)
- Formatters - Render builders to specific formats (Text, JSON, YAML, Markdown, XML)
- 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:
- Use golden files for complex output verification
- Test each supported format separately
- Verify E2E tests pass after refactoring
See internal/format/README.md for comprehensive documentation.
Index ¶
- Constants
- func AlignText(text string, width int, align Alignment) string
- func Blue(text string) string
- func Bold(text string) string
- func FormatBytes(bytes int64) string
- func FormatDuration(d time.Duration) string
- func FormatNumber(n int64) string
- func GetStatusSymbol(severity StatusSeverity) string
- func Green(text string) string
- func ListFormatters() []string
- func Red(text string) string
- func RegisterFormatter(name string, formatter Formatter)
- func StripANSI(s string) string
- func TruncateString(s string, maxLen int) string
- func Yellow(text string) string
- type Alignment
- type BufferedWriter
- type Buildable
- type BuilderType
- type Error
- type ErrorType
- type Formatter
- type GraphContent
- type List
- type ListItem
- type ListType
- type Progress
- func (p *Progress) Percentage() float64
- func (p *Progress) SetCurrent(current int) *Progress
- func (p *Progress) SetMessage(msg string) *Progress
- func (p *Progress) ShowBar(width int) *Progress
- func (p *Progress) ShowPercentage() *Progress
- func (p *Progress) Type() BuilderType
- func (p *Progress) Validate() error
- type ProgressType
- type Registry
- type Section
- func (s *Section) AddDivider() *Section
- func (s *Section) AddKeyValue(key, value string) *Section
- func (s *Section) AddKeyValuef(key, format string, args ...any) *Section
- func (s *Section) AddSubsection(sub *Section) *Section
- func (s *Section) AddTextLine(text string) *Section
- func (s *Section) SetLevel(level int) *Section
- func (s *Section) Type() BuilderType
- func (s *Section) Validate() error
- type SectionItem
- type SectionItemType
- type Status
- type StatusSeverity
- type Table
- func (t *Table) AddRow(cells ...string) *Table
- func (t *Table) AddRowf(formats []string, values [][]any) *Table
- func (t *Table) Compact() *Table
- func (t *Table) HideHeader() *Table
- func (t *Table) SetAlignments(alignments ...Alignment) *Table
- func (t *Table) Type() BuilderType
- func (t *Table) Validate() error
- type Writer
Constants ¶
const ( SymbolSuccess = "✓" SymbolError = "✗" SymbolWarning = "⚠" SymbolInfo = "○" SymbolRunning = "▸" SymbolStopped = "■" )
Status symbols
const MaxListDepth = 5
MaxListDepth is the maximum allowed nesting depth for lists
const MaxSectionDepth = 5
MaxSectionDepth is the maximum allowed nesting depth for sections
Variables ¶
This section is empty.
Functions ¶
func FormatBytes ¶
FormatBytes formats bytes into human-readable format (B, KB, MB, GB, TB, PB, EB)
func FormatDuration ¶
FormatDuration formats a duration into human-readable format
func FormatNumber ¶
FormatNumber formats a number with thousands separators
func GetStatusSymbol ¶
func GetStatusSymbol(severity StatusSeverity) string
GetStatusSymbol returns the appropriate symbol for a status severity
func ListFormatters ¶
func ListFormatters() []string
ListFormatters returns all registered formatter names
func RegisterFormatter ¶
RegisterFormatter adds a formatter to the default registry
func TruncateString ¶
TruncateString truncates a string to maxLen characters, adding "..." if truncated
Types ¶
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 (*Error) WithSuggestion ¶
WithSuggestion sets a suggestion for resolving the error
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 ¶
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
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 ¶
Percentage returns the completion percentage (0-100)
func (*Progress) SetCurrent ¶
SetCurrent updates the current progress value
func (*Progress) SetMessage ¶
SetMessage sets the progress message
func (*Progress) ShowPercentage ¶
ShowPercentage enables percentage display
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
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 ¶
NewSection creates a new section with the given title
func (*Section) AddDivider ¶
WithDivider adds a divider line under the section title
func (*Section) AddKeyValue ¶
AddKeyValue adds a key-value pair to the section
func (*Section) AddKeyValuef ¶
AddKeyValuef adds a formatted key-value pair to the section
func (*Section) AddSubsection ¶
AddSubsection adds a nested subsection
func (*Section) AddTextLine ¶
AddTextLine adds a plain text line to the section
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) WithSymbol ¶
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 (*Table) HideHeader ¶
HideHeader hides the table header row
func (*Table) SetAlignments ¶
SetAlignments sets the column alignments
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