niceyaml

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

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

Go to latest
Published: Jan 16, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

README

Nice YAML!

Go Reference Go Report Card Latest tag License

Package niceyaml combines the powers of go-yaml, bubbletea, and more.

It enables friendly and predictable handling of YAML documents in your CLI or TUI applications.

Also supports all YAML-compatible document formats like KYAML or JSON.

Features

Pretty Printing

  • Render YAML with syntax highlighting via lipgloss, directly from tokenized input
  • Wrap YAML errors from go-yaml's parser with fully styled source annotations
  • Supports custom color schemes, style overlays (e.g. highlights), diff rendering, and more
  • Includes a viewport bubble for your Bubble Tea applications

view

themes

JSON Schema Generation & Validation

  1. Generate JSON schemas from structs via invopop/jsonschema
  2. Provide generated schemas to users, include them via embedding
  3. Use your JSON schemas to validate the Generators via santhosh-tekuri/jsonschema
  4. Users receive the same feedback from your application and their YAML language server!

validate

Installation

go get github.com/macropower/niceyaml@latest

Usage

Core Abstractions

Package niceyaml adds a few abstractions on top of go-yaml:

  • Line - Tokens for a single line of YAML content
  • Lines - Collection of Lines representing one or more YAML documents
  • Source - Manages Lines while abstracting away go-yaml lexer/parser details

Most use cases will only need to interact with Source. It satisfies most interfaces accepted by other niceyaml utilities.

These abstractions enable straightforward iteration over arbitrary lines of tokens from one or more YAML documents, while maintaining the original token details from the lexer. It cleanly solves common problems introduced by multi-line and/or overlapping tokens in diffs, partial rendering, and/or search.

flowchart LR
    A["Input"]
    subgraph Source
        B["Lexer"] --> C["Parser"]
    end
    A --> Source
    C --> D["Decoder"]
    D --> E["Struct"]

Printing YAML with Lipgloss Styles

Printing Diffs Between YAML Revisions

Searching YAML Content

Schema Generation and Validation

Full YAML Viewport Example

See cmd/nyaml for a complete Bubble Tea application that loads, pages, searches, diffs, and validates YAML documents.

Documentation

Overview

Package niceyaml provides utilities for working with YAML documents, built on top of github.com/goccy/go-yaml.

It enables consistent, intuitive, and predictable experiences for developers and users when working with YAML and YAML-compatible documents.

Line Management

The core abstraction is Source, which organizes YAML tokens by line number. A Source value can be created from various sources:

Use WithName to assign a name to Source for identification. Use Source.File to parse tokens into an ast.File for further processing.

Source.Lines and Source.Runes provide iterators for traversing lines and individual runes with their positions.

Each line.Line contains the tokens for that line, along with optional metadata:

Position Tracking

position.Position represents a 0-indexed line and column location within a document. position.Range defines a half-open range [Start, End) for selecting spans of text. Create positions and ranges using position.New and position.NewRange.

These types integrate with the Printer for highlighting and with the Finder for search results.

Revision Tracking

Revision represents a version of Source in a doubly-linked chain, enabling navigation through document history:

origin := niceyaml.NewRevision(original)
tip := origin.Append(modified)
tip.Origin() // returns origin

Diff Generation

FullDiff and SummaryDiff compute differences between two revisions using a longest common subsequence (LCS) algorithm:

full := niceyaml.NewFullDiff(origin, tip)
full.Source()  // all lines with inserted/deleted flags

summary := niceyaml.NewSummaryDiff(origin, tip, 3)
summary.Source()  // changed lines with 3 lines of context

The summary output follows unified diff format with hunk headers.

Style System

The style.Style type identifies token categories for syntax highlighting. style.Styles maps style identifiers to lipgloss styles. Use theme.Charm for a sensible default palette, or provide a custom StyleGetter to the Printer.

Styled YAML Printing

The Printer type renders YAML tokens with syntax highlighting via lipgloss. Use Printer.Print with any LineIterator (such as *Source) to render output. Alternatively, use Printer.PrintSlice to render a subset of lines.

Configure printers using PrinterOption functions:

Built-in gutter functions include DefaultGutter, DiffGutter, LineNumberGutter, and NoGutter.

Use Printer.SetWidth to enable word wrapping, and Printer.AddStyleToRange to highlight specific position.Range spans.

Error Formatting

The Error type wraps errors with YAML source context and precise location information. When printed, errors display the relevant portion of the source with the error location highlighted.

