miettego

package module
v0.0.0-...-fd8aac8 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

README

miettego

A Go port of Rust's miette — fancy diagnostic errors with beautiful, human-readable error reports for CLI tools and compilers.

lint::unused_variable

  ⚠ unused variable `transformed`
   ╭─[processor.go:3:5]
 2 │     result := fetchFromDB()
 3 │     transformed := transform(result)
   ·     ─────┬─────
   ·          ╰── assigned but never used
 4 │     return result
   ╰────
  help: prefix with an underscore: `_transformed`

Screenshots

1 2 3

Features

  • Graphical report handler — Unicode box-drawing, colored output with ANSI/RGB, multi-line highlights, multi-label support, word wrapping
  • Narratable report handler — Plain text output optimized for screen readers and non-TTY environments
  • JSON report handler — Machine-readable diagnostic output
  • Source code snippets — Point at exact byte ranges with labeled spans, context lines, and file names
  • Cause chains — Walk diagnostic and standard Go error chains (Unwrap())
  • Related diagnostics — Attach related errors rendered alongside or nested within the main diagnostic
  • Severity levels — Error, Warning, Advice with distinct icons and styles
  • Theming — Unicode, ASCII, Emoji character sets; ANSI, RGB, and no-color style presets; fully customizable
  • Wide character support — Correct alignment for CJK, emoji, and other multi-width Unicode
  • Tab handling — Configurable tab width with proper underline alignment
  • Terminal detection — Auto-detects color, Unicode, hyperlink support, and terminal width

Installation

go get github.com/DeluxeOwl/miettego

Requires Go 1.25+.

Quick Start

package main

import (
	"os"

	m "github.com/DeluxeOwl/miettego"
)

func main() {
	src := `func processData() {
    result := fetchFromDB()
    transformed := transform(result)
    return result
}`

	diag := m.NewMietteDiagnostic("unused variable `transformed`").
		WithCode("lint::unused_variable").
		WithSeverity(m.SeverityWarning).
		WithHelp("prefix with an underscore: `_transformed`").
		WithSourceCode(m.NewNamedSource("processor.go", m.NewStringSource(src))).
		WithLabels([]m.LabeledSpan{
			m.LabelAt(m.NewSourceSpan(53, 11), "assigned but never used"),
		})

	handler := m.NewMietteHandlerOpts().
		ForceGraphical(true).
		Color(true).
		Width(80).
		Build()

	handler.RenderReport(os.Stderr, diag)
}

Core Concepts

The Diagnostic Interface

Any error that wants pretty-printed output implements the Diagnostic interface:

type Diagnostic interface {
    error
    Code() string               // unique diagnostic code, e.g. "parse::unexpected_token"
    DiagSeverity() *Severity    // Error, Warning, or Advice (nil defaults to Error)
    Help() string               // additional help text
    URL() string                // link to more information
    DiagSourceCode() SourceCode // source code to display
    Labels() []LabeledSpan      // labels pointing at source spans
    Related() []Diagnostic      // related diagnostics
    DiagnosticSource() Diagnostic // cause chain (distinct from Go's Unwrap)
}
MietteDiagnostic — The Builder

For most use cases, use the built-in builder:

diag := miettego.NewMietteDiagnostic("mismatched types").
    WithCode("type::mismatch").
    WithSeverity(miettego.SeverityError).
    WithHelp("consider converting with .parse::<i32>()").
    WithURL("https://example.com/help").
    WithSourceCode(miettego.NewNamedSource("types.rs", miettego.NewStringSource(src))).
    WithLabels([]miettego.LabeledSpan{
        miettego.LabelAt(miettego.NewSourceSpan(17, 7), "this is a `&str`"),
        miettego.LabelAt(miettego.NewSourceSpan(43, 4), "expected `i32`, found `&str`"),
    })

You can also implement Diagnostic on your own error types for tighter integration.

Source Code and Spans

SourceSpan is a byte range (offset + length) into source text:

span := miettego.NewSourceSpan(27, 1) // offset 27, length 1

LabeledSpan attaches an optional label to a span:

miettego.LabelAt(span, "unexpected token")    // labeled span
miettego.LabelAtOffset(4, "expected ')'")     // zero-length span (points at offset)
miettego.LabelUnderline(span)                 // underline with no label text

SourceCode provides the actual text. Wrap strings with NewStringSource:

source := miettego.NewStringSource("let x = 1 +* 2;")

NamedSource adds a filename to any SourceCode:

named := miettego.NewNamedSource("main.rs", source)
// Renders as: ╭─[main.rs:2:3]
Severity Levels
miettego.SeverityError   // × icon (default)
miettego.SeverityWarning // ⚠ icon
miettego.SeverityAdvice  // ☞ icon
Cause Chains

Chain diagnostics together. The cause chain is walked via DiagnosticSource() first, then via Go's standard Unwrap():

inner := miettego.NewMietteDiagnostic("invalid digit found in string").
    WithCode("parse::int")

diag := miettego.NewMietteDiagnostic("failed to parse config").
    WithCode("config::parse_error").
    WithDiagnosticSource(inner)

Attach related errors that render alongside the main diagnostic:

diag := miettego.NewMietteDiagnostic("unknown keyword `FORM`").
    WithRelated([]miettego.Diagnostic{related1, related2})

