spec

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: MIT Imports: 14 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.

Documentation

Overview

Package spec defines the herdr-panel spec format: a TOML file describing a panel's stores, settings fields, lists, buttons and the commands behind them.

Load reads and validates a spec. Every problem is reported with its file:line:col, all at once, as an Errors value. A spec can also be built in Go and checked with Validate.

A spec runs commands, so a spec is code: see docs/security.md.

Index

Constants

View Source
const (
	NSRow   = "row"
	NSField = "field"
	NSCtx   = "ctx"
	NSEnv   = "env"
	// NSSel reads the selected row of another list: {sel.<list id>.<column>}.
	NSSel = "sel"
)

Namespaces a placeholder may use.

View Source
const DefaultTimeout = 10 * time.Second

DefaultTimeout bounds a command whose spec gives none.

View Source
const MaxSize = 1 << 20

MaxSize bounds a spec file; a panel description is never this large.

View Source
const Version = 1

Version is the spec format version this package reads.

Variables

View Source
var CtxNames = []string{
	"workspace_id", "tab_id", "pane_id", "cwd",
	"plugin_id", "config_dir", "state_dir", "spec_dir",
}

CtxNames are the names {ctx.*} accepts.

View Source
var ErrMissing = errors.New("no value")

ErrMissing is wrapped by Expand when a placeholder has no value.

View Source
var ReservedKeys = []string{
	"?", "/", "q", "esc", "enter", "space", "tab", "shift+tab",
	"up", "down", "left", "right", "pgup", "pgdown", "home", "end",
	"delete", "backspace",
	"ctrl+c", "ctrl+s", "ctrl+r",
}

ReservedKeys are bound by every panel and cannot be an action's shortcut. The vim aliases h, j, k and l are not reserved: a shortcut on one of them wins, and the arrow keys still move.

View Source
var StoreKinds = []StoreKind{EnvFile, TOMLFile}

StoreKinds are the kinds this version reads.

Functions

func CheckInt

func CheckInt(f *Field, s string) error

CheckInt reports whether s is a valid value for an int or duration field.

func CheckText

func CheckText(f *Field, s string) error

CheckText reports whether s is a valid value for a text field.

func EnvName

func EnvName(s string) string

EnvName is a field id or row column as it appears in a command's environment: PANEL_FIELD_<EnvName(id)>, PANEL_ROW_<EnvName(column)>. Letters are upper-cased and anything other than a letter or digit becomes _.

func ExpandArgv

func ExpandArgv(argv []Template, v Values, dir string) ([]string, error)

ExpandArgv expands each element of a command on its own, and resolves a relative program ("./x", "bin/x") against dir. A bare name ("herdr") is left for PATH lookup.

func ExpandPath

func ExpandPath(t Template, v Values, dir string) (string, error)

ExpandPath expands a path template, then a leading ~, then makes it absolute against dir.

A path that starts with {env.X} needs X to be non-empty: an empty one would turn "{env.X}/config.toml" into "/config.toml".

func HostVersion

func HostVersion() string

HostVersion is the version of this module in the running binary: "v0.3.1", or "devel" for a build from a working tree or one whose go.mod replaces this module (a go.work or a replace directive builds from local source, whatever version the requirement names).

func IsSpecError

func IsSpecError(err error) bool

IsSpecError reports whether err describes a problem in the spec itself, as opposed to failing to read it.

func JSONSchema

func JSONSchema() []byte