Create errors with NewError and configure with ErrorOption functions:

Use Source.WrapError to wrap errors with source annotations.

String Finding

The Finder type searches for strings within YAML tokens, returning position.Range values that can be used with Printer.AddStyleToRange for highlighting matches. Configure search behavior with WithNormalizer to apply text normalization such as StandardNormalizer for case-insensitive matching.

YAML Utilities

Encoder and Decoder wrap go-yaml functionality for encoding and decoding YAML documents with consistent error handling and validation. Two validation interfaces are available:

  • Validator: For self-validation (implemented by decoded types)
  • SchemaValidator: For schema-based validation (e.g., JSON schema)

Decoder provides an iterator-based API via Decoder.Documents, which yields DocumentDecoder instances for each document in a multi-document YAML file:

source := niceyaml.NewSourceFromString(yamlContent)
file, err := source.File()
if err != nil {
    return source.WrapError(err)
}
decoder := niceyaml.NewDecoder(file)
for _, doc := range decoder.Documents() {
    var config Config
    if err := doc.Unmarshal(&config); err != nil {
        return source.WrapError(err)
    }
}

DocumentDecoder provides methods for working with individual documents: DocumentDecoder.Unmarshal (validates and decodes), DocumentDecoder.Decode, DocumentDecoder.ValidateSchema, DocumentDecoder.GetValue, and their context-aware variants.

NewPathBuilder and NewPath create [*yaml.Path]s for pointing to specific YAML paths programmatically.

Schema Generation and Validation

The github.com/macropower/niceyaml/schema/generator package provides JSON schema generation from Go types. Use [generator.New] with options like [generator.WithPackagePaths] to include source comments as descriptions.

The github.com/macropower/niceyaml/schema/validator package validates data against JSON schemas. Use [validator.New] to create validators that return Error values with precise YAML path information.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoSource = errors.New("no source provided")

ErrNoSource indicates no source was provided to resolve an error path.

View Source
var PrettyEncoderOptions = []yaml.EncodeOption{
	yaml.Indent(2),
	yaml.IndentSequence(true),
}

PrettyEncoderOptions are default encoding options which can be used by NewEncoder to produce prettier-friendly YAML output.

Functions

func NewPath

func NewPath(children ...string) *yaml.Path

NewPath returns a new *yaml.Path pointing to the root path, appending any provided children. It is a convenience function that can be used to build simple paths (e.g. '$.kind'). For more complex paths (e.g. with array indices), use NewPathBuilder.

func NewPathBuilder

func NewPathBuilder() *yaml.PathBuilder

NewPathBuilder returns a new yaml.PathBuilder initialized to the root path.

Types

type Decoder

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

Decoder provides iteration over YAML documents in an *ast.File. It wraps a parsed YAML file and yields DocumentDecoder instances for each document, enabling document-by-document processing of both single and multi-document YAML streams.

Create instances with NewDecoder.

func NewDecoder

func NewDecoder(f *ast.File) *Decoder

NewDecoder creates a new Decoder for the given *ast.File.

func (*Decoder) Documents

func (d *Decoder) Documents() iter.Seq2[int, *DocumentDecoder]

Documents returns an iterator over all documents in the YAML file. Each iteration yields the document index and a DocumentDecoder for that document.

func (*Decoder) Len

func (d *Decoder) Len() int

Len returns the number of YAML documents in the file.

type DocumentDecoder

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

DocumentDecoder decodes and validates a single *ast.DocumentNode. It provides several methods for working with YAML documents:

Use DocumentDecoder.Unmarshal for types implementing SchemaValidator or Validator to get automatic validation. Use DocumentDecoder.Decode when you only need decoding without validation hooks.

All decoding methods convert YAML errors to Error with source annotations.

Create instances with NewDocumentDecoder.

func NewDocumentDecoder

func NewDocumentDecoder(doc *ast.DocumentNode) *DocumentDecoder

NewDocumentDecoder creates a new DocumentDecoder for the given *ast.DocumentNode.

func (*DocumentDecoder) Decode

func (dd *DocumentDecoder) Decode(v any) error

Decode decodes the document into v. This is a convenience wrapper around DocumentDecoder.DecodeContext with context.Background.

YAML decoding errors are converted to Error with source annotations.

func (*DocumentDecoder) DecodeContext

func (dd *DocumentDecoder) DecodeContext(ctx context.Context, v any) error