Report Handlers

Graphical (default)

Rich terminal output with box-drawing, colors, and underlines:

handler := miettego.NewGraphicalReportHandler()
handler.RenderReport(os.Stderr, diag)
Narratable

Plain text for screen readers and non-TTY:

handler := miettego.NewNarratableReportHandler()
handler.RenderReport(os.Stderr, diag)

Output:

oops!
    Diagnostic severity: error
Begin snippet for bad_file.rs starting at line 1, column 1

snippet line 2:   text
    label at line 2, columns 3 to 6: this bit here
diagnostic help: try doing it better next time?
diagnostic code: oops::my::bad
JSON

Machine-readable output:

handler := miettego.NewJSONReportHandler()
handler.RenderReport(os.Stdout, diag)
Using MietteHandlerOpts

The options builder auto-detects terminal capabilities and produces the right handler:

handler := miettego.NewMietteHandlerOpts().
    Width(80).               // wrap width
    Color(true).             // force color on/off
    Unicode(true).           // force Unicode on/off
    ContextLines(2).         // lines of context around highlights
    TabWidth(4).             // displayed tab width
    Footer("see docs").      // footer text
    WithCauseChain().        // include cause chain (default)
    ForceGraphical(true).    // force graphical mode
    Build()

Theming

Built-in Themes
miettego.UnicodeTheme()        // Unicode chars + ANSI colors (default)
miettego.ASCIITheme()          // ASCII chars + ANSI colors
miettego.UnicodeNoColorTheme() // Unicode chars, no color
miettego.NoneTheme()           // ASCII chars, no color
Character Sets
miettego.UnicodeCharacters() // ╭─│╰ ×⚠☞
miettego.ASCIICharacters()   // ,-|` x!>
miettego.EmojiCharacters()   // ╭─│╰ 💥⚠️💡
Style Presets
miettego.ANSIStyles() // standard ANSI colors
miettego.RGBStyles()  // 24-bit RGB colors
miettego.NoStyles()   // no styling
Custom Theme
theme := miettego.GraphicalTheme{
    Characters: miettego.UnicodeCharacters(),
    Styles:     miettego.RGBStyles(),
}
handler := miettego.NewGraphicalReportHandlerThemed(theme)

Advanced Usage

Primary Labels

Mark a label as primary to control which span appears in the header [file:line:col]:

miettego.NewPrimaryLabeledSpanWithSpan(strPtr("nope"), span)
Multi-line Highlights

Spans that cross line boundaries render as multi-line regions with arrows:

 2 │ ╭─▶   text
 3 │ ├─▶     here
   · ╰──── these two lines
Multi-line Label Text

Labels can contain newlines for multi-line descriptions:

miettego.LabelAt(span, "this bit here\nand\nthis\ntoo")
   · ──┬─
   ·   ╰─┤ this bit here
   ·     │ and
   ·     │ this
   ·     │ too

Render related diagnostics inline instead of as siblings:

handler.SetShowRelatedAsNested(true)

When supported, diagnostic codes link to their URL:

diag.WithCode("parse::err").WithURL("https://example.com/help")
OffsetFromLocation

Convert a 1-based line/column location to a byte offset:

offset := miettego.OffsetFromLocation(source, 3, 5) // line 3, column 5

License

See LICENSE for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func VisualWidth

func VisualWidth(s string) int

VisualWidth returns the visual width of a string (ignoring ANSI escapes).

Types

type ChainLink struct {
	Kind       ErrorKind
	Diagnostic Diagnostic
	StdError   error
}

ChainLink represents a single link in a diagnostic cause chain.

func (ChainLink) Message

func (cl ChainLink) Message() string

Message returns the error message for this chain link.

type Color

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

Color represents a terminal color.

type Diagnostic

type Diagnostic interface {
	error

	// Code returns a unique diagnostic code that can be used to look up more
	// information about this Diagnostic. Returns empty string if not set.
	Code() string

	// DiagSeverity returns the diagnostic severity. Defaults to SeverityError.
	DiagSeverity() *Severity

	// Help returns additional help text related to this Diagnostic.
	// Returns empty string if not set.
	Help() string

	// URL returns a URL to visit for a more detailed explanation.
	// Returns empty string if not set.
	URL() string

	// DiagSourceCode returns the source code to apply this Diagnostic's labels to.
	// Returns nil if not set.
	DiagSourceCode() SourceCode

	// Labels returns the labels to apply to this Diagnostic's source code.
	// Returns nil if no labels.
	Labels() []LabeledSpan

	// Related returns additional related Diagnostics.
	// Returns nil if no related diagnostics.
	Related() []Diagnostic

	// DiagnosticSource returns the cause of the error as a Diagnostic.
	// This is distinct from Go's standard error unwrapping.
	// Returns nil if no diagnostic source.
	DiagnosticSource() Diagnostic
}

Diagnostic is the core interface. Any error that wants pretty printing should implement this. It embeds Go's error interface.

All methods are optional in concept — return zero values to skip:

  • Code() returns "" for no code
  • DiagSeverity() returns SeverityError by default
  • Help() returns "" for no help
  • URL() returns "" for no URL
  • DiagSourceCode() returns nil for no source code
  • Labels() returns nil for no labels
  • Related() returns nil for no related diagnostics
  • DiagnosticSource() returns nil for no cause diagnostic

