schema

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 9 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

cmdguard/schema

Emit a JSON Schema draft 2020-12 document describing a cmdguard config struct or a whole CLI, from the same struct tags that drive flags, environment variables, and strict config-key checking.

Experimental surface — the API may still change before the first tagged release.

What you get

  • One property per accepted config key, including nested objects and arrays (array element shapes under items).
  • Constraints translated from validate tags (min/max/pattern, string length bounds), values tags as enum, and default tags as default.
  • cmdguard facts JSON Schema has no home for under x-cmdguard: the flag, the env var, cmdguard-only formats (duration, hostport, path), and the secret marker.
  • additionalProperties: false everywhere: a key the schema rejects is the same key strict config loading rejects. The schema and the binary can never disagree, because both are generated from v4.ConfigKeys.

Usage

package main

import (
    "os"

    "github.com/larsartmann/cmdguard/schema"
    "github.com/larsartmann/cmdguard/v4/pkg/cmdguard/v4"
)

func main() {
    cli, _ := v4.NewCLI[AppConfig]("myapp", "My app", AppConfig{})

    if err := schema.Emit(os.Stdout, cli.Config()); err != nil {
        panic(err)
    }
}

FromConfig(cfg) builds the document, FromCLI(cli) adds the CLI's name and short description as title/description, Emit writes indented JSON to an io.Writer, and Marshal returns it as bytes. Output is deterministic: properties are emitted in sorted key order.

A typical pattern is a hidden schema subcommand (or a build-time generator) that writes config.schema.json next to your binary.

Editor and CI integration

Point your editor at the emitted file with a $schema reference, or pass it to a validator in CI:

# GitHub Actions example using check-jsonschema (pip install check-jsonschema)
- name: Validate example config
  run: check-jsonschema --schemafile config.schema.json config.example.yaml

Committing an emitted schema lets consumers, editors, and CI validate configs without running your binary.

Development

cd schema
go test ./...
# regenerate the golden fixture after changing the emitter:
go test ./... -run TestFromConfig_Golden -update-golden

The golden test (testdata/config.schema.json) fails on any emitter change; regenerate intentionally and review the diff. If the test reports schema drift on an unchanged emitter, suspect nondeterministic output — plain Go maps marshal in random order under encoding/json/v2, which is why properties use the sorted PropertyMap.

Documentation

Overview

Package schema turns a cmdguard config struct into a JSON Schema document.

The point is to let editors, CI pipelines, and non-Go tools validate a config file without running the binary. The schema is derived from the same struct tags that drive flags and strict config loading (v5.ConfigKeys), so it cannot accept a key the loader rejects or miss one it accepts.

This package deliberately lives outside the core module: it is a build-time code generator, not runtime machinery, and core has no reason to carry it.

Validation at runtime is already covered by [cmdguard.WithStrictConfigKeys]; this package is for everything that happens before the binary runs.

Index

Constants

View Source
const Dialect = "https://json-schema.org/draft/2020-12/schema"

Dialect is the JSON Schema dialect emitted. Draft 2020-12 is what editors and CI validators support today.

View Source
const ExtensionKey = "x-cmdguard"

ExtensionKey names the non-standard hints cmdguard adds to a property. It is namespaced so a validator ignores it and a tool can read it.

Variables

This section is empty.

Functions

func CommandSchemas

func CommandSchemas(description *v5.CLIDescription) map[string]*Document

CommandSchemas builds one flag schema per command path from the machine contract. Keys are command paths ("app", "app deploy"); each document describes the flags that command accepts, including inherited ones.

This is for tooling that drives a binary: a config schema constrains a file, a flag schema constrains an invocation.

func Emit

func Emit(writer io.Writer, cfg any) error

Emit writes the schema as indented JSON to writer.

func Marshal

func Marshal(cfg any) ([]byte, error)

Marshal returns the schema as indented JSON.

Types

type Document

type Document struct {
	Schema               string      `json:"$schema"`
	Title                string      `json:"title,omitempty"`
	Description          string      `json:"description,omitempty"`
	Type                 string      `json:"type"`
	Properties           PropertyMap `json:"properties"`
	Required             []string    `json:"required,omitempty"`
	AdditionalProperties bool        `json:"additionalProperties"`
}

Document is a JSON Schema describing a cmdguard config file.

func FromCLI

func FromCLI[T any](cli *v5.CLI[T]) (*Document, error)

FromCLI builds the schema for a CLI's config, using the CLI's name and short description as the document's title and description.

func FromConfig

func FromConfig(cfg any) (*Document, error)

FromConfig builds the schema for a cmdguard config struct.

The result rejects unknown keys (additionalProperties: false) to match strict config loading: a typo caught by the schema is the same typo the binary would reject.

type Hints

type Hints struct {
	// Flag is the command-line flag that sets the same value.
	Flag string `json:"flag,omitempty"`
	// Env is the environment variable that sets the same value.
	Env string `json:"env,omitempty"`
	// Format is a cmdguard-specific type hint (duration, hostport, path) for
	// values JSON Schema only sees as strings.
	Format string `json:"format,omitempty"`
	// Secret marks a value that must never be logged or committed.
	Secret bool `json:"secret,omitempty"`
}

Hints carries metadata JSON Schema has no home for.

type Property

type Property struct {
	Type                 string      `json:"type,omitempty"`
	Description          string      `json:"description,omitempty"`
	Default              any         `json:"default,omitempty"`
	Enum                 []string    `json:"enum,omitempty"`
	Minimum              *float64    `json:"minimum,omitempty"`
	Maximum              *float64    `json:"maximum,omitempty"`
	MinLength            *int        `json:"minLength,omitempty"`
	MaxLength            *int        `json:"maxLength,omitempty"`
	Pattern              string      `json:"pattern,omitempty"`
	Format               string      `json:"format,omitempty"`
	Properties           PropertyMap `json:"properties,omitempty"`
	Required             []string    `json:"required,omitempty"`
	Items                *Property   `json:"items,omitempty"`
	AdditionalProperties *bool       `json:"additionalProperties,omitempty"`
	Hints                *Hints      `json:"x-cmdguard,omitempty"`
}

Property describes one accepted key. Standard fields carry the constraints a validator enforces; Hints carries what only cmdguard knows.

type PropertyMap

type PropertyMap map[string]*Property

PropertyMap is a set of named properties. Plain Go maps marshal in map iteration order under encoding/json/v2, so this type sorts its keys: generated schemas are byte-for-byte reproducible.

func (PropertyMap) MarshalJSONTo

func (m PropertyMap) MarshalJSONTo(out *jsontext.Encoder) error

Jump to

Keyboard shortcuts

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