DecodeContext decodes the document into v with context.Context. YAML decoding errors are converted to Error with source annotations.

func (*DocumentDecoder) GetValue

func (dd *DocumentDecoder) GetValue(path *yaml.Path) (string, bool)

GetValue returns the string representation of the value at the given path, or an empty string and false if the path is nil, the document body is a directive, or no value exists at the path.

func (*DocumentDecoder) Unmarshal

func (dd *DocumentDecoder) Unmarshal(v any) error

Unmarshal validates and decodes the document into v. This is a convenience wrapper around DocumentDecoder.UnmarshalContext with context.Background.

If v implements SchemaValidator, ValidateSchema is called before decoding. If v implements Validator, Validate is called after successful decoding.

func (*DocumentDecoder) UnmarshalContext

func (dd *DocumentDecoder) UnmarshalContext(ctx context.Context, v any) error

UnmarshalContext validates and decodes the document into v with context.Context. If v implements SchemaValidator, ValidateSchema is called before decoding. If v implements Validator, Validate is called after successful decoding.

func (*DocumentDecoder) ValidateSchema

func (dd *DocumentDecoder) ValidateSchema(sv SchemaValidator) error

ValidateSchema decodes the document to [any] and validates it using sv. This is a convenience wrapper around DocumentDecoder.ValidateSchemaContext with context.Background.

func (*DocumentDecoder) ValidateSchemaContext

func (dd *DocumentDecoder) ValidateSchemaContext(ctx context.Context, sv SchemaValidator) error

ValidateSchemaContext decodes the document to [any] and validates it using sv with context.Context. Returns decoding errors or errors from [SchemaValidator.ValidateSchema].

type Encoder

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

Encoder wraps yaml.Encoder for convenience. Create instances with NewEncoder.

func NewEncoder

func NewEncoder(w io.Writer, opts ...yaml.EncodeOption) *Encoder

NewEncoder creates a new Encoder by wrapping yaml.NewEncoder. Any provided [yaml.EncodeOption]s are passed to the underlying yaml.Encoder.

func (*Encoder) Close

func (e *Encoder) Close() error

Close calls yaml.Encoder.Close.

func (*Encoder) Encode

func (e *Encoder) Encode(v any) error

Encode calls yaml.Encoder.Encode.

type Error

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

Error represents a YAML error with optional source annotation. To enable annotated error output that shows the relevant YAML location, provide:

Create instances with NewError.

func NewError

func NewError(err error, opts ...ErrorOption) *Error

NewError creates a new Error with the given underlying error and options. Default SourceLines is 4.

func (Error) Error

func (e Error) Error() string

Error returns the error message with source annotation if available.

func (*Error) Path

func (e *Error) Path() string

Path returns the *yaml.Path where the error occurred as a string.

func (*Error) SetOption

func (e *Error) SetOption(opts ...ErrorOption)

SetOption applies the provided [ErrorOption]s to the Error.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error, enabling errors.Is and errors.As.

type ErrorOption

type ErrorOption func(e *Error)

ErrorOption configures an Error.

func WithErrorToken

func WithErrorToken(tk *token.Token) ErrorOption

WithErrorToken sets the token where the error occurred.

func WithPath

func WithPath(path *yaml.Path) ErrorOption

WithPath sets the YAML path where the error occurred.

func WithPrinter

func WithPrinter(p StyledSlicePrinter) ErrorOption

WithPrinter sets the printer used for formatting the error source.

func WithSource

func WithSource(src FileGetter) ErrorOption

WithSource sets the FileGetter for resolving the error path. See *Source for an implementation.

func WithSourceLines

func WithSourceLines(lines int) ErrorOption

WithSourceLines sets the number of context lines to show around the error.

type FileGetter

type FileGetter interface {
	File() (*ast.File, error)
}

FileGetter gets an *ast.File. See *Source for an implementation.

type Finder

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

Finder searches for strings within YAML tokens. Create instances with NewFinder, then call Finder.Load to provide the source data. The Finder preprocesses the source when loaded, allowing efficient repeated searches with different search strings.

func NewFinder

func NewFinder(opts ...FinderOption) *Finder

NewFinder creates a new Finder with the given options. Call Finder.Load to provide a LineIterator before searching. By default, no normalization is applied. Use WithNormalizer to enable case-insensitive or diacritic-insensitive matching.

func (*Finder) Find

func (f *Finder) Find(search string) []position.Range