type DiagnosticChain

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

DiagnosticChain iterates over a chain of diagnostic/error causes.

func DiagnosticChainFromDiag

func DiagnosticChainFromDiag(diag Diagnostic) *DiagnosticChain

DiagnosticChainFromDiag creates a DiagnosticChain starting from a Diagnostic. It walks the chain via DiagnosticSource() and then Unwrap() for standard errors.

func (*DiagnosticChain) Len

func (dc *DiagnosticChain) Len() int

Len returns the number of links in the chain.

func (dc *DiagnosticChain) Links() []ChainLink

Links returns all the links in the chain.

type ErrorKind

type ErrorKind int

ErrorKind represents either a Diagnostic or a standard Go error in a cause chain.

const (
	// ErrorKindDiagnostic is a Diagnostic error.
	ErrorKindDiagnostic ErrorKind = iota
	// ErrorKindStdError is a standard Go error.
	ErrorKindStdError
)

type GraphicalReportHandler

type GraphicalReportHandler struct {
	Links                LinkStyle
	TermWidth            int
	Theme                GraphicalTheme
	Footer               string
	ContextLines         int
	TabWidth             int
	WithCauseChain       bool
	WrapLines            bool
	BreakWords           bool
	WithPrimarySpanStart bool
	LinkDisplayText      string
	ShowRelatedAsNested  bool
}

GraphicalReportHandler renders diagnostics with Unicode box-drawing, ANSI colors, and other graphical elements.

func NewGraphicalReportHandler

func NewGraphicalReportHandler() *GraphicalReportHandler

NewGraphicalReportHandler creates a new handler with default settings.

func NewGraphicalReportHandlerThemed

func NewGraphicalReportHandlerThemed(theme GraphicalTheme) *GraphicalReportHandler

NewGraphicalReportHandlerThemed creates a new handler with the given theme.

func (*GraphicalReportHandler) RenderReport

func (h *GraphicalReportHandler) RenderReport(w io.Writer, diag Diagnostic) error

RenderReport renders a Diagnostic to the given writer.

func (*GraphicalReportHandler) SetBreakWords

func (h *GraphicalReportHandler) SetBreakWords(breakWords bool) *GraphicalReportHandler

SetBreakWords enables or disables word breaking during wrapping.

func (*GraphicalReportHandler) SetContextLines

func (h *GraphicalReportHandler) SetContextLines(lines int) *GraphicalReportHandler

SetContextLines sets the number of context lines around errors.

func (*GraphicalReportHandler) SetFooter

SetFooter sets the global footer text.

func (*GraphicalReportHandler) SetLinkDisplayText

func (h *GraphicalReportHandler) SetLinkDisplayText(text string) *GraphicalReportHandler

SetLinkDisplayText sets the display text for links.

SetLinks configures whether to enable error code linkification.

func (*GraphicalReportHandler) SetShowRelatedAsNested

func (h *GraphicalReportHandler) SetShowRelatedAsNested(show bool) *GraphicalReportHandler

SetShowRelatedAsNested enables or disables rendering related errors as nested.

func (*GraphicalReportHandler) SetTabWidth

func (h *GraphicalReportHandler) SetTabWidth(width int) *GraphicalReportHandler

SetTabWidth sets the displayed tab width in spaces.

func (*GraphicalReportHandler) SetTermWidth

func (h *GraphicalReportHandler) SetTermWidth(width int) *GraphicalReportHandler

SetTermWidth sets the terminal width for wrapping.

func (*GraphicalReportHandler) SetWithCauseChain

func (h *GraphicalReportHandler) SetWithCauseChain(with bool) *GraphicalReportHandler

SetWithCauseChain enables or disables cause chain rendering.

func (*GraphicalReportHandler) SetWithPrimarySpanStart

func (h *GraphicalReportHandler) SetWithPrimarySpanStart(with bool) *GraphicalReportHandler

SetWithPrimarySpanStart enables or disables primary span start info.

func (*GraphicalReportHandler) SetWrapLines

func (h *GraphicalReportHandler) SetWrapLines(wrap bool) *GraphicalReportHandler

SetWrapLines enables or disables line wrapping.

type GraphicalTheme

type GraphicalTheme struct {
	// Characters to be used for drawing.
	Characters ThemeCharacters
	// Styles to be used for painting.
	Styles ThemeStyles
}

GraphicalTheme is the theme used by GraphicalReportHandler to render fancy Diagnostic reports.

A theme consists of two things: the set of characters to be used for drawing, and the Styles to be used to paint various items.

func ASCIITheme

func ASCIITheme() GraphicalTheme

ASCIITheme returns an ASCII-art-based graphical theme with ANSI styling.

func DefaultTheme

func DefaultTheme() GraphicalTheme

DefaultTheme returns the default theme based on terminal detection and environment variables (NO_COLOR, TERM, etc.).

func NoneTheme

func NoneTheme() GraphicalTheme

NoneTheme returns a "basic" graphical theme that skips colors and unicode characters and just does monochrome ASCII art.

func UnicodeNoColorTheme

func UnicodeNoColorTheme() GraphicalTheme

UnicodeNoColorTheme returns a graphical theme that draws in monochrome, while still using unicode characters.