JSONSchema returns a JSON Schema (draft 2020-12) for the spec format, for editors (taplo, VS Code's Even Better TOML) and agents. It describes shape and types; references between fields, stores and placeholders are checked by Validate, which a schema cannot express.

func SelRef added in v0.2.0

func SelRef(name string) (list, column string)

SelRef splits the name of a {sel.<list>.<column>} placeholder.

func ValidKeyName

func ValidKeyName(k string) bool

ValidKeyName reports whether k is a key as Bubble Tea names it: a printable character ("r", "R", "?"), a named key ("enter", "f5"), or either after ctrl+, alt+ or shift+. After ctrl+ or alt+ a letter is lower case, and shift+ never precedes a letter (shift+a arrives as A).

func Validate

func Validate(s *Spec) error

Validate checks a spec built in Go. It first fills in what the TOML decoder would: the format version, the save mode, a field's id and label from its key, bool values "true"/"false", command timeouts, after = refresh, the id column and column titles. It then checks the shapes the decoder checks (enums, bounds, non-empty commands) and everything Parse checks. It returns an Errors value listing every problem; calling it again changes nothing.

A bool Default is stored as written: with TrueValue "1", write Default "1", not "true". Unlike the TOML default, a Store built in Go creates its file only when Create is set.

Types

type Action

type Action struct {
	Label   string
	Key     string // a shortcut, as Bubble Tea names keys; "" for none
	Run     *Command
	Confirm Template // a question asked in the panel before running; "" for none
	After   After
	Pos     Pos
}

Action is a button or a row action.

type After

type After string

After says what a panel does when an action succeeds.

const (
	AfterRefresh After = "refresh" // reload lists and stores
	AfterClose   After = "close"   // close the panel
	AfterNothing After = "none"
	// AfterCloseThenRun closes the panel first and then runs the command,
	// detached, once the panel has exited; its result is never shown. It is
	// for an action that opens something the open panel would be in the way
	// of, such as another popup.
	AfterCloseThenRun After = "close_then_run"
)

The After values.

type ChoiceItem

type ChoiceItem struct {
	Value string
	Label string
}

ChoiceItem is one value a choice field can take.

type Column

type Column struct {
	Key   string
	Title string
	Width int // 0 shares the remaining width
}

Column is one column of a list.

type Command

type Command struct {
	Argv    []Template
	Timeout time.Duration
	Pos     Pos
}

Command is an argument vector run without a shell.

func (*Command) SelLists added in v0.2.0

func (c *Command) SelLists() []string

SelLists are the list ids a command's arguments follow with {sel.*}.

type Dim

type Dim struct {
	Cells   int
	Percent int
}

Dim is one popup dimension: a number of cells or a percentage of the terminal. The zero value means "not set".

func (Dim) IsZero

func (d Dim) IsZero() bool

IsZero reports whether the dimension is unset.

type Error

type Error struct {
	File string
	Pos  Pos
	Msg  string
}

Error is one problem in a spec, at a place in its file.

func (*Error) Error

func (e *Error) Error() string

type Errors

type Errors []*Error

Errors is every problem found in one spec, in file order. Load and Validate return it rather than stopping at the first problem, so an editor or an agent can fix them all in one pass.

func (Errors) Error

func (es Errors) Error() string

func (Errors) Unwrap

func (es Errors) Unwrap() []error

Unwrap lets errors.As find each *Error.

type Field

type Field struct {
	ID          string // unique in the spec; {field.<ID>} refers to it
	Store       string
	Key         string
	Type        FieldType
	Label       string
	Help        string
	Default     string // the value shown when the store has none, as stored
	Required    bool   // an empty value blocks Save
	Choices     []ChoiceItem
	Min, Max    *int64
	Pattern     string // a regular expression a text value must match in full
	MaxLen      int
	Placeholder string
	TrueValue   string // what a bool stores; "true" by default
	FalseValue  string // "false" by default
	Test        *Command
	Pos         Pos
}

Field is one editable value in a store.

type FieldType

type FieldType string

FieldType is a field's kind of value.

const (
	Bool     FieldType = "bool"
	Choice   FieldType = "choice"
	Int      FieldType = "int"
	Duration FieldType = "duration_s" // whole seconds, shown as 1m30s
	Text     FieldType = "text"
	Secret   FieldType = "secret" // never shown; only set or unset
)

The field types.

type Pos

type Pos struct {
	Line, Col int
}

Pos is a position in a spec file. Line and Col start at 1; the zero value means "no position", for errors about the file as a whole.

type SaveMode

type SaveMode string

SaveMode says when edited values are written to their store.

const (
	// SaveThenApply writes all edits on Save, then runs each changed store's
	// apply command. It is the default.
	SaveThenApply SaveMode = "save_then_apply"
	// Live writes each edit as it is made, then applies it.
	Live SaveMode = "live"
)

type Section

type Section struct {
	// Title may use {sel.*}, {ctx.*} and {env.*} placeholders (see
	// ExpandTitle); {{ and }} are literal braces.
	Title string
	Kind  SectionKind
	// ID names a list section, so other sections can follow its selected row
	// with {sel.<id>.<column>}. Only lists have one; it may be empty.
	ID string

	Fields []*Field // FieldsSection

	Source     *Command // ListSection and TextSection: prints rows or text
	Every      time.Duration
	Columns    []Column
	IDColumn   string
	Empty      string // shown when a list has no rows
	RowActions []*Action

	Buttons []*Action // ButtonsSection

	Text string // TextSection, when there is no source

	View string // ViewSection: the name the host supplies a View under

	Pos Pos
}

Section is one titled part of the panel.

func (*Section) ExpandTitle added in v0.2.0

func (s *Section) ExpandTitle(v Values) string

ExpandTitle is the section's title with its placeholders filled in. A value that is missing, such as {sel.*} while nothing is selected, shows as "…"; a title that is not a valid template shows as written.

type SectionKind

type SectionKind string

SectionKind is what a section shows.

const (
	FieldsSection  SectionKind = "fields"
	ListSection    SectionKind = "list"
	ButtonsSection SectionKind = "buttons"
	TextSection    SectionKind = "text"
	// ViewSection is drawn by Go code the panel's host supplies under the
	// section's View name (see panel.Options.Views). Experimental.
	ViewSection SectionKind = "view"
)

The section kinds.

type Size

type Size struct {
	Width, Height Dim
}

Size is the popup size an opener asks herdr for. herdr's own popups take either form.

type Spec

type Spec struct {
	File     string // the path it was loaded from, or "" when built in Go
	Dir      string // relative paths and programs resolve against this
	Version  int
	Requires string // a minimum herdr-panel version, ">=0.3"; "" for none
	Title    string
	Size     Size
	Save     SaveMode
	Stores   []*Store // in file order
	Sections []*Section
	// contains filtered or unexported fields
}

Spec is a validated panel description.

func Load

func Load(path string) (*Spec, error)

Load reads, decodes and validates the spec at path. Its errors carry the path and the line and column of each problem.

func Parse

func Parse(data []byte, file, dir string) (*Spec, error)

Parse decodes and validates a spec held in memory. file names it in errors; dir is where relative paths and programs resolve.

func (*Spec) Fields

func (s *Spec) Fields() []*Field

Fields returns every field in every section, in order.

func (*Spec) List added in v0.2.0

func (s *Spec) List(id string) *Section

List returns the list section with the given id, or nil.

func (*Spec) Store

func (s *Spec) Store(name string) *Store

Store returns the store with this name, or nil.

type Store

type Store struct {
	Name   string
	Kind   StoreKind
	Path   Template // expanded with {env.*} and {ctx.*}; relative to Dir
	Create bool     // create the file on first save when it does not exist
	Apply  *Command // run after a save that changed this store; may be nil
	Pos    Pos
}

Store is where field values live.

type StoreKind

type StoreKind string

StoreKind names a store implementation.

const (
	// EnvFile is a KEY=value file: comments, order, quoting and `export`
	// are kept.
	EnvFile StoreKind = "envfile"
	// TOMLFile is a TOML file whose top-level keys hold the fields: only
	// edited lines change, so comments, tables and order are kept.
	TOMLFile StoreKind = "tomlfile"
)

The store kinds.

type Template

type Template struct {
	Raw string
	// contains filtered or unexported fields
}

Template is a string with placeholders: {row.<column>}, {field.<id>}, {sel.<list>.<column>}, {ctx.<name>}, {env.<NAME>} and {env.<NAME>:-default}. {{ and }} stand for literal braces.

A template always expands to exactly one string. In an argument vector each element expands on its own, so a value with spaces or quotes stays one argument and can never become two, or become shell syntax.

func MustTemplate

func MustTemplate(s string) Template

MustTemplate parses s and panics on a syntax error; for specs built in Go.

func ParseTemplate

func ParseTemplate(s string) (Template, error)

ParseTemplate parses s. It checks syntax only; which namespaces and names are allowed depends on where the template is used (see Validate).

func (Template) Expand

func (t Template) Expand(v Values) (string, error)

Expand fills in every placeholder.

func (Template) IsZero

func (t Template) IsZero() bool

IsZero reports whether the template is empty.

func (Template) Placeholders

func (t Template) Placeholders() [][2]string

Placeholders returns the namespace and name of each placeholder.

func (Template) String

func (t Template) String() string

String returns the template as written.

type Values

type Values interface {
	Lookup(ns, name string) (string, bool)
}

Values supplies placeholder values. Lookup returns false when the value is unknown; Expand then fails, except for {env.X:-default}.

type ValuesFunc

type ValuesFunc func(ns, name string) (string, bool)

ValuesFunc adapts a function to Values.

func (ValuesFunc) Lookup

func (f ValuesFunc) Lookup(ns, name string) (string, bool)

Lookup calls f.

Jump to

Keyboard shortcuts

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