Find finds all occurrences of the search string in the preprocessed source. It returns a slice of position.Range indicating the start and end positions of each match. Positions are 0-indexed. The slice is provided in the order the matches appear in the source. Returns nil if the search string is empty or the finder has no source data.

func (*Finder) Load

func (f *Finder) Load(lines LineIterator)

Load preprocesses the given LineIterator, building the internal source string and position map for searching. This method must be called before using Finder.Find.

type FinderOption

type FinderOption func(*Finder)

FinderOption configures a Finder.

func WithNormalizer

func WithNormalizer(normalizer Normalizer) FinderOption

WithNormalizer sets a Normalizer applied to both the search string and source text before matching. See StandardNormalizer for an example.

type FullDiff

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

FullDiff represents a complete diff between two [SourceGetter]s. Create instances with NewFullDiff.

func NewFullDiff

func NewFullDiff(a, b SourceGetter) *FullDiff

NewFullDiff creates a new FullDiff.

func (*FullDiff) Source

func (d *FullDiff) Source() *Source

Source returns a *Source representing the diff between the two [SourceGetter]s. The returned Source contains merged tokens from both revisions: unchanged lines use tokens from b, while changed lines include deleted tokens from a followed by inserted tokens from b. Source contains flags for deleted/inserted lines.

type GutterContext

type GutterContext struct {
	Styles     StyleGetter
	Index      int
	Number     int
	TotalLines int
	Flag       line.Flag
	Soft       bool
}

GutterContext provides context about the current line for gutter rendering. It is passed to GutterFunc to determine the appropriate gutter content.

type GutterFunc

type GutterFunc func(GutterContext) string

GutterFunc returns the gutter content for a line based on GutterContext. The returned string is rendered as the leftmost content before the line content.

var NoGutter GutterFunc = func(GutterContext) string { return "" }

NoGutter is a GutterFunc that returns an empty string for all lines.

func DefaultGutter

func DefaultGutter() GutterFunc

DefaultGutter creates a GutterFunc that renders both line numbers and diff markers. This is the default gutter used by NewPrinter.

func DiffGutter

func DiffGutter() GutterFunc

DiffGutter creates a GutterFunc that renders diff-style markers only (" ", "+", "-"). No line numbers are rendered. Uses style.GenericInserted and style.GenericDeleted for styling.

func LineNumberGutter

func LineNumberGutter() GutterFunc

LineNumberGutter creates a GutterFunc that renders styled line numbers only. For soft-wrapped continuation lines, renders " - " as a continuation marker. No diff markers are rendered. Uses style.Comment foreground for styling.

type LineIterator

type LineIterator interface {
	Lines() iter.Seq2[position.Position, line.Line]
	Runes() iter.Seq2[position.Position, rune]
	Len() int
	IsEmpty() bool
}

LineIterator provides line-by-line access to YAML tokens. See Source for an implementation.

type NamedLineIterator

type NamedLineIterator interface {
	LineIterator
	Name() string
}

NamedLineIterator extends LineIterator with a Name. See Source for an implementation.

type Normalizer

type Normalizer interface {
	Normalize(in string) string
}

Normalizer transforms strings for comparison (e.g., removing diacritics). See StandardNormalizer for an implementation.

type Printer

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

Printer renders YAML tokens with syntax highlighting using lipgloss.Style. It supports custom styles, gutters, and styled range overlays for highlighting specific positions such as errors. Create instances with NewPrinter.

func NewPrinter

func NewPrinter(opts ...PrinterOption) *Printer

NewPrinter creates a new Printer. By default it uses theme.Charm and DefaultGutter.

func (*Printer) AddStyleToRange

func (p *Printer) AddStyleToRange(s *lipgloss.Style, ranges ...position.Range)

AddStyleToRange adds a style to apply to the character range [r.Start, r.End). The range is half-open: Start is inclusive, End is exclusive. Line and column are 0-indexed. Overlapping range colors are blended; transforms are composed (overlay wraps base).

func (*Printer) ClearStyles

func (p *Printer) ClearStyles()

ClearStyles removes all previously added styles.

func (*Printer) Print

func (p *Printer) Print(lines LineIterator) string

Print prints any LineIterator.

func (*Printer) PrintSlice

func (p *Printer) PrintSlice(lines LineIterator, minLine, maxLine int) string

PrintSlice prints a slice of lines from any LineIterator. It prints in the range [minLine, maxLine] as defined by the [LineIterator.Lines] index. If minLine < 0, includes from the beginning; if maxLine < 0, includes to the end.

