format

package module
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2025 License: MIT Imports: 29 Imported by: 2

README

go-output

A comprehensive Go library for outputting structured data in multiple formats. This library provides a unified interface to convert your data into JSON, YAML, CSV, HTML, tables, markdown, DOT graphs, Mermaid diagrams, and Draw.io files.

Features

  • Multiple Output Formats: Support for 9 different output formats
  • Unified Interface: Single API for all output types
  • Rich Formatting: Colors, styling, table of contents, section headers
  • File & Cloud Output: Write to local files or S3 buckets
  • Graph Generation: Create flowcharts and diagrams from relationship data
  • CLI Integration: Perfect for adding multiple output options to command-line tools
  • Progress Indicators: Visual progress bars for long-running tasks

Supported Output Formats

  • json - Standard JSON output
  • yaml - YAML format for configuration files
  • csv - Comma-separated values for spreadsheets
  • html - Full HTML pages with styling and navigation
  • table - Console-friendly tables with various styles
  • markdown - GitHub-flavored markdown with table support
  • dot - GraphViz DOT format for graph visualization
  • mermaid - Mermaid diagrams (flowcharts, pie charts, Gantt charts)
  • drawio - Draw.io/Diagrams.net CSV import format

Quick Start

go get github.com/ArjenSchwarz/go-output
package main

import format "github.com/ArjenSchwarz/go-output"

func main() {
    settings := format.NewOutputSettings()
    settings.SetOutputFormat("table")
    settings.Title = "Employee Report"

    output := format.OutputArray{
        Settings: settings,
        Keys:     []string{"Name", "Department", "Active"},
    }

    output.AddContents(map[string]interface{}{
        "Name":       "Alice Johnson",
        "Department": "Engineering",
        "Active":     true,
    })

    output.Write()
}

Progress Indicators

Progress bars can be displayed for supported formats (table, markdown and html).

settings := format.NewOutputSettings()
settings.SetOutputFormat("table")

p := format.NewProgress(settings)
p.SetTotal(2)
for i := 0; i < 2; i++ {
    p.Increment(1)
}
p.Complete()

Documentation

📖 Complete Documentation - Comprehensive guide covering all features, configuration options, and API reference

🚀 Getting Started Guide - Quick introduction and setup instructions

💡 Examples - Working code examples demonstrating all features

Dependencies

This library uses several excellent external packages:

Usage in Projects

This library is used by various CLI tools for flexible output formatting. If you only need specific functionality, consider using the underlying packages directly. However, if you need multiple output formats with a consistent interface, go-output provides significant value.

Contributing

Contributions are welcome! Here's how you can help:

Reporting Issues
  • Use the GitHub issue tracker for bug reports and feature requests
  • Provide clear examples and steps to reproduce issues
  • Include Go version and operating system information
Development Setup
# Clone the repository
git clone https://github.com/ArjenSchwarz/go-output.git
cd go-output

# Run tests
go test ./...

# Run examples
cd examples
go run basic_usage.go
Code Contributions
  • Fork the repository and create a feature branch
  • Follow Go best practices and maintain existing code style
  • Add tests for new functionality
  • Update documentation for new features
  • Ensure all tests pass before submitting
Code Style
  • Use gofmt for formatting
  • Follow standard Go naming conventions
  • Add comments for exported functions and types
  • Keep functions focused and testable
Testing
  • Add unit tests for new features
  • Maintain or improve test coverage
  • Test with multiple Go versions when possible
  • Include integration tests for complex features

License

This project is open source. See the LICENSE file for details.

Changelog

See CHANGELOG.md for version history and changes.


Need help? Check the documentation, browse the examples, or create an issue for support.

Documentation

Overview

Package format contains helpers for rendering output in different formats. Progress support is provided through the Progress interface with both a real terminal implementation and a no-op fallback. All progress implementations are safe for concurrent use by multiple goroutines.

Basic usage:

settings := format.NewOutputSettings()
settings.SetOutputFormat("table")
p := format.NewProgress(settings)
p.SetTotal(3)
for i := 0; i < 3; i++ {
    p.Increment(1)
}
p.Complete()

Index

Constants

This section is empty.

Variables