func UnicodeTheme

func UnicodeTheme() GraphicalTheme

UnicodeTheme returns a graphical theme that draws using both ANSI colors and unicode characters.

Note that full RGB colors aren't enabled by default because they're an accessibility hazard, especially in the context of terminal themes that can change the background color and make hardcoded colors illegible.

type JSONReportHandler

type JSONReportHandler struct{}

JSONReportHandler renders diagnostics as machine-readable JSON.

func NewJSONReportHandler

func NewJSONReportHandler() *JSONReportHandler

NewJSONReportHandler creates a new JSONReportHandler.

func (*JSONReportHandler) RenderReport

func (h *JSONReportHandler) RenderReport(w io.Writer, diag Diagnostic) error

RenderReport renders a Diagnostic as JSON to the given writer.

type LabeledSpan

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

LabeledSpan is a SourceSpan with an optional label and primary flag.

func LabelAt

func LabelAt(span SourceSpan, label string) LabeledSpan

LabelAt creates a new label at the specified span with the given label text.

func LabelAtOffset

func LabelAtOffset(offset int, label string) LabeledSpan

LabelAtOffset creates a new label that points at a specific offset.

func LabelUnderline

func LabelUnderline(span SourceSpan) LabeledSpan

LabelUnderline creates a new label without text, that underlines a specific span.

func NewLabeledSpan

func NewLabeledSpan(label *string, offset, length int) LabeledSpan

NewLabeledSpan creates a new labeled span.

func NewLabeledSpanWithSpan

func NewLabeledSpanWithSpan(label *string, span SourceSpan) LabeledSpan

NewLabeledSpanWithSpan creates a new labeled span using an existing span.

func NewPrimaryLabeledSpanWithSpan

func NewPrimaryLabeledSpanWithSpan(label *string, span SourceSpan) LabeledSpan

NewPrimaryLabeledSpanWithSpan creates a new labeled primary span using an existing span.

func (LabeledSpan) Inner

func (ls LabeledSpan) Inner() SourceSpan

Inner returns the inner SourceSpan.

func (LabeledSpan) IsEmpty

func (ls LabeledSpan) IsEmpty() bool

IsEmpty returns true if this LabeledSpan is empty.

func (LabeledSpan) Label

func (ls LabeledSpan) Label() *string

Label returns the optional label string for this LabeledSpan.

func (LabeledSpan) Len

func (ls LabeledSpan) Len() int

Len returns the number of bytes this LabeledSpan spans.

func (LabeledSpan) Offset

func (ls LabeledSpan) Offset() int

Offset returns the 0-based starting byte offset.

func (LabeledSpan) Primary

func (ls LabeledSpan) Primary() bool

Primary returns true if this LabeledSpan is a primary span.

func (*LabeledSpan) SetLabel

func (ls *LabeledSpan) SetLabel(label *string)

SetLabel changes the text of the label.

type LinkStyle

type LinkStyle int

LinkStyle controls how diagnostic URLs are displayed.

const (
	// LinkStyleNone hides URLs entirely.
	LinkStyleNone LinkStyle = iota
	// LinkStyleLink renders URLs as terminal hyperlinks (OSC 8).
	LinkStyleLink
	// LinkStyleText renders URLs as plain text next to the code.
	LinkStyleText
)

type MietteDiagnostic

type MietteDiagnostic struct {
	// Message is the displayed diagnostic message.
	Message string
	// DiagCode is the unique diagnostic code.
	DiagCode string
	// Sev is the diagnostic severity.
	Sev *Severity
	// HelpText is additional help text.
	HelpText string
	// DiagURL is a URL for more detailed information.
	DiagURL string
	// DiagLabels are labels to apply to the source code.
	DiagLabels []LabeledSpan
	// Source is the source code to apply labels to.
	Source SourceCode
	// RelatedDiags are additional related diagnostics.
	RelatedDiags []Diagnostic
	// CauseDiag is the diagnostic source (cause).
	CauseDiag Diagnostic
}

MietteDiagnostic is a diagnostic that can be created at runtime. It implements the Diagnostic interface and provides a builder pattern for convenient construction.

func NewMietteDiagnostic

func NewMietteDiagnostic(message string) *MietteDiagnostic

NewMietteDiagnostic creates a new dynamic diagnostic with the given message.

func (*MietteDiagnostic) AndLabel

func (d *MietteDiagnostic) AndLabel(label LabeledSpan) *MietteDiagnostic

AndLabel appends a new label to the existing labels.

func (*MietteDiagnostic) AndLabels

func (d *MietteDiagnostic) AndLabels(labels []LabeledSpan) *MietteDiagnostic

AndLabels appends new labels to the existing labels.

func (*MietteDiagnostic) Code

func (d *MietteDiagnostic) Code() string

Code implements the Diagnostic interface.

func (*MietteDiagnostic) DiagSeverity

func (d *MietteDiagnostic) DiagSeverity() *Severity

DiagSeverity implements the Diagnostic interface.

func (*MietteDiagnostic) DiagSourceCode

func (d *MietteDiagnostic) DiagSourceCode() SourceCode

DiagSourceCode implements the Diagnostic interface.

func (*MietteDiagnostic) DiagnosticSource