func (*Printer) SetAnnotationsEnabled

func (p *Printer) SetAnnotationsEnabled(enabled bool)

SetAnnotationsEnabled sets whether annotations are rendered. Defaults to true.

func (*Printer) SetWidth

func (p *Printer) SetWidth(width int)

SetWidth sets the width for word wrapping. A width of 0 disables wrapping.

func (*Printer) SetWordWrap

func (p *Printer) SetWordWrap(enabled bool)

SetWordWrap sets whether word wrapping is enabled. Defaults to true. Word wrapping requires a width to be set via Printer.SetWidth.

func (*Printer) Style

func (p *Printer) Style(s style.Style) *lipgloss.Style

Style retrieves the underlying lipgloss.Style for the given style.Style.

type PrinterOption

type PrinterOption func(*Printer)

PrinterOption configures a Printer.

func WithGutter

func WithGutter(fn GutterFunc) PrinterOption

WithGutter sets the GutterFunc for rendering. Pass NoGutter to disable gutters entirely, or DiffGutter for diff markers only. By default, DefaultGutter is used which renders line numbers and diff markers.

func WithStyle

func WithStyle(s lipgloss.Style) PrinterOption

WithStyle configures the printer with the given container style.

func WithStyles

func WithStyles(s StyleGetter) PrinterOption

WithStyles configures the printer with the given StyleGetter.

type Revision

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

Revision represents NamedLineIterator at one or more revisions. It may form a linked or doubly-linked list to track changes across revisions. It is not required to have multiple revisions; a single revision is valid. Create instances with NewRevision.

func NewRevision

func NewRevision(li NamedLineIterator) *Revision

NewRevision creates a new Revision. The provided values are set at the head. You may use Revision.Append or Revision.Prepend to add more revisions. A builder pattern is supported for values that are known at compile time.

func (*Revision) Append

func (t *Revision) Append(li NamedLineIterator) *Revision

Append adds a new revision after the NamedLineIterator at the head. Returns the newly added revision.

func (*Revision) At

func (t *Revision) At(index int) *Revision

At returns the revision at the given zero-based index. If index exceeds the available revisions, it stops at the last one. This is equivalent to Origin().Seek(index).

func (*Revision) AtOrigin

func (t *Revision) AtOrigin() bool

AtOrigin returns true if this is the original revision in the sequence.

func (*Revision) AtTip

func (t *Revision) AtTip() bool

AtTip returns true if this is the latest revision in the sequence.

func (*Revision) Index

func (t *Revision) Index() int

Index returns the zero-based index of the Revision at the head.

func (*Revision) Len

func (t *Revision) Len() int

Len returns the total number of revisions in the sequence.

func (*Revision) Name

func (t *Revision) Name() string

Name returns the name of the NamedLineIterator at the head.

func (*Revision) Names

func (t *Revision) Names() []string

Names returns the names of all revisions in order from origin to latest.

func (*Revision) Origin

func (t *Revision) Origin() *Revision

Origin goes to the original revision in the sequence.

func (*Revision) Prepend

func (t *Revision) Prepend(li NamedLineIterator) *Revision

Prepend adds a new revision before the NamedLineIterator at the head. Returns the newly added revision.

func (*Revision) Seek

func (t *Revision) Seek(n int) *Revision

Seek moves n revisions forward (n > 0) or backward (n < 0) in the sequence. If n exceeds the available revisions, it stops at the end.

func (*Revision) Source

func (t *Revision) Source() NamedLineIterator

Source returns the NamedLineIterator at the head.

func (*Revision) Tip

func (t *Revision) Tip() *Revision

Tip goes to the latest revision in the sequence.

type SchemaValidator

type SchemaValidator interface {
	ValidateSchema(data any) error
}

SchemaValidator is implemented by types that validate arbitrary data against a schema. If a type implements this interface, DocumentDecoder.Unmarshal will automatically decode the document to [any] and call ValidateSchema before decoding to the typed struct. See [validator.Validator] for an implementation.

type Source

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

Source represents a collection of token.Tokens organized into line.Lines with associated metadata. Create instances with NewSourceFromString, NewSourceFromToken, or NewSourceFromTokens.

func NewSourceFromString

func NewSourceFromString(src string, opts ...SourceOption) *Source

NewSourceFromString creates a new Source from a YAML string using lexer.Tokenize.

