yamlexpr

package module
v0.0.0-...-0ccdf5d Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2025 License: MIT Imports: 11 Imported by: 0

README

yamlexpr

Go Reference Go Report Card PkgGoDev Test Coverage

YAML composition, interpolation, and conditional evaluation for Go.

Example YAML

matrix:                                     # Document expansion on root level
  environment: [production, development]    # Iteration dimensions.

environment: ${environment}                 # Interpolation from matrix vars.
port: 8080

services:
  - for: service in available_services      # Loops
    if: "${service.enabled}"                # Conditions
    name: "${service.name}"                 # Interpolation
    replicas: "${service.replicas}"

database:
  include: "database-${environment}.yaml"   # Composition
# database-development.yaml
host: localhost
port: 5432

The main goals of yamlexpr is to be a lightweight data traversal engine, upon which new functionality can be built. It evaluates data and produces a deterministic plain yaml output. That output can be used further to provide execution pipelines, documentation and other uses.

Features

  • Variable Interpolation: Use ${variable.path} syntax in string values
  • Conditionals: Include/exclude blocks with if: directive
  • For Loops: Iterate and expand templates with for: directive
  • Matrix Expansion: Generate combinations with matrix: directive (with exclude: and include:)
  • Composition: Include external YAML files with include: directive
  • Document Expansion: Root-level directives create multiple output documents
Getting Started
Feature Documentation
  • Interpolation - Variable substitution with ${variable} syntax
  • Conditionals - Include/exclude with if: directive
  • For Loops - Iterate and expand with for: directive
  • Matrix - Generate combinations with matrix: directive
  • Include - Compose files with include: directive
  • Document Expansion - Root-level directives creating multiple documents
Reference

Installation

go get github.com/titpetric/yamlexpr

Quick Start

Load and Evaluate YAML from a File
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/titpetric/yamlexpr"
)

func main() {
	// Create an Expr evaluator with the current directory as the filesystem
	expr := yamlexpr.New(os.DirFS("."))

	// Load and evaluate a YAML file
	// Returns a slice of Documents (may be multiple if using root-level for: or matrix:)
	docs, err := expr.Load("config.yaml")
	if err != nil {
		log.Fatal(err)
	}

	// Process each resulting document
	for i, doc := range docs {
		fmt.Printf("Document %d: %+v\n", i, doc)
	}
}
Parse and Evaluate YAML Data
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/titpetric/yamlexpr"
)

func main() {
	// Create an Expr evaluator
	expr := yamlexpr.New(os.DirFS("."))

	// Prepare your YAML data as Document (map[string]any)
	data := yamlexpr.Document{
		"name": "production",
		"env": map[string]any{
			"debug": false,
			"port":  8080,
		},
		"services": []any{
			map[string]any{"name": "api", "active": true},
			map[string]any{"name": "worker", "active": false},
		},
	}

	// Parse with variable interpolation, conditionals, and composition
	docs, err := expr.Parse(data)
	if err != nil {
		log.Fatal(err)
	}

	// Process each resulting document
	for i, doc := range docs {
		fmt.Printf("Document %d: %+v\n", i, doc)
	}
}

API

Expr.Load(filename string) (map[string]any, error)

Loads a YAML file and evaluates all expressions in it. Files are resolved relative to the filesystem provided to New().

expr := yamlexpr.New(os.DirFS("."))
config, err := expr.Load("config.yaml")
Expr.Process(doc any) (any, error)

Processes a YAML document (parsed as map[string]any or []any) with expression evaluation.

result, err := expr.Process(yamlData)
Expr.ProcessWithStack(doc any, st *stack.Stack) (any, error)

Processes a YAML document with a custom variable stack for access to additional variables beyond the document's root keys.

result, err := expr.ProcessWithStack(yamlData, customStack)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultConfig aliases model.DefaultConfig.
	DefaultConfig = model.DefaultConfig
	// NewContext aliases model.NewContext.
	NewContext = model.NewContext
	// WithFS aliases model.WithFS.
	WithFS = model.WithFS
	// WithSyntax aliases model.WithFS.
	WithSyntax = model.WithSyntax
	// ParseDocument aliases frontmatter.ParseDocument.
	ParseDocument = frontmatter.ParseDocument
)

Model function/value aliases.

Functions

func MapMatchesSpec

func MapMatchesSpec(m map[string]any, spec map[string]any) bool

MapMatchesSpec checks if a map contains all key:value pairs from a specification map. Used for matrix include/exclude matching and other spec-based filtering. Returns true only if every key in spec exists in the map with an equal value.

func ValuesEqual

func ValuesEqual(a, b any) bool

ValuesEqual checks if two values are equal, handling primitives and type coercion. Used for comparing values in matrix specs where YAML may parse numbers as float64 or int.

Types

type Config

type Config = model.Config

Config aliases model.Config.

type ConfigOption

type ConfigOption = model.ConfigOption

ConfigOption aliases model.ConfigOption.

type Context

type Context = model.Context

Context aliases model.Context.

type ContextOptions

type ContextOptions = model.ContextOptions

ContextOptions aliases model.ContextOptions.

type DirectiveHandler

type DirectiveHandler = model.DirectiveHandler

DirectiveHandler aliases model.DirectiveHandler.

type Document

type Document map[string]any

Document represents a single YAML document after processing.

type DocumentContent

type DocumentContent = frontmatter.DocumentContent

DocumentContent aliases frontmatter.DocumentContent.

type Expr

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

Expr evaluates YAML documents with variable interpolation, conditionals, and composition.

func New

func New(rootFS fs.FS, opts ...ConfigOption) *Expr

New creates a new Expr evaluator with the given filesystem for includes. Optional ConfigOption arguments can be passed to customize directive syntax.

func (*Expr) Load

func (e *Expr) Load(filename string) ([]Document, error)

Load loads a YAML file and processes it with expression evaluation. Returns a slice of Documents. For root-level for: or similar directives, may return multiple documents. For regular documents, returns a single-item slice. The filename is resolved relative to the filesystem provided to New().

func (*Expr) Parse

func (e *Expr) Parse(doc Document) ([]Document, error)

Parse processes a Document (map[string]any) with expression evaluation. Returns a slice of Documents. For root-level for: directives, may return multiple documents. For regular documents, returns a single-item slice.

type ForLoopExpr

type ForLoopExpr struct {
	// Variables is a list of variable names to bind. Can include "_" to omit.
	Variables []string

	// Source is the name of the variable to iterate over.
	Source string
}

ForLoopExpr represents a parsed for loop expression.

type MatrixDirective

type MatrixDirective struct {
	// Dimensions contains array values that form the cartesian product.
	Dimensions map[string][]any
	// Variables contains non-array values to add to each combination.
	Variables map[string]any
	// Include specifies additional custom combinations to add.
	Include []map[string]any
	// Exclude specifies combinations to filter out from the product.
	Exclude []map[string]any
}

MatrixDirective represents the parsed matrix configuration Fields are exported for testing purposes.

type Syntax

type Syntax = model.Syntax

Syntax aliases model.SyntaxHandler.

Directories

Path Synopsis
cmd
yamlexpr command

Jump to

Keyboard shortcuts

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