config

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package config loads, checks and describes the mockzilla-codegen config file.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrRead       = errors.New("read config")
	ErrDecode     = errors.New("decode config")
	ErrUnknownKey = errors.New("unknown config key")
	ErrInvalid    = errors.New("invalid config")
	ErrByteSize   = errors.New("invalid byte size")
	ErrDuration   = errors.New("invalid duration")
)

Functions

func Schema

func Schema() ([]byte, error)

Schema returns the JSON schema (draft 2020-12) of the config file, built from the config types. Keys are sorted, so the output is the same on every run.

Types

type ByteSize

type ByteSize int64

ByteSize is a number of bytes, written as a plain integer or with a unit: 512KB, 32MB, 1GB. Units are powers of 1024.

func (*ByteSize) UnmarshalText

func (s *ByteSize) UnmarshalText(text []byte) error

UnmarshalText parses a size such as 1024, 512KB or 32MB.

type Client

type Client struct {
	Name         string    `yaml:"name" desc:"Name of the client type. Defaults to Client."`
	Timeout      *Duration `` /* 143-byte string literal not displayed */
	WithResponse bool      `yaml:"with-response" desc:"Also generate methods that return the raw HTTP response."`
	Streaming    bool      `` /* 130-byte string literal not displayed */
}

Client controls client generation.

type Config

type Config struct {
	Spec        Spec                `yaml:"spec" desc:"Input spec and how to prepare it before generation."`
	Package     string              `yaml:"package" desc:"Go package of the default output file. Defaults to its folder name."`
	Header      string              `` /* 160-byte string literal not displayed */
	Naming      Naming              `yaml:"naming" desc:"How Go names are built."`
	Imports     []Import            `` /* 131-byte string literal not displayed */
	Models      *Models             `yaml:"models" desc:"Models generation. Always on."`
	Server      *Server             `yaml:"server" desc:"Server generation. Present means generate."`
	Client      *Client             `yaml:"client" desc:"Client generation. Present means generate."`
	MCP         *MCP                `yaml:"mcp" desc:"MCP server generation. Present means generate. Needs client."`
	Templates   map[string]Template `yaml:"templates" desc:"Template overrides, keyed by block name: the text, or the file that holds it."`
	ExtraFiles  map[string]Template `` /* 146-byte string literal not displayed */
	UserContext map[string]any      `yaml:"user-context" desc:"Free-form values passed to templates."`
	Output      Output              `yaml:"output" desc:"Where generated files go."`
	// contains filtered or unexported fields
}

Config is the whole mockzilla-codegen config file.

func Load

func Load(path string, edits ...func(*Config)) (*Config, error)

Load reads and parses the config file at path. Relative paths in it resolve against the directory of the file.

func Parse

func Parse(data []byte, dir string, edits ...func(*Config)) (*Config, error)

Parse decodes a config, rejects unknown keys, runs the edits, fills in defaults and validates the result. Relative paths in it resolve against dir.

func (*Config) Resolve

func (c *Config) Resolve(p string) string

Resolve returns p joined with the directory of the config file. Absolute paths and URLs come back unchanged.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the config and returns a *ValidationError listing every problem, or nil. A spec path is not required here: it can come from the command line or from memory.

type Duration

type Duration time.Duration

Duration is a time.Duration written as text, such as 30s or 1m30s.

func (*Duration) UnmarshalText

func (d *Duration) UnmarshalText(text []byte) error

UnmarshalText parses a duration such as 30s or 1m30s. Negative durations are rejected.

type Filter

type Filter struct {
	Include FilterSet `yaml:"include" desc:"Keep only what matches."`
	Exclude FilterSet `yaml:"exclude" desc:"Drop what matches. Wins over include."`
}

Filter selects the parts of the spec to keep. Exclude wins over include.

type FilterSet

type FilterSet struct {
	Paths            []string            `yaml:"paths" desc:"Operation paths."`
	Tags             []string            `yaml:"tags" desc:"Operation tags."`
	OperationIDs     []string            `yaml:"operation-ids" desc:"Operation IDs."`
	Webhooks         []string            `yaml:"webhooks" desc:"Webhook names."`
	Extensions       []string            `yaml:"extensions" desc:"x- keys on component schemas, such as x-internal: include keeps only these, exclude drops them."`
	SchemaProperties map[string][]string `yaml:"schema-properties" desc:"Properties per component schema name."`
}

FilterSet lists what a filter matches.

type GoType

type GoType struct {
	Type   string `yaml:"type" desc:"Go type, such as uuid.UUID or int64."`
	Import string `yaml:"import" desc:"Import path of the type's package, found as for x-go-type when left out."`
}

GoType is a Go type and the package it comes from.

type Import

type Import struct {
	Package string `yaml:"package" desc:"Import path."`
	Alias   string `` /* 167-byte string literal not displayed */
}

Import is a package that Go code the generator does not write itself refers to: the text of a template override, an x-go-type. A generated file imports it when its code names it.

func (Import) Name

func (imp Import) Name() string

Name is the name code refers to the package by: the alias, else the one the path gives. It is empty under _ and for a path that gives no name.

type Issue

type Issue struct {
	Key     string
	Message string
}

Issue is one problem in a config, at a dotted key path such as server.framework.

type MCP

type MCP struct {
	DefaultSkip bool `yaml:"default-skip" desc:"Skip operations unless x-mcp turns them on."`
}

MCP controls MCP server generation.

type ModelValidation

