Documentation
¶
Overview ¶
Package argwild parses command lines into a reusable, structured form.
argwild is built around three ideas:
Switches. A switch is an option token led by "-" (short, single-character name), "--" (long name), or "+" (a value-only or short-style token, used for things like the "+32" line-number convention). Every switch records whether it was bare, explicitly turned on ("-o+"), explicitly turned off ("-o-"), or given one or more values.
Operands. Any positional token that is not a switch. Operands act as phase dividers, ffmpeg-style: global switches, an operand, switches that apply to the next phase, another operand, and so on.
Stanzas. The parse result is an ordered sequence of stanzas. Each stanza is either an ArgSet (a run of consecutive switches) or an Operand. Order is preserved exactly; argwild stays neutral about whether an ArgSet binds to the operand before or after it — that is the caller's decision.
A switch value may be a bare word, a quoted string, a number, or a PSL block written in parentheses. PSL (PawScript Serialized List) blocks are parsed with the pawscript library, and the entire parse tree can be handed back to pawscript for serialization via Result.ToPSL and Result.ToPSLString.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ArgSet ¶
type ArgSet struct {
Switches []Switch
}
ArgSet is a run of consecutive switches with no operand between them.
type Lead ¶
type Lead int
Lead identifies which introducer began a switch.
const ( // LeadShort is a single dash: "-o". The name is exactly one character and // everything after it attaches as a value. LeadShort Lead = iota // LeadLong is a double dash: "--option". The name may be multiple // characters; values attach via "=", a space (for quoted/numeric values), // or an immediately following quote or PSL block. LeadLong // LeadPlus is a plus sign: "+". When followed by a digit the name is empty // and the digits are a value (the "+32" line-number form). When followed by // a letter it behaves like a short switch: "+x=4". LeadPlus )
type ParseError ¶
ParseError describes a failure to parse a command line, with the rune offset at which the problem was detected.
func (*ParseError) Error ¶
func (e *ParseError) Error() string
type Result ¶
type Result struct {
Stanzas []Stanza
}
Result is the top-level parse output: an ordered sequence of stanzas.
func Parse ¶
Parse parses the current process's command-line arguments (os.Args without the program name) into a Result. It is equivalent to ParseArgs(os.Args[1:]).
func ParseArgs ¶
ParseArgs parses an already-split argument vector, such as os.Args[1:].
Each element is an atomic token: elements containing whitespace are re-quoted so the parser treats them as single quoted values, reconstructing an equivalent command line before applying the full grammar. This means the spacing rules still apply across elements — for example ParseArgs([]string{ "-o", "12"}) binds 12 to -o (space before a numeric value binds), while ParseArgs([]string{"-o", "NotThis"}) leaves -o bare and NotThis an operand (space before a bare word does not bind).
For complete control over quoting and spacing, parse a raw string with ParseString instead.
func ParseString ¶
ParseString parses a raw command-line string into a Result.
This is the full-fidelity entry point: it understands quoting, the spacing rules, comma-chained values, and parenthesized PSL blocks directly from the text, so it is the right choice for command lines a user typed into a prompt.
Example ¶
ExampleParseString shows the ffmpeg-style stanza decomposition: global switches, an operand, phase switches, another operand.
package main
import (
"fmt"
"github.com/phroun/argwild"
)
func main() {
r, err := argwild.ParseString(`--verbose -o=2 input.mp4 --codec=x264 output.mp4`)
if err != nil {
panic(err)
}
for _, st := range r.Stanzas {
fmt.Println(st)
}
}
Output: args[--verbose -o=2] operand(input.mp4) args[--codec=x264] operand(output.mp4)
func (*Result) Operands ¶
Operands returns every operand in order, ignoring argument sets. This is a convenience for callers that only care about the phase dividers.
func (*Result) ToPSL ¶
ToPSL converts the whole parse result into a pawscript PSLList so it can be serialized with pawscript's PSL serializer and reparsed losslessly.
The shape is an ordered list of stanza maps:
operand stanza: (kind: "operand", value: <value>) arg-set stanza: (kind: "args", switches: (<switch>, <switch>, ...))
Each switch is:
(lead: "-"|"--"|"+", name: <string>, state: "bare"|"on"|"off"|"valued", values: (<value>, ...))
Values become plain PSL scalars (string / int64 / float64) or, for PSL-block arguments, the nested PSL structure itself.
func (*Result) ToPSLString ¶
ToPSLString serializes the parse result to a PSL string. When pretty is true the output is indented across multiple lines.
Example ¶
ExampleResult_ToPSLString shows the whole parse serialized to PSL, ready to hand back to the pawscript library.
package main
import (
"fmt"
"github.com/phroun/argwild"
)
func main() {
r, _ := argwild.ParseString(`+32 file.txt -o "a, b", 3`)
fmt.Println(r.ToPSLString(false))
}
Output: ((kind: "args", switches: ((lead: "+", name: "", state: "valued", values: (32)))), (kind: "operand", value: "file.txt"), (kind: "args", switches: ((lead: "-", name: "o", state: "valued", values: ("a, b", 3)))))
type Stanza ¶
type Stanza interface {
// String renders the stanza for debugging.
String() string
// contains filtered or unexported methods
}
Stanza is one element of a parse result: either an *ArgSet or an *Operand. Use a type switch to distinguish them.
type State ¶
type State int
State describes how a switch was written with respect to on/off/value.
const ( // StateBare is a switch with no polarity marker and no value: "-o". StateBare State = iota // StateOn is an explicitly enabled switch: "-o+". StateOn // StateOff is an explicitly disabled switch: "-o-". StateOff // StateValued is a switch carrying one or more values. Values is non-empty. StateValued )
type Switch ¶
type Switch struct {
Lead Lead
Name string // "o", "option", or "" for the "+32" value-only form.
State State
Values []Value
}
Switch is a single parsed option.
Example ¶
ExampleSwitch shows inspecting on/off/bare state and typed values.
package main
import (
"fmt"
"github.com/phroun/argwild"
)
func main() {
r, _ := argwild.ParseString(`-a -b+ -c- -d=5`)
for _, sw := range r.ArgSets()[0].Switches {
switch {
case sw.IsOn():
fmt.Printf("%s: on\n", sw.Name)
case sw.IsOff():
fmt.Printf("%s: off\n", sw.Name)
case sw.HasValues():
v, _ := sw.First()
fmt.Printf("%s: value %s\n", sw.Name, v.AsString())
default:
fmt.Printf("%s: bare\n", sw.Name)
}
}
}
Output: a: bare b: on c: off d: value 5
type Value ¶
type Value struct {
Kind ValueKind
// Text holds the literal text for KindBare and KindQuoted values (without
// the surrounding quotes), and the original source spelling for KindNumber.
Text string
// Int and Float hold the parsed number when Kind == KindNumber. IsFloat
// reports which one is authoritative.
Int int64
Float float64
IsFloat bool
// PSL holds the parsed PSL structure when Kind == KindPSL. It is a
// pawscript PSLList or PSLMap (both are Go maps/slices of interface{}), so
// it embeds directly into a serialized parse tree.
PSL interface{}
}
Value is a single argument value attached to a switch or standing alone as an operand.
func (Value) AsString ¶
AsString returns a human-readable rendering of the value. For PSL blocks it returns the block's serialized form.
type ValueKind ¶
type ValueKind int
ValueKind identifies the lexical form of a Value.
const ( // KindBare is an unquoted, non-numeric word: the "Arg" in "-oArg". KindBare ValueKind = iota // KindQuoted is a quoted string: the "Quoted Arg" in `-o"Quoted Arg"`. KindQuoted // KindNumber is an integer or floating-point literal: the 12 in "-o12". KindNumber // KindPSL is a parenthesized PSL block, parsed into PSL. The parsed result // is stored in Value.PSL. KindPSL )