Documentation
¶
Overview ¶
Package uf parses, evaluates, and generates uf command specifications.
Index ¶
- Constants
- Variables
- func CheckEvalConfig(a Config, arguments, env []string) error
- func CheckExampleConfig(a Config, arguments, env []string) error
- func CmpLexish(d, o string) int
- func DeclarationSyntaxError(line string) (int, error, bool)
- func EvalConfig(a Config, arguments, env []string) (vals map[string]any, src map[string]Source, err error)
- func EvalConfigPrefix(a Config, arguments, env []string) (vals map[string]any, src map[string]Source, remainder []string, err error)
- func EvalExampleConfigPrefix(a Config, arguments, env []string) (vals map[string]any, src map[string]Source, remainder []string, err error)
- func EvalOne(b Bounds, name, def string, values ...string) (v any, err error)
- func NeighborTableBytes() string
- func ParseConfigWithLocations(raw string) (Config, DefinitionLocations, error)
- func ParseErrorf(format string, args ...any) error
- type Bounds
- type Config
- func (c *Config) AppendDefs(dst []Def) []Def
- func (c Config) AppendText(dst []byte) ([]byte, error)
- func (c Config) Equal(d Config) bool
- func (c Config) MarshalJSONTo(enc *jsontext.Encoder) error
- func (c Config) RegisterFlagSet(fs *flag.FlagSet) error
- func (c Config) String() string
- func (c Config) Synopsis() string
- func (c *Config) UnmarshalJSONFrom(dec *jsontext.Decoder) error
- func (c *Config) UnmarshalText(b []byte) error
- func (c Config) Usage(name string) string
- func (c Config) WrappedSynopsis(linewidth int) string
- type Copyright
- type DeclarationScan
- type DeclarationSpan
- type DeclarationSpanRole
- type Def
- func (a Def) AppendText(dst []byte) ([]byte, error)
- func (a Def) AppendTextWithIndices(dst []byte) ([]byte, DefSpans, error)
- func (d Def) Equal(e Def) bool
- func (a Def) MarshalJSONTo(enc *jsontext.Encoder) error
- func (a Def) String() string
- func (a *Def) UnmarshalJSONFrom(dec *jsontext.Decoder) error
- func (a *Def) UnmarshalText(b []byte) error
- type DefSpans
- type DefinitionKey
- type DefinitionLocations
- type ErrorChild
- type Example
- type LanguageFragment
- type License
- type Location
- type Parent
- type ParseError
- type PositionalRepeatError
- type Repeat
- type Source
- type SubcommandDeclarationError
- type TextSpan
- type Token
- type TokenType
- type VarType
Examples ¶
Constants ¶
const ( // DEC selects decimal output and is also the zero value for numericLiteralFormat. DEC = 0b00 // BIN selects 0b-prefixed output. BIN = 0b01 // OCT selects 0o-prefixed output. OCT = 0b10 // HEX selects 0x-prefixed output. HEX = 0b11 // FMT_MASK extracts DEC, BIN, OCT, or HEX from a format flag set. FMT_MASK = 0b11 // MARK_MASK extracts the temporary MARK_SPECIAL and MARK_DEC state bits. MARK_MASK = 0b1100 // MARK_SPECIAL allows the first 0, 1, or -1 on an all-special line to carry the selected base. MARK_SPECIAL = 0b1000 // MARK_DEC records that the first special value has already carried the selected base. MARK_DEC = 0b0100 )
Numeric format flags preserve the spelling base of integer literals when a parsed definition is serialized. DEC, BIN, OCT, and HEX occupy the low two bits and are ordered by precedence: decimal, binary, octal, hex. MARK_SPECIAL and MARK_DEC occupy the high bits used while walking one line; they are not part of the base.
const DefaultCopyright string = `copyright uf "Efron Licht" 2026 "BSD 3-Clause" "https://gitlab.com/efronlicht/uf/-/blob/master/LICENSE.md"`
DefaultCopyright is the default copyright record for UF documents.
Variables ¶
var ( NAMEPAT = `^(?:` + flagNamePat + `|` + quotedPat + `|` + identPat + `)$` SOURCEPAT = `^(?:flag|arg[1-9]|env)$` TYPEPAT = `^(?:bool|duration|float|int|string|subcmd|time)$` REPEATPAT = `^(?:\?|\+|\*)$` BOUNDSPAT = `^\[(?:\s*` + boundsBodyPat + `\s*)?\]$` DEFAULTPAT = `^=\s*` + valuePat + `$` COMMENTPAT = `^#.*$` APPPAT = `^app\s+(?:` + appNamePat + `|` + quotedPat + `)$` PARENTPAT = `^parent\s+` + valuePat + `\s+` + valuePat + `$` PAT = "^(?P<source>flag|arg[1-9]|env)\\s+(?P<name>" + flagNamePat + `|` + quotedPat + `|` + identPat + `)` + `\s+(?P<type>bool|duration|float|int|string|subcmd|time)` + `(?:\s*(?P<repeat>\?|\+|\*))?` + `(?:\s+\[(?P<bounds>(?:\s*` + boundsBodyPat + `\s*)?)\])?` + `(?:\s*(?P<default>=\s*` + valuePat + `))?` + `(?:\s*(?P<comment>#.*))?$` )
var ErrOrphanComment = errors.New("comment is not attached to a declaration: move it immediately above (or to the right of) an app, env, flag, or arg, or attach it to the app declaration as the app doc comment")
ErrOrphanComment reports a comment that does not belong to a declaration.
Functions ¶
func CheckEvalConfig ¶
CheckEvalConfig validates arguments and environment values. It may return an error wrapping *ParseError.
Example ¶
ExampleCheckEvalConfig checks a command line before using its values.
cfg := MustParseConfig("app tool\nflag -count int = 1\n")
if err := CheckEvalConfig(cfg, []string{"tool", "-count", "3"}, nil); err != nil {
panic(err)
}
fmt.Println("arguments accepted")
Output: arguments accepted
func CheckExampleConfig ¶ added in v0.2.0
CheckExampleConfig validates an example while allowing required environment values to be inherited by the shell.
func CmpLexish ¶ added in v0.5.1
CmpLexish compares two strings lexicographically, ignoring leading hyphens and case. On ties, the strings are compared using their original byte values.
func DeclarationSyntaxError ¶
DeclarationSyntaxError reports the first grammar error without semantic validation.
Example ¶
ExampleDeclarationSyntaxError locates a malformed declaration.
offset, err, ok := DeclarationSyntaxError("flag -count")
fmt.Println("syntax error:", ok)
fmt.Println("offset:", offset)
fmt.Println("message:", err)
Output: syntax error: true offset: 11 message: flag requires a type after the name; expected one of bool|duration|float|int|string|subcmd|time
func EvalConfig ¶
func EvalConfig(a Config, arguments, env []string) (vals map[string]any, src map[string]Source, err error)
EvalConfig evaluates arguments and environment values. It may return an error wrapping *ParseError.
Example ¶
ExampleEvalConfig evaluates flags and positional arguments into typed values.
cfg := MustParseConfig("app tool\nflag -count int = 1\narg1 name string\n")
values, _, err := EvalConfig(cfg, []string{"tool", "-count", "3", "Ada"}, nil)
if err != nil {
panic(err)
}
fmt.Println("count:", values["-count"])
fmt.Println("name:", values["name"])
Output: count: 3 name: Ada
func EvalConfigPrefix ¶
func EvalConfigPrefix(a Config, arguments, env []string) (vals map[string]any, src map[string]Source, remainder []string, err error)
EvalConfigPrefix evaluates a command through its terminal subcmd positional and returns the remaining argv. The subcmd value is the canonical identity from an identity-to-spelling bound such as [uf-borrow: borrow].
func EvalExampleConfigPrefix ¶ added in v0.2.0
func EvalExampleConfigPrefix(a Config, arguments, env []string) (vals map[string]any, src map[string]Source, remainder []string, err error)
EvalExampleConfigPrefix evaluates a subcommand example while allowing required environment values to be inherited by the shell.
func EvalOne ¶
EvalOne validates and converts values according to bounds. It returns validation errors without source locations.
Example ¶
ExampleEvalOne parses one value using explicit bounds.
value, err := EvalOne(Bounds{Type: INT}, "0", "42")
if err != nil {
panic(err)
}
fmt.Println("value:", value)
Output: value: 42
func NeighborTableBytes ¶
func NeighborTableBytes() string
NeighborTableBytes returns the keyboard-neighbor table in generated-parser form.
func ParseConfigWithLocations ¶
func ParseConfigWithLocations(raw string) (Config, DefinitionLocations, error)
ParseConfigWithLocations parses a configuration and returns source locations for its declarations.
Example ¶
ExampleParseConfigWithLocations keeps source locations for later diagnostics.
cfg, locations, err := ParseConfigWithLocations("app tool\nflag -count int = 1\n")
if err != nil {
panic(err)
}
location := locations[DefinitionKey{Source: FLAG, Name: "-count"}]
fmt.Println("application:", cfg.App)
fmt.Println("flag line:", location.LineTable[0]+1)
Output: application: tool flag line: 1
func ParseErrorf ¶ added in v0.1.2
ParseErrorf formats an error and moves a nested parse location to the front.
Types ¶
type Bounds ¶
type Bounds struct {
Enum map[string]string `json:"enum,omitempty,omitzero"` // choices like [a b c] or [k0:v0 k1:v1]
Max string `json:"max,omitempty,omitzero"` // if non-empty, must parse as Type: [[MIN]..=[MAX]]
Min string `json:"min,omitempty,omitzero"` // if non-empty, must parse as Type:
Pattern string `json:"pattern,omitempty,omitzero"` // if non-empty, an alternative to enum and range bounds: [~PAT]
Repeat Repeat `json:"repeat,omitempty,omitzero"` // specifies how many times the value can be repeated: 0 (exactly once), '*' (many), '+' (at least one), '?' (optional)
Type VarType `json:"type,omitempty,omitzero"` // bool | duration | float | int | string | subcmd | time
}
Bounds represents the constraints that can be applied to a value. In UF form, they look like this: [<bounds go here>] All components are optional.
func (Bounds) AppendText ¶
AppendText appends bounds in .uf syntax.
type Config ¶
type Config struct {
App string // Name of the application: `app myprogram`
AppComment string // Comment for the application, typically describing its purpose.
Copyrights []Copyright // Copyright records for the application.
Environment []Def // Environment variable definitions for the application, as sorted key-value pairs.
Examples []Example // Example command-line invocations for the application
Flags []Def // Flag definitions for the application, as sorted-by-key key-value pairs.
Parent Parent // Parent command and alias for the application, if any.
Positional []Def // Positional argument definitions for the application, as sorted-by-key key-value pairs.
Shebang string // Shebang line for the application, if any. It should almost always be #!/usr/bin/env uf.
Subcmds []string // List of subcmds for the application: if len > 0, then the trailing positional arguments (after len(c.Positional)-1) are reserved for the subcmd.
}
Config represents a fully parsed and validated UF configuration file.
ParseConfig("app grep\nflag -r bool") -> Config{App: "grep", Flags: []Def{...}}
func MustParseConfig ¶
MustParseConfig parses a .uf document and panics if it is invalid.
Example ¶
ExampleMustParseConfig parses a known-valid declaration without manual error handling.
cfg := MustParseConfig("app copy\narg1 source string\n")
fmt.Println("application:", cfg.App)
fmt.Println("argument:", cfg.Positional[0].Name)
Output: application: copy argument: source
func ParseConfig ¶
ParseConfig parses and validates a complete UF configuration.
ParseConfig("app grep\n") -> Config{App: "grep"}
Example ¶
ExampleParseConfig returns a config and an error for a declaration.
cfg, err := ParseConfig("app grep\nflag -ignore-case bool = false\n")
if err != nil {
panic(err)
}
fmt.Println("application:", cfg.App)
fmt.Println("flag:", cfg.Flags[0].Name)
Output: application: grep flag: -ignore-case
func ParseConfigFile ¶
ParseConfigFile parses and validates a UF configuration while retaining filename context in errors.
func (*Config) AppendDefs ¶
AppendDefs appends all definitions from c and sorts the result by name.
func (Config) AppendText ¶
AppendText appends the textual representation of the Config to dst and returns the resulting slice and any error encountered. This is the underlying implementation used by WriteTo and String()
Example ¶
ExampleConfig_AppendText serializes a config back to UF syntax.
cfg := MustParseConfig("app copy\nflag -verbose bool = false\n")
text, err := cfg.AppendText(nil)
if err != nil {
panic(err)
}
fmt.Print(string(text))
Output: app copy copyright uf "Efron Licht" 2026 "BSD 3-Clause" "https://gitlab.com/efronlicht/uf/-/blob/master/LICENSE.md" flag -verbose bool = false
func (Config) Equal ¶
Configs are equal if all of their fields are equal, recursively checking nested structures, slices, etc.
func (Config) MarshalJSONTo ¶
MarshalJSONTo encodes the full configuration as JSON.
func (Config) RegisterFlagSet ¶
RegisterFlagSet adds c's flags to fs.
-verbose -> verbose in fs
Example ¶
ExampleConfig_RegisterFlagSet shows registering a config with a flag.FlagSet. The generated usage text includes both flags and positional arguments from the spec.
const spec = `
app copy
flag -count int [1..=10] = 1 # number of items
flag -verbose bool = false # enable logs
arg1 input string
arg2 output string
`
cfg := MustParseConfig(spec)
fs := flag.NewFlagSet("copy", flag.ContinueOnError)
if err := cfg.RegisterFlagSet(fs); err != nil {
panic(err)
}
fs.SetOutput(os.Stdout)
fs.Usage()
Output: copy [-count int] [-verbose] input output Usage of copy: -count value number of items (default 1) -verbose enable logs (default false)
func (Config) Synopsis ¶
Synopsis returns a one-line summary of the configuration, like "command [flags] <args>". Subcommand positionals list their accepted spellings as alternatives.
cfg := Config{
App: "mygrep",
Flags: []Def{
{Name: "-verbose", Type: BOOL, Default: "false", Comment: "enable verbose logging", Source: FLAG},
{Name: "-output", Type: STRING, Default: "out", Source: FLAG}, {Name: "-expression", Type: STRING, Source: FLAG, Repeat: REPEAT_AT_LEAST_ONE},
{Name: "-include", Type: STRING, Source: FLAG, Repeat: REPEAT_MANY}}, Positional: []Def{{Name: "pattern", Type: STRING, Source: ARG1},
{Name: "file", Type: STRING, Source: ARG1, Repeat: REPEAT_MANY},
},
}
fmt.Println(cfg.Synopsis())
// Output: mygrep -expression string [-expression string ...] [-include string ...] [-output string] [-verbose] pattern [file ...]
Example ¶
ExampleConfig_Synopsis shows the synopsis generated for a config declaration. Repeated flags and positional arguments are marked in the synopsis with their grammar.
cfg := Config{App: "mygrep", Flags: []Def{{Name: "-verbose", Type: BOOL, Default: "false", Comment: "enable verbose logging", Source: FLAG}, {Name: "-output", Type: STRING, Default: "out", Source: FLAG}, {Name: "-expression", Type: STRING, Source: FLAG, Repeat: REPEAT_AT_LEAST_ONE}, {Name: "-include", Type: STRING, Source: FLAG, Repeat: REPEAT_MANY}}, Positional: []Def{{Name: "pattern", Type: STRING, Source: ARG1}, {Name: "file", Type: STRING, Source: ARG2, Repeat: REPEAT_MANY}}}
fmt.Println(cfg.Synopsis())
Output: mygrep -expression string [-expression string ...] [-include string ...] [-output string] [-verbose] pattern [file ...]
func (*Config) UnmarshalJSONFrom ¶
UnmarshalJSONFrom decodes a compact JSON configuration into a Config.
func (*Config) UnmarshalText ¶
UnmarshalText parses a complete UF configuration from text.
func (Config) Usage ¶
Usage returns a command-line usage line for the configuration.
Example ¶
ExampleConfig_Usage renders a command's usage text from its declarations.
cfg := MustParseConfig("app copy\nflag -verbose bool = false\narg1 source string\n")
fmt.Print(cfg.Usage("copy"))
Output: copy [-verbose=false] source
func (Config) WrappedSynopsis ¶
WrappedSynopsis is as Synopsis, but wraps lines to the given width.
type Copyright ¶
type Copyright struct {
Name string `json:"name,omitempty,omitzero"` // name of the copyrighted work.
Holder string `json:"holder,omitempty,omitzero"` // copyright holder.
Year int `json:"year,omitempty,omitzero"` // copyright year.
License string `json:"license,omitempty,omitzero"` // license name.
Link *url.URL `json:"link,omitempty,omitzero"` // license or project URL.
Comment string `json:"comment,omitempty,omitzero"` // human-readable note.
}
Copyright records one copyright holder and license for an application.
func RequiredCopyright ¶
func RequiredCopyright() (cr Copyright)
RequiredCopyright returns the copyright record every generated UF document must contain.
func (Copyright) AppendText ¶
AppendText appends c as a copyright declaration in UF syntax: "copyright <name> <holder> <year> <license> [<link>] # <comment>"
func (Copyright) MarshalJSONTo ¶
MarshalJSONTo encodes a copyright through the package's compact JSON representation.
func (*Copyright) UnmarshalJSONFrom ¶
UnmarshalJSONFrom decodes one compact JSON copyright.
func (*Copyright) UnmarshalText ¶
UnmarshalText parses one copyright declaration.
type DeclarationScan ¶
type DeclarationScan struct {
Spans []DeclarationSpan // source spans in line order.
InvalidStart int // first invalid byte, or -1 when valid.
CommentStart int // `#` byte, or -1 when there is no comment.
}
DeclarationScan contains source-preserving declaration spans and recovery metadata.
func ScanDeclarationLine ¶
func ScanDeclarationLine(line string, dst []DeclarationSpan) DeclarationScan
ScanDeclarationLine maps `flag -v bool [1..=3]` to reusable byte spans. InvalidStart and CommentStart are -1 when no corresponding boundary exists.
type DeclarationSpan ¶
type DeclarationSpan struct {
Start int // first byte, such as 5 for the name in `flag -v bool`.
End int // byte after the span.
Role DeclarationSpanRole // syntax role, such as DeclarationRoleName.
Quoted bool // whether the span includes quotes, such as `"-#"`.
Quote byte // opening quote byte, or zero when unquoted.
}
DeclarationSpan is a byte range and structural role within one declaration line.
type DeclarationSpanRole ¶
type DeclarationSpanRole uint8
DeclarationSpanRole describes the syntactic role of one declaration span.
const ( // DeclarationRoleUnknown marks a span without a recognized role. DeclarationRoleUnknown DeclarationSpanRole = iota // DeclarationRoleSource marks `flag`, `env`, or `arg1` through `arg9`. DeclarationRoleSource // DeclarationRoleName marks a declaration name such as `-verbose`. DeclarationRoleName // DeclarationRoleType marks a type such as `string`. DeclarationRoleType // DeclarationRoleRepeat marks `?`, `*`, or `+`. DeclarationRoleRepeat // DeclarationRoleOperator marks syntax such as `[`, `=`, or `..=`. DeclarationRoleOperator // DeclarationRoleBoundValue marks values inside `[ ... ]`. DeclarationRoleBoundValue // DeclarationRolePatternValue marks a pattern such as `"[a-z]+"`. DeclarationRolePatternValue // DeclarationRoleDefaultValue marks text after a declaration default `=`. DeclarationRoleDefaultValue )
type Def ¶
type Def struct {
Name string `json:"name,omitempty,omitzero"` // flag, environment, or positional name.
Comment string `json:"comment,omitempty,omitzero"` // documentation shown for the declaration.
Default string `json:"default,omitempty,omitzero"` // default value when one is set.
EmptyString bool `json:"-"` // whether an explicit empty string is the default.
Source `json:"source,omitempty,omitzero"` // declaration source such as flag or arg1.
Bounds `json:"embed"` // type, repeat mode, and value constraints.
// contains filtered or unexported fields
}
Def describes one flag, environment variable, or positional argument declaration.
ParseDef("flag -n int [1..=10] = 3") -> Def{Name: "-n", Default: "3", ...}
func ParseAppendDefs ¶ added in v0.3.0
ParseAppendDefs parses one declaration and appends it to dst.
ParseAppendDefs(nil, "flag -n int", nil) -> []Def{
{Name: "-n", Source: FLAG, Bounds: Bounds{Type: INT}},
}
Example ¶
ExampleParseAppendDefs adds a declaration to an existing list.
defs, offset, err := ParseAppendDefs(nil, "flag -verbose bool = false", nil)
if err != nil {
panic(err)
}
fmt.Println("declarations:", len(defs))
fmt.Println("offset:", offset)
Output: declarations: 1 offset: 0
func ParseDef ¶
ParseDef parses exactly one flag, environment, or positional declaration.
ParseDef("flag -n int") -> Def{Name: "-n", Source: FLAG, Bounds: Bounds{Type: INT}}
Example ¶
ExampleParseDef parses one flag declaration.
defs, err := ParseDefs("flag -count int = 1")
if err != nil {
panic(err)
}
fmt.Println("name:", defs[0].Name)
fmt.Println("type:", defs[0].Bounds.Type)
Output: name: -count type: int
func ParseDefs ¶ added in v0.3.0
ParseDefs parses one or more flag, environment, or positional declarations.
ParseDefs("flag -n int\nflag -v bool = false") -> []Def{
{Name: "-n", Source: FLAG, Bounds: Bounds{Type: INT}},
{Name: "-v", Source: FLAG, Default: "false", Bounds: Bounds{Type: BOOL}},
}
func (Def) AppendText ¶
AppendText serializes a definition in .uf syntax.
Def{Name: "-n", Source: FLAG, Bounds: Bounds{Type: INT}} -> `flag -n int`
Example ¶
ExampleDef_AppendText serializes one declaration.
def := Def{Name: "-count", Type: INT, Default: "1", Source: FLAG}
text, err := def.AppendText(nil)
if err != nil {
panic(err)
}
fmt.Print(string(text))
Output: flag -count int = 1
func (Def) AppendTextWithIndices ¶
AppendTextWithIndices serializes a definition such as `flag -n int` and records half-open byte spans in DefSpans so an editor can select each emitted field.
func (Def) MarshalJSONTo ¶
MarshalJSONTo encodes a definition as JSON with the `bounds` embedded.
func (*Def) UnmarshalJSONFrom ¶
UnmarshalJSONFrom decodes one compact JSON definition into a Def.
func (*Def) UnmarshalText ¶
UnmarshalText parses one definition from UF text. Just delegates to ParseDef.
type DefSpans ¶
type DefSpans struct {
Source TextSpan // declaration source such as flag or arg1.
Name TextSpan // flag, environment, or positional name.
Type TextSpan // declared value type.
Bounds TextSpan // repeat marker and bound expression.
Default TextSpan // default value after '='.
Comment TextSpan // trailing or preceding documentation comment.
}
DefSpans represents where the components of a definition are located within the source file.
ScanDeclarationLine("flag -n int", nil) -> DeclarationScan{Spans: []DeclarationSpan{...}}
type DefinitionKey ¶
type DefinitionKey = parseerror.DefinitionKey
type DefinitionLocations ¶
type DefinitionLocations = map[DefinitionKey]parseerror.Location // maps definition keys to their locations in the source file
type ErrorChild ¶ added in v0.2.0
type ErrorChild = parseerror.Child // Child associates an error with an offset relative to its parent parse error.
type Example ¶
type Example struct {
Description string `json:"description,omitempty,omitzero"` // human-readable description of the example
Raw string `json:"raw,omitempty,omitzero"` // raw command-line string, held on to if the example can't be fully parsed via known Args and Env
Env []string `json:"env,omitempty,omitzero"` // Fully parsed command-line configuration including shebang, app comment, positional arguments, flags, and environment variables.
Args []string `json:"args,omitempty,omitzero"` // example positional arguments or flags for the application
}
A single example command-line invocation for the application.
func NormalizeExample ¶ added in v0.2.0
NormalizeExample applies the same environment and flag ordering used by evaluator help. It handles each invocation before a shell separator independently and leaves raw examples unchanged.
func NormalizeExampleWithSubcommands ¶ added in v0.2.0
func NormalizeExampleWithSubcommands(a Config, example Example, resolve func(string) (Config, bool)) Example
NormalizeExampleWithSubcommands normalizes nested command paths using resolved child configs. The resolver receives a canonical subcommand identity from a bounds map.
func (Example) AppendText ¶
AppendText appends an example in .uf syntax.
func (*Example) ClearRaw ¶ added in v0.2.0
func (e *Example) ClearRaw()
ClearRaw removes the generated raw marker while preserving the rest of the comment.
type LanguageFragment ¶ added in v0.2.0
type LanguageFragment struct {
// contains filtered or unexported fields
}
LanguageFragment stores plain and highlighted text produced for one language.
type License ¶
type License struct {
What string `json:"what,omitempty,omitzero"` // what the license is for
Name string `json:"name,omitempty,omitzero"` // name of the licenseholder
Year int `json:"year,omitempty,omitzero"` // year of the license
Ref string `json:"text,omitempty,omitzero"` // human-readable text of the license: keep it short.
WhatURL *url.URL `json:"url,omitempty,omitzero"` // optional: specific URL for the license: like https://gitlab.com/efronlicht/uf/-/blob/master/LICENSE.md
RefURL *url.URL `json:"ref_url,omitempty,omitzero"` // optional: reference URL for the license: i.e, https://opensource.org/licenses/BSD-3-Clause for the BSD 3-Clause License
}
License represents the license information for the application.
type Location ¶ added in v0.2.0
type Location = parseerror.Location
Location identifies a byte offset in source text
type Parent ¶
type Parent struct {
Name string `json:"name,omitempty,omitzero"` // parent command name.
Alias string `json:"alias,omitempty,omitzero"` // alias used to invoke the parent.
}
Parent identifies the command and alias that invoke an application as a subcmd.
type ParseError ¶
type ParseError = parseerror.Error // ParseError associates an error with a byte offset in source text.
type PositionalRepeatError ¶
type PositionalRepeatError struct {
Name string // the name of the positional argument
Source Source // the source of the positional argument (ARG1, ..., ARG9)
Repeat Repeat // the repeat constraint for the positional argument (0, '*', '+', '?')
}
PositionalRepeatError reports a * or + repeat on a nonterminal positional argument.
func (*PositionalRepeatError) Error ¶
func (e *PositionalRepeatError) Error() string
Error describes an invalid repeat marker on a positional argument.
type Repeat ¶
type Repeat byte
Repeat controls how many values a declaration accepts: exactly one, ?, *, or +.
string* -> REPEAT_MANY
const ( // REPEAT_EXACTLY_ONCE is the zero value and requires one value. REPEAT_EXACTLY_ONCE Repeat = 0 // REPEAT_MANY allows zero or more values. REPEAT_MANY Repeat = '*' // REPEAT_AT_LEAST_ONE requires one or more values. REPEAT_AT_LEAST_ONE Repeat = '+' // REPEAT_OPTIONAL allows zero or one value. REPEAT_OPTIONAL Repeat = '?' )
type Source ¶
type Source = string
Source identifies whether a declaration is a flag, environment variable, or positional argument.
const ( ARG0 Source = "arg0" ARG1 Source = "arg1" ARG2 Source = "arg2" ARG3 Source = "arg3" ARG4 Source = "arg4" ARG5 Source = "arg5" ARG6 Source = "arg6" ARG7 Source = "arg7" ARG8 Source = "arg8" ARG9 Source = "arg9" ENV Source = "env" FLAG Source = "flag" )
flag, env, arg1..=arg9 begin variable declarations
type SubcommandDeclarationError ¶
type SubcommandDeclarationError struct {
Name string // the name of the subcommand
Source Source // the source of the subcommand (ARG1, ..., ARG9)
Rule string // the rule that was violated for the subcommand declaration
}
SubcommandDeclarationError reports an invalid subcommand positional declaration.
func (*SubcommandDeclarationError) Error ¶
func (e *SubcommandDeclarationError) Error() string
Error formats the violated rule for an invalid subcommand declaration.
type TextSpan ¶
TextSpan represents a span of text within a source file, including its start and end positions.
type Token ¶
type Token struct {
Start, End int // byte range in the source text.
TokenType TokenType // lexical category.
}
Token is one lexical item and its byte range in the source.
Lex("flag") -> Token{Start: 0, End: 4, ...}
func AppendLex ¶
AppendLex appends the lexical prefix of raw to tokens and returns the first lexical error.
func Lex ¶
Lex returns the lexical prefix even when raw contains an invalid or unterminated token.
Example ¶
ExampleLex returns the lexical prefix of a declaration.
raw := "flag -count int = 2 # some comment"
tokens, err := Lex(raw)
if err != nil {
panic(err)
}
for _, token := range tokens {
fmt.Printf("%d %d %c %q\n", token.Start, token.End, rune(token.TokenType), raw[token.Start:token.End])
}
Output: 0 4 s "flag" 5 11 s "-count" 12 15 s "int" 16 17 = "=" 18 19 s "2" 20 21 # "#" 22 26 c "some" 27 34 c "comment"
type TokenType ¶
type TokenType int
TokenType identifies one lexical item in UF syntax.
const ( T_UNKNOWN TokenType = 0 T_COLON TokenType = ':' T_COMMENT_CONTENTS TokenType = 'c' // after '#', before '\n' T_COMMENT_START TokenType = '#' // unquoted '#' starts a comment T_EQUALS TokenType = '=' // unquoted '=' starts a default T_NEWLINE TokenType = 'n' // newline character '\n' T_PATTERN_START TokenType = '~' // unquoted '~' starts a pattern in a bounds T_QUOTE_START TokenType = 'q' // unquoted '"' starts a quoted string T_QUOTED_STRING TokenType = 'S' // contents of a quoted string T_EMPTY_STRING TokenType = 'e' // empty string literal "" T_RANGE TokenType = '.' // range marker in bounds T_REPEAT_PLUS TokenType = '+' // repetition marker '+' (one or more) T_REPEAT_STAR TokenType = '*' // repetition marker '*' (zero or more) T_REPEAT_OPTIONAL TokenType = '?' // repetition marker '?' (zero or one) T_SQUAREBRACKET_END TokenType = ']' // closing square bracket (ends bounds or subcommand) T_SQUAREBRACKET_START TokenType = '[' // opening square bracket (starts bounds or subcommand) T_UNQUOTED_STRING TokenType = 's' // unquoted string (declaration kind, name, or value) )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package ac generates shell argument-completion scripts.
|
Package ac generates shell argument-completion scripts. |
|
cmd
|
|
|
cookreadme
command
|
|
|
incrversion
command
incrversion increments the version in a JSON object.
|
incrversion increments the version in a JSON object. |
|
juf
command
juf is a command-line utility for evaluating uf configurations in JSON format.
|
juf is a command-line utility for evaluating uf configurations in JSON format. |
|
randfuzz
command
Command randfuzz generates randomized fuzz inputs for uf parsers.
|
Command randfuzz generates randomized fuzz inputs for uf parsers. |
|
uf
command
Command uf is the toolchain for managing and executing uf subcmds, including: // try `uf list` to see available subcmds, then uf <subcmd> -h for help about a specific subcmd.
|
Command uf is the toolchain for managing and executing uf subcmds, including: // try `uf list` to see available subcmds, then uf <subcmd> -h for help about a specific subcmd. |
|
ufborrow
command
|
|
|
ufclean
command
|
|
|
ufcomplete
command
|
|
|
ufcomplete/ufcompletecli
Command ufcomplete generates standalone shell completion entries from .uf files.
|
Command ufcomplete generates standalone shell completion entries from .uf files. |
|
ufexplain
command
|
|
|
uffmt
command
|
|
|
ufgen
command
|
|
|
ufgen-bootstrap
command
Command ufgen-bootstrap regenerates parser and example sources without the generated ufgen CLI.
|
Command ufgen-bootstrap regenerates parser and example sources without the generated ufgen CLI. |
|
ufgen/examples/go
command
Command grep is a generated example command for searching files.
|
Command grep is a generated example command for searching files. |
|
ufgen/ufgencli
Command ufgen generates source code from uf command specifications.
|
Command ufgen generates source code from uf command specifications. |
|
ufgrammargen
command
Command ufgrammargen generates uf grammar source files.
|
Command ufgrammargen generates uf grammar source files. |
|
ufimport
command
|
|
|
ufinit
command
|
|
|
ufinstalltldr
command
|
|
|
uflend
command
|
|
|
ufls
command
|
|
|
ufmcp
command
Command ufmcp runs the UF MCP server as a standalone stdio process.
|
Command ufmcp runs the UF MCP server as a standalone stdio process. |
|
ufneighborsgen
command
Command ufneighborsgen generates neighboring parser states.
|
Command ufneighborsgen generates neighboring parser states. |
|
ufsyntax
command
|
|
|
ufsyntax/ufsyntaxcli
Command ufsyntax generates the Sublime syntax definition for .uf files.
|
Command ufsyntax generates the Sublime syntax definition for .uf files. |
|
Package highlight applies the embedded uf syntax with Chroma.
|
Package highlight applies the embedded uf syntax with Chroma. |
|
internal
|
|
|
Package man renders uf command specifications as man pages.
|
Package man renders uf command specifications as man pages. |
|
Package sublime generates Sublime Text syntax definitions from ABNF and EBNF grammars.
|
Package sublime generates Sublime Text syntax definitions from ABNF and EBNF grammars. |
|
Package syntax embeds the generated uf syntax definition.
|
Package syntax embeds the generated uf syntax definition. |
|
Package ufexplain explains uf command specifications.
|
Package ufexplain explains uf command specifications. |
|
Package ufgen generates source code from uf configuration files.
|
Package ufgen generates source code from uf configuration files. |
|
Package ufls implements the uf language server used by the VS Code extension.
|
Package ufls implements the uf language server used by the VS Code extension. |