View Source
var TableStyles = map[string]table.Style{
	"Default":                    table.StyleDefault,
	"Bold":                       table.StyleBold,
	"ColoredBright":              table.StyleColoredBright,
	"ColoredDark":                table.StyleColoredDark,
	"ColoredBlackOnBlueWhite":    table.StyleColoredBlackOnBlueWhite,
	"ColoredBlackOnCyanWhite":    table.StyleColoredBlackOnCyanWhite,
	"ColoredBlackOnGreenWhite":   table.StyleColoredBlackOnGreenWhite,
	"ColoredBlackOnMagentaWhite": table.StyleColoredBlackOnMagentaWhite,
	"ColoredBlackOnYellowWhite":  table.StyleColoredBlackOnYellowWhite,
	"ColoredBlackOnRedWhite":     table.StyleColoredBlackOnRedWhite,
	"ColoredBlueWhiteOnBlack":    table.StyleColoredBlueWhiteOnBlack,
	"ColoredCyanWhiteOnBlack":    table.StyleColoredCyanWhiteOnBlack,
	"ColoredGreenWhiteOnBlack":   table.StyleColoredGreenWhiteOnBlack,
	"ColoredMagentaWhiteOnBlack": table.StyleColoredMagentaWhiteOnBlack,
	"ColoredRedWhiteOnBlack":     table.StyleColoredRedWhiteOnBlack,
	"ColoredYellowWhiteOnBlack":  table.StyleColoredYellowWhiteOnBlack,
}

TableStyles is a lookup map for getting the table styles based on a string

Functions

func PrintByteSlice

func PrintByteSlice(contents []byte, outputFile string, targetBucket S3Output) (err error)

PrintByteSlice prints the provided contents to stdout or the provided filepath

Types

type FromToColumns

type FromToColumns struct {
	From  string
	To    string
	Label string
}

FromToColumns is used to set the From and To columns for graphical output formats

type NoOpProgress added in v1.5.0

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

NoOpProgress implements Progress but performs no operations.

func (*NoOpProgress) Complete added in v1.5.0

func (nop *NoOpProgress) Complete()

Complete marks the progress as finished successfully.

func (*NoOpProgress) Fail added in v1.5.0

func (nop *NoOpProgress) Fail(err error)

Fail marks the progress as failed. The error is only logged when debug is enabled.

func (*NoOpProgress) Increment added in v1.5.0

func (nop *NoOpProgress) Increment(n int)

Increment increases the progress by n.

func (*NoOpProgress) IsActive added in v1.5.0

func (nop *NoOpProgress) IsActive() bool

IsActive always returns false for NoOpProgress.

func (*NoOpProgress) SetColor added in v1.5.0

func (nop *NoOpProgress) SetColor(color ProgressColor)

SetColor changes the color setting. It does not produce any output.

func (*NoOpProgress) SetContext added in v1.5.0

func (nop *NoOpProgress) SetContext(ctx context.Context)

SetContext stores the context. No operation for NoOpProgress other than enabling debug logging when the context is cancelled.

func (*NoOpProgress) SetCurrent added in v1.5.0

func (nop *NoOpProgress) SetCurrent(current int)

SetCurrent sets the current progress value.

func (*NoOpProgress) SetStatus added in v1.5.0

func (nop *NoOpProgress) SetStatus(status string)

SetStatus updates the status message. It is ignored for NoOpProgress.

func (*NoOpProgress) SetTotal added in v1.5.0

func (nop *NoOpProgress) SetTotal(total int)

SetTotal sets the total steps expected.

type OutputArray

type OutputArray struct {
	Settings *OutputSettings
	Contents []OutputHolder
	Keys     []string
}

OutputArray holds all the different OutputHolders that will be provided as output, as well as the keys (headers) that will actually need to be printed

func (*OutputArray) AddContents

func (output *OutputArray) AddContents(contents map[string]interface{})

AddContents adds the provided map[string]interface{} to the OutputHolder and that in turn to the OutputArray

func (*OutputArray) AddHeader

func (output *OutputArray) AddHeader(header string)

func (*OutputArray) AddHolder

func (output *OutputArray) AddHolder(holder OutputHolder)

AddHolder adds the provided OutputHolder to the OutputArray

func (*OutputArray) AddToBuffer

func (output *OutputArray) AddToBuffer()

func (*OutputArray) ContentsAsInterfaces

func (output *OutputArray) ContentsAsInterfaces() [][]interface{}

func (*OutputArray) ContentsAsInterfacesWithAllKeys added in v1.5.1

func (output *OutputArray) ContentsAsInterfacesWithAllKeys() [][]interface{}

func (OutputArray) GetContentsMap

