Documentation
¶
Overview ¶
Package output provides a flexible output generation library for Go applications. It supports multiple output formats (JSON, YAML, CSV, HTML, Markdown, etc.) with a document-builder pattern that eliminates global state and provides thread-safe operations.
Package output provides a flexible document construction and rendering system for Go.
Overview ¶
The go-output v2 library is a complete redesign providing a thread-safe, immutable Document-Builder pattern to convert structured data into various output formats including JSON, YAML, CSV, HTML, console tables, Markdown, DOT graphs, Mermaid diagrams, and Draw.io files.
Key features:
- Thread-safe operations with proper mutex usage
- Immutable documents after Build() for safety
- Exact preservation of user-specified column ordering
- Multiple output formats (JSON, YAML, CSV, HTML, Tables, Markdown, DOT, Mermaid, Draw.io)
- Document-Builder pattern with clean separation of concerns
- Modern Go 1.24+ features with 'any' instead of 'interface{}'
- No global state - complete elimination from v1
- Per-content transformations for filtering, sorting, limiting, and more
Basic Usage ¶
Create a document using the builder pattern:
builder := output.New()
builder.Table("users", userData, output.WithKeys("name", "email", "age"))
builder.Text("Summary statistics")
doc := builder.Build()
Render to a specific format:
out := output.NewOutput(
output.WithFormat(output.JSON()),
output.WithWriter(output.NewStdoutWriter()),
)
err := out.Render(context.Background(), doc)
Content Types ¶
The library supports multiple content types:
- TableContent: Tabular data with schema-driven key ordering
- TextContent: Unstructured text with styling options
- RawContent: Format-specific content (HTML snippets, etc.)
- SectionContent: Grouped content with hierarchical structure
- GraphContent: Network/relationship diagrams
- ChartContent: Gantt charts, pie charts, and other visualizations
- CollapsibleSection: Expandable/collapsible sections for HTML/Markdown
Output Formats ¶
Supported output formats:
- JSON: Structured data for APIs
- YAML: Configuration files
- CSV: Spreadsheet-compatible data
- HTML: Web reports with templates
- Table: Console/terminal tables
- Markdown: Documentation with optional ToC
- DOT: GraphViz diagrams
- Mermaid: Mermaid.js diagrams
- Draw.io: Import into Draw.io
Per-Content Transformations ¶
The v2 library introduces per-content transformations, allowing you to attach operations directly to content items at creation time:
builder.Table("users", userData,
output.WithKeys("name", "email", "age"),
output.WithTransformations(
output.NewFilterOp(func(r output.Record) bool {
return r["age"].(int) >= 18
}),
output.NewSortOp(output.SortKey{Column: "name", Direction: output.Ascending}),
output.NewLimitOp(10),
),
)
Transformations execute during rendering, allowing different tables in the same document to have different transformation logic.
Available Operations ¶
The library provides several built-in operations:
- FilterOp: Filter records based on a predicate function - SortOp: Sort records by one or more columns - LimitOp: Limit the number of records - GroupByOp: Group records by columns with aggregation - AddColumnOp: Add calculated columns
Create operations using constructor functions:
filter := output.NewFilterOp(predicate) sort := output.NewSortOp(keys...) limit := output.NewLimitOp(count) groupBy := output.NewGroupByOp(columns, aggregates) addCol := output.NewAddColumnOp(name, fn, position)
Thread Safety Requirements ¶
Operations attached to content MUST be thread-safe and stateless:
1. Operations MUST NOT contain mutable state modified during Apply() 2. Operations MUST be safe for concurrent execution from multiple goroutines 3. Operations MUST NOT capture mutable variables in closures
Example of UNSAFE operation (captures loop variable by reference):
// WRONG - captures loop variable by reference
for _, threshold := range thresholds {
builder.Table(name, data,
output.WithTransformations(
output.NewFilterOp(func(r Record) bool {
return r["value"].(int) > threshold // BUG!
}),
),
)
}
Example of SAFE operation (explicit value capture):
// CORRECT - captures value explicitly
for _, threshold := range thresholds {
t := threshold // Capture value
builder.Table(name, data,
output.WithTransformations(
output.NewFilterOp(func(r Record) bool {
return r["value"].(int) > t // Safe
}),
),
)
}
Transformation Execution ¶
Transformations execute lazily during document rendering:
1. Builder constructs content with attached transformations 2. Build() creates an immutable document 3. Renderer applies transformations just before output
This design: - Preserves original data in the document - Supports context-aware rendering with cancellation - Enables efficient rendering with minimal memory overhead
Performance Characteristics ¶
Per-content transformations have the following performance profile:
- Memory overhead: O(1) per content item (slice of operation references) - Build time: O(c) where c = number of content items - Rendering time: O(c × t × r) where c = content items, t = transformations per content, r = records per table - Each operation clones content during Apply(), chained operations result in multiple clones
The library is designed to handle documents with at least 100 content items, each having up to 10 transformations, with good performance.
Context Cancellation ¶
Transformations respect context cancellation:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
out := output.NewOutput(
output.WithFormat(output.JSON()),
output.WithWriter(output.NewStdoutWriter()),
)
err := out.Render(ctx, doc) // Respects timeout
Context is checked once before each operation in the transformation chain, providing responsive cancellation without performance overhead in tight loops.
Error Handling ¶
The library uses fail-fast error handling - rendering stops immediately on the first transformation error:
builder.Table("users", data,
output.WithTransformations(
output.NewSortOp(output.SortKey{Column: "nonexistent"}), // Error!
),
)
doc := builder.Build()
err := out.Render(ctx, doc) // Returns error with context about which operation failed
Error messages include: - Content ID and type - Operation index and name - Detailed error description
Key Order Preservation ¶
A critical feature of v2 is exact key order preservation for tables:
// Keys appear in specified order, never alphabetized
builder.Table("users", data, output.WithKeys("name", "age", "email"))
Three ways to specify key order:
1. WithKeys() - explicit key list 2. WithSchema() - full schema with field definitions 3. WithAutoSchema() - auto-detect from data (map iteration order, not recommended)
Content Types ¶
The library supports multiple content types:
- TableContent: Tabular data with schema-driven key ordering - TextContent: Unstructured text with styling options - RawContent: Format-specific content (HTML snippets, etc.) - SectionContent: Grouped content with hierarchical structure
All content types support transformations through the WithTransformations() option.
Pipeline API Removal ¶
The document-level Pipeline API has been removed in v2.4.0. Use per-content transformations instead:
// REMOVED in v2.4.0:
// doc.Pipeline().Filter(predicate).Sort(keys...).Execute()
// Use instead:
builder.Table("data", records,
output.WithTransformations(
output.NewFilterOp(predicate),
output.NewSortOp(keys...),
),
)
See the migration guide (v2/docs/PIPELINE_MIGRATION.md) for detailed migration examples.
Best Practices ¶
1. Use explicit WithKeys() or WithSchema() for reliable key ordering 2. Design operations to be stateless and thread-safe 3. Capture values explicitly in closures, not loop variables 4. Use context for cancellation of long-running transformations 5. Test operations with concurrent execution to verify thread safety
For comprehensive best practices, see v2/BEST_PRACTICES.md.
Example: Complete Workflow ¶
package main
import (
"context"
"log"
output "github.com/ArjenSchwarz/go-output/v2"
)
func main() {
// Sample data
users := []output.Record{
{"name": "Alice", "email": "[email protected]", "age": 30},
{"name": "Bob", "email": "[email protected]", "age": 25},
{"name": "Charlie", "email": "[email protected]", "age": 35},
}
// Build document with transformations
builder := output.New()
builder.Table("users", users,
output.WithKeys("name", "email", "age"),
output.WithTransformations(
output.NewFilterOp(func(r output.Record) bool {
return r["age"].(int) >= 30
}),
output.NewSortOp(output.SortKey{
Column: "name",
Direction: output.Ascending,
}),
),
)
doc := builder.Build()
// Render to JSON
out := output.NewOutput(
output.WithFormat(output.JSON()),
output.WithWriter(output.NewStdoutWriter()),
)
if err := out.Render(context.Background(), doc); err != nil {
log.Fatalf("Render error: %v", err)
}
}
Further Reading ¶
- Getting Started: v2/docs/GETTING-STARTED.md - Quick start guide
- Documentation: v2/docs/DOCUMENTATION.md - Complete API documentation
- Migration from v1: v2/docs/MIGRATION.md - Migrate from v1 to v2
- Pipeline Migration: v2/docs/PIPELINE_MIGRATION.md - Migrate from Pipeline API to per-content transformations
- Best Practices: v2/docs/BEST_PRACTICES.md - Safe operation patterns and performance tips
- API Reference: v2/docs/API.md - Detailed API reference
- Examples: v2/examples/ - Runnable examples demonstrating features
Index ¶
- Constants
- Variables
- func ApplyRawOptions(opts ...RawOption) *rawConfig
- func ApplySectionOptions(opts ...SectionOption) *sectionConfig
- func ApplyTableOptions(opts ...TableOption) *tableConfig
- func ApplyTextOptions(opts ...TextOption) *textConfig
- func AsError[T error](err error, target *T) bool
- func CollapsibleFormatter(summaryTemplate string, detailFunc func(any) any, opts ...CollapsibleOption) func(any) any
- func CollectErrors(operation string, errors ...error) error
- func DetectType(v any) string
- func DisableGlobalDebugTracing()
- func EnableGlobalDebugTracing(level DebugLevel, output io.Writer)
- func ErrorListFormatter(opts ...CollapsibleOption) func(any) any
- func ErrorWithContext(operation string, cause error, contextPairs ...any) error
- func FailFast(errors ...error) error
- func FilePathFormatter(maxLength int, opts ...CollapsibleOption) func(any) any
- func GenerateID() string
- func GetPanicValue(err error) any
- func GetStackTrace(err error) string
- func GlobalError(operation string, message string, args ...any)
- func GlobalInfo(operation string, message string, args ...any)
- func GlobalTrace(operation string, message string, args ...any)
- func GlobalWarn(operation string, message string, args ...any)
- func IsCancelled(err error) bool
- func IsPanic(err error) bool
- func JSONFormatter(maxLength int, opts ...CollapsibleOption) func(any) any
- func NewMarkdownRendererWithFrontMatter(frontMatter map[string]string) *markdownRenderer
- func NewMarkdownRendererWithOptions(includeToC bool, frontMatter map[string]string) *markdownRenderer
- func NewMarkdownRendererWithToC(enabled bool) *markdownRenderer
- func SafeExecute(operation string, fn func() error) error
- func SafeExecuteWithResult(operation string, fn func() (any, error)) (any, error)
- func SafeExecuteWithResultAndTracer(tracer *DebugTracer, operation string, fn func() (any, error)) (result any, finalErr error)
- func SafeExecuteWithTracer(tracer *DebugTracer, operation string, fn func() error) (finalErr error)
- func SetGlobalDebugTracer(tracer *DebugTracer)
- func StyleBold(text string) string
- func StyleBoldIf(text string, useBold bool) string
- func StyleInfo(text string) string
- func StyleInfoIf(text string, useColor bool) string
- func StyleNegative(text string) string
- func StyleNegativeIf(text string, useColor bool) string
- func StylePositive(text string) string
- func StylePositiveIf(text string, useColor bool) string
- func StyleWarning(text string) string
- func StyleWarningIf(text string, useColor bool) string
- func ValidateInput(field string, value any, validator func(any) error) error
- func ValidateMapNonEmpty[K comparable, V any](field string, value map[K]V) error
- func ValidateNonEmpty(field, value string) error
- func ValidateNonNil(field string, value any) error
- func ValidateSliceNonEmpty[T any](field string, value []T) error
- func ValidateStatelessOperation(t *testing.T, op Operation, testContent Content) error
- type AddColumnOp
- func (o *AddColumnOp) Apply(ctx context.Context, content Content) (Content, error)
- func (o *AddColumnOp) ApplyWithFormat(ctx context.Context, content Content, format string) (Content, error)
- func (o *AddColumnOp) CanOptimize(with Operation) bool
- func (o *AddColumnOp) CanTransform(content Content, format string) bool
- func (o *AddColumnOp) Name() string
- func (o *AddColumnOp) Validate() error
- type AggregateFunc
- type Builder
- func (b *Builder) AddCollapsibleSection(title string, content []Content, opts ...CollapsibleSectionOption) *Builder
- func (b *Builder) AddCollapsibleTable(title string, table *TableContent, opts ...CollapsibleSectionOption) *Builder
- func (b *Builder) AddContent(content Content) *Builder
- func (b *Builder) Build() *Document
- func (b *Builder) Chart(title, chartType string, data any) *Builder
- func (b *Builder) CollapsibleSection(title string, fn func(*Builder), opts ...CollapsibleSectionOption) *Builder
- func (b *Builder) DrawIO(title string, records []Record, header DrawIOHeader) *Builder
- func (b *Builder) Errors() []error
- func (b *Builder) GanttChart(title string, tasks []GanttTask) *Builder
- func (b *Builder) Graph(title string, edges []Edge) *Builder
- func (b *Builder) HasErrors() bool
- func (b *Builder) Header(text string) *Builder
- func (b *Builder) PieChart(title string, slices []PieSlice, showData bool) *Builder
- func (b *Builder) Raw(format string, data []byte, opts ...RawOption) *Builder
- func (b *Builder) Section(title string, fn func(*Builder), opts ...SectionOption) *Builder
- func (b *Builder) SetMetadata(key string, value any) *Builder
- func (b *Builder) Table(title string, data any, opts ...TableOption) *Builder
- func (b *Builder) Text(text string, opts ...TextOption) *Builder
- type CancelledError
- type ChartContent
- func (c *ChartContent) AppendBinary(b []byte) ([]byte, error)
- func (c *ChartContent) AppendText(b []byte) ([]byte, error)
- func (c *ChartContent) Clone() Content
- func (c *ChartContent) GetChartType() string
- func (c *ChartContent) GetData() any
- func (c *ChartContent) GetTitle() string
- func (c *ChartContent) GetTransformations() []Operation
- func (c *ChartContent) ID() string
- func (c *ChartContent) Type() ContentType
- type CollapsibleOption
- func WithCodeFences(language string) CollapsibleOption
- func WithCollapsibleExpanded(expanded bool) CollapsibleOption
- func WithExpanded(expanded bool) CollapsibleOptiondeprecated
- func WithFormatHint(format string, hints map[string]any) CollapsibleOption
- func WithMaxLength(length int) CollapsibleOption
- func WithTruncateIndicator(indicator string) CollapsibleOption
- func WithoutCodeFences() CollapsibleOption
- type CollapsibleSection
- type CollapsibleSectionOption
- type CollapsibleValue
- type ColorScheme
- type ColorTransformer
- type Content
- type ContentType
- type ContextError
- type DataIntegrityValidator
- type DataTransformer
- type DebugLevel
- type DebugTracer
- func (dt *DebugTracer) AddContext(key string, value any)
- func (dt *DebugTracer) ClearContext()
- func (dt *DebugTracer) Error(operation string, message string, args ...any)
- func (dt *DebugTracer) GetLevel() DebugLevel
- func (dt *DebugTracer) Info(operation string, message string, args ...any)
- func (dt *DebugTracer) IsEnabled() bool
- func (dt *DebugTracer) RemoveContext(key string)
- func (dt *DebugTracer) SetLevel(level DebugLevel)
- func (dt *DebugTracer) Trace(operation string, message string, args ...any)
- func (dt *DebugTracer) TraceOperation(operation string, fn func() error) error
- func (dt *DebugTracer) TraceOperationWithResult(operation string, fn func() (any, error)) (any, error)
- func (dt *DebugTracer) Warn(operation string, message string, args ...any)
- type DefaultCollapsibleSection
- func NewCollapsibleMultiTable(title string, tables []*TableContent, opts ...CollapsibleSectionOption) *DefaultCollapsibleSection
- func NewCollapsibleReport(title string, content []Content, opts ...CollapsibleSectionOption) *DefaultCollapsibleSection
- func NewCollapsibleSection(title string, content []Content, opts ...CollapsibleSectionOption) *DefaultCollapsibleSection
- func NewCollapsibleTable(title string, table *TableContent, opts ...CollapsibleSectionOption) *DefaultCollapsibleSection
- func (cs *DefaultCollapsibleSection) AppendBinary(b []byte) ([]byte, error)
- func (cs *DefaultCollapsibleSection) AppendText(b []byte) ([]byte, error)
- func (cs *DefaultCollapsibleSection) Clone() Content
- func (cs *DefaultCollapsibleSection) Content() []Content
- func (cs *DefaultCollapsibleSection) FormatHint(format string) map[string]any
- func (cs *DefaultCollapsibleSection) GetTransformations() []Operation
- func (cs *DefaultCollapsibleSection) ID() string
- func (cs *DefaultCollapsibleSection) IsExpanded() bool
- func (cs *DefaultCollapsibleSection) Level() int
- func (cs *DefaultCollapsibleSection) Title() string
- func (cs *DefaultCollapsibleSection) Type() ContentType
- type DefaultCollapsibleValue
- func (d *DefaultCollapsibleValue) CodeLanguage() string
- func (d *DefaultCollapsibleValue) Details() any
- func (d *DefaultCollapsibleValue) FormatHint(format string) map[string]any
- func (d *DefaultCollapsibleValue) IsExpanded() bool
- func (d *DefaultCollapsibleValue) String() string
- func (d *DefaultCollapsibleValue) Summary() string
- func (d *DefaultCollapsibleValue) UseCodeFences() bool
- type Document
- type DrawIOConnection
- type DrawIOContent
- func (d *DrawIOContent) AppendBinary(b []byte) ([]byte, error)
- func (d *DrawIOContent) AppendText(b []byte) ([]byte, error)
- func (d *DrawIOContent) Clone() Content
- func (d *DrawIOContent) GetHeader() DrawIOHeader
- func (d *DrawIOContent) GetRecords() []Record
- func (d *DrawIOContent) GetTitle() string
- func (d *DrawIOContent) GetTransformations() []Operation
- func (d *DrawIOContent) ID() string
- func (d *DrawIOContent) Type() ContentType
- type DrawIOHeader
- type Edge
- type EmojiTransformer
- type EnhancedColorTransformer
- type EnhancedEmojiTransformer
- type EnhancedSortTransformer
- type ErrorSource
- type Field
- type FileWriter
- type FileWriterOption
- type FilterOp
- func (o *FilterOp) Apply(ctx context.Context, content Content) (Content, error)
- func (o *FilterOp) ApplyWithFormat(ctx context.Context, content Content, format string) (Content, error)
- func (o *FilterOp) CanOptimize(with Operation) bool
- func (o *FilterOp) CanTransform(content Content, format string) bool
- func (o *FilterOp) Name() string
- func (o *FilterOp) Validate() error
- type Format
- func CSV() Format
- func DOT() Format
- func DrawIO() Format
- func HTML() Format
- func HTMLFragment() Format
- func HTMLWithTemplate(template *HTMLTemplate) Format
- func JSON() Format
- func Markdown() Format
- func MarkdownWithFrontMatter(frontMatter map[string]string) Format
- func MarkdownWithOptions(includeToC bool, frontMatter map[string]string) Format
- func MarkdownWithToC(enabled bool) Format
- func Mermaid() Format
- func Table() Format
- func TableBold() Format
- func TableColoredBright() Format
- func TableDefault() Format
- func TableLight() Format
- func TableRounded() Format
- func TableWithMaxColumnWidth(maxColumnWidth int) Format
- func TableWithStyle(styleName string) Format
- func TableWithStyleAndMaxColumnWidth(styleName string, maxColumnWidth int) Format
- func YAML() Format
- type FormatAwareOperation
- type FormatAwareTransformer
- type FormatDetector
- func (fd *FormatDetector) IsGraphFormat(format string) bool
- func (fd *FormatDetector) IsStructuredFormat(format string) bool
- func (fd *FormatDetector) IsTabularFormat(format string) bool
- func (fd *FormatDetector) IsTextBasedFormat(format string) bool
- func (fd *FormatDetector) RequiresEscaping(format string) bool
- func (fd *FormatDetector) SupportsColors(format string) bool
- func (fd *FormatDetector) SupportsEmoji(format string) bool
- func (fd *FormatDetector) SupportsLineSplitting(format string) bool
- func (fd *FormatDetector) SupportsSorting(format string) bool
- type GanttData
- type GanttTask
- type GraphContent
- func (g *GraphContent) AppendBinary(b []byte) ([]byte, error)
- func (g *GraphContent) AppendText(b []byte) ([]byte, error)
- func (g *GraphContent) Clone() Content
- func (g *GraphContent) GetEdges() []Edge
- func (g *GraphContent) GetNodes() []string
- func (g *GraphContent) GetTitle() string
- func (g *GraphContent) GetTransformations() []Operation
- func (g *GraphContent) ID() string
- func (g *GraphContent) Type() ContentType
- type GroupByOp
- func (o *GroupByOp) Apply(ctx context.Context, content Content) (Content, error)
- func (o *GroupByOp) ApplyWithFormat(ctx context.Context, content Content, format string) (Content, error)
- func (o *GroupByOp) CanOptimize(with Operation) bool
- func (o *GroupByOp) CanTransform(content Content, format string) bool
- func (o *GroupByOp) Name() string
- func (o *GroupByOp) Validate() error
- type HTMLTemplate
- type LimitOp
- func (o *LimitOp) Apply(ctx context.Context, content Content) (Content, error)
- func (o *LimitOp) ApplyWithFormat(ctx context.Context, content Content, format string) (Content, error)
- func (o *LimitOp) CanOptimize(with Operation) bool
- func (o *LimitOp) CanTransform(content Content, format string) bool
- func (o *LimitOp) Name() string
- func (o *LimitOp) Validate() error
- type LineSplitTransformer
- type MemoryOptimizedProcessor
- func (mop *MemoryOptimizedProcessor) GetBuffer() *strings.Builder
- func (mop *MemoryOptimizedProcessor) GetStringSlice() []string
- func (mop *MemoryOptimizedProcessor) ProcessLargeDetails(details any, maxLength int) (any, error)
- func (mop *MemoryOptimizedProcessor) ReturnBuffer(buf *strings.Builder)
- func (mop *MemoryOptimizedProcessor) ReturnStringSlice(slice []string)
- type MultiError
- func (e *MultiError) Add(err error)
- func (e *MultiError) AddContext(key string, value any) *MultiError
- func (e *MultiError) AddWithSource(err error, component string, details map[string]any)
- func (e *MultiError) Error() string
- func (e *MultiError) ErrorOrNil() error
- func (e *MultiError) HasErrors() bool
- func (e *MultiError) Unwrap() error
- type MultiWriteError
- type MultiWriter
- type Operation
- type OperationStat
- type Output
- func (o *Output) Close() error
- func (o *Output) GetFormats() []Format
- func (o *Output) GetProgress() Progress
- func (o *Output) GetTransformers() []Transformer
- func (o *Output) GetWriters() []Writer
- func (o *Output) Render(ctx context.Context, doc *Document) error
- func (o *Output) RenderTo(doc *Document) error
- type OutputOption
- func WithFormat(format Format) OutputOption
- func WithFormats(formats ...Format) OutputOption
- func WithFrontMatter(fm map[string]string) OutputOption
- func WithMetadata(key string, value any) OutputOption
- func WithProgress(progress Progress) OutputOption
- func WithTOC(enabled bool) OutputOption
- func WithTableStyle(style string) OutputOption
- func WithTransformer(transformer Transformer) OutputOption
- func WithTransformers(transformers ...Transformer) OutputOption
- func WithWriter(writer Writer) OutputOption
- func WithWriters(writers ...Writer) OutputOption
- type PanicError
- type PieData
- type PieSlice
- type PipelineError
- type ProcessedValue
- type Progress
- func NewAutoProgress(opts ...ProgressOption) Progress
- func NewNoOpProgress() Progress
- func NewPrettyProgress(opts ...ProgressOption) Progress
- func NewProgress(opts ...ProgressOption) Progress
- func NewProgressForFormat(format Format, opts ...ProgressOption) Progress
- func NewProgressForFormatName(formatName string, opts ...ProgressOption) Progress
- func NewProgressForFormats(formats []Format, opts ...ProgressOption) Progress
- type ProgressColor
- type ProgressConfig
- type ProgressOption
- func WithETA(show bool) ProgressOption
- func WithPercentage(show bool) ProgressOption
- func WithPrefix(prefix string) ProgressOption
- func WithProgressColor(color ProgressColor) ProgressOption
- func WithProgressStatus(status string) ProgressOption
- func WithProgressWriter(w io.Writer) ProgressOption
- func WithRate(show bool) ProgressOption
- func WithSuffix(suffix string) ProgressOption
- func WithTemplate(template string) ProgressOption
- func WithTrackerLength(length int) ProgressOption
- func WithUpdateInterval(interval time.Duration) ProgressOption
- func WithWidth(width int) ProgressOption
- type RawContent
- func (r *RawContent) AppendBinary(b []byte) ([]byte, error)
- func (r *RawContent) AppendText(b []byte) ([]byte, error)
- func (r *RawContent) Clone() Content
- func (r *RawContent) Data() []byte
- func (r *RawContent) Format() string
- func (r *RawContent) GetTransformations() []Operation
- func (r *RawContent) ID() string
- func (r *RawContent) Type() ContentType
- type RawOption
- type Record
- type RemoveColorsTransformer
- type RenderError
- type Renderer
- func NewCSVRendererWithCollapsible(config RendererConfig) Renderer
- func NewHTMLRendererWithCollapsible(config RendererConfig) Renderer
- func NewMarkdownRendererWithCollapsible(config RendererConfig) Renderer
- func NewTableRendererWithCollapsible(styleName string, config RendererConfig) Renderer
- func NewTableRendererWithStyle(styleName string) Renderer
- func NewTableRendererWithStyleAndWidth(styleName string, maxColumnWidth int) Renderer
- type RendererConfig
- type S3ClientAPI
- type S3GetObjectAPI
- type S3PutObjectAPI
- type S3Writer
- type S3WriterOption
- type Schema
- type SectionContent
- func (s *SectionContent) AddContent(content Content)
- func (s *SectionContent) AppendBinary(b []byte) ([]byte, error)
- func (s *SectionContent) AppendText(b []byte) ([]byte, error)
- func (s *SectionContent) Clone() Content
- func (s *SectionContent) Contents() []Content
- func (s *SectionContent) GetTransformations() []Operation
- func (s *SectionContent) ID() string
- func (s *SectionContent) Level() int
- func (s *SectionContent) Title() string
- func (s *SectionContent) Type() ContentType
- type SectionOption
- type SortDirection
- type SortKey
- type SortOp
- func (o *SortOp) Apply(ctx context.Context, content Content) (Content, error)
- func (o *SortOp) ApplyWithFormat(ctx context.Context, content Content, format string) (Content, error)
- func (o *SortOp) CanOptimize(with Operation) bool
- func (o *SortOp) CanTransform(content Content, format string) bool
- func (o *SortOp) Name() string
- func (o *SortOp) Validate() error
- type SortTransformer
- type StderrWriter
- type StdoutWriter
- type StreamingValueProcessor
- type StructuredError
- type TableContent
- func (t *TableContent) AppendBinary(b []byte) ([]byte, error)
- func (t *TableContent) AppendText(b []byte) ([]byte, error)
- func (t *TableContent) Clone() Content
- func (t *TableContent) GetTransformations() []Operation
- func (t *TableContent) ID() string
- func (t *TableContent) Records() []Record
- func (t *TableContent) Schema() *Schema
- func (t *TableContent) Title() string
- func (tc *TableContent) Transform(fn TransformFunc) error
- func (t *TableContent) Type() ContentType
- type TableOption
- type TextContent
- func (t *TextContent) AppendBinary(b []byte) ([]byte, error)
- func (t *TextContent) AppendText(b []byte) ([]byte, error)
- func (t *TextContent) Clone() Content
- func (t *TextContent) GetTransformations() []Operation
- func (t *TextContent) ID() string
- func (t *TextContent) Style() TextStyle
- func (t *TextContent) Text() string
- func (t *TextContent) Type() ContentType
- type TextOption
- type TextStyle
- type TransformContext
- type TransformError
- type TransformFunc
- type TransformInfo
- type TransformPipeline
- func (tp *TransformPipeline) Add(transformer Transformer)
- func (tp *TransformPipeline) Clear()
- func (tp *TransformPipeline) Count() int
- func (tp *TransformPipeline) Get(name string) Transformer
- func (tp *TransformPipeline) Has(name string) bool
- func (tp *TransformPipeline) Info() []TransformInfo
- func (tp *TransformPipeline) Remove(name string) bool
- func (tp *TransformPipeline) Transform(ctx context.Context, input []byte, format string) ([]byte, error)
- type TransformStats
- type TransformableContent
- type Transformer
- type TransformerAdapter
- type ValidationError
- type WriteError
- type Writer
- type WriterError
- type WriterFunc
Constants ¶
const ( ChartTypeGantt = "gantt" ChartTypePie = "pie" ChartTypeFlowchart = "flowchart" )
ChartType constants for different chart types
const ( DrawIOLayoutAuto = "auto" DrawIOLayoutNone = "none" DrawIOLayoutHorizontalFlow = "horizontalflow" DrawIOLayoutVerticalFlow = "verticalflow" DrawIOLayoutHorizontalTree = "horizontaltree" DrawIOLayoutVerticalTree = "verticaltree" DrawIOLayoutOrganic = "organic" DrawIOLayoutCircle = "circle" )
Layout constants for Draw.io
const ( DrawIODefaultConnectionStyle = "curved=1;endArrow=blockThin;endFill=1;fontSize=11;" DrawIOBidirectionalConnectionStyle = "curved=1;endArrow=blockThin;endFill=1;fontSize=11;startArrow=blockThin;startFill=1;" DrawIODefaultParentStyle = "" /* 129-byte string literal not displayed */ )
Connection style constants
const ( FormatJSON = "json" FormatYAML = "yaml" FormatMarkdown = "markdown" FormatTable = "table" FormatCSV = "csv" FormatHTML = "html" FormatText = "text" FormatDOT = "dot" FormatMermaid = "mermaid" FormatDrawIO = "drawio" )
Format name constants
const ( // HTMLAppendMarker is the HTML comment marker used for append mode operations. // // When a FileWriter or S3Writer operates in append mode with HTML format, this marker // indicates the insertion point for new content. New HTML fragments are inserted // immediately before this marker, allowing multiple appends while preserving the // overall HTML structure. // // The marker is automatically included when rendering a full HTML page (useTemplate=true). // It is positioned near the end of the document, before the closing </body> and </html> tags. // // HTML fragments (useTemplate=false) do not include the marker, as they are meant to be // inserted into existing HTML documents that already contain it. // // Required for Append Mode: When appending to an existing HTML file, the file MUST // contain this marker or an error will be returned. The FileWriter will not attempt // to guess an insertion point. // // Marker Location: The marker should appear only once in the document and should be // placed before any closing tags (</body>, </html>). Multiple markers or incorrectly // positioned markers will cause undefined behavior. HTMLAppendMarker = "<!-- go-output-append -->" )
Constants for repeated strings
Variables ¶
var DefaultRendererConfig = RendererConfig{ ForceExpansion: false, MaxDetailLength: 500, TruncateIndicator: "[...truncated]", TableHiddenIndicator: "[details hidden - use --expand for full view]", HTMLCSSClasses: map[string]string{ "details": "collapsible-cell", "summary": "collapsible-summary", "content": "collapsible-details", }, DataTransformers: make([]*TransformerAdapter, 0), ByteTransformers: NewTransformPipeline(), }
DefaultRendererConfig provides sensible default configuration values
Functions ¶
func ApplyRawOptions ¶
func ApplyRawOptions(opts ...RawOption) *rawConfig
ApplyRawOptions applies all options to the raw content configuration
func ApplySectionOptions ¶
func ApplySectionOptions(opts ...SectionOption) *sectionConfig
ApplySectionOptions applies all options to the section configuration
func ApplyTableOptions ¶
func ApplyTableOptions(opts ...TableOption) *tableConfig
ApplyTableOptions applies all options to the table configuration
func ApplyTextOptions ¶
func ApplyTextOptions(opts ...TextOption) *textConfig
ApplyTextOptions applies all options to the text configuration
func CollapsibleFormatter ¶ added in v2.1.0
func CollapsibleFormatter(summaryTemplate string, detailFunc func(any) any, opts ...CollapsibleOption) func(any) any
CollapsibleFormatter creates a field formatter that produces collapsible values Takes summaryTemplate and detailFunc parameters (Requirement 2.4) Returns field formatter that produces CollapsibleValue instances
func CollectErrors ¶
CollectErrors collects all non-nil errors into a MultiError
func DetectType ¶
DetectType attempts to determine the type of a value
func DisableGlobalDebugTracing ¶
func DisableGlobalDebugTracing()
DisableGlobalDebugTracing disables global debug tracing
func EnableGlobalDebugTracing ¶
func EnableGlobalDebugTracing(level DebugLevel, output io.Writer)
EnableGlobalDebugTracing enables global debug tracing at the specified level
func ErrorListFormatter ¶ added in v2.1.0
func ErrorListFormatter(opts ...CollapsibleOption) func(any) any
ErrorListFormatter creates a formatter for error arrays (Requirement 9.1, 9.2)
func ErrorWithContext ¶
ErrorWithContext wraps an error with context information
func FilePathFormatter ¶ added in v2.1.0
func FilePathFormatter(maxLength int, opts ...CollapsibleOption) func(any) any
FilePathFormatter creates a formatter for long file paths (Requirement 9.3, 9.4)
func GetPanicValue ¶
GetPanicValue extracts the panic value from a PanicError
func GetStackTrace ¶
GetStackTrace extracts the stack trace from a PanicError
func GlobalError ¶
GlobalError logs an error message using the global tracer
func GlobalInfo ¶
GlobalInfo logs an info message using the global tracer
func GlobalTrace ¶
GlobalTrace logs a trace message using the global tracer
func GlobalWarn ¶
GlobalWarn logs a warning message using the global tracer
func IsCancelled ¶
IsCancelled checks if an error represents a cancellation
func JSONFormatter ¶ added in v2.1.0
func JSONFormatter(maxLength int, opts ...CollapsibleOption) func(any) any
JSONFormatter creates a formatter for complex data structures (Requirement 9.5)
func NewMarkdownRendererWithFrontMatter ¶
NewMarkdownRendererWithFrontMatter creates a markdown renderer with front matter
func NewMarkdownRendererWithOptions ¶
func NewMarkdownRendererWithOptions(includeToC bool, frontMatter map[string]string) *markdownRenderer
NewMarkdownRendererWithOptions creates a markdown renderer with both ToC and front matter
func NewMarkdownRendererWithToC ¶
func NewMarkdownRendererWithToC(enabled bool) *markdownRenderer
NewMarkdownRendererWithToC creates a markdown renderer with table of contents enabled
func SafeExecute ¶
SafeExecute executes a function with panic recovery
func SafeExecuteWithResult ¶
SafeExecuteWithResult executes a function with panic recovery and returns both result and error
func SafeExecuteWithResultAndTracer ¶
func SafeExecuteWithResultAndTracer(tracer *DebugTracer, operation string, fn func() (any, error)) (result any, finalErr error)
SafeExecuteWithResultAndTracer executes a function with panic recovery, result return, and optional debug tracing
func SafeExecuteWithTracer ¶
func SafeExecuteWithTracer(tracer *DebugTracer, operation string, fn func() error) (finalErr error)
SafeExecuteWithTracer executes a function with panic recovery and optional debug tracing
func SetGlobalDebugTracer ¶
func SetGlobalDebugTracer(tracer *DebugTracer)
SetGlobalDebugTracer sets the global debug tracer
func StyleBoldIf ¶ added in v2.3.0
StyleBoldIf conditionally applies bold styling based on useBold flag. When useBold is false, returns the original text unchanged.
func StyleInfo ¶ added in v2.3.0
StyleInfo applies blue styling to text (for informational content).
func StyleInfoIf ¶ added in v2.3.0
StyleInfoIf conditionally applies info styling based on useColor flag. When useColor is false, returns the original text unchanged.
func StyleNegative ¶ added in v2.3.0
StyleNegative applies bold red styling to text (for failure/negative states). Alias for StyleWarning to match v1 naming patterns.
func StyleNegativeIf ¶ added in v2.3.0
StyleNegativeIf conditionally applies negative styling based on useColor flag. When useColor is false, returns the original text unchanged.
func StylePositive ¶ added in v2.3.0
StylePositive applies bold green styling to text (for success/positive states). Equivalent to v1's StringPositiveInline with colors enabled.
func StylePositiveIf ¶ added in v2.3.0
StylePositiveIf conditionally applies positive styling based on useColor flag. When useColor is false, returns the original text unchanged.
func StyleWarning ¶ added in v2.3.0
StyleWarning applies bold red styling to text (for warnings/errors). Equivalent to v1's StringWarningInline with colors enabled.
func StyleWarningIf ¶ added in v2.3.0
StyleWarningIf conditionally applies warning styling based on useColor flag. When useColor is false, returns the original text unchanged. This is useful for respecting terminal capabilities or user preferences.
func ValidateInput ¶
ValidateInput performs early validation with helpful error messages
func ValidateMapNonEmpty ¶
func ValidateMapNonEmpty[K comparable, V any](field string, value map[K]V) error
ValidateMapNonEmpty validates that a map is not empty
func ValidateNonEmpty ¶
ValidateNonEmpty validates that a string field is not empty
func ValidateNonNil ¶
ValidateNonNil validates that a value is not nil
func ValidateSliceNonEmpty ¶
ValidateSliceNonEmpty validates that a slice is not empty
func ValidateStatelessOperation ¶ added in v2.4.0
ValidateStatelessOperation validates that an operation is stateless by applying it twice to cloned content and comparing the results using reflect.DeepEqual().
This utility helps detect non-deterministic operations that might cause issues in concurrent environments. An operation is considered stateless if:
- It produces the same output when given the same input
- It doesn't modify shared mutable state
- It doesn't depend on external factors like time or random numbers
Limitations:
- Only detects output non-determinism, not hidden state mutations
- Cannot detect external side effects (file writes, network calls)
- Cannot detect non-deterministic operations that happen to match twice
Usage Example:
func TestMyOperation_IsStateless(t *testing.T) {
op := NewMyOperation(config)
testContent := &TableContent{...}
if err := ValidateStatelessOperation(t, op, testContent); err != nil {
t.Fatalf("Operation is not stateless: %v", err)
}
}
Thread Safety: Operations that pass this validation are safe for concurrent use with per-content transformations, as they don't maintain mutable state that could cause data races.
Types ¶
type AddColumnOp ¶ added in v2.2.0
type AddColumnOp struct {
// contains filtered or unexported fields
}
AddColumnOp implements operation to add calculated fields
func NewAddColumnOp ¶ added in v2.2.0
func NewAddColumnOp(name string, fn func(Record) any, position *int) *AddColumnOp
NewAddColumnOp creates a new addColumn operation
func (*AddColumnOp) ApplyWithFormat ¶ added in v2.2.0
func (o *AddColumnOp) ApplyWithFormat(ctx context.Context, content Content, format string) (Content, error)
ApplyWithFormat applies the addColumn operation with format context
func (*AddColumnOp) CanOptimize ¶ added in v2.2.0
func (o *AddColumnOp) CanOptimize(with Operation) bool
CanOptimize returns true if this addColumn can be optimized with another operation
func (*AddColumnOp) CanTransform ¶ added in v2.2.0
func (o *AddColumnOp) CanTransform(content Content, format string) bool
CanTransform checks if addColumn operation applies to the given content and format
func (*AddColumnOp) Name ¶ added in v2.2.0
func (o *AddColumnOp) Name() string
Name returns the operation name
func (*AddColumnOp) Validate ¶ added in v2.2.0
func (o *AddColumnOp) Validate() error
Validate checks if the addColumn operation is valid
type AggregateFunc ¶ added in v2.2.0
AggregateFunc defines the signature for aggregate functions
func AverageAggregate ¶ added in v2.2.0
func AverageAggregate(field string) AggregateFunc
AverageAggregate returns an aggregate function that calculates the average
func CountAggregate ¶ added in v2.2.0
func CountAggregate() AggregateFunc
CountAggregate returns an aggregate function that counts records
func MaxAggregate ¶ added in v2.2.0
func MaxAggregate(field string) AggregateFunc
MaxAggregate returns an aggregate function that finds the maximum value
func MinAggregate ¶ added in v2.2.0
func MinAggregate(field string) AggregateFunc
MinAggregate returns an aggregate function that finds the minimum value
func SumAggregate ¶ added in v2.2.0
func SumAggregate(field string) AggregateFunc
SumAggregate returns an aggregate function that sums numeric values
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder constructs documents with a fluent API
func (*Builder) AddCollapsibleSection ¶ added in v2.1.0
func (b *Builder) AddCollapsibleSection(title string, content []Content, opts ...CollapsibleSectionOption) *Builder
AddCollapsibleSection adds a collapsible section containing the provided content
func (*Builder) AddCollapsibleTable ¶ added in v2.1.0
func (b *Builder) AddCollapsibleTable(title string, table *TableContent, opts ...CollapsibleSectionOption) *Builder
AddCollapsibleTable adds a collapsible section containing a single table
func (*Builder) AddContent ¶
AddContent is a helper method to safely add content
func (*Builder) CollapsibleSection ¶ added in v2.1.0
func (b *Builder) CollapsibleSection(title string, fn func(*Builder), opts ...CollapsibleSectionOption) *Builder
CollapsibleSection groups content under an expandable/collapsible section with hierarchical structure
func (*Builder) DrawIO ¶
func (b *Builder) DrawIO(title string, records []Record, header DrawIOHeader) *Builder
DrawIO adds Draw.io diagram content with CSV configuration
func (*Builder) GanttChart ¶
GanttChart adds a Gantt chart with tasks
func (*Builder) Section ¶
func (b *Builder) Section(title string, fn func(*Builder), opts ...SectionOption) *Builder
Section groups content under a heading with hierarchical structure
func (*Builder) SetMetadata ¶
SetMetadata sets a metadata key-value pair
type CancelledError ¶
type CancelledError struct {
Operation string // The operation that was cancelled
Cause error // The cancellation cause (usually context.Canceled or context.DeadlineExceeded)
}
CancelledError represents an operation that was cancelled
func NewCancelledError ¶
func NewCancelledError(operation string, cause error) *CancelledError
NewCancelledError creates a new cancelled error
func (*CancelledError) Error ¶
func (e *CancelledError) Error() string
Error returns the error message
func (*CancelledError) Unwrap ¶
func (e *CancelledError) Unwrap() error
Unwrap returns the underlying error
type ChartContent ¶
type ChartContent struct {
// contains filtered or unexported fields
}
ChartContent represents specialized chart data for Gantt, pie charts, etc.
func NewChartContent ¶
func NewChartContent(title, chartType string, data any) *ChartContent
NewChartContent creates a new chart content
func NewGanttChart ¶
func NewGanttChart(title string, tasks []GanttTask) *ChartContent
NewGanttChart creates a new Gantt chart content
func NewPieChart ¶
func NewPieChart(title string, slices []PieSlice, showData bool) *ChartContent
NewPieChart creates a new pie chart content
func (*ChartContent) AppendBinary ¶
func (c *ChartContent) AppendBinary(b []byte) ([]byte, error)
AppendBinary implements encoding.BinaryAppender
func (*ChartContent) AppendText ¶
func (c *ChartContent) AppendText(b []byte) ([]byte, error)
AppendText implements encoding.TextAppender
func (*ChartContent) Clone ¶ added in v2.4.0
func (c *ChartContent) Clone() Content
Clone creates a deep copy of the ChartContent
func (*ChartContent) GetChartType ¶
func (c *ChartContent) GetChartType() string
GetChartType returns the chart type
func (*ChartContent) GetTitle ¶
func (c *ChartContent) GetTitle() string
GetTitle returns the chart title
func (*ChartContent) GetTransformations ¶ added in v2.4.0
func (c *ChartContent) GetTransformations() []Operation
GetTransformations returns the transformations attached to this chart
type CollapsibleOption ¶ added in v2.1.0
type CollapsibleOption func(*DefaultCollapsibleValue)
CollapsibleOption configures a DefaultCollapsibleValue
func WithCodeFences ¶ added in v2.1.2
func WithCodeFences(language string) CollapsibleOption
WithCodeFences enables wrapping details content in code fences
func WithCollapsibleExpanded ¶ added in v2.3.0
func WithCollapsibleExpanded(expanded bool) CollapsibleOption
WithCollapsibleExpanded sets whether the collapsible value should be expanded by default
func WithExpanded
deprecated
added in
v2.1.0
func WithExpanded(expanded bool) CollapsibleOption
WithExpanded sets whether the collapsible value should be expanded by default
Deprecated: Use WithCollapsibleExpanded instead for consistency with section options
func WithFormatHint ¶ added in v2.1.0
func WithFormatHint(format string, hints map[string]any) CollapsibleOption
WithFormatHint adds format-specific rendering hints
func WithMaxLength ¶ added in v2.1.0
func WithMaxLength(length int) CollapsibleOption
WithMaxLength sets the maximum character length for details before truncation
func WithTruncateIndicator ¶ added in v2.1.0
func WithTruncateIndicator(indicator string) CollapsibleOption
WithTruncateIndicator sets the indicator text used when content is truncated
func WithoutCodeFences ¶ added in v2.1.2
func WithoutCodeFences() CollapsibleOption
WithoutCodeFences explicitly disables code fence wrapping
type CollapsibleSection ¶ added in v2.1.0
type CollapsibleSection interface {
Content // Implement the Content interface to integrate with the content system
// Title returns the section title/summary
Title() string
// Content returns the nested content items
Content() []Content
// IsExpanded returns whether this section should be expanded by default
IsExpanded() bool
// Level returns the nesting level (0-3 supported per Requirement 15.9)
Level() int
// FormatHint provides renderer-specific hints
FormatHint(format string) map[string]any
}
CollapsibleSection represents entire content blocks that can be expanded/collapsed (Requirement 15)
type CollapsibleSectionOption ¶ added in v2.1.0
type CollapsibleSectionOption func(*DefaultCollapsibleSection)
CollapsibleSectionOption is a functional option for CollapsibleSection configuration
func WithSectionExpanded ¶ added in v2.1.0
func WithSectionExpanded(expanded bool) CollapsibleSectionOption
WithSectionExpanded sets whether the section should be expanded by default
func WithSectionFormatHint ¶ added in v2.1.0
func WithSectionFormatHint(format string, hints map[string]any) CollapsibleSectionOption
WithSectionFormatHint adds format-specific hints for the section
func WithSectionLevel ¶ added in v2.1.0
func WithSectionLevel(level int) CollapsibleSectionOption
WithSectionLevel sets the nesting level (0-3 supported per Requirement 15.9)
type CollapsibleValue ¶ added in v2.1.0
type CollapsibleValue interface {
// Summary returns the collapsed view (what users see initially)
Summary() string
// Details returns the expanded content of any type to support structured data
Details() any
// IsExpanded returns whether this should be expanded by default
IsExpanded() bool
// FormatHint provides renderer-specific hints
FormatHint(format string) map[string]any
}
CollapsibleValue represents a value that can be expanded/collapsed across formats This interface enables table cells and content to display summary information with expandable details, working consistently across all output formats.
type ColorScheme ¶
type ColorScheme struct {
Success string // Color for positive/success values
Warning string // Color for warning values
Error string // Color for error/failure values
Info string // Color for informational values
}
ColorScheme defines color configuration
func DefaultColorScheme ¶
func DefaultColorScheme() ColorScheme
DefaultColorScheme returns a default color scheme
type ColorTransformer ¶
type ColorTransformer struct {
// contains filtered or unexported fields
}
ColorTransformer adds ANSI color codes to output
func NewColorTransformer ¶
func NewColorTransformer() *ColorTransformer
NewColorTransformer creates a new color transformer with default scheme
func NewColorTransformerWithScheme ¶
func NewColorTransformerWithScheme(scheme ColorScheme) *ColorTransformer
NewColorTransformerWithScheme creates a color transformer with custom scheme
func (*ColorTransformer) CanTransform ¶
func (c *ColorTransformer) CanTransform(format string) bool
CanTransform checks if this transformer applies to the given format
func (*ColorTransformer) Name ¶
func (c *ColorTransformer) Name() string
Name returns the transformer name
func (*ColorTransformer) Priority ¶
func (c *ColorTransformer) Priority() int
Priority returns the transformer priority (lower = earlier)
type Content ¶
type Content interface {
// Type returns the content type
Type() ContentType
// ID returns a unique identifier for this content
ID() string
// Clone creates a deep copy of this content
Clone() Content
// GetTransformations returns the transformations attached to this content
GetTransformations() []Operation
// Encoding interfaces for efficient serialization
encoding.TextAppender
encoding.BinaryAppender
}
Content is the core interface all content must implement
type ContentType ¶
type ContentType int
ContentType identifies the type of content
const ( // ContentTypeTable represents tabular data content ContentTypeTable ContentType = iota // ContentTypeText represents unstructured text content ContentTypeText // ContentTypeRaw represents format-specific raw content ContentTypeRaw // ContentTypeSection represents grouped content with a heading ContentTypeSection )
func (ContentType) String ¶
func (ct ContentType) String() string
String returns the string representation of the ContentType
type ContextError ¶
type ContextError struct {
Operation string // The operation that failed (e.g., "render", "transform", "write")
Context map[string]any // Additional context information
Cause error // The underlying error
}
ContextError represents an error with additional context information
func NewContextError ¶
func NewContextError(operation string, cause error) *ContextError
NewContextError creates a new context error
func (*ContextError) AddContext ¶
func (e *ContextError) AddContext(key string, value any) *ContextError
AddContext adds context information to the error
func (*ContextError) Error ¶
func (e *ContextError) Error() string
Error returns the error message with context
func (*ContextError) Unwrap ¶
func (e *ContextError) Unwrap() error
Unwrap returns the underlying error
type DataIntegrityValidator ¶
type DataIntegrityValidator struct {
// contains filtered or unexported fields
}
DataIntegrityValidator ensures transformers don't modify original document data
func NewDataIntegrityValidator ¶
func NewDataIntegrityValidator(originalData []byte) *DataIntegrityValidator
NewDataIntegrityValidator creates a validator for the original data
func (*DataIntegrityValidator) GetOriginalData ¶
func (div *DataIntegrityValidator) GetOriginalData() []byte
GetOriginalData returns a copy of the original data
func (*DataIntegrityValidator) ValidateIntegrity ¶
func (div *DataIntegrityValidator) ValidateIntegrity(currentData []byte) bool
ValidateIntegrity checks that the original data hasn't been modified
type DataTransformer ¶ added in v2.2.0
type DataTransformer interface {
// Name returns the transformer name for identification
Name() string
// TransformData modifies structured content data
TransformData(ctx context.Context, content Content, format string) (Content, error)
// CanTransform checks if this transformer applies to the given content and format
CanTransform(content Content, format string) bool
// Priority determines transform order (lower = earlier)
Priority() int
// Describe returns a human-readable description for debugging
Describe() string
}
DataTransformer operates on structured data before rendering
type DebugLevel ¶
type DebugLevel int
DebugLevel represents the level of debug output
const ( // DebugOff disables all debug output DebugOff DebugLevel = iota // DebugError shows only errors and panics DebugError // DebugWarn shows warnings, errors, and panics DebugWarn // DebugInfo shows general information, warnings, errors, and panics DebugInfo // DebugTrace shows detailed trace information including all operations DebugTrace )
func (DebugLevel) String ¶
func (dl DebugLevel) String() string
String returns the string representation of the debug level
type DebugTracer ¶
type DebugTracer struct {
// contains filtered or unexported fields
}
DebugTracer provides debug tracing capabilities for the rendering pipeline
func GetGlobalDebugTracer ¶
func GetGlobalDebugTracer() *DebugTracer
GetGlobalDebugTracer returns the global debug tracer
func NewDebugTracer ¶
func NewDebugTracer(level DebugLevel, output io.Writer) *DebugTracer
NewDebugTracer creates a new debug tracer
func (*DebugTracer) AddContext ¶
func (dt *DebugTracer) AddContext(key string, value any)
AddContext adds context information to the tracer
func (*DebugTracer) ClearContext ¶
func (dt *DebugTracer) ClearContext()
ClearContext clears all context information
func (*DebugTracer) Error ¶
func (dt *DebugTracer) Error(operation string, message string, args ...any)
Error logs an error-level message
func (*DebugTracer) GetLevel ¶
func (dt *DebugTracer) GetLevel() DebugLevel
GetLevel returns the current debug level
func (*DebugTracer) Info ¶
func (dt *DebugTracer) Info(operation string, message string, args ...any)
Info logs an info-level message
func (*DebugTracer) IsEnabled ¶
func (dt *DebugTracer) IsEnabled() bool
IsEnabled returns whether debug tracing is enabled
func (*DebugTracer) RemoveContext ¶
func (dt *DebugTracer) RemoveContext(key string)
RemoveContext removes context information from the tracer
func (*DebugTracer) SetLevel ¶
func (dt *DebugTracer) SetLevel(level DebugLevel)
SetLevel sets the debug level
func (*DebugTracer) Trace ¶
func (dt *DebugTracer) Trace(operation string, message string, args ...any)
Trace logs a trace-level message
func (*DebugTracer) TraceOperation ¶
func (dt *DebugTracer) TraceOperation(operation string, fn func() error) error
TraceOperation traces an operation with start and end messages
func (*DebugTracer) TraceOperationWithResult ¶
func (dt *DebugTracer) TraceOperationWithResult(operation string, fn func() (any, error)) (any, error)
TraceOperationWithResult traces an operation with start, end, and result information
type DefaultCollapsibleSection ¶ added in v2.1.0
type DefaultCollapsibleSection struct {
// contains filtered or unexported fields
}
DefaultCollapsibleSection provides a standard implementation for section-level collapsible content
func NewCollapsibleMultiTable ¶ added in v2.1.0
func NewCollapsibleMultiTable(title string, tables []*TableContent, opts ...CollapsibleSectionOption) *DefaultCollapsibleSection
NewCollapsibleMultiTable creates a collapsible section containing multiple tables
func NewCollapsibleReport ¶ added in v2.1.0
func NewCollapsibleReport(title string, content []Content, opts ...CollapsibleSectionOption) *DefaultCollapsibleSection
NewCollapsibleReport creates a collapsible section with mixed content types
func NewCollapsibleSection ¶ added in v2.1.0
func NewCollapsibleSection(title string, content []Content, opts ...CollapsibleSectionOption) *DefaultCollapsibleSection
NewCollapsibleSection creates a new collapsible section
func NewCollapsibleTable ¶ added in v2.1.0
func NewCollapsibleTable(title string, table *TableContent, opts ...CollapsibleSectionOption) *DefaultCollapsibleSection
NewCollapsibleTable creates a collapsible section containing a single table
func (*DefaultCollapsibleSection) AppendBinary ¶ added in v2.1.0
func (cs *DefaultCollapsibleSection) AppendBinary(b []byte) ([]byte, error)
AppendBinary implements encoding.BinaryAppender
func (*DefaultCollapsibleSection) AppendText ¶ added in v2.1.0
func (cs *DefaultCollapsibleSection) AppendText(b []byte) ([]byte, error)
AppendText implements encoding.TextAppender with collapsible section rendering
func (*DefaultCollapsibleSection) Clone ¶ added in v2.4.0
func (cs *DefaultCollapsibleSection) Clone() Content
Clone creates a deep copy of the DefaultCollapsibleSection
func (*DefaultCollapsibleSection) Content ¶ added in v2.1.0
func (cs *DefaultCollapsibleSection) Content() []Content
Content returns the nested content items
func (*DefaultCollapsibleSection) FormatHint ¶ added in v2.1.0
func (cs *DefaultCollapsibleSection) FormatHint(format string) map[string]any
FormatHint provides renderer-specific hints
func (*DefaultCollapsibleSection) GetTransformations ¶ added in v2.4.0
func (cs *DefaultCollapsibleSection) GetTransformations() []Operation
GetTransformations returns the transformations attached to this collapsible section
func (*DefaultCollapsibleSection) ID ¶ added in v2.1.0
func (cs *DefaultCollapsibleSection) ID() string
ID returns the unique identifier for this content
func (*DefaultCollapsibleSection) IsExpanded ¶ added in v2.1.0
func (cs *DefaultCollapsibleSection) IsExpanded() bool
IsExpanded returns whether this section should be expanded by default
func (*DefaultCollapsibleSection) Level ¶ added in v2.1.0
func (cs *DefaultCollapsibleSection) Level() int
Level returns the nesting level (0-3 supported per Requirement 15.9)
func (*DefaultCollapsibleSection) Title ¶ added in v2.1.0
func (cs *DefaultCollapsibleSection) Title() string
Title returns the section title/summary
func (*DefaultCollapsibleSection) Type ¶ added in v2.1.0
func (cs *DefaultCollapsibleSection) Type() ContentType
Type returns the content type for CollapsibleSection
type DefaultCollapsibleValue ¶ added in v2.1.0
type DefaultCollapsibleValue struct {
// contains filtered or unexported fields
}
DefaultCollapsibleValue provides a standard implementation of CollapsibleValue
func NewCollapsibleValue ¶ added in v2.1.0
func NewCollapsibleValue(summary string, details any, opts ...CollapsibleOption) *DefaultCollapsibleValue
NewCollapsibleValue creates a new collapsible value with configuration options
func (*DefaultCollapsibleValue) CodeLanguage ¶ added in v2.1.2
func (d *DefaultCollapsibleValue) CodeLanguage() string
CodeLanguage returns the language to use for syntax highlighting in code fences
func (*DefaultCollapsibleValue) Details ¶ added in v2.1.0
func (d *DefaultCollapsibleValue) Details() any
Details returns the expanded content with character limit truncation Implements lazy evaluation to avoid unnecessary processing (Requirement 10.3)
func (*DefaultCollapsibleValue) FormatHint ¶ added in v2.1.0
func (d *DefaultCollapsibleValue) FormatHint(format string) map[string]any
FormatHint returns renderer-specific hints for the given format Implements lazy evaluation to avoid processing hints when not used (Requirement 10.5)
func (*DefaultCollapsibleValue) IsExpanded ¶ added in v2.1.0
func (d *DefaultCollapsibleValue) IsExpanded() bool
IsExpanded returns whether this should be expanded by default
func (*DefaultCollapsibleValue) String ¶ added in v2.1.0
func (d *DefaultCollapsibleValue) String() string
String implements the Stringer interface for debugging
func (*DefaultCollapsibleValue) Summary ¶ added in v2.1.0
func (d *DefaultCollapsibleValue) Summary() string
Summary returns the collapsed view with fallback handling
func (*DefaultCollapsibleValue) UseCodeFences ¶ added in v2.1.2
func (d *DefaultCollapsibleValue) UseCodeFences() bool
UseCodeFences returns whether details should be wrapped in code fences
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document represents a collection of content to be output
func (*Document) GetContents ¶
GetContents returns a copy of the document's contents to prevent external modification
func (*Document) GetMetadata ¶
GetMetadata returns a copy of the document's metadata
type DrawIOConnection ¶
type DrawIOConnection struct {
From string // Source column
To string // Target column
Invert bool // Invert direction
Label string // Connection label
Style string // Connection style (curved, straight, etc.)
}
DrawIOConnection defines relationships between nodes
type DrawIOContent ¶
type DrawIOContent struct {
// contains filtered or unexported fields
}
DrawIOContent represents Draw.io diagram data for CSV export
func NewDrawIOContent ¶
func NewDrawIOContent(title string, records []Record, header DrawIOHeader) *DrawIOContent
NewDrawIOContent creates a new Draw.io content
func NewDrawIOContentFromTable ¶
func NewDrawIOContentFromTable(table *TableContent, header DrawIOHeader) *DrawIOContent
NewDrawIOContentFromTable creates Draw.io content from table data
func (*DrawIOContent) AppendBinary ¶
func (d *DrawIOContent) AppendBinary(b []byte) ([]byte, error)
AppendBinary implements encoding.BinaryAppender
func (*DrawIOContent) AppendText ¶
func (d *DrawIOContent) AppendText(b []byte) ([]byte, error)
AppendText implements encoding.TextAppender
func (*DrawIOContent) Clone ¶ added in v2.4.0
func (d *DrawIOContent) Clone() Content
Clone creates a deep copy of the DrawIOContent
func (*DrawIOContent) GetHeader ¶
func (d *DrawIOContent) GetHeader() DrawIOHeader
GetHeader returns the Draw.io header configuration
func (*DrawIOContent) GetRecords ¶
func (d *DrawIOContent) GetRecords() []Record
GetRecords returns the data records
func (*DrawIOContent) GetTitle ¶
func (d *DrawIOContent) GetTitle() string
GetTitle returns the Draw.io content title
func (*DrawIOContent) GetTransformations ¶ added in v2.4.0
func (d *DrawIOContent) GetTransformations() []Operation
GetTransformations returns the transformations attached to this Draw.io content
func (*DrawIOContent) Type ¶
func (d *DrawIOContent) Type() ContentType
Type returns the content type
type DrawIOHeader ¶
type DrawIOHeader struct {
Label string // Node label with placeholders (%Name%)
Style string // Node style with placeholders (%Image%)
Ignore string // Columns to ignore in metadata
Connections []DrawIOConnection // Connection definitions
Link string // Link column
Layout string // Layout type (auto, horizontalflow, etc.)
NodeSpacing int // Spacing between nodes
LevelSpacing int // Spacing between levels
EdgeSpacing int // Spacing between edges
Parent string // Parent column for hierarchical diagrams
ParentStyle string // Style for parent nodes
Height string // Node height
Width string // Node width
Padding int // Padding when auto-sizing
Left string // X coordinate column
Top string // Y coordinate column
Identity string // Identity column
Namespace string // Namespace prefix
}
DrawIOHeader configures Draw.io CSV import behavior (v1 compatibility)
func DefaultDrawIOHeader ¶
func DefaultDrawIOHeader() DrawIOHeader
DefaultDrawIOHeader returns a header with default Draw.io settings
type EmojiTransformer ¶
type EmojiTransformer struct{}
EmojiTransformer converts text-based indicators to emoji equivalents
func (*EmojiTransformer) CanTransform ¶
func (e *EmojiTransformer) CanTransform(format string) bool
CanTransform checks if this transformer applies to the given format
func (*EmojiTransformer) Name ¶
func (e *EmojiTransformer) Name() string
Name returns the transformer name
func (*EmojiTransformer) Priority ¶
func (e *EmojiTransformer) Priority() int
Priority returns the transformer priority (lower = earlier)
type EnhancedColorTransformer ¶
type EnhancedColorTransformer struct {
*ColorTransformer
// contains filtered or unexported fields
}
EnhancedColorTransformer provides format-specific color handling
func NewEnhancedColorTransformer ¶
func NewEnhancedColorTransformer() *EnhancedColorTransformer
NewEnhancedColorTransformer creates an enhanced color transformer
func (*EnhancedColorTransformer) CanTransform ¶
func (etc *EnhancedColorTransformer) CanTransform(format string) bool
CanTransform checks if colors are supported for the format
type EnhancedEmojiTransformer ¶
type EnhancedEmojiTransformer struct {
*EmojiTransformer
// contains filtered or unexported fields
}
EnhancedEmojiTransformer provides format-specific emoji transformations
func NewEnhancedEmojiTransformer ¶
func NewEnhancedEmojiTransformer() *EnhancedEmojiTransformer
NewEnhancedEmojiTransformer creates an enhanced emoji transformer
func (*EnhancedEmojiTransformer) CanTransform ¶
func (eet *EnhancedEmojiTransformer) CanTransform(format string) bool
CanTransform provides enhanced format detection for emoji
type EnhancedSortTransformer ¶
type EnhancedSortTransformer struct {
*SortTransformer
// contains filtered or unexported fields
}
EnhancedSortTransformer provides format-specific sorting
func NewEnhancedSortTransformer ¶
func NewEnhancedSortTransformer(key string, ascending bool) *EnhancedSortTransformer
NewEnhancedSortTransformer creates an enhanced sort transformer
func (*EnhancedSortTransformer) CanTransform ¶
func (est *EnhancedSortTransformer) CanTransform(format string) bool
CanTransform checks if sorting is supported for the format
type ErrorSource ¶
type ErrorSource struct {
Component string // Component that generated the error (e.g., "renderer", "transformer", "writer")
Details map[string]any // Additional source details
}
ErrorSource provides information about where an error originated
type Field ¶
type Field struct {
Name string
Type string
Formatter func(any) any // Enhanced to support CollapsibleValue returns
Hidden bool
}
Field defines a table field
type FileWriter ¶
type FileWriter struct {
// contains filtered or unexported fields
}
FileWriter writes rendered output to files using a pattern
HTML Rendering Mode Selection: When appending HTML content in append mode, callers should: 1. For new files: Render with HTML format (full page with <!-- go-output-append --> marker) 2. For existing files: Render with HTMLFragment format (no page structure, content only)
The FileWriter will automatically detect file existence and append appropriately. The marker positioning ensures that fragments are inserted before the marker, preserving the original HTML structure and allowing multiple appends.
func NewFileWriter ¶
func NewFileWriter(dir, pattern string) (*FileWriter, error)
NewFileWriter creates a new FileWriter with the specified directory and pattern
func NewFileWriterWithOptions ¶
func NewFileWriterWithOptions(dir, pattern string, opts ...FileWriterOption) (*FileWriter, error)
NewFileWriterWithOptions creates a FileWriter with options
func (*FileWriter) GetDirectory ¶
func (fw *FileWriter) GetDirectory() string
GetDirectory returns the base directory for this writer
func (*FileWriter) SetExtension ¶
func (fw *FileWriter) SetExtension(format, ext string)
SetExtension sets a custom extension for a format
type FileWriterOption ¶
type FileWriterOption func(*FileWriter)
FileWriterOption configures a FileWriter
func WithAbsolutePaths ¶ added in v2.0.2
func WithAbsolutePaths() FileWriterOption
WithAbsolutePaths allows absolute paths in filenames
func WithAppendMode ¶ added in v2.4.0
func WithAppendMode() FileWriterOption
WithAppendMode enables append mode for the FileWriter.
When append mode is enabled, the FileWriter will append new content to existing files instead of replacing them. The append behavior varies by format:
- JSON/YAML: Byte-level appending (useful for NDJSON-style logging). This produces concatenated output like {"a":1}{"b":2}, not merged JSON structures.
- CSV: Headers are automatically skipped when appending to existing files. Only data rows are appended to preserve CSV structure.
- HTML: Uses the <!-- go-output-append --> comment marker system. New HTML fragments are inserted before the marker. The target file must contain this marker or an error will be returned. For new files, a full HTML page with the marker is created.
- Other formats (Table, Markdown, etc.): Pure byte-level appending.
Thread Safety: The FileWriter uses sync.Mutex to serialize write operations when multiple goroutines share the same FileWriter instance. This provides thread-safety within a single process, but does NOT protect across separate FileWriter instances or separate processes writing to the same file.
File Creation: If the target file does not exist, it will be created with the configured permissions (default 0644). The append mode will not take effect until subsequent writes to the same file.
UTF-8 Encoding: All files are assumed to be UTF-8 encoded. Non-UTF-8 files may produce unexpected results.
Example:
// Create FileWriter with append mode
fw, err := output.NewFileWriterWithOptions(
"./logs",
"app-{format}.{ext}",
output.WithAppendMode(),
)
// First write creates the file
fw.Write(ctx, output.FormatJSON, []byte(`{"event":"start"}`))
// Second write appends (NDJSON pattern)
fw.Write(ctx, output.FormatJSON, []byte(`{"event":"end"}`))
// Result: {"event":"start"}{"event":"end"}
func WithDisallowUnsafeAppend ¶ added in v2.4.0
func WithDisallowUnsafeAppend() FileWriterOption
WithDisallowUnsafeAppend prevents appending to JSON/YAML files.
By default, FileWriter allows byte-level appending to JSON and YAML files when WithAppendMode() is enabled. This is useful for NDJSON-style logging where each line is a separate JSON object. However, this produces concatenated output like {"a":1}{"b":2} which is NOT valid JSON for most parsers.
When WithDisallowUnsafeAppend() is enabled, any attempt to append to JSON or YAML files will return an error. This helps prevent accidental creation of invalid structured data files.
This option has no effect if WithAppendMode() is not enabled.
Example:
// Prevent accidental JSON/YAML appending
fw, err := output.NewFileWriterWithOptions(
"./output",
"report-{format}.{ext}",
output.WithAppendMode(),
output.WithDisallowUnsafeAppend(), // Forbid JSON/YAML appending
)
// This will succeed (HTML supports safe appending)
fw.Write(ctx, output.FormatHTML, htmlData)
// This will return an error
fw.Write(ctx, output.FormatJSON, jsonData)
func WithExtensions ¶
func WithExtensions(extensions map[string]string) FileWriterOption
WithExtensions sets custom format to extension mappings
func WithPermissions ¶ added in v2.4.0
func WithPermissions(perm os.FileMode) FileWriterOption
WithPermissions sets custom file permissions for newly created files.
The default permission is 0644 (rw-r--r--), which allows the owner to read and write, while others can only read. This is the standard Unix permission for user-created files.
Common permission values:
- 0644: Owner read/write, group/others read only (default)
- 0600: Owner read/write, no access for others (secure)
- 0666: Read/write for everyone (less secure)
- 0755: Owner read/write/execute, others read/execute (for directories)
This option only affects new file creation. Permissions of existing files are not modified.
Example:
// Create files with restricted permissions
fw, err := output.NewFileWriterWithOptions(
"./secure",
"data-{format}.{ext}",
output.WithPermissions(0600), // Only owner can read/write
)
type FilterOp ¶ added in v2.2.0
type FilterOp struct {
// contains filtered or unexported fields
}
FilterOp implements filtering operation using predicate functions
func NewFilterOp ¶ added in v2.2.0
NewFilterOp creates a new filter operation with the given predicate
func (*FilterOp) ApplyWithFormat ¶ added in v2.2.0
func (o *FilterOp) ApplyWithFormat(ctx context.Context, content Content, format string) (Content, error)
ApplyWithFormat applies the filter operation with format context
func (*FilterOp) CanOptimize ¶ added in v2.2.0
CanOptimize returns true if this filter can be optimized with another operation
func (*FilterOp) CanTransform ¶ added in v2.2.0
CanTransform checks if filter operation applies to the given content and format
type Format ¶
Format represents an output format configuration
func HTML ¶
func HTML() Format
HTML returns a Format configured for complete HTML documents with the default template
func HTMLFragment ¶ added in v2.4.0
func HTMLFragment() Format
HTMLFragment returns a Format configured for HTML fragments without template wrapping
func HTMLWithTemplate ¶ added in v2.4.0
func HTMLWithTemplate(template *HTMLTemplate) Format
HTMLWithTemplate creates an HTML format with a custom template If template is nil, produces fragment output (no template wrapping) If template is provided, produces complete HTML document with the template
func MarkdownWithFrontMatter ¶
MarkdownWithFrontMatter creates a markdown format with front matter for v1 compatibility
func MarkdownWithOptions ¶
MarkdownWithOptions creates a markdown format with ToC and front matter for v1 compatibility
func MarkdownWithToC ¶
MarkdownWithToC creates a markdown format with table of contents for v1 compatibility
func Table ¶
func Table() Format
Table returns a Format configured for terminal table output with default style
func TableBold ¶
func TableBold() Format
TableBold returns a Format configured for terminal table output with Bold style
func TableColoredBright ¶
func TableColoredBright() Format
TableColoredBright returns a Format configured for terminal table output with ColoredBright style
func TableDefault ¶
func TableDefault() Format
TableDefault returns a Format configured for terminal table output with Default style
func TableLight ¶
func TableLight() Format
TableLight returns a Format configured for terminal table output with Light style
func TableRounded ¶
func TableRounded() Format
TableRounded returns a Format configured for terminal table output with Rounded style
func TableWithMaxColumnWidth ¶ added in v2.3.0
TableWithMaxColumnWidth creates a table format with maximum column width
func TableWithStyle ¶
TableWithStyle creates a table format with the specified style for v1 compatibility
func TableWithStyleAndMaxColumnWidth ¶ added in v2.3.0
TableWithStyleAndMaxColumnWidth creates a table format with specified style and maximum column width
type FormatAwareOperation ¶ added in v2.2.0
type FormatAwareOperation interface {
Operation
// ApplyWithFormat applies the operation with format context
ApplyWithFormat(ctx context.Context, content Content, format string) (Content, error)
// CanTransform checks if this operation applies to the given content and format
CanTransform(content Content, format string) bool
}
FormatAwareOperation extends Operation with format awareness
type FormatAwareTransformer ¶
type FormatAwareTransformer struct {
// contains filtered or unexported fields
}
FormatAwareTransformer wraps existing transformers with enhanced format detection
func NewFormatAwareTransformer ¶
func NewFormatAwareTransformer(transformer Transformer) *FormatAwareTransformer
NewFormatAwareTransformer wraps a transformer with format awareness
func (*FormatAwareTransformer) CanTransform ¶
func (fat *FormatAwareTransformer) CanTransform(format string) bool
CanTransform provides enhanced format detection
func (*FormatAwareTransformer) Name ¶
func (fat *FormatAwareTransformer) Name() string
Name returns the underlying transformer name
func (*FormatAwareTransformer) Priority ¶
func (fat *FormatAwareTransformer) Priority() int
Priority returns the underlying transformer priority
type FormatDetector ¶
type FormatDetector struct{}
FormatDetector provides advanced format detection capabilities
func NewFormatDetector ¶
func NewFormatDetector() *FormatDetector
NewFormatDetector creates a new format detector
func (*FormatDetector) IsGraphFormat ¶
func (fd *FormatDetector) IsGraphFormat(format string) bool
IsGraphFormat checks if a format is for graph/diagram output
func (*FormatDetector) IsStructuredFormat ¶
func (fd *FormatDetector) IsStructuredFormat(format string) bool
IsStructuredFormat checks if a format is structured (like JSON, YAML)
func (*FormatDetector) IsTabularFormat ¶
func (fd *FormatDetector) IsTabularFormat(format string) bool
IsTabularFormat checks if a format represents tabular data
func (*FormatDetector) IsTextBasedFormat ¶
func (fd *FormatDetector) IsTextBasedFormat(format string) bool
IsTextBasedFormat checks if a format supports text-based transformations
func (*FormatDetector) RequiresEscaping ¶
func (fd *FormatDetector) RequiresEscaping(format string) bool
RequiresEscaping checks if a format requires special character escaping
func (*FormatDetector) SupportsColors ¶
func (fd *FormatDetector) SupportsColors(format string) bool
SupportsColors checks if a format supports ANSI color codes
func (*FormatDetector) SupportsEmoji ¶
func (fd *FormatDetector) SupportsEmoji(format string) bool
SupportsEmoji checks if a format supports emoji characters
func (*FormatDetector) SupportsLineSplitting ¶
func (fd *FormatDetector) SupportsLineSplitting(format string) bool
SupportsLineSplitting checks if a format supports line splitting transformations
func (*FormatDetector) SupportsSorting ¶
func (fd *FormatDetector) SupportsSorting(format string) bool
SupportsSorting checks if a format supports data sorting
type GanttTask ¶
type GanttTask struct {
ID string
Title string
StartDate string
EndDate string
Duration string
Dependencies []string
Status string // "active", "done", "crit"
Section string // Section name for grouping
}
GanttTask represents a task in a Gantt chart
type GraphContent ¶
type GraphContent struct {
// contains filtered or unexported fields
}
GraphContent represents graph/diagram data
func NewGraphContent ¶
func NewGraphContent(title string, edges []Edge) *GraphContent
NewGraphContent creates a new graph content
func NewGraphContentFromTable ¶
func NewGraphContentFromTable(table *TableContent, fromColumn, toColumn string, labelColumn string) (*GraphContent, error)
NewGraphContentFromTable extracts graph data from table content using from/to columns
func (*GraphContent) AppendBinary ¶
func (g *GraphContent) AppendBinary(b []byte) ([]byte, error)
AppendBinary implements encoding.BinaryAppender
func (*GraphContent) AppendText ¶
func (g *GraphContent) AppendText(b []byte) ([]byte, error)
AppendText implements encoding.TextAppender
func (*GraphContent) Clone ¶ added in v2.4.0
func (g *GraphContent) Clone() Content
Clone creates a deep copy of the GraphContent
func (*GraphContent) GetEdges ¶
func (g *GraphContent) GetEdges() []Edge
GetEdges returns the graph edges
func (*GraphContent) GetNodes ¶
func (g *GraphContent) GetNodes() []string
GetNodes returns unique nodes from all edges
func (*GraphContent) GetTitle ¶
func (g *GraphContent) GetTitle() string
GetTitle returns the graph title
func (*GraphContent) GetTransformations ¶ added in v2.4.0
func (g *GraphContent) GetTransformations() []Operation
GetTransformations returns the transformations attached to this graph
type GroupByOp ¶ added in v2.2.0
type GroupByOp struct {
// contains filtered or unexported fields
}
GroupByOp implements grouping and aggregation operations
func NewGroupByOp ¶ added in v2.2.0
func NewGroupByOp(groupBy []string, aggregates map[string]AggregateFunc) *GroupByOp
NewGroupByOp creates a new groupBy operation
func (*GroupByOp) Apply ¶ added in v2.2.0
Apply groups table records and applies aggregate functions
func (*GroupByOp) ApplyWithFormat ¶ added in v2.2.0
func (o *GroupByOp) ApplyWithFormat(ctx context.Context, content Content, format string) (Content, error)
ApplyWithFormat applies the groupBy operation with format context
func (*GroupByOp) CanOptimize ¶ added in v2.2.0
CanOptimize returns true if this groupBy can be optimized with another operation
func (*GroupByOp) CanTransform ¶ added in v2.2.0
CanTransform checks if groupBy operation applies to the given content and format
type HTMLTemplate ¶ added in v2.4.0
type HTMLTemplate struct {
// Document metadata
//
// Title is the page title displayed in the browser tab and document head.
// Defaults to "Output Report" if empty. This field is HTML-escaped to prevent XSS.
Title string
// Language is the HTML lang attribute value that specifies the page language.
// Defaults to "en" if empty. This field is HTML-escaped to prevent XSS.
Language string
// Charset is the character encoding for the HTML document.
// Defaults to "UTF-8" if empty. This field is HTML-escaped to prevent XSS.
Charset string
// Meta tags
//
// Viewport is the viewport meta tag content controlling device rendering.
// Defaults to "width=device-width, initial-scale=1.0" if empty.
// This field is HTML-escaped to prevent XSS.
Viewport string
// Description is the page description meta tag for search engines and social media.
// Optional. This field is HTML-escaped to prevent XSS.
Description string
// Author is the page author meta tag.
// Optional. This field is HTML-escaped to prevent XSS.
Author string
// MetaTags contains additional custom meta tags as name → content pairs.
// Optional. Both names and values are HTML-escaped to prevent XSS.
MetaTags map[string]string
// Styling
//
// CSS contains embedded CSS content included directly in a <style> tag.
// Optional. WARNING: This content is NOT escaped or validated. Ensure this contains
// only trusted CSS from reliable sources. Malicious CSS can break document structure
// via </style> injection or potentially leak data.
CSS string
// ExternalCSS contains URLs to external stylesheets to be linked in the <head>.
// Optional. WARNING: URLs are HTML-escaped but NOT validated for safety. Ensure URLs
// use http:// or https:// schemes. JavaScript URLs (javascript:) are possible and
// create XSS risks.
ExternalCSS []string
// ThemeOverrides contains CSS custom property overrides applied after the main CSS.
// Use this to customize theme colors and other CSS variables without replacing
// the entire CSS block. Example: map[string]string{"--color-primary": "#ff0000"}.
// Optional. Property names and values are HTML-escaped to prevent injection,
// but no validation is performed on the CSS content itself.
ThemeOverrides map[string]string
// Additional content
//
// HeadExtra contains additional HTML content injected into the <head> section.
// Optional. WARNING: This content is NOT escaped or validated. Only use with content
// from trusted sources. Including user-provided content creates XSS vulnerabilities.
// Common use cases: custom fonts, analytics scripts, meta tags.
HeadExtra string
// BodyClass is the CSS class attribute value for the <body> element.
// Optional. This field is HTML-escaped to prevent XSS.
BodyClass string
// BodyAttrs contains additional attributes for the <body> element as name → value pairs.
// Optional. WARNING: Attribute names and values are HTML-escaped but event handlers
// (onclick, onload, etc.) are allowed. Ensure this map contains only safe attributes.
BodyAttrs map[string]string
// BodyExtra contains additional HTML content injected before the closing </body> tag.
// Optional. WARNING: This content is NOT escaped or validated. Only use with content
// from trusted sources. Including user-provided content creates XSS vulnerabilities.
// Common use cases: analytics scripts, tracking pixels, footer content.
BodyExtra string
}
HTMLTemplate defines the structure for HTML document templates with metadata, styling options, and customization points for full HTML document generation.
All string fields containing user-controlled content are HTML-escaped before inclusion in the final document to prevent XSS injection. Fields containing pre-validated content (CSS, scripts) are included as-is and are the user's responsibility to validate for safety.
var DefaultHTMLTemplate *HTMLTemplate
DefaultHTMLTemplate provides modern responsive styling with sensible defaults. It includes embedded CSS with mobile-first responsive design, modern CSS features (flexbox, grid), and accessibility support. The CSS uses custom properties for theming. This is initialized in html_css.go's init() function to ensure CSS constants are set.
var MermaidHTMLTemplate *HTMLTemplate
MermaidHTMLTemplate is optimized for diagram rendering with Mermaid.js integration. It includes CSS optimizations for mermaid diagram display and all features of DefaultHTMLTemplate. This is initialized in html_css.go's init() function to ensure CSS constants are set.
var MinimalHTMLTemplate *HTMLTemplate
MinimalHTMLTemplate provides basic HTML structure with no styling. Use this template when you want to apply your own CSS or embed in pages with existing styling. This is initialized in html_css.go's init() function.
type LimitOp ¶ added in v2.2.0
type LimitOp struct {
// contains filtered or unexported fields
}
LimitOp implements limit operation to restrict the number of records
func NewLimitOp ¶ added in v2.2.0
NewLimitOp creates a new limit operation with the given count
func (*LimitOp) ApplyWithFormat ¶ added in v2.2.0
func (o *LimitOp) ApplyWithFormat(ctx context.Context, content Content, format string) (Content, error)
ApplyWithFormat applies the limit operation with format context
func (*LimitOp) CanOptimize ¶ added in v2.2.0
CanOptimize returns true if this limit can be optimized with another operation
func (*LimitOp) CanTransform ¶ added in v2.2.0
CanTransform checks if limit operation applies to the given content and format
type LineSplitTransformer ¶
type LineSplitTransformer struct {
// contains filtered or unexported fields
}
LineSplitTransformer splits cells containing multiple values into separate rows
func NewLineSplitTransformer ¶
func NewLineSplitTransformer(separator string) *LineSplitTransformer
NewLineSplitTransformer creates a new line split transformer
func NewLineSplitTransformerDefault ¶
func NewLineSplitTransformerDefault() *LineSplitTransformer
NewLineSplitTransformerDefault creates a line split transformer with default newline separator
func (*LineSplitTransformer) CanTransform ¶
func (l *LineSplitTransformer) CanTransform(format string) bool
CanTransform checks if this transformer applies to the given format
func (*LineSplitTransformer) Name ¶
func (l *LineSplitTransformer) Name() string
Name returns the transformer name
func (*LineSplitTransformer) Priority ¶
func (l *LineSplitTransformer) Priority() int
Priority returns the transformer priority (lower = earlier)
type MemoryOptimizedProcessor ¶ added in v2.1.0
type MemoryOptimizedProcessor struct {
// contains filtered or unexported fields
}
MemoryOptimizedProcessor handles large content processing with memory pooling This implements memory-efficient processing for large content (Requirement 10.4, 10.6, 10.7)
func NewMemoryOptimizedProcessor ¶ added in v2.1.0
func NewMemoryOptimizedProcessor(config RendererConfig) *MemoryOptimizedProcessor
NewMemoryOptimizedProcessor creates a processor with memory pooling for large datasets
func (*MemoryOptimizedProcessor) GetBuffer ¶ added in v2.1.0
func (mop *MemoryOptimizedProcessor) GetBuffer() *strings.Builder
GetBuffer retrieves a buffer from the pool for efficient string building
func (*MemoryOptimizedProcessor) GetStringSlice ¶ added in v2.1.0
func (mop *MemoryOptimizedProcessor) GetStringSlice() []string
GetStringSlice retrieves a string slice from the pool
func (*MemoryOptimizedProcessor) ProcessLargeDetails ¶ added in v2.1.0
func (mop *MemoryOptimizedProcessor) ProcessLargeDetails(details any, maxLength int) (any, error)
ProcessLargeDetails efficiently processes large detail content with memory management This avoids redundant transformations for large content (Requirement 10.4)
func (*MemoryOptimizedProcessor) ReturnBuffer ¶ added in v2.1.0
func (mop *MemoryOptimizedProcessor) ReturnBuffer(buf *strings.Builder)
ReturnBuffer returns a buffer to the pool for reuse
func (*MemoryOptimizedProcessor) ReturnStringSlice ¶ added in v2.1.0
func (mop *MemoryOptimizedProcessor) ReturnStringSlice(slice []string)
ReturnStringSlice returns a string slice to the pool for reuse
type MultiError ¶
type MultiError struct {
Operation string // The operation that failed
Errors []error // The list of errors that occurred
SourceMap map[error]ErrorSource // Maps errors to their sources
Context map[string]any // Additional context for the operation
}
MultiError represents multiple errors that occurred during an operation
func NewMultiError ¶
func NewMultiError(operation string) *MultiError
NewMultiError creates a new multi-error
func (*MultiError) AddContext ¶
func (e *MultiError) AddContext(key string, value any) *MultiError
AddContext adds context information to the multi-error
func (*MultiError) AddWithSource ¶
func (e *MultiError) AddWithSource(err error, component string, details map[string]any)
AddWithSource adds an error with source information to the multi-error
func (*MultiError) Error ¶
func (e *MultiError) Error() string
Error returns a formatted message for all errors
func (*MultiError) ErrorOrNil ¶
func (e *MultiError) ErrorOrNil() error
ErrorOrNil returns the MultiError if it has errors, otherwise nil
func (*MultiError) HasErrors ¶
func (e *MultiError) HasErrors() bool
HasErrors returns true if there are any errors
func (*MultiError) Unwrap ¶
func (e *MultiError) Unwrap() error
Unwrap returns the first error for compatibility with errors.Unwrap
type MultiWriteError ¶
type MultiWriteError struct {
Errors []error
}
MultiWriteError represents errors from multiple writers
func (*MultiWriteError) Error ¶
func (e *MultiWriteError) Error() string
Error returns a combined error message
func (*MultiWriteError) Unwrap ¶
func (e *MultiWriteError) Unwrap() []error
Unwrap returns the underlying errors for errors.Is and errors.As
type MultiWriter ¶
type MultiWriter struct {
// contains filtered or unexported fields
}
MultiWriter writes rendered output to multiple destinations
func NewMultiWriter ¶
func NewMultiWriter(writers ...Writer) *MultiWriter
NewMultiWriter creates a new MultiWriter with the specified writers
func (*MultiWriter) AddWriter ¶
func (mw *MultiWriter) AddWriter(w Writer)
AddWriter adds a writer to the multi-writer
func (*MultiWriter) RemoveWriter ¶
func (mw *MultiWriter) RemoveWriter(w Writer)
RemoveWriter removes a writer from the multi-writer
func (*MultiWriter) Write ¶
Write implements the Writer interface, writing to all configured writers
func (*MultiWriter) WriterCount ¶
func (mw *MultiWriter) WriterCount() int
WriterCount returns the number of configured writers
type Operation ¶ added in v2.2.0
type Operation interface {
Name() string
Apply(ctx context.Context, content Content) (Content, error)
CanOptimize(with Operation) bool
Validate() error
}
Operation represents a pipeline operation
type OperationStat ¶ added in v2.2.0
OperationStat tracks individual operation metrics
type Output ¶
type Output struct {
// contains filtered or unexported fields
}
Output manages rendering and writing documents to multiple formats and destinations
func NewOutput ¶
func NewOutput(opts ...OutputOption) *Output
NewOutput creates a new Output instance with the given options
func (*Output) GetFormats ¶
GetFormats returns a copy of the configured formats
func (*Output) GetProgress ¶
GetProgress returns the configured progress indicator
func (*Output) GetTransformers ¶
func (o *Output) GetTransformers() []Transformer
GetTransformers returns a copy of the configured transformers
func (*Output) GetWriters ¶
GetWriters returns a copy of the configured writers
type OutputOption ¶
type OutputOption func(*Output)
OutputOption configures Output instances
func WithFormat ¶
func WithFormat(format Format) OutputOption
WithFormat adds an output format to the Output
func WithFormats ¶
func WithFormats(formats ...Format) OutputOption
WithFormats adds multiple output formats to the Output
func WithFrontMatter ¶
func WithFrontMatter(fm map[string]string) OutputOption
WithFrontMatter sets markdown front matter for v1 compatibility
func WithMetadata ¶
func WithMetadata(key string, value any) OutputOption
WithMetadata sets metadata for the output
func WithProgress ¶
func WithProgress(progress Progress) OutputOption
WithProgress sets the progress indicator for the Output
func WithTOC ¶
func WithTOC(enabled bool) OutputOption
WithTOC enables or disables table of contents generation for v1 compatibility
func WithTableStyle ¶
func WithTableStyle(style string) OutputOption
WithTableStyle sets the table style for v1 compatibility
func WithTransformer ¶
func WithTransformer(transformer Transformer) OutputOption
WithTransformer adds a transformer to the Output pipeline
func WithTransformers ¶
func WithTransformers(transformers ...Transformer) OutputOption
WithTransformers adds multiple transformers to the Output pipeline
func WithWriter ¶
func WithWriter(writer Writer) OutputOption
WithWriter adds a writer to the Output
func WithWriters ¶
func WithWriters(writers ...Writer) OutputOption
WithWriters adds multiple writers to the Output
type PanicError ¶
type PanicError struct {
Operation string // The operation that panicked
Value any // The panic value
Stack []byte // The stack trace
Cause error // Optional underlying error if the panic value was an error
}
PanicError represents an error that was recovered from a panic
func NewPanicError ¶
func NewPanicError(operation string, panicValue any) *PanicError
NewPanicError creates a new panic error
func (*PanicError) StackTrace ¶
func (pe *PanicError) StackTrace() string
StackTrace returns the stack trace as a string
func (*PanicError) Unwrap ¶
func (pe *PanicError) Unwrap() error
Unwrap returns the underlying error if the panic value was an error
type PipelineError ¶ added in v2.2.0
type PipelineError struct {
Operation string // The operation that failed (e.g., "Filter", "Sort", "Execute")
Stage int // Pipeline stage where error occurred (0-based)
Input any // Sample of data that caused the failure (may be nil for privacy)
Cause error // The underlying error
Context map[string]any // Additional context information
PipelineCtx map[string]any // Overall pipeline context
}
PipelineError represents an error that occurred during pipeline execution
func NewPipelineError ¶ added in v2.2.0
func NewPipelineError(operation string, stage int, cause error) *PipelineError
NewPipelineError creates a new pipeline error
func NewPipelineErrorWithInput ¶ added in v2.2.0
func NewPipelineErrorWithInput(operation string, stage int, input any, cause error) *PipelineError
NewPipelineErrorWithInput creates a new pipeline error with input sample
func (*PipelineError) AddContext ¶ added in v2.2.0
func (e *PipelineError) AddContext(key string, value any) *PipelineError
AddContext adds context information to the pipeline error
func (*PipelineError) AddPipelineContext ¶ added in v2.2.0
func (e *PipelineError) AddPipelineContext(key string, value any) *PipelineError
AddPipelineContext adds pipeline-level context information
func (*PipelineError) Error ¶ added in v2.2.0
func (e *PipelineError) Error() string
Error returns the error message with pipeline context
func (*PipelineError) Unwrap ¶ added in v2.2.0
func (e *PipelineError) Unwrap() error
Unwrap returns the underlying error
type ProcessedValue ¶ added in v2.1.0
type ProcessedValue struct {
Value any
IsCollapsible bool
CollapsibleValue CollapsibleValue
// contains filtered or unexported fields
}
ProcessedValue represents a value that has been processed through field formatting with cached type information to minimize type assertions (Requirement 10.1)
func (*ProcessedValue) GetDetails ¶ added in v2.1.0
func (pv *ProcessedValue) GetDetails() any
GetDetails returns the details from a CollapsibleValue with lazy evaluation This avoids unnecessary processing when details are not accessed (Requirement 10.3)
func (*ProcessedValue) String ¶ added in v2.1.0
func (pv *ProcessedValue) String() string
String returns the string representation with caching to avoid redundant conversions
type Progress ¶
type Progress interface {
// Core progress methods
SetTotal(total int)
SetCurrent(current int)
Increment(delta int)
SetStatus(status string)
Complete()
Fail(err error)
// v1 compatibility methods
SetColor(color ProgressColor)
IsActive() bool
SetContext(ctx context.Context)
// v2 enhancements
Close() error
}
Progress provides progress indication for long operations with full v1 compatibility
func NewAutoProgress ¶
func NewAutoProgress(opts ...ProgressOption) Progress
NewAutoProgress creates a progress indicator with automatic format detection This is a convenience function that detects format from writer or uses default
func NewNoOpProgress ¶
func NewNoOpProgress() Progress
NewNoOpProgress creates a progress indicator that does nothing
func NewPrettyProgress ¶
func NewPrettyProgress(opts ...ProgressOption) Progress
NewPrettyProgress creates a new professional progress indicator using go-pretty
func NewProgress ¶
func NewProgress(opts ...ProgressOption) Progress
NewProgress creates a new text-based progress indicator
func NewProgressForFormat ¶
func NewProgressForFormat(format Format, opts ...ProgressOption) Progress
NewProgressForFormat creates a progress indicator appropriate for the given format
func NewProgressForFormatName ¶
func NewProgressForFormatName(formatName string, opts ...ProgressOption) Progress
NewProgressForFormatName creates a progress indicator appropriate for the given format name
func NewProgressForFormats ¶
func NewProgressForFormats(formats []Format, opts ...ProgressOption) Progress
NewProgressForFormats creates a progress indicator appropriate for multiple output formats
type ProgressColor ¶
type ProgressColor int
ProgressColor defines the color used for a progress indicator (v1 compatibility)
const ( // ProgressColorDefault is the neutral color ProgressColorDefault ProgressColor = iota // ProgressColorGreen indicates a success state ProgressColorGreen // ProgressColorRed indicates an error state ProgressColorRed // ProgressColorYellow indicates a warning state ProgressColorYellow // ProgressColorBlue indicates an informational state ProgressColorBlue )
type ProgressConfig ¶
type ProgressConfig struct {
// v1 compatibility options
Color ProgressColor
Status string
TrackerLength int
// Output writer for progress display (defaults to os.Stderr)
Writer io.Writer
// UpdateInterval controls how often the progress is refreshed (defaults to 100ms)
UpdateInterval time.Duration
// ShowPercentage controls whether to show percentage complete
ShowPercentage bool
// ShowETA controls whether to estimate time to completion
ShowETA bool
// ShowRate controls whether to show processing rate
ShowRate bool
// Template for progress display format
Template string
// Width of the progress bar (for bar-style progress)
Width int
// Prefix to show before the progress indicator
Prefix string
// Suffix to show after the progress indicator
Suffix string
}
ProgressConfig holds configuration for progress indicators (v1 compatible)
type ProgressOption ¶
type ProgressOption func(*ProgressConfig)
ProgressOption configures a ProgressConfig
func WithETA ¶
func WithETA(show bool) ProgressOption
WithETA enables or disables estimated time to completion
func WithPercentage ¶
func WithPercentage(show bool) ProgressOption
WithPercentage enables or disables percentage display
func WithPrefix ¶
func WithPrefix(prefix string) ProgressOption
WithPrefix sets a prefix for the progress display
func WithProgressColor ¶
func WithProgressColor(color ProgressColor) ProgressOption
WithProgressColor sets the progress color (v1 compatibility)
func WithProgressStatus ¶
func WithProgressStatus(status string) ProgressOption
WithProgressStatus sets an initial status message (v1 compatibility)
func WithProgressWriter ¶
func WithProgressWriter(w io.Writer) ProgressOption
WithProgressWriter sets the output writer for progress display
func WithRate ¶
func WithRate(show bool) ProgressOption
WithRate enables or disables processing rate display
func WithSuffix ¶
func WithSuffix(suffix string) ProgressOption
WithSuffix sets a suffix for the progress display
func WithTemplate ¶
func WithTemplate(template string) ProgressOption
WithTemplate sets a custom progress display template
func WithTrackerLength ¶
func WithTrackerLength(length int) ProgressOption
WithTrackerLength sets the width of the progress bar (v1 compatibility)
func WithUpdateInterval ¶
func WithUpdateInterval(interval time.Duration) ProgressOption
WithUpdateInterval sets the progress refresh interval
type RawContent ¶
type RawContent struct {
// contains filtered or unexported fields
}
RawContent represents format-specific content
func NewRawContent ¶
func NewRawContent(format string, data []byte, opts ...RawOption) (*RawContent, error)
NewRawContent creates a new raw content with the given format and data
func (*RawContent) AppendBinary ¶
func (r *RawContent) AppendBinary(b []byte) ([]byte, error)
AppendBinary implements encoding.BinaryAppender
func (*RawContent) AppendText ¶
func (r *RawContent) AppendText(b []byte) ([]byte, error)
AppendText implements encoding.TextAppender
func (*RawContent) Clone ¶ added in v2.4.0
func (r *RawContent) Clone() Content
Clone creates a deep copy of the RawContent
func (*RawContent) Data ¶
func (r *RawContent) Data() []byte
Data returns a copy of the raw data to prevent external modification
func (*RawContent) Format ¶
func (r *RawContent) Format() string
Format returns the format of the raw content
func (*RawContent) GetTransformations ¶ added in v2.4.0
func (r *RawContent) GetTransformations() []Operation
GetTransformations returns the transformations attached to this raw content
func (*RawContent) ID ¶
func (r *RawContent) ID() string
ID returns the unique identifier for this content
type RawOption ¶
type RawOption func(*rawConfig)
RawOption configures raw content creation
func WithDataPreservation ¶
WithDataPreservation enables or disables data preservation (copying)
func WithFormatValidation ¶
WithFormatValidation enables or disables format validation
func WithRawTransformations ¶ added in v2.4.0
WithRawTransformations sets transformations for the raw content
type RemoveColorsTransformer ¶
type RemoveColorsTransformer struct{}
RemoveColorsTransformer removes ANSI color codes from output (for file output)
func NewRemoveColorsTransformer ¶
func NewRemoveColorsTransformer() *RemoveColorsTransformer
NewRemoveColorsTransformer creates a new color removal transformer
func (*RemoveColorsTransformer) CanTransform ¶
func (r *RemoveColorsTransformer) CanTransform(_ string) bool
CanTransform checks if this transformer applies to the given format
func (*RemoveColorsTransformer) Name ¶
func (r *RemoveColorsTransformer) Name() string
Name returns the transformer name
func (*RemoveColorsTransformer) Priority ¶
func (r *RemoveColorsTransformer) Priority() int
Priority returns the transformer priority (lower = earlier)
type RenderError ¶
type RenderError struct {
Format string
Content Content
Renderer string // Type information about the renderer
Operation string // Specific operation that failed (e.g., "encode", "format", "stream")
Context map[string]any // Additional context information
Cause error
}
RenderError indicates rendering failure with detailed context
func NewRenderError ¶
func NewRenderError(format string, content Content, cause error) *RenderError
NewRenderError creates a new render error with context
func NewRenderErrorWithDetails ¶
func NewRenderErrorWithDetails(format, renderer, operation string, content Content, cause error) *RenderError
NewRenderErrorWithDetails creates a new render error with detailed context
func (*RenderError) AddContext ¶
func (e *RenderError) AddContext(key string, value any) *RenderError
AddContext adds context information to the render error
func (*RenderError) Unwrap ¶
func (e *RenderError) Unwrap() error
Unwrap returns the underlying error
type Renderer ¶
type Renderer interface {
// Format returns the output format name
Format() string
// Render converts the document to bytes
Render(ctx context.Context, doc *Document) ([]byte, error)
// RenderTo streams output to a writer
RenderTo(ctx context.Context, doc *Document, w io.Writer) error
// SupportsStreaming indicates if streaming is supported
SupportsStreaming() bool
}
Renderer converts a document to a specific format
func NewCSVRendererWithCollapsible ¶ added in v2.1.0
func NewCSVRendererWithCollapsible(config RendererConfig) Renderer
NewCSVRendererWithCollapsible creates a CSV renderer with collapsible configuration
func NewHTMLRendererWithCollapsible ¶ added in v2.1.0
func NewHTMLRendererWithCollapsible(config RendererConfig) Renderer
NewHTMLRendererWithCollapsible creates an HTML renderer with collapsible configuration
func NewMarkdownRendererWithCollapsible ¶ added in v2.1.0
func NewMarkdownRendererWithCollapsible(config RendererConfig) Renderer
NewMarkdownRendererWithCollapsible creates a markdown renderer with collapsible configuration
func NewTableRendererWithCollapsible ¶ added in v2.1.0
func NewTableRendererWithCollapsible(styleName string, config RendererConfig) Renderer
NewTableRendererWithCollapsible creates a table renderer with collapsible configuration
func NewTableRendererWithStyle ¶
NewTableRendererWithStyle creates a table renderer with specific style
func NewTableRendererWithStyleAndWidth ¶ added in v2.3.0
NewTableRendererWithStyleAndWidth creates a table renderer with specific style and max column width
type RendererConfig ¶ added in v2.1.0
type RendererConfig struct {
// Global expansion override (Requirement 13: Global Expansion Control)
ForceExpansion bool
// Character limits for detail truncation (Requirement 10: configurable with 500 default)
MaxDetailLength int
TruncateIndicator string
// Format-specific settings (Requirement 14: Configurable Renderer Settings)
TableHiddenIndicator string
HTMLCSSClasses map[string]string
// Transformer configuration (Task 10.2: Dual transformer system)
DataTransformers []*TransformerAdapter
ByteTransformers *TransformPipeline
}
RendererConfig provides collapsible-specific configuration for renderers
type S3ClientAPI ¶ added in v2.4.0
type S3ClientAPI interface {
S3PutObjectAPI
S3GetObjectAPI
}
S3ClientAPI combines Get and Put operations for full S3Writer functionality. When a client implements both interfaces, the S3Writer can support append mode using the download-modify-upload pattern.
The interface is satisfied by:
- github.com/aws/aws-sdk-go-v2/service/s3 (*s3.Client) - implements both operations
- Clients implementing only S3PutObjectAPI can still be used but without append mode
type S3GetObjectAPI ¶ added in v2.4.0
type S3GetObjectAPI interface {
GetObject(ctx context.Context, params *s3.GetObjectInput, optFns ...func(*s3.Options)) (*s3.GetObjectOutput, error)
}
S3GetObjectAPI defines the minimal interface for S3 GetObject operations. This interface is used for append mode support, allowing the S3Writer to download existing objects before modifying and re-uploading them.
The interface is satisfied by:
- github.com/aws/aws-sdk-go-v2/service/s3 (*s3.Client)
- Mock implementations for testing (using the same AWS SDK types)
type S3PutObjectAPI ¶ added in v2.3.1
type S3PutObjectAPI interface {
PutObject(ctx context.Context, params *s3.PutObjectInput, optFns ...func(*s3.Options)) (*s3.PutObjectOutput, error)
}
S3PutObjectAPI defines the minimal interface for S3 PutObject operations. This interface uses actual AWS SDK v2 types, making it directly compatible with *s3.Client without requiring any adapter or type conversion.
The interface is satisfied by:
- github.com/aws/aws-sdk-go-v2/service/s3 (*s3.Client)
- Mock implementations for testing (using the same AWS SDK types)
Example usage with AWS SDK v2:
import (
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/ArjenSchwarz/go-output/v2"
)
cfg, _ := config.LoadDefaultConfig(context.TODO())
s3Client := s3.NewFromConfig(cfg)
writer := output.NewS3Writer(s3Client, "my-bucket", "path/to/file.json")
type S3Writer ¶
type S3Writer struct {
// contains filtered or unexported fields
}
S3Writer writes rendered output to S3
func NewS3Writer ¶
func NewS3Writer(client S3PutObjectAPI, bucket, keyPattern string) *S3Writer
NewS3Writer creates a new S3Writer that works with AWS SDK v2 s3.Client. The client parameter should be an *s3.Client from github.com/aws/aws-sdk-go-v2/service/s3.
Example:
import (
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/ArjenSchwarz/go-output/v2"
)
cfg, _ := config.LoadDefaultConfig(context.TODO())
s3Client := s3.NewFromConfig(cfg)
writer := output.NewS3Writer(s3Client, "my-bucket", "reports/{format}.{ext}")
func NewS3WriterWithOptions ¶
func NewS3WriterWithOptions(client S3PutObjectAPI, bucket, keyPattern string, opts ...S3WriterOption) *S3Writer
NewS3WriterWithOptions creates an S3Writer with options
func (*S3Writer) SetContentType ¶
SetContentType sets a custom content type for a format
type S3WriterOption ¶
type S3WriterOption func(*S3Writer)
S3WriterOption configures an S3Writer
func WithContentTypes ¶
func WithContentTypes(contentTypes map[string]string) S3WriterOption
WithContentTypes sets custom content types
func WithMaxAppendSize ¶ added in v2.4.0
func WithMaxAppendSize(maxSize int64) S3WriterOption
WithMaxAppendSize sets the maximum object size for append operations. The S3Writer will return an error if attempting to append to an object that exceeds this size limit. This prevents memory exhaustion and excessive bandwidth usage during the download-modify-upload process.
The default maximum size is 100MB (104857600 bytes). The maxSize parameter must be greater than 0.
func WithS3AppendMode ¶ added in v2.4.0
func WithS3AppendMode() S3WriterOption
WithS3AppendMode enables append mode for the S3Writer. When enabled, the S3Writer uses a download-modify-upload pattern to append new content to existing S3 objects. This is designed for infrequent updates to small objects (e.g., sporadic NDJSON logging).
IMPORTANT: The append operation is NOT atomic. The S3Writer uses ETag-based conditional updates to detect concurrent modifications, but there is no locking mechanism. If a concurrent modification is detected, an error is returned.
Recommendation: Enable S3 versioning for data protection when using append mode.
type Schema ¶
type Schema struct {
Fields []Field
// contains filtered or unexported fields
}
Schema defines table structure with explicit key ordering
func DetectSchemaFromData ¶
DetectSchemaFromData creates a schema from the provided data, preserving key order
func DetectSchemaFromMap ¶
DetectSchemaFromMap creates a schema from a map, preserving insertion order
func NewSchemaFromFields ¶
NewSchemaFromFields creates a schema from field definitions with preserved order
func NewSchemaFromKeys ¶
NewSchemaFromKeys creates a schema from simple key list
func (*Schema) GetFieldNames ¶
GetFieldNames returns the field names in their preserved order
func (*Schema) GetKeyOrder ¶
GetKeyOrder returns the preserved key order for the schema
func (*Schema) SetKeyOrder ¶
SetKeyOrder explicitly sets the key order for the schema
func (*Schema) VisibleFieldCount ¶
VisibleFieldCount returns the number of non-hidden fields
type SectionContent ¶
type SectionContent struct {
// contains filtered or unexported fields
}
SectionContent represents grouped content with a hierarchical structure
func NewSectionContent ¶
func NewSectionContent(title string, opts ...SectionOption) *SectionContent
NewSectionContent creates a new section content with the given title and options
func (*SectionContent) AddContent ¶
func (s *SectionContent) AddContent(content Content)
AddContent adds content to this section
func (*SectionContent) AppendBinary ¶
func (s *SectionContent) AppendBinary(b []byte) ([]byte, error)
AppendBinary implements encoding.BinaryAppender
func (*SectionContent) AppendText ¶
func (s *SectionContent) AppendText(b []byte) ([]byte, error)
AppendText implements encoding.TextAppender with hierarchical rendering
func (*SectionContent) Clone ¶ added in v2.4.0
func (s *SectionContent) Clone() Content
Clone creates a deep copy of the SectionContent
func (*SectionContent) Contents ¶
func (s *SectionContent) Contents() []Content
Contents returns a copy of the section contents to prevent external modification
func (*SectionContent) GetTransformations ¶ added in v2.4.0
func (s *SectionContent) GetTransformations() []Operation
GetTransformations returns the transformations attached to this section
func (*SectionContent) ID ¶
func (s *SectionContent) ID() string
ID returns the unique identifier for this content
func (*SectionContent) Level ¶
func (s *SectionContent) Level() int
Level returns the section level (for hierarchical rendering)
func (*SectionContent) Title ¶
func (s *SectionContent) Title() string
Title returns the section title
func (*SectionContent) Type ¶
func (s *SectionContent) Type() ContentType
Type returns the content type
type SectionOption ¶
type SectionOption func(*sectionConfig)
SectionOption configures section creation
func WithLevel ¶
func WithLevel(level int) SectionOption
WithLevel sets the hierarchical level of the section
func WithSectionTransformations ¶ added in v2.4.0
func WithSectionTransformations(ops ...Operation) SectionOption
WithSectionTransformations sets transformations for the section content
type SortDirection ¶ added in v2.2.0
type SortDirection int
SortDirection defines the direction for sorting operations
const ( // Ascending sort direction Ascending SortDirection = iota // Descending sort direction Descending )
func (SortDirection) String ¶ added in v2.2.0
func (d SortDirection) String() string
String returns the string representation of the sort direction
type SortKey ¶ added in v2.2.0
type SortKey struct {
Column string // Column name to sort by
Direction SortDirection // Sort direction
}
SortKey defines a column and direction for sorting
type SortOp ¶ added in v2.2.0
type SortOp struct {
// contains filtered or unexported fields
}
SortOp implements sorting operation using keys or custom comparators
func NewSortOpWithComparator ¶ added in v2.2.0
NewSortOpWithComparator creates a new sort operation with a custom comparator
func (*SortOp) ApplyWithFormat ¶ added in v2.2.0
func (o *SortOp) ApplyWithFormat(ctx context.Context, content Content, format string) (Content, error)
ApplyWithFormat applies the sort operation with format context
func (*SortOp) CanOptimize ¶ added in v2.2.0
CanOptimize returns true if this sort can be optimized with another operation
func (*SortOp) CanTransform ¶ added in v2.2.0
CanTransform checks if sort operation applies to the given content and format
type SortTransformer ¶
type SortTransformer struct {
// contains filtered or unexported fields
}
SortTransformer sorts table data by a specified key
func NewSortTransformer ¶
func NewSortTransformer(key string, ascending bool) *SortTransformer
NewSortTransformer creates a new sort transformer
func NewSortTransformerAscending ¶
func NewSortTransformerAscending(key string) *SortTransformer
NewSortTransformerAscending creates a sort transformer with ascending order
func (*SortTransformer) CanTransform ¶
func (s *SortTransformer) CanTransform(format string) bool
CanTransform checks if this transformer applies to the given format
func (*SortTransformer) Name ¶
func (s *SortTransformer) Name() string
Name returns the transformer name
func (*SortTransformer) Priority ¶
func (s *SortTransformer) Priority() int
Priority returns the transformer priority (lower = earlier)
type StderrWriter ¶ added in v2.6.0
type StderrWriter struct {
// contains filtered or unexported fields
}
StderrWriter writes rendered output to standard error
func NewStderrWriter ¶ added in v2.6.0
func NewStderrWriter() *StderrWriter
NewStderrWriter creates a new StderrWriter
func (*StderrWriter) SetWriter ¶ added in v2.6.0
func (sw *StderrWriter) SetWriter(w io.Writer)
SetWriter sets a custom writer (useful for testing)
type StdoutWriter ¶
type StdoutWriter struct {
// contains filtered or unexported fields
}
StdoutWriter writes rendered output to standard output
func NewStdoutWriter ¶
func NewStdoutWriter() *StdoutWriter
NewStdoutWriter creates a new StdoutWriter
func (*StdoutWriter) SetWriter ¶
func (sw *StdoutWriter) SetWriter(w io.Writer)
SetWriter sets a custom writer (useful for testing)
type StreamingValueProcessor ¶ added in v2.1.0
type StreamingValueProcessor struct {
// contains filtered or unexported fields
}
StreamingValueProcessor handles large dataset processing with minimal memory footprint This maintains streaming capabilities for large datasets (Requirement 10.2)
func NewStreamingValueProcessor ¶ added in v2.1.0
func NewStreamingValueProcessor(config RendererConfig) *StreamingValueProcessor
NewStreamingValueProcessor creates a processor optimized for large datasets
func (*StreamingValueProcessor) ProcessBatch ¶ added in v2.1.0
func (svp *StreamingValueProcessor) ProcessBatch(values []any, fields []*Field, processor func(*ProcessedValue) error) error
ProcessBatch processes a batch of values efficiently without loading all details into memory This avoids unnecessary memory allocation when processing large datasets (Requirement 10.2)
type StructuredError ¶
type StructuredError struct {
Code string `json:"code"` // Error code for programmatic identification
Message string `json:"message"` // Human-readable error message
Component string `json:"component"` // Component that generated the error
Operation string `json:"operation"` // Operation that failed
Context map[string]any `json:"context"` // Additional context information
Details map[string]any `json:"details"` // Detailed error information
Timestamp string `json:"timestamp"` // When the error occurred
Cause error `json:"-"` // Underlying error (not serialized)
}
StructuredError provides machine-readable error information for programmatic analysis
func NewStructuredError ¶
func NewStructuredError(code, component, operation, message string) *StructuredError
NewStructuredError creates a new structured error
func NewStructuredErrorWithCause ¶
func NewStructuredErrorWithCause(code, component, operation, message string, cause error) *StructuredError
NewStructuredErrorWithCause creates a new structured error with an underlying cause
func ToStructuredError ¶
func ToStructuredError(err error, defaultCode, defaultComponent, defaultOperation string) *StructuredError
ToStructuredError converts any error to a StructuredError for analysis
func (*StructuredError) AddContext ¶
func (e *StructuredError) AddContext(key string, value any) *StructuredError
AddContext adds context information to the structured error
func (*StructuredError) AddDetail ¶
func (e *StructuredError) AddDetail(key string, value any) *StructuredError
AddDetail adds detailed information to the structured error
func (*StructuredError) Error ¶
func (e *StructuredError) Error() string
Error implements the error interface
func (*StructuredError) Unwrap ¶
func (e *StructuredError) Unwrap() error
Unwrap returns the underlying error
type TableContent ¶
type TableContent struct {
// contains filtered or unexported fields
}
TableContent represents tabular data with preserved key ordering
func NewTableContent ¶
func NewTableContent(title string, data any, opts ...TableOption) (*TableContent, error)
NewTableContent creates a new table content with the given data and options
func (*TableContent) AppendBinary ¶
func (t *TableContent) AppendBinary(b []byte) ([]byte, error)
AppendBinary implements encoding.BinaryAppender
func (*TableContent) AppendText ¶
func (t *TableContent) AppendText(b []byte) ([]byte, error)
AppendText implements encoding.TextAppender preserving key order
func (*TableContent) Clone ¶ added in v2.2.0
func (t *TableContent) Clone() Content
Clone creates a deep copy of the TableContent
func (*TableContent) GetTransformations ¶ added in v2.4.0
func (t *TableContent) GetTransformations() []Operation
GetTransformations returns the transformations attached to this table
func (*TableContent) ID ¶
func (t *TableContent) ID() string
ID returns the unique identifier for this content
func (*TableContent) Records ¶
func (t *TableContent) Records() []Record
Records returns the table records
func (*TableContent) Schema ¶
func (t *TableContent) Schema() *Schema
Schema returns the table schema
func (*TableContent) Transform ¶ added in v2.2.0
func (tc *TableContent) Transform(fn TransformFunc) error
Transform applies a transformation function to the table's records
type TableOption ¶
type TableOption func(*tableConfig)
TableOption configures table creation
func WithAutoSchema ¶
func WithAutoSchema() TableOption
WithAutoSchema enables automatic schema detection from data When enabled, the system will preserve the order keys appear in the source data
func WithAutoSchemaOrdered ¶
func WithAutoSchemaOrdered(keys ...string) TableOption
WithAutoSchemaOrdered enables automatic schema detection with custom key order
func WithKeys ¶
func WithKeys(keys ...string) TableOption
WithKeys sets explicit key ordering (for v1 compatibility)
func WithSchema ¶
func WithSchema(fields ...Field) TableOption
WithSchema explicitly sets the table schema with key order
func WithTransformations ¶ added in v2.4.0
func WithTransformations(ops ...Operation) TableOption
WithTransformations attaches one or more operations to the table content. Operations execute during rendering in the order specified.
Transformations enable filtering, sorting, limiting, grouping, and other operations to be applied to individual tables without affecting other content in the document.
Thread Safety Requirements: Operations MUST be stateless and thread-safe. Do not create operations with:
- Mutable state modified during Apply()
- Closures capturing mutable variables by reference
- External side effects (file writes, network calls, etc.)
Example usage:
builder.Table("users", userData,
output.WithKeys("name", "email", "age"),
output.WithTransformations(
output.NewFilterOp(func(r Record) bool {
return r["age"].(int) >= 18
}),
output.NewSortOp(output.SortKey{Column: "name", Direction: output.Ascending}),
output.NewLimitOp(10),
),
)
See v2/BEST_PRACTICES.md for safe operation patterns and v2/MIGRATION.md for examples migrating from the deprecated Pipeline API.
type TextContent ¶
type TextContent struct {
// contains filtered or unexported fields
}
TextContent represents unstructured text with styling options
func NewTextContent ¶
func NewTextContent(text string, opts ...TextOption) *TextContent
NewTextContent creates a new text content with the given text and options
func (*TextContent) AppendBinary ¶
func (t *TextContent) AppendBinary(b []byte) ([]byte, error)
AppendBinary implements encoding.BinaryAppender
func (*TextContent) AppendText ¶
func (t *TextContent) AppendText(b []byte) ([]byte, error)
AppendText implements encoding.TextAppender
func (*TextContent) Clone ¶ added in v2.4.0
func (t *TextContent) Clone() Content
Clone creates a deep copy of the TextContent
func (*TextContent) GetTransformations ¶ added in v2.4.0
func (t *TextContent) GetTransformations() []Operation
GetTransformations returns the transformations attached to this text
func (*TextContent) ID ¶
func (t *TextContent) ID() string
ID returns the unique identifier for this content
type TextOption ¶
type TextOption func(*textConfig)
TextOption configures text creation
func WithHeader ¶
func WithHeader(header bool) TextOption
WithHeader marks text as a header (for v1 AddHeader compatibility)
func WithTextStyle ¶
func WithTextStyle(style TextStyle) TextOption
WithTextStyle sets the complete text style
func WithTextTransformations ¶ added in v2.4.0
func WithTextTransformations(ops ...Operation) TextOption
WithTextTransformations sets transformations for the text content
type TextStyle ¶
type TextStyle struct {
Bold bool // Bold text
Italic bool // Italic text
Color string // Text color (format-specific interpretation)
Size int // Text size (format-specific interpretation)
Header bool // Whether this text is a header (for v1 AddHeader compatibility)
}
TextStyle defines text formatting options
type TransformContext ¶ added in v2.2.0
type TransformContext struct {
Format string
Document *Document
Metadata map[string]any
Stats TransformStats
}
TransformContext carries metadata through the transformation pipeline
type TransformError ¶
TransformError represents an error that occurred during transformation
func NewTransformError ¶
func NewTransformError(transformer, format string, input []byte, cause error) *TransformError
NewTransformError creates a new transform error
func (*TransformError) Error ¶
func (e *TransformError) Error() string
func (*TransformError) Unwrap ¶
func (e *TransformError) Unwrap() error
type TransformFunc ¶ added in v2.2.0
TransformFunc defines the transformation function signature
type TransformInfo ¶
type TransformInfo struct {
Name string
Priority int
Formats []string // Formats this transformer can handle
}
TransformInfo provides information about transformers in the pipeline
type TransformPipeline ¶
type TransformPipeline struct {
// contains filtered or unexported fields
}
TransformPipeline manages a collection of transformers with priority-based ordering
func NewTransformPipeline ¶
func NewTransformPipeline() *TransformPipeline
NewTransformPipeline creates a new transform pipeline
func (*TransformPipeline) Add ¶
func (tp *TransformPipeline) Add(transformer Transformer)
Add adds a transformer to the pipeline
func (*TransformPipeline) Clear ¶
func (tp *TransformPipeline) Clear()
Clear removes all transformers from the pipeline
func (*TransformPipeline) Count ¶
func (tp *TransformPipeline) Count() int
Count returns the number of transformers in the pipeline
func (*TransformPipeline) Get ¶
func (tp *TransformPipeline) Get(name string) Transformer
Get returns a transformer by name, or nil if not found
func (*TransformPipeline) Has ¶
func (tp *TransformPipeline) Has(name string) bool
Has checks if a transformer with the given name exists in the pipeline
func (*TransformPipeline) Info ¶
func (tp *TransformPipeline) Info() []TransformInfo
Info returns information about all transformers in the pipeline, ordered by priority
func (*TransformPipeline) Remove ¶
func (tp *TransformPipeline) Remove(name string) bool
Remove removes a transformer from the pipeline by name
type TransformStats ¶ added in v2.2.0
type TransformStats struct {
InputRecords int
OutputRecords int
FilteredCount int
Duration time.Duration
Operations []OperationStat
}
TransformStats tracks transformation metrics
type TransformableContent ¶ added in v2.2.0
type TransformableContent interface {
Content
// Clone creates a deep copy for transformation
Clone() Content
// Transform applies a transformation function
Transform(fn TransformFunc) error
}
TransformableContent extends Content with transformation support
type Transformer ¶
type Transformer interface {
// Name returns the transformer name
Name() string
// Transform modifies the input bytes
Transform(ctx context.Context, input []byte, format string) ([]byte, error)
// CanTransform checks if this transformer applies to the given format
CanTransform(format string) bool
// Priority determines transform order (lower = earlier)
Priority() int
}
Transformer modifies content or output
type TransformerAdapter ¶ added in v2.2.0
type TransformerAdapter struct {
// contains filtered or unexported fields
}
TransformerAdapter wraps transformers for unified handling
func NewTransformerAdapter ¶ added in v2.2.0
func NewTransformerAdapter(transformer any) *TransformerAdapter
NewTransformerAdapter creates a new adapter for any transformer type
func (*TransformerAdapter) AsByteTransformer ¶ added in v2.2.0
func (ta *TransformerAdapter) AsByteTransformer() Transformer
AsByteTransformer returns the transformer as a byte Transformer, or nil
func (*TransformerAdapter) AsDataTransformer ¶ added in v2.2.0
func (ta *TransformerAdapter) AsDataTransformer() DataTransformer
AsDataTransformer returns the transformer as a DataTransformer, or nil
func (*TransformerAdapter) IsDataTransformer ¶ added in v2.2.0
func (ta *TransformerAdapter) IsDataTransformer() bool
IsDataTransformer checks if the wrapped transformer is a DataTransformer
type ValidationError ¶
type ValidationError struct {
Field string // The field that failed validation
Value any // The value that was invalid
Message string // Human-readable error message
Cause error // Optional underlying error
}
ValidationError indicates invalid input with detailed field information
func NewValidationError ¶
func NewValidationError(field string, value any, message string) *ValidationError
NewValidationError creates a new validation error
func NewValidationErrorWithCause ¶
func NewValidationErrorWithCause(field string, value any, message string, cause error) *ValidationError
NewValidationErrorWithCause creates a new validation error with an underlying cause
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error returns the error message
func (*ValidationError) Unwrap ¶
func (e *ValidationError) Unwrap() error
Unwrap returns the underlying error
type WriteError ¶
WriteError represents an error that occurred during writing
type Writer ¶
type Writer interface {
// Write outputs the rendered data for the specified format
Write(ctx context.Context, format string, data []byte) error
}
Writer outputs rendered data to various destinations
type WriterError ¶
type WriterError struct {
Writer string // Type information about the writer
Format string // Format being written
Operation string // Specific operation that failed (e.g., "write", "open", "close")
Context map[string]any // Additional context information
Cause error // The underlying error
}
WriterError represents an error that occurred during writing
func NewWriterError ¶
func NewWriterError(writer, format string, cause error) *WriterError
NewWriterError creates a new writer error with context
func NewWriterErrorWithDetails ¶
func NewWriterErrorWithDetails(writer, format, operation string, cause error) *WriterError
NewWriterErrorWithDetails creates a new writer error with detailed context
func (*WriterError) AddContext ¶
func (e *WriterError) AddContext(key string, value any) *WriterError
AddContext adds context information to the writer error
func (*WriterError) Unwrap ¶
func (e *WriterError) Unwrap() error
Unwrap returns the underlying error
type WriterFunc ¶
WriterFunc is an adapter to allow the use of ordinary functions as Writers
Source Files
¶
- base_renderer.go
- collapsible.go
- collapsible_formatters.go
- collapsible_section.go
- content.go
- csv_renderer.go
- debug.go
- doc.go
- document.go
- errors.go
- file_writer.go
- format_aware.go
- graph_content.go
- graph_renderers.go
- html_css.go
- html_renderer.go
- html_template.go
- json_yaml_renderer.go
- markdown_renderer.go
- multi_writer.go
- operations.go
- output.go
- pipeline.go
- progress.go
- progress_noop.go
- progress_pretty.go
- progress_pretty_unix.go
- progress_text.go
- raw_options.go
- renderer.go
- s3_writer.go
- schema.go
- section_options.go
- stderr_writer.go
- stdout_writer.go
- styling.go
- table_options.go
- table_renderer.go
- test_helpers.go
- testing_utils.go
- text_options.go
- transform_data.go
- transformer.go
- transformers.go
- writer.go