func (d *MietteDiagnostic) DiagnosticSource() Diagnostic

DiagnosticSource implements the Diagnostic interface.

func (*MietteDiagnostic) Error

func (d *MietteDiagnostic) Error() string

Error implements the error interface.

func (*MietteDiagnostic) Help

func (d *MietteDiagnostic) Help() string

Help implements the Diagnostic interface.

func (*MietteDiagnostic) Labels

func (d *MietteDiagnostic) Labels() []LabeledSpan

Labels implements the Diagnostic interface.

func (*MietteDiagnostic) Related

func (d *MietteDiagnostic) Related() []Diagnostic

Related implements the Diagnostic interface.

func (*MietteDiagnostic) URL

func (d *MietteDiagnostic) URL() string

URL implements the Diagnostic interface.

func (*MietteDiagnostic) WithCode

func (d *MietteDiagnostic) WithCode(code string) *MietteDiagnostic

WithCode returns the diagnostic with the given code.

func (*MietteDiagnostic) WithDiagnosticSource

func (d *MietteDiagnostic) WithDiagnosticSource(source Diagnostic) *MietteDiagnostic

WithDiagnosticSource returns the diagnostic with the given cause diagnostic.

func (*MietteDiagnostic) WithHelp

func (d *MietteDiagnostic) WithHelp(help string) *MietteDiagnostic

WithHelp returns the diagnostic with the given help text.

func (*MietteDiagnostic) WithLabel

func (d *MietteDiagnostic) WithLabel(label LabeledSpan) *MietteDiagnostic

WithLabel returns the diagnostic with the given label, replacing any existing labels.

func (*MietteDiagnostic) WithLabels

func (d *MietteDiagnostic) WithLabels(labels []LabeledSpan) *MietteDiagnostic

WithLabels returns the diagnostic with the given labels, replacing any existing labels.

func (*MietteDiagnostic) WithRelated

func (d *MietteDiagnostic) WithRelated(related []Diagnostic) *MietteDiagnostic

WithRelated returns the diagnostic with the given related diagnostics.

func (*MietteDiagnostic) WithSeverity

func (d *MietteDiagnostic) WithSeverity(severity Severity) *MietteDiagnostic

WithSeverity returns the diagnostic with the given severity.

func (*MietteDiagnostic) WithSourceCode

func (d *MietteDiagnostic) WithSourceCode(source SourceCode) *MietteDiagnostic

WithSourceCode returns the diagnostic with the given source code.

func (*MietteDiagnostic) WithURL

func (d *MietteDiagnostic) WithURL(url string) *MietteDiagnostic

WithURL returns the diagnostic with the given URL.

type MietteError

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

MietteError represents errors within the miette library itself.

func NewIOError

func NewIOError(err error) *MietteError

NewIOError creates a new IO MietteError wrapping the given error.

func NewOutOfBoundsError

func NewOutOfBoundsError() *MietteError

NewOutOfBoundsError creates a new out-of-bounds MietteError.

func (*MietteError) Code

func (e *MietteError) Code() string

Code implements the Diagnostic interface.

func (*MietteError) DiagSeverity

func (e *MietteError) DiagSeverity() *Severity

DiagSeverity implements the Diagnostic interface.

func (*MietteError) DiagSourceCode

func (e *MietteError) DiagSourceCode() SourceCode

DiagSourceCode implements the Diagnostic interface.

func (*MietteError) DiagnosticSource

func (e *MietteError) DiagnosticSource() Diagnostic

DiagnosticSource implements the Diagnostic interface.

func (*MietteError) Error

func (e *MietteError) Error() string

Error implements the error interface.

func (*MietteError) Help

func (e *MietteError) Help() string

Help implements the Diagnostic interface.

func (*MietteError) Kind

func (e *MietteError) Kind() MietteErrorKind

Kind returns the kind of this MietteError.

func (*MietteError) Labels

func (e *MietteError) Labels() []LabeledSpan

Labels implements the Diagnostic interface.

func (*MietteError) Related

func (e *MietteError) Related() []Diagnostic

Related implements the Diagnostic interface.

func (*MietteError) URL

func (e *MietteError) URL() string

URL implements the Diagnostic interface.

func (*MietteError) Unwrap

func (e *MietteError) Unwrap() error

Unwrap returns the wrapped error, if any.

type MietteErrorKind

type MietteErrorKind int

MietteErrorKind represents the kind of MietteError.

const (
	// ErrOutOfBounds is returned when a SourceSpan extends beyond the bounds of a SourceCode.
	ErrOutOfBounds MietteErrorKind = iota
	// ErrIOError is returned when something went wrong while reading a SourceCode.
	ErrIOError
)

type MietteHandlerOpts

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

MietteHandlerOpts is a builder for creating report handlers. It auto-detects terminal capabilities and produces either a GraphicalReportHandler or NarratableReportHandler.

func NewMietteHandlerOpts

func NewMietteHandlerOpts() *MietteHandlerOpts

NewMietteHandlerOpts creates a new MietteHandlerOpts with default settings.

func (*MietteHandlerOpts) BreakWords

func (o *MietteHandlerOpts) BreakWords(breakWords bool) *MietteHandlerOpts

BreakWords enables or disables word breaking during wrapping.

func (*MietteHandlerOpts) Build

