Skip to content

Latest commit

 

History

History
98 lines (73 loc) · 1.89 KB

README.md

File metadata and controls

98 lines (73 loc) · 1.89 KB

yaml-cel

yaml-cel is a lightweight Go library for evaluating CEL (Common Expression Language) expressions embedded in YAML templates. It allows you to create dynamic configuration templates and evaluate them against runtime data, producing strongly typed Go structs.

Features

  • Define CEL expressions inline in YAML using !cel tag
  • Built-in distinct() function to deduplicate string arrays
  • Evaluate templates into any Go struct using generics

Installation

go get github.com/k8shell-io/yaml-cel/pkg/yamlcel

Running Tests

go test -v ./...

Quick Start

Define a YAML template

user:
  username: !cel "username"
  uid: !cel "uid"
  org:
    name: !cel "org.name"
  roles: !cel "distinct(roles)"
  valid: true

Define your Go struct

type User struct {
    Username string
    UID      int
    Org      struct {
        Name string
    }
    Roles []string
    Valid bool
}

Evaluate the template

tmpl := yamlcel.CELTemplate{}
_ = yaml.Unmarshal([]byte(yamldoc), &tmpl)

resource := map[string]any{
    "username": "john",
    "uid":      1001,
    "org": map[string]any{
        "name": "k8shell",
    },
    "roles": []string{"admin", "user", "admin"},
}

user, err := yamlcel.EvalToStruct[User](&tmpl, resource, nil, "user")
if err != nil {
    log.Fatal(err)
}

fmt.Println(user.Username) // "john"
fmt.Println(user.Roles)    // ["admin", "user"]

API

EvalToStruct[T any]

func EvalToStruct[T any](
  t *CELTemplate,
  resource map[string]any,
  extraFields map[string]string,
  root string,
) (*T, error)
  • resource: runtime input data (map)
  • extraFields: optional additional string variables
  • root: optional root key (use "" for top-level mapping)

License

Apache 2.0

Credits

Built with ❤️ by the k8shell.io team.