func (output OutputArray) GetContentsMap() []map[string]string

GetContentsMap returns a stringmap of the output contents

func (OutputArray) GetContentsMapRaw

func (output OutputArray) GetContentsMapRaw() []map[string]interface{}

GetContentsMapRaw returns a interface map of the output contents

func (OutputArray) GetContentsMapRawWithAllKeys added in v1.5.1

func (output OutputArray) GetContentsMapRawWithAllKeys() []map[string]interface{}

GetContentsMapRawWithAllKeys returns a interface map of the output contents using all collected keys

func (OutputArray) GetContentsMapWithAllKeys added in v1.5.1

func (output OutputArray) GetContentsMapWithAllKeys() []map[string]string

GetContentsMapWithAllKeys returns a stringmap of the output contents using all collected keys

func (OutputArray) HtmlTableOnly

func (output OutputArray) HtmlTableOnly() []byte

HtmlTableOnly returns a byte array containing an HTML table of the OutputArray

func (*OutputArray) KeysAsInterface

func (output *OutputArray) KeysAsInterface() []interface{}

func (*OutputArray) KeysAsInterfaceWithAllKeys added in v1.5.1

func (output *OutputArray) KeysAsInterfaceWithAllKeys() []interface{}

func (OutputArray) Write

func (output OutputArray) Write()

Write will provide the output as configured in the configuration

type OutputHolder

type OutputHolder struct {
	Contents map[string]interface{}
}

OutputHolder holds key-value pairs that belong together in the output

type OutputSettings

type OutputSettings struct {
	// Defines whether a table of contents should be added
	HasTOC bool
	// The header information for a draw.io/diagrams.net CSV import
	DrawIOHeader drawio.Header
	// FrontMatter can be provided for a Markdown output
	FrontMatter map[string]string
	// The columns for graphical interfaces to show how parent-child relationships connect
	FromToColumns *FromToColumns
	// The type of Mermaid diagram
	MermaidSettings *mermaid.Settings
	// The name of the file the output should be saved to
	OutputFile string
	// The format of the output file
	OutputFileFormat string
	// The format of the output that should be used
	OutputFormat string
	// Store the output in the provided S3 bucket
	S3Bucket S3Output
	// For table heavy outputs, should there be extra spacing between tables
	SeparateTables bool
	// Does the output need to be appended to an existing file?
	ShouldAppend bool
	// For columnar outputs (table, html, csv, markdown) split rows with multiple values into separate rows
	SplitLines bool
	// The key the output should be sorted by
	SortKey string
	// For tables, how wide can a table be?
	TableMaxColumnWidth int
	// The style of the table
	TableStyle table.Style
	// The title of the output
	Title string
	// Should colors be shown in the output
	UseColors bool
	// Should emoji be shown in the output
	UseEmoji bool
	// Should progress output be shown
	ProgressEnabled bool
	// ProgressOptions configures the progress indicator
	ProgressOptions ProgressOptions
}

func NewOutputSettings

func NewOutputSettings() *OutputSettings

NewOutputSettings creates and returns a new OutputSettings object with some default values

func (*OutputSettings) AddFromToColumns

func (settings *OutputSettings) AddFromToColumns(from string, to string)

AddFromToColumns sets from to columns for graphical formats

func (*OutputSettings) AddFromToColumnsWithLabel

func (settings *OutputSettings) AddFromToColumnsWithLabel(from string, to string, label string)

AddFromToColumns sets from to columns for graphical formats

func (*OutputSettings) DisableProgress added in v1.5.0

func (settings *OutputSettings) DisableProgress()

DisableProgress turns off progress output.

func (*OutputSettings) EnableProgress added in v1.5.0

func (settings *OutputSettings) EnableProgress()

EnableProgress turns on progress output.

func (*OutputSettings) GetDefaultExtension

func (settings *OutputSettings) GetDefaultExtension() string

func (*OutputSettings) GetSeparator

func (settings *OutputSettings) GetSeparator() string

func (*OutputSettings) NeedsFromToColumns

func (settings *OutputSettings) NeedsFromToColumns() bool

NeedsFromToColumns verifies if a format requires from and to columns to be set

func (*OutputSettings) SetOutputFormat

func (settings *OutputSettings) SetOutputFormat(format string)

SetOutputFormat sets the expected output format

func (*OutputSettings) SetS3Bucket

func (settings *OutputSettings) SetS3Bucket(client *s3.Client, bucket string, path string)