func NewSourceFromToken

func NewSourceFromToken(tk *token.Token, opts ...SourceOption) *Source

NewSourceFromToken creates a new Source from a seed *token.Token. It collects all token.Tokens by walking the token chain from start to end.

func NewSourceFromTokens

func NewSourceFromTokens(tks token.Tokens, opts ...SourceOption) *Source

NewSourceFromTokens creates a new Source from token.Tokens. See line.NewLines for details on token splitting behavior.

func (*Source) Annotate

func (s *Source) Annotate(idx int, ann line.Annotation)

Annotate sets a line.Annotation on the line.Line at the given index. Panics if idx is out of range.

func (*Source) Content

func (s *Source) Content() string

Content returns the combined content of all [Line]s as a string. [Line]s are joined with newlines.

func (*Source) File

func (s *Source) File() (*ast.File, error)

File returns an *ast.File for the Source tokens. The file is lazily parsed on first call using parser.Parse with options provided via WithParserOptions. Subsequent calls return the cached result. Any YAML parsing errors are converted to Error with source annotations.

func (*Source) Flag

func (s *Source) Flag(idx int, flag line.Flag)

Flag sets a line.Flag on the line.Line at the given index. Panics if idx is out of range.

func (*Source) IsEmpty

func (s *Source) IsEmpty() bool

IsEmpty returns true if there are no lines.

func (*Source) Len

func (s *Source) Len() int

Len returns the number of lines.

func (*Source) Line

func (s *Source) Line(idx int) line.Line

Line returns the line.Line at the given index. Panics if idx is out of range.

func (*Source) Lines

func (s *Source) Lines() iter.Seq2[position.Position, line.Line]

Lines returns an iterator over all lines. Each iteration yields a position.Position and the line.Line at that position.

func (*Source) Name

func (s *Source) Name() string

Name returns the name of the Source.

func (*Source) Runes

func (s *Source) Runes() iter.Seq2[position.Position, rune]

Runes returns an iterator over all runes. Each iteration yields a position.Position and the rune at that position.

func (*Source) String

func (s *Source) String() string

String reconstructs all [Line]s as a string, including any annotations. This should generally only be used for debugging.

func (*Source) TokenPositionRanges

func (s *Source) TokenPositionRanges(positions ...position.Position) []position.Range

TokenPositionRanges returns all token position ranges that are part of the same joined token group as the tokens at the given [position.Position]s. For non-joined lines, returns the range of the token at each given column. Duplicate ranges are removed. Returns nil if no tokens exist at any of the given positions.

func (*Source) TokenPositionRangesFromToken

func (s *Source) TokenPositionRangesFromToken(tk *token.Token) []position.Range

TokenPositionRangesFromToken returns all position ranges for a given token. Returns nil if the token is nil or not found in the Source.

func (*Source) Tokens

func (s *Source) Tokens() token.Tokens

Tokens reconstructs the full token.Tokens stream from all [Line]s. See line.Lines.Tokens for details on token recombination behavior.

func (*Source) Validate

func (s *Source) Validate() error

Validate checks the integrity of the Source. See line.Lines.Validate for details on validation checks.

func (*Source) WrapError

func (s *Source) WrapError(err error) error

WrapError wraps an error with additional context for Error types. It applies any [ErrorOption]s provided and sets the source to this Source. If the error isn't an Error, it returns the original error unmodified.

type SourceGetter

type SourceGetter interface {
	Source() NamedLineIterator
}

SourceGetter gets a NamedLineIterator. See Revision for an implementation.

type SourceOption

type SourceOption func(*Source)

SourceOption configures Source creation.

func WithErrorOptions

func WithErrorOptions(opts ...ErrorOption) SourceOption

WithErrorOptions sets the [ErrorOption]s used when wrapping errors with Source.WrapError.

func WithName

func WithName(name string) SourceOption

WithName sets the name for the Source.

func WithParserOptions

func WithParserOptions(opts ...parser.Option) SourceOption

WithParserOptions sets the parser options used when parsing the Source into an *ast.File. These options are passed to parser.Parse in addition to parser.ParseComments, which is always included.

type StandardNormalizer

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

StandardNormalizer removes diacritics and lowercases strings for case-insensitive matching. For example, "Ö" becomes "o". Note that unicode.Mn is the unicode key for nonspacing marks. Create instances with NewStandardNormalizer.

func NewStandardNormalizer