func (o *MietteHandlerOpts) Build() ReportHandler

Build creates a ReportHandler based on the configured options.

func (*MietteHandlerOpts) Color

func (o *MietteHandlerOpts) Color(color bool) *MietteHandlerOpts

Color forces or disables color output.

func (*MietteHandlerOpts) ContextLines

func (o *MietteHandlerOpts) ContextLines(lines int) *MietteHandlerOpts

ContextLines sets the number of context lines around errors.

func (*MietteHandlerOpts) Footer

func (o *MietteHandlerOpts) Footer(footer string) *MietteHandlerOpts

Footer sets a footer to be displayed at the bottom of the report.

func (*MietteHandlerOpts) ForceGraphical

func (o *MietteHandlerOpts) ForceGraphical(force bool) *MietteHandlerOpts

ForceGraphical forces graphical rendering.

func (*MietteHandlerOpts) ForceNarrated

func (o *MietteHandlerOpts) ForceNarrated(force bool) *MietteHandlerOpts

ForceNarrated forces narrated rendering.

func (*MietteHandlerOpts) LinkDisplayText

func (o *MietteHandlerOpts) LinkDisplayText(text string) *MietteHandlerOpts

LinkDisplayText sets the display text for links.

func (*MietteHandlerOpts) SetGraphicalTheme

func (o *MietteHandlerOpts) SetGraphicalTheme(theme GraphicalTheme) *MietteHandlerOpts

GraphicalTheme sets a graphical theme for the handler.

func (*MietteHandlerOpts) SetRGBColors

func (o *MietteHandlerOpts) SetRGBColors(rgb RGBColors) *MietteHandlerOpts

SetRGBColors controls which color format to use.

func (*MietteHandlerOpts) ShowRelatedAsNested

func (o *MietteHandlerOpts) ShowRelatedAsNested() *MietteHandlerOpts

ShowRelatedAsNested renders related errors as nested.

func (*MietteHandlerOpts) ShowRelatedAsSiblings

func (o *MietteHandlerOpts) ShowRelatedAsSiblings() *MietteHandlerOpts

ShowRelatedAsSiblings renders related errors as siblings.

func (*MietteHandlerOpts) TabWidth

func (o *MietteHandlerOpts) TabWidth(width int) *MietteHandlerOpts

TabWidth sets the displayed tab width in spaces.

func (o *MietteHandlerOpts) TerminalLinks(linkify bool) *MietteHandlerOpts

TerminalLinks sets whether to enable error code linkification.

func (*MietteHandlerOpts) Unicode

func (o *MietteHandlerOpts) Unicode(unicode bool) *MietteHandlerOpts

Unicode forces or disables unicode character display.

func (*MietteHandlerOpts) Width

func (o *MietteHandlerOpts) Width(width int) *MietteHandlerOpts

Width sets the width to wrap the report at.

func (*MietteHandlerOpts) WithCauseChain

func (o *MietteHandlerOpts) WithCauseChain() *MietteHandlerOpts

WithCauseChain includes the cause chain in the report.

func (*MietteHandlerOpts) WithPrimarySpanStart

func (o *MietteHandlerOpts) WithPrimarySpanStart(with bool) *MietteHandlerOpts

WithPrimarySpanStart enables primary span start info (file:line:col).

func (*MietteHandlerOpts) WithoutCauseChain

func (o *MietteHandlerOpts) WithoutCauseChain() *MietteHandlerOpts

WithoutCauseChain excludes the cause chain from the report.

func (*MietteHandlerOpts) WrapLines

func (o *MietteHandlerOpts) WrapLines(wrap bool) *MietteHandlerOpts

WrapLines enables or disables line wrapping.

type MietteSpanContents

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

MietteSpanContents is the basic implementation of the SpanContents interface.

func NewMietteSpanContents

func NewMietteSpanContents(
	data []byte,
	span SourceSpan,
	line, column, lineCount int,
) *MietteSpanContents

NewMietteSpanContents creates a new MietteSpanContents.

func NewNamedMietteSpanContents

func NewNamedMietteSpanContents(
	name string,
	data []byte,
	span SourceSpan,
	line, column, lineCount int,
) *MietteSpanContents

NewNamedMietteSpanContents creates a new MietteSpanContents with a name.

func (*MietteSpanContents) Column

func (c *MietteSpanContents) Column() int

Column returns the 0-indexed starting column.

func (*MietteSpanContents) Data

func (c *MietteSpanContents) Data() []byte

Data returns the bytes of the source code.

func (*MietteSpanContents) Language

func (c *MietteSpanContents) Language() string

Language returns the optional language name.

func (*MietteSpanContents) Line

func (c *MietteSpanContents) Line() int

Line returns the 0-indexed starting line.

func (*MietteSpanContents) LineCount

func (c *MietteSpanContents) LineCount() int

LineCount returns the total number of lines covered.

func (*MietteSpanContents) Name

func (c *MietteSpanContents) Name() string

Name returns the optional name for this SpanContents.

func (*MietteSpanContents) Span

func (c *MietteSpanContents) Span() SourceSpan

Span returns the SourceSpan covered by this SpanContents.

func (*MietteSpanContents) WithLanguage

func (c *MietteSpanContents) WithLanguage(language string) *MietteSpanContents