type ModelValidation struct {
	Skip     bool `yaml:"skip" desc:"Generate no Validate methods."`
	Response bool `` /* 140-byte string literal not displayed */
}

ModelValidation controls the generated Validate methods.

type Models

type Models struct {
	IntType      string            `yaml:"int-type" enum:"int,int32,int64" desc:"Go type for integers without a format. Defaults to int."`
	Descriptions *bool             `` /* 146-byte string literal not displayed */
	ExtraTags    []string          `yaml:"extra-tags" desc:"Struct tags added next to json, such as yaml."`
	Validation   ModelValidation   `yaml:"validation" desc:"Generated Validate methods."`
	ErrorMapping map[string]string `yaml:"error-mapping" desc:"Error types, mapped to the path of their message field."`
	FormatTypes  map[string]GoType `` /* 126-byte string literal not displayed */
	Nullable     bool              `` /* 142-byte string literal not displayed */
}

Models controls model generation.

type Naming

type Naming struct {
	Initialisms []string `yaml:"initialisms" desc:"Extra initialisms kept upper case, such as PSP."`
	EnumPrefix  *bool    `yaml:"enum-prefix" desc:"Prefix enum constants with their type name. Defaults to true."`
}

Naming controls how Go names are built.

type OptionalProperties

type OptionalProperties struct {
	Min  int   `yaml:"min" desc:"Fewest optional properties kept per schema."`
	Max  int   `yaml:"max" desc:"Most optional properties kept per schema."`
	Seed int64 `yaml:"seed" desc:"Seed for picking a count between min and max."`
}

OptionalProperties sets how many optional properties survive simplification.

type Output

type Output struct {
	File     string              `yaml:"file" desc:"Default file for every part. Defaults to ./gen.go."`
	Files    map[string][]string `yaml:"files" desc:"Parts moved to other files, keyed by file path. The most specific selector wins."`
	Packages map[string]string   `yaml:"packages" desc:"Package names keyed by folder. Other folders use their own name."`
	Module   string              `yaml:"module" desc:"Module path, only needed when no go.mod is found."`
	Format   *bool               `yaml:"format" desc:"Format generated files with go/format. Defaults to true."`
}

Output says where generated files go.

type Scaffold

type Scaffold struct {
	Service    string   `yaml:"service" desc:"File for the service implementation stub."`
	Middleware string   `yaml:"middleware" desc:"File for the middleware stub."`
	Main       string   `yaml:"main" desc:"File for the main package that runs the server."`
	Overwrite  bool     `yaml:"overwrite" desc:"Write scaffold files even when they exist."`
	Port       int      `yaml:"port" desc:"Port the scaffolded server listens on. Defaults to 8080."`
	Timeout    Duration `yaml:"timeout" desc:"Request timeout of the scaffolded server. Defaults to 30s."`
}

Scaffold lists the starter files and their settings.

type Server

type Server struct {
	Framework          string           `` /* 159-byte string literal not displayed */
	Name               string           `yaml:"name" desc:"Name of the service interface. Defaults to Service."`
	Validation         ServerValidation `yaml:"validation" desc:"Checks the server runs on requests and responses."`
	MultipartMaxMemory ByteSize         `yaml:"multipart-max-memory" desc:"Memory for multipart forms before spilling to disk. Defaults to 32MB."`
	Scaffold           Scaffold         `yaml:"scaffold" desc:"Starter files, written once."`
}

Server controls server generation.

type ServerValidation

type ServerValidation struct {
	Request  bool `yaml:"request" desc:"Validate requests before calling the service."`
	Response bool `yaml:"response" desc:"Validate responses before writing them."`
}

ServerValidation controls what the server validates.

type Simplify

type Simplify struct {
	Unions             bool                `yaml:"unions" desc:"Collapse each oneOf and anyOf to one variant."`
	OptionalProperties *OptionalProperties `yaml:"optional-properties" desc:"Cap the optional properties kept per schema."`
}

Simplify lists the spec rewrites to apply.

type Spec

type Spec struct {
	Path     string    `yaml:"path" desc:"Path or URL of the OpenAPI spec. A CLI argument or in-memory spec overrides it."`
	Overlays []string  `yaml:"overlays" desc:"Overlay files or URLs, applied in order."`
	Filter   Filter    `yaml:"filter" desc:"Parts of the spec to keep or drop."`
	Prune    *bool     `yaml:"prune" desc:"Remove components nothing refers to. Defaults to true."`
	Simplify *Simplify `yaml:"simplify" desc:"Rewrites that make the spec simpler to generate from."`
}

Spec is the input spec and the steps that prepare it.

type Template

type Template struct {
	Text string `yaml:"-"`
	File string `yaml:"file" desc:"File that holds the template text, relative to the config."`
}

Template is the override of one template block: Text, or File, the file that holds the text. In YAML it is the text itself, or a mapping with the key file.

func (*Template) UnmarshalYAML

func (t *Template) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML reads a scalar as the text and a mapping as the file.

type UnknownKeyError

type UnknownKeyError struct {
	Keys []string
}

UnknownKeyError lists every key in a config file that matches no field, as dotted paths.

func (*UnknownKeyError) Error

func (e *UnknownKeyError) Error() string

func (*UnknownKeyError) Unwrap

func (e *UnknownKeyError) Unwrap() error

type ValidationError

type ValidationError struct {
	Issues []Issue
}

ValidationError lists every problem Validate found.

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Jump to

Keyboard shortcuts

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