func NewStandardNormalizer() *StandardNormalizer

NewStandardNormalizer creates a new StandardNormalizer.

func (*StandardNormalizer) Normalize

func (n *StandardNormalizer) Normalize(in string) string

Normalize implements Normalizer.

type StyleGetter

type StyleGetter interface {
	Style(s style.Style) *lipgloss.Style
}

StyleGetter retrieves styles by category. See style.Styles for an implementation.

type StyledPrinter

type StyledPrinter interface {
	TokenStyler
	Print(lines LineIterator) string
}

StyledPrinter extends TokenStyler with printing capabilities. See Printer for an implementation.

type StyledSlicePrinter

type StyledSlicePrinter interface {
	TokenStyler
	PrintSlice(lines LineIterator, minLine, maxLine int) string
}

StyledSlicePrinter extends TokenStyler with slice printing capabilities. See Printer for an implementation.

type SummaryDiff

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

SummaryDiff represents a summarized diff between two [SourceGetter]s. Create instances with NewSummaryDiff.

func NewSummaryDiff

func NewSummaryDiff(a, b SourceGetter, context int) *SummaryDiff

NewSummaryDiff creates a new SummaryDiff with the specified context lines. A context of 0 shows only the changed lines. Negative values are treated as 0.

func (*SummaryDiff) Source

func (d *SummaryDiff) Source() *Source

Source returns a *Source representing a summarized diff between two revisions. It shows only changed lines with the specified number of context lines around each change. Hunk headers are stored in [Line.Annotation.Content] for each hunk's first line.

type TokenStyler

type TokenStyler interface {
	StyleGetter
	AddStyleToRange(s *lipgloss.Style, ranges ...position.Range)
	ClearStyles()
}

TokenStyler manages style ranges for YAML tokens. See Printer for an implementation.

type Validator

type Validator interface {
	Validate() error
}

Validator is implemented by types that validate themselves. If a type implements this interface, DocumentDecoder.Unmarshal will automatically call Validate after successful decoding.

Directories

Path Synopsis
bubbles
yamlviewport
Package yamlviewport provides a Bubble Tea component for viewing and navigating YAML data structures.
Package yamlviewport provides a Bubble Tea component for viewing and navigating YAML data structures.
cmd
nyaml command
Package main provides the nyaml CLI for viewing and validating YAML files.
Package main provides the nyaml CLI for viewing and validating YAML files.
examples
diffs command
finder command
printer command
schemas/cafe
Package cafe is an example.
Package cafe is an example.
schemas/cafe/schemagen command
Package main generates a JSON schema for the cafe example.
Package main generates a JSON schema for the cafe example.
schemas/cafe/spec
Package spec defines the cafe specification schema.
Package spec defines the cafe specification schema.
Package fangs provides utilities for integrating niceyaml with github.com/charmbracelet/fang, a Cobra companion library.
Package fangs provides utilities for integrating niceyaml with github.com/charmbracelet/fang, a Cobra companion library.
internal
colors
Package colors provides utilities for color and style manipulation.
Package colors provides utilities for color and style manipulation.
styletree
Package styletree provides an augmented AVL tree for efficient interval stabbing queries.
Package styletree provides an augmented AVL tree for efficient interval stabbing queries.
Package lexers provides helpers for tokenizing YAML strings.
Package lexers provides helpers for tokenizing YAML strings.
Package line provides abstractions for line-by-line go-yaml Token processing.
Package line provides abstractions for line-by-line go-yaml Token processing.
Package position defines line and column positions and ranges within a document.
Package position defines line and column positions and ranges within a document.
Package schema provides utilities for working with JSON schemas.
Package schema provides utilities for working with JSON schemas.
generator
Package generator provides JSON Schema generation from Go types.
Package generator provides JSON Schema generation from Go types.
validator
Package validator provides JSON Schema validation for data.
Package validator provides JSON Schema validation for data.
Package style provides types and constants for YAML syntax highlighting.
Package style provides types and constants for YAML syntax highlighting.
theme
Package theme provides pre-built style themes for YAML syntax highlighting.
Package theme provides pre-built style themes for YAML syntax highlighting.
Package tokens provides structures and utilities for handling YAML tokens.
Package tokens provides structures and utilities for handling YAML tokens.
Package yamltest provides helpers for testing niceyaml and/or go-yaml.
Package yamltest provides helpers for testing niceyaml and/or go-yaml.

Jump to

Keyboard shortcuts

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