WithLanguage sets the language for syntax highlighting.

type NamedSource

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

NamedSource wraps a SourceCode to give it a filename. This causes the filename to appear in rendered output like: ╭─[filename.rs:1:12]

func NewNamedSource

func NewNamedSource(name string, source SourceCode) *NamedSource

NewNamedSource creates a new NamedSource wrapping the given SourceCode with a name.

func (*NamedSource) Inner

func (ns *NamedSource) Inner() SourceCode

Inner returns a reference to the inner SourceCode.

func (*NamedSource) Name

func (ns *NamedSource) Name() string

Name returns the name of this NamedSource.

func (*NamedSource) ReadSpan

func (ns *NamedSource) ReadSpan(
	span SourceSpan,
	contextLinesBefore, contextLinesAfter int,
) (SpanContents, error)

ReadSpan implements the SourceCode interface by delegating to the inner source and adding the filename to the result.

func (*NamedSource) WithLanguage

func (ns *NamedSource) WithLanguage(language string) *NamedSource

WithLanguage sets the language for syntax highlighting and returns the NamedSource.

type NarratableReportHandler

type NarratableReportHandler struct {
	ContextLines   int
	WithCauseChain bool
	Footer         string
}

NarratableReportHandler renders plain text and avoids extraneous graphics. It's optimized for screen readers and braille users, but is also used in non-graphical environments, such as non-TTY output.

func NewNarratableReportHandler

func NewNarratableReportHandler() *NarratableReportHandler

NewNarratableReportHandler creates a new NarratableReportHandler.

func (*NarratableReportHandler) RenderReport

func (h *NarratableReportHandler) RenderReport(w io.Writer, diag Diagnostic) error

RenderReport renders a Diagnostic to the given writer.

func (*NarratableReportHandler) SetContextLines

func (h *NarratableReportHandler) SetContextLines(lines int) *NarratableReportHandler

SetContextLines sets the number of context lines.

func (*NarratableReportHandler) SetFooter

SetFooter sets the footer text.

func (*NarratableReportHandler) SetWithCauseChain

func (h *NarratableReportHandler) SetWithCauseChain(with bool) *NarratableReportHandler

SetWithCauseChain enables or disables cause chain rendering.

type RGBColors

type RGBColors int

RGBColors controls the color format used for graphical rendering.

const (
	// RGBColorsNever always uses ANSI, regardless of terminal support for RGB.
	RGBColorsNever RGBColors = iota
	// RGBColorsPreferred uses RGB colors if the terminal supports them.
	RGBColorsPreferred
	// RGBColorsAlways uses RGB colors even if the terminal does not support them.
	RGBColorsAlways
)

type ReportHandler

type ReportHandler interface {
	RenderReport(w io.Writer, diag Diagnostic) error
}

ReportHandler is the interface for rendering diagnostics.

type Severity

type Severity int

Severity represents the severity level of a diagnostic.

const (
	// SeverityError is a critical failure. The program cannot continue.
	// This is the default severity.
	SeverityError Severity = iota
	// SeverityWarning is a warning. Please take note.
	SeverityWarning
	// SeverityAdvice is just some help. Here's how you could be doing it better.
	SeverityAdvice
)

func (Severity) String

func (s Severity) String() string

String returns the string representation of the severity.

type SourceCode

type SourceCode interface {
	// ReadSpan reads the bytes for a specific span, keeping a certain number
	// of lines before and after the span as context.
	ReadSpan(span SourceSpan, contextLinesBefore, contextLinesAfter int) (SpanContents, error)
}

SourceCode is anything that can provide source text for a span.

type SourceOffset

type SourceOffset int

SourceOffset represents a byte offset from the beginning of a SourceCode.

func OffsetFromLocation

func OffsetFromLocation(source string, locLine, locCol int) SourceOffset

OffsetFromLocation converts a 1-based line/column location into a byte offset. This function is infallible: giving an out-of-range line/column pair will return the offset of the last byte in the source.

type SourceSpan

type SourceSpan struct {
	// Offset is the absolute byte offset from the beginning of a SourceCode.
	Offset int
	// Length is the total length of the span, in bytes.
	Length int
}

SourceSpan represents a byte range in source code.

func NewSourceSpan

func NewSourceSpan(offset, length int) SourceSpan

NewSourceSpan creates a new SourceSpan from an offset and length.

func (SourceSpan) End

func (s SourceSpan) End() int

End returns the byte offset of the end of this span (exclusive).

func (SourceSpan) IsEmpty

func (s SourceSpan) IsEmpty() bool

IsEmpty returns whether this SourceSpan has a length of zero. It may still be useful to point to a specific point.

type SpanContents

type SpanContents interface {
	// Data returns the bytes of the source code covered by this span.
	Data() []byte
	// Span returns the SourceSpan covered by this SpanContents.
	Span() SourceSpan
	// Name returns an optional (file?) name for the container of this SpanContents.
	// Returns empty string if unnamed.
	Name() string
	// Line returns the 0-indexed line in the associated SourceCode where the data begins.
	Line() int
	// Column returns the 0-indexed column in the associated SourceCode where the data begins.
	Column() int
	// LineCount returns the total number of lines covered by this SpanContents.
	LineCount() int
	// Language returns the optional language name for this source code.
	// Returns empty string if unknown.
	Language() string
}