func (*OutputSettings) StringBold

func (settings *OutputSettings) StringBold(text string) string

func (*OutputSettings) StringBoldInline

func (settings *OutputSettings) StringBoldInline(text string) string

func (*OutputSettings) StringFailure

func (settings *OutputSettings) StringFailure(text interface{}) string

func (*OutputSettings) StringInfo

func (settings *OutputSettings) StringInfo(text interface{}) string

func (*OutputSettings) StringPositive

func (settings *OutputSettings) StringPositive(text string) string

func (*OutputSettings) StringPositiveInline

func (settings *OutputSettings) StringPositiveInline(text string) string

func (*OutputSettings) StringSuccess

func (settings *OutputSettings) StringSuccess(text interface{}) string

func (*OutputSettings) StringWarning

func (settings *OutputSettings) StringWarning(text string) string

func (*OutputSettings) StringWarningInline

func (settings *OutputSettings) StringWarningInline(text string) string

type PrettyProgress added in v1.5.0

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

PrettyProgress wraps go-pretty's progress.Writer to implement the Progress interface. All methods are guarded by a mutex making the type safe for concurrent use by multiple goroutines.

func (*PrettyProgress) Complete added in v1.5.0

func (pp *PrettyProgress) Complete()

Complete marks the progress as done successfully.

func (*PrettyProgress) Fail added in v1.5.0

func (pp *PrettyProgress) Fail(err error)

Fail marks the progress as failed with the error message.

func (*PrettyProgress) Increment added in v1.5.0

func (pp *PrettyProgress) Increment(n int)

Increment increases the progress by n.

func (*PrettyProgress) IsActive added in v1.5.0

func (pp *PrettyProgress) IsActive() bool

IsActive reports if progress output is running.

func (*PrettyProgress) SetColor added in v1.5.0

func (pp *PrettyProgress) SetColor(color ProgressColor)

SetColor changes the progress bar color.

func (*PrettyProgress) SetContext added in v1.5.0

func (pp *PrettyProgress) SetContext(ctx context.Context)

SetContext sets a context that, when cancelled, stops the progress.

func (*PrettyProgress) SetCurrent added in v1.5.0

func (pp *PrettyProgress) SetCurrent(current int)

SetCurrent sets the current progress value.

func (*PrettyProgress) SetStatus added in v1.5.0

func (pp *PrettyProgress) SetStatus(status string)

SetStatus updates the status message.

func (*PrettyProgress) SetTotal added in v1.5.0

func (pp *PrettyProgress) SetTotal(total int)

SetTotal sets the expected total value.

type Progress added in v1.5.0

type Progress interface {
	// SetTotal sets the total number of steps for this progress.
	SetTotal(total int)
	// SetCurrent sets the current progress value.
	SetCurrent(current int)
	// Increment increases the current value by n.
	Increment(n int)
	// SetStatus updates the displayed status message.
	SetStatus(status string)
	// SetColor changes the color of the progress indicator.
	SetColor(color ProgressColor)
	// Complete marks the progress as finished successfully.
	Complete()
	// Fail marks the progress as failed with the provided error.
	Fail(err error)
	// IsActive returns true when the progress indicator is running.
	IsActive() bool
	// SetContext sets a context used to cancel the progress.
	SetContext(ctx context.Context)
}

Progress describes an abstract progress indicator. Implementations must be safe for concurrent use by multiple goroutines.

func NewProgress added in v1.5.0

func NewProgress(settings *OutputSettings) Progress

NewProgress returns a progress implementation based on the output format and settings. Use the returned Progress instance to update progress from your application. The implementation chosen depends on the configured output format.

type ProgressColor added in v1.5.0

type ProgressColor int

ProgressColor defines the color used for a progress indicator.

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 ProgressOptions added in v1.5.0

type ProgressOptions struct {
	// Color specifies the default color for the progress indicator.
	Color ProgressColor
	// Status sets an optional initial status message.
	Status string
	// TrackerLength sets the width of the progress bar. Values <= 0
	// use a sensible default.
	TrackerLength int
}

ProgressOptions configures the behaviour of a Progress implementation.

type S3Output

type S3Output struct {
	S3Client *s3.Client
	Bucket   string
	Path     string
}

type SavedSection added in v1.5.1

type SavedSection struct {
	Title    string
	Keys     []string
	Contents []OutputHolder
}

Store section structure for table-based formats

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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