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:
- NewSourceFromString: Parse YAML from a string
- NewSourceFromToken: Build from a single token
- NewSourceFromTokens: Build from a token slice
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:
- line.Annotation: Extra content such as error messages or diff headers
- line.Flag: Category markers (line.FlagInserted, line.FlagDeleted, line.FlagAnnotation)
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:
- WithStyle: Set the container style
- WithStyles: Provide custom token styles via StyleGetter
- WithGutter: Set a gutter function for line prefixes
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:
- WithSourceLines: Number of context lines to display
- WithPath: YAML path where the error occurred
- WithSource: Source for resolving the error path
- WithErrorToken: Token associated with the error
- WithPrinter: Customize error source formatting
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 ¶
- Variables
- func NewPath(children ...string) *yaml.Path
- func NewPathBuilder() *yaml.PathBuilder
- type Decoder
- type DocumentDecoder
- func (dd *DocumentDecoder) Decode(v any) error
- func (dd *DocumentDecoder) DecodeContext(ctx context.Context, v any) error
- func (dd *DocumentDecoder) GetValue(path *yaml.Path) (string, bool)
- func (dd *DocumentDecoder) Unmarshal(v any) error
- func (dd *DocumentDecoder) UnmarshalContext(ctx context.Context, v any) error
- func (dd *DocumentDecoder) ValidateSchema(sv SchemaValidator) error
- func (dd *DocumentDecoder) ValidateSchemaContext(ctx context.Context, sv SchemaValidator) error
- type Encoder
- type Error
- type ErrorOption
- type FileGetter
- type Finder
- type FinderOption
- type FullDiff
- type GutterContext
- type GutterFunc
- type LineIterator
- type NamedLineIterator
- type Normalizer
- type Printer
- func (p *Printer) AddStyleToRange(s *lipgloss.Style, ranges ...position.Range)
- func (p *Printer) ClearStyles()
- func (p *Printer) Print(lines LineIterator) string
- func (p *Printer) PrintSlice(lines LineIterator, minLine, maxLine int) string
- func (p *Printer) SetAnnotationsEnabled(enabled bool)
- func (p *Printer) SetWidth(width int)
- func (p *Printer) SetWordWrap(enabled bool)
- func (p *Printer) Style(s style.Style) *lipgloss.Style
- type PrinterOption
- type Revision
- func (t *Revision) Append(li NamedLineIterator) *Revision
- func (t *Revision) At(index int) *Revision
- func (t *Revision) AtOrigin() bool
- func (t *Revision) AtTip() bool
- func (t *Revision) Index() int
- func (t *Revision) Len() int
- func (t *Revision) Name() string
- func (t *Revision) Names() []string
- func (t *Revision) Origin() *Revision
- func (t *Revision) Prepend(li NamedLineIterator) *Revision
- func (t *Revision) Seek(n int) *Revision
- func (t *Revision) Source() NamedLineIterator
- func (t *Revision) Tip() *Revision
- type SchemaValidator
- type Source
- func (s *Source) Annotate(idx int, ann line.Annotation)
- func (s *Source) Content() string
- func (s *Source) File() (*ast.File, error)
- func (s *Source) Flag(idx int, flag line.Flag)
- func (s *Source) IsEmpty() bool
- func (s *Source) Len() int
- func (s *Source) Line(idx int) line.Line
- func (s *Source) Lines() iter.Seq2[position.Position, line.Line]
- func (s *Source) Name() string
- func (s *Source) Runes() iter.Seq2[position.Position, rune]
- func (s *Source) String() string
- func (s *Source) TokenPositionRanges(positions ...position.Position) []position.Range
- func (s *Source) TokenPositionRangesFromToken(tk *token.Token) []position.Range
- func (s *Source) Tokens() token.Tokens
- func (s *Source) Validate() error
- func (s *Source) WrapError(err error) error
- type SourceGetter
- type SourceOption
- type StandardNormalizer
- type StyleGetter
- type StyledPrinter
- type StyledSlicePrinter
- type SummaryDiff
- type TokenStyler
- type Validator
Constants ¶
This section is empty.
Variables ¶
var ErrNoSource = errors.New("no source provided")
ErrNoSource indicates no source was provided to resolve an error path.
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 ¶
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 (*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.
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:
- DocumentDecoder.GetValue: Extract a value at a path as a string.
- DocumentDecoder.Decode: Decode to a typed struct.
- DocumentDecoder.ValidateSchema: Validate against a SchemaValidator.
- DocumentDecoder.Unmarshal: Full validation and decoding pipeline.
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.
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:
- WithErrorToken directly specifies the error location, OR
- WithPath combined with WithSource to resolve the path
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) Path ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
SetAnnotationsEnabled sets whether annotations are rendered. Defaults to true.
func (*Printer) SetWidth ¶
SetWidth sets the width for word wrapping. A width of 0 disables wrapping.
func (*Printer) SetWordWrap ¶
SetWordWrap sets whether word wrapping is enabled. Defaults to true. Word wrapping requires a width to be set via Printer.SetWidth.
func (*Printer) 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 ¶
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) Name ¶
Name returns the name of the NamedLineIterator at the head.
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 ¶
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.
type SchemaValidator ¶
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 ¶
Content returns the combined content of all [Line]s as a string. [Line]s are joined with newlines.
func (*Source) File ¶
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 ¶
Flag sets a line.Flag on the line.Line at the given index. Panics if idx is out of range.
func (*Source) Lines ¶
Lines returns an iterator over all lines. Each iteration yields a position.Position and the line.Line at that position.
func (*Source) Runes ¶
Runes returns an iterator over all runes. Each iteration yields a position.Position and the rune at that position.
func (*Source) String ¶
String reconstructs all [Line]s as a string, including any annotations. This should generally only be used for debugging.
func (*Source) TokenPositionRanges ¶
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 ¶
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 ¶
Tokens reconstructs the full token.Tokens stream from all [Line]s. See line.Lines.Tokens for details on token recombination behavior.
func (*Source) Validate ¶
Validate checks the integrity of the Source. See line.Lines.Validate for details on validation checks.
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 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 ¶
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.
Source Files
¶
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. |


