spectral

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package spectral provides a Go implementation of the Spectral rule engine for evaluating declarative OpenAPI linting rules.

Spectral rules use JSONPath expressions to select nodes in YAML/JSON documents, then apply built-in validation functions to each match. This enables teams to write custom rules in YAML without compiling Go.

Usage

Load rules from a ruleset and create an engine:

rs, _ := rulesets.LoadFile("my-rules.yaml")
rules := spectral.ParseRules(rs)
engine := spectral.NewEngine(rules, logger)
diagnostics := engine.Execute(yamlContent)

Built-in Functions

The BuiltinFunctions map provides these validators:

  • truthy, falsy, defined, undefined — boolean presence checks
  • pattern — regex matching
  • casing — naming convention enforcement (camel, snake, kebab, etc.)
  • length — min/max length validation
  • enumeration — allowed value lists
  • schema — JSON Schema validation
  • alphabetical — ordering checks
  • or, xor — logical combinators

JSONPath

EvaluateJSONPath evaluates JSONPath expressions against yaml.Node trees and returns Match results with node references for precise source location tracking.

Package spectral implements a Spectral-compatible YAML rule engine for evaluating declarative linting rules against YAML/JSON documents. It supports JSONPath-based targeting via the "given" field and Spectral's built-in validation functions via the "then" field.

Index

Constants

This section is empty.

Variables

View Source
var BuiltinFunctions = map[string]SpectralFunc{
	"truthy":                     funcTruthy,
	"falsy":                      funcFalsy,
	"defined":                    funcDefined,
	"undefined":                  funcUndefined,
	"pattern":                    funcPattern,
	"casing":                     funcCasing,
	"length":                     funcLength,
	"enumeration":                funcEnumeration,
	"schema":                     funcSchema,
	"alphabetical":               funcAlphabetical,
	"or":                         funcOr,
	"xor":                        funcXor,
	"typedEnum":                  funcTypedEnum,
	"unreferencedReusableObject": funcUnreferencedReusableObject,
}

BuiltinFunctions maps Spectral function names to their implementations.

Functions

func EvaluateJSONPath

func EvaluateJSONPath(root *yaml.Node, expr string) ([]*yaml.Node, error)

EvaluateJSONPath compiles and evaluates a JSONPath expression against a YAML node tree. Returns all matching nodes with their source positions preserved. The parsed path is cached across calls; evaluation itself still runs per call.

func ExpandMessage

func ExpandMessage(template string, values map[string]string) string

ExpandMessage replaces Spectral message template placeholders.

Types

type Engine

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

Engine evaluates Spectral custom rules against YAML/JSON documents. It implements the gossip treesitter.Analyzer interface so it can be registered on the DiagnosticEngine and participate in the standard diagnostic pipeline.

func NewEngine

func NewEngine(rules []Rule, logger *slog.Logger) *Engine

NewEngine creates a Spectral rule engine with the given custom rules.

func (*Engine) Analyzer

func (e *Engine) Analyzer() treesitter.Analyzer

Analyzer returns a gossip Analyzer that runs Spectral custom rules.

func (*Engine) Execute

func (e *Engine) Execute(content []byte) []protocol.Diagnostic

Execute runs all custom rules against the given document content and returns diagnostics with source positions derived from the yaml.Node tree.

func (*Engine) Rules

func (e *Engine) Rules() []Rule

Rules returns a snapshot of the current rule set.

func (*Engine) SetRules

func (e *Engine) SetRules(rules []Rule)

SetRules replaces the engine's rule set. Safe for concurrent use.

type FunctionCall

type FunctionCall struct {
	Field           string                 // optional sub-field to check on matched nodes
	Function        string                 // built-in function name (e.g., "truthy", "pattern")
	FunctionOptions map[string]interface{} // function-specific configuration
}

FunctionCall represents a single validation step within a rule's "then" clause.

type Issue

type Issue struct {
	Node    *yaml.Node
	Message string
}

Issue is a single validation failure produced by a built-in function.

type Match

type Match struct {
	Node  *yaml.Node  // YAML node at the match location (preserves line/column)
	Path  string      // JSONPath expression that produced this match
	Value interface{} // decoded Go value for function evaluation
}

Match represents a JSONPath match result with its source node and decoded value.

type Rule

type Rule struct {
	ID               string
	Description      string
	Message          string // supports {{value}}, {{path}}, {{property}} placeholders
	Severity         ctypes.Severity
	Given            []string       // JSONPath expressions
	Then             []FunctionCall // validation steps
	Formats          []string       // oas2, oas3, oas3_0, oas3_1
	Recommended      bool
	DocumentationURL string
}

Rule is a fully parsed Spectral rule ready for execution.

func ParseRules

func ParseRules(rs *rulesets.RuleSet) []Rule

ParseRules converts resolved RuleDefinitions from a RuleSet into executable Rule values, filtering out override-only entries (those with no given/then). Rules that only override severity for native rules are excluded.

type SpectralFunc

type SpectralFunc func(node *yaml.Node, field string, opts map[string]interface{}) []Issue

SpectralFunc validates a YAML node and returns any issues found. The field parameter narrows the check to a specific child of the node. Options come from the rule's functionOptions.

Jump to

Keyboard shortcuts

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