SpanContents holds the data read from a SourceCode for a given span.

type StringSource

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

StringSource wraps a string to implement the SourceCode interface.

func NewStringSource

func NewStringSource(s string) *StringSource

NewStringSource creates a new StringSource from a string.

func (*StringSource) ReadSpan

func (s *StringSource) ReadSpan(
	span SourceSpan,
	contextLinesBefore, contextLinesAfter int,
) (SpanContents, error)

ReadSpan implements the SourceCode interface.

type Style

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

Style represents ANSI styling for terminal output. It is a simplified equivalent of owo_colors::Style.

func NewStyle

func NewStyle() Style

NewStyle creates a new empty (unstyled) Style.

func (Style) Blue

func (s Style) Blue() Style

Blue sets the foreground color to blue.

func (Style) Bold

func (s Style) Bold() Style

Bold sets the style to bold.

func (Style) Cyan

func (s Style) Cyan() Style

Cyan sets the foreground color to cyan.

func (Style) Dimmed

func (s Style) Dimmed() Style

Dimmed sets the style to dimmed.

func (Style) FgRGB

func (s Style) FgRGB(r, g, b uint8) Style

FgRGB sets the foreground color to an RGB value.

func (Style) Green

func (s Style) Green() Style

Green sets the foreground color to green.

func (Style) IsPlain

func (s Style) IsPlain() bool

IsPlain returns true if this style has no formatting at all.

func (Style) Italic

func (s Style) Italic() Style

Italic sets the style to italic.

func (Style) Magenta

func (s Style) Magenta() Style

Magenta sets the foreground color to magenta.

func (Style) Paint

func (s Style) Paint(text string) string

Paint applies the style to the given text and returns the styled string. If the style is plain (no formatting), it returns the text unchanged.

func (Style) PaintChar

func (s Style) PaintChar(ch rune) string

PaintChar applies the style to a single character and returns the styled string.

func (Style) Red

func (s Style) Red() Style

Red sets the foreground color to red.

func (Style) Underline

func (s Style) Underline() Style

Underline sets the style to underlined.

func (Style) White

func (s Style) White() Style

White sets the foreground color to white.

func (Style) Yellow

func (s Style) Yellow() Style

Yellow sets the foreground color to yellow.

type ThemeCharacters

type ThemeCharacters struct {
	HBar      rune // horizontal bar, e.g. '─'
	VBar      rune // vertical bar, e.g. '│'
	XBar      rune // cross bar, e.g. '┼'
	VBarBreak rune // vertical bar break (for continuation), e.g. '·'

	UArrow rune // up arrow, e.g. '▲'
	RArrow rune // right arrow, e.g. '▶'

	LTop rune // left top corner, e.g. '╭'
	MTop rune // middle top, e.g. '┬'
	RTop rune // right top corner, e.g. '╮'
	LBot rune // left bottom corner, e.g. '╰'
	RBot rune // right bottom corner, e.g. '╯'
	MBot rune // middle bottom, e.g. '┴'

	LBox rune // left box bracket, e.g. '['
	RBox rune // right box bracket, e.g. ']'

	LCross rune // left cross, e.g. '├'
	RCross rune // right cross, e.g. '┤'

	Underbar  rune // underbar for single-char highlight, e.g. '┬'
	Underline rune // underline for multi-char highlight, e.g. '─'

	Error   string // error icon, e.g. "×"
	Warning string // warning icon, e.g. "⚠"
	Advice  string // advice icon, e.g. "☞"
}

ThemeCharacters defines the characters to be used when drawing diagnostics.

func ASCIICharacters

func ASCIICharacters() ThemeCharacters

ASCIICharacters returns ASCII-art-based graphical characters. Works well on older terminals.

func EmojiCharacters

func EmojiCharacters() ThemeCharacters

EmojiCharacters returns emoji-heavy unicode characters.

func UnicodeCharacters

func UnicodeCharacters() ThemeCharacters

UnicodeCharacters returns fancy unicode-based graphical characters.

func (ThemeCharacters) SeverityIcon

func (tc ThemeCharacters) SeverityIcon(sev Severity) string

SeverityIcon returns the icon character for a given severity.

type ThemeStyles

type ThemeStyles struct {
	// Error is the style for things highlighted as "error".
	Error Style
	// Warning is the style for things highlighted as "warning".
	Warning Style
	// Advice is the style for things highlighted as "advice".
	Advice Style
	// Help is the style for help text.
	Help Style
	// Link is the style for filenames/links/URLs.
	Link Style
	// Linum is the style for line numbers.
	Linum Style
	// Highlights are styles to cycle through for diagnostic highlight lines and text.
	Highlights []Style
}

ThemeStyles defines styles for various parts of graphical rendering.

func ANSIStyles

func ANSIStyles() ThemeStyles

ANSIStyles returns ANSI color-based styles.

func NoStyles

func NoStyles() ThemeStyles

NoStyles returns no styling — plain monochrome text.

func RGBStyles

func RGBStyles() ThemeStyles

RGBStyles returns nice RGB-colored styles.

func (ThemeStyles) StyleForSeverity

func (ts ThemeStyles) StyleForSeverity(sev Severity) Style

StyleForSeverity returns the appropriate style for a given severity.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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