Add support for "event"-like interface to parsing

and drop the querier
pull/1/head
Dan Buch 2 years ago
parent c93d1cd4f0
commit b97681c710
Signed by: meatballhat
GPG Key ID: A12F782281063434

@ -1,3 +1,5 @@
BENCHTIME ?= 10s
.PHONY: all .PHONY: all
all: test all: test
@ -9,6 +11,10 @@ clean:
test: test:
go test -v -coverprofile=coverage.out ./... go test -v -coverprofile=coverage.out ./...
.PHONY: bench
bench:
go test -v -bench . -benchtime $(BENCHTIME) ./...
.PHONY: show-cover .PHONY: show-cover
show-cover: show-cover:
go tool cover -func=coverage.out go tool cover -func=coverage.out

@ -20,6 +20,7 @@ library [parser](https://pkg.go.dev/go/parser).
- support both POSIX-y and Windows-y styles - support both POSIX-y and Windows-y styles
- build a printable/JSON-able parse tree - build a printable/JSON-able parse tree
- support rich error reporting - support rich error reporting
- support event-like reactive parsing
<!-- <!--
vim:tw=90 vim:tw=90

@ -1,6 +1,7 @@
package argh package argh
import ( import (
"errors"
"fmt" "fmt"
"log" "log"
"os" "os"
@ -11,6 +12,8 @@ import (
var ( var (
tracingEnabled = os.Getenv("ARGH_TRACING") == "enabled" tracingEnabled = os.Getenv("ARGH_TRACING") == "enabled"
traceLogger *log.Logger traceLogger *log.Logger
Error = errors.New("argh error")
) )
func init() { func init() {

@ -3,12 +3,26 @@ package argh_test
import ( import (
"flag" "flag"
"fmt" "fmt"
"strconv"
"testing" "testing"
"time" "time"
"git.meatballhat.com/x/argh" "git.meatballhat.com/x/argh"
) )
func ptrTo[T any](v T) *T {
return &v
}
func ptrFrom[T any](v *T) T {
if v != nil {
return *v
}
var zero T
return zero
}
func BenchmarkStdlibFlag(b *testing.B) { func BenchmarkStdlibFlag(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
func() { func() {
@ -22,7 +36,16 @@ func BenchmarkStdlibFlag(b *testing.B) {
uFlag := fl.Uint("u", 11, "") uFlag := fl.Uint("u", 11, "")
u64Flag := fl.Uint64("u64", 11111111111111111111, "") u64Flag := fl.Uint64("u64", 11111111111111111111, "")
_ = fl.Parse([]string{}) _ = fl.Parse([]string{
"-ok",
"-dur", "42h42m10s",
"-f64", "4242424242.42",
"-i", "-42",
"-i64", "-4242424242",
"-s", "the answer",
"-u", "42",
"-u64", "4242424242",
})
_ = fmt.Sprint( _ = fmt.Sprint(
"fl", fl, "fl", fl,
"okFlag", *okFlag, "okFlag", *okFlag,
@ -41,23 +64,118 @@ func BenchmarkStdlibFlag(b *testing.B) {
func BenchmarkArgh(b *testing.B) { func BenchmarkArgh(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
func() { func() {
var (
okFlag *bool
durFlag *time.Duration
f64Flag *float64
iFlag *int
i64Flag *int64
sFlag *string
uFlag *uint
u64Flag *uint64
)
pCfg := argh.NewParserConfig() pCfg := argh.NewParserConfig()
pCfg.Prog = &argh.CommandConfig{ pCfg.Prog = &argh.CommandConfig{
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"ok": {}, "ok": {
"dur": {}, On: func(fl argh.Flag) {
"f64": {}, okFlag = ptrTo(true)
"i": {}, },
"i64": {}, },
"s": {}, "dur": {
"u": {}, NValue: 1,
"u64": {}, On: func(fl argh.Flag) {
if v, ok := fl.Values["0"]; ok {
if pt, err := time.ParseDuration(v); err != nil {
durFlag = ptrTo(pt)
}
}
},
},
"f64": {
NValue: 1,
On: func(fl argh.Flag) {
if v, ok := fl.Values["0"]; ok {
if f, err := strconv.ParseFloat(v, 64); err == nil {
f64Flag = ptrTo(f)
}
}
},
},
"i": {
NValue: 1,
On: func(fl argh.Flag) {
if v, ok := fl.Values["0"]; ok {
if i, err := strconv.ParseInt(v, 10, 64); err == nil {
iFlag = ptrTo(int(i))
}
}
},
},
"i64": {
NValue: 1,
On: func(fl argh.Flag) {
if v, ok := fl.Values["0"]; ok {
if i, err := strconv.ParseInt(v, 10, 64); err == nil {
i64Flag = ptrTo(i)
}
}
},
},
"s": {
NValue: 1,
On: func(fl argh.Flag) {
if v, ok := fl.Values["0"]; ok {
sFlag = ptrTo(v)
}
},
},
"u": {
NValue: 1,
On: func(fl argh.Flag) {
if v, ok := fl.Values["0"]; ok {
if u, err := strconv.ParseUint(v, 10, 64); err == nil {
uFlag = ptrTo(uint(u))
}
}
},
},
"u64": {
NValue: 1,
On: func(fl argh.Flag) {
if v, ok := fl.Values["0"]; ok {
if u, err := strconv.ParseUint(v, 10, 64); err == nil {
u64Flag = ptrTo(u)
}
}
},
},
}, },
}, },
} }
_, _ = argh.ParseArgs([]string{}, pCfg) _, _ = argh.ParseArgs([]string{
"--ok",
"--dur", "42h42m10s",
"--f64", "4242424242.42",
"-i", "-42",
"--i64", "-4242424242",
"-s", "the answer",
"-u", "42",
"--u64", "4242424242",
}, pCfg)
_ = fmt.Sprint(
"okFlag", ptrFrom(okFlag),
"durFlag", ptrFrom(durFlag),
"f64Flag", ptrFrom(f64Flag),
"iFlag", ptrFrom(iFlag),
"i64Flag", ptrFrom(i64Flag),
"sFlag", ptrFrom(sFlag),
"uFlag", ptrFrom(uFlag),
"u64Flag", ptrFrom(u64Flag),
)
}() }()
} }
} }

@ -0,0 +1,69 @@
package argh
// ToAST accepts a slice of nodes as expected from ParseArgs and
// returns an AST with parse-time artifacts dropped and reorganized
// where applicable.
func ToAST(parseTree []Node) []Node {
ret := []Node{}
for i, node := range parseTree {
tracef("ToAST i=%d node type=%T", i, node)
if _, ok := node.(*ArgDelimiter); ok {
continue
}
if _, ok := node.(*StopFlag); ok {
continue
}
if v, ok := node.(*CompoundShortFlag); ok {
if v.Nodes != nil {
ret = append(ret, ToAST(v.Nodes)...)
}
continue
}
if v, ok := node.(*Command); ok {
astNodes := ToAST(v.Nodes)
if len(astNodes) == 0 {
astNodes = nil
}
ret = append(
ret,
&Command{
Name: v.Name,
Values: v.Values,
Nodes: astNodes,
})
continue
}
if v, ok := node.(*Flag); ok {
astNodes := ToAST(v.Nodes)
if len(astNodes) == 0 {
astNodes = nil
}
ret = append(
ret,
&Flag{
Name: v.Name,
Values: v.Values,
Nodes: astNodes,
},
)
continue
}
ret = append(ret, node)
}
return ret
}

@ -29,7 +29,7 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
ast := argh.NewQuerier(pt.Nodes).AST() ast := argh.ToAST(pt.Nodes)
if asJSON { if asJSON {
b, err := json.MarshalIndent(ast, "", " ") b, err := json.MarshalIndent(ast, "", " ")

@ -26,10 +26,13 @@ type ParseTree struct {
func ParseArgs(args []string, pCfg *ParserConfig) (*ParseTree, error) { func ParseArgs(args []string, pCfg *ParserConfig) (*ParseTree, error) {
p := &parser{} p := &parser{}
p.init(
if err := p.init(
strings.NewReader(strings.Join(args, string(nul))), strings.NewReader(strings.Join(args, string(nul))),
pCfg, pCfg,
) ); err != nil {
return nil, err
}
tracef("ParseArgs(...) parser=%+#v", p) tracef("ParseArgs(...) parser=%+#v", p)
@ -40,11 +43,11 @@ func (p *parser) addError(msg string) {
p.errors.Add(Position{Column: int(p.pos)}, msg) p.errors.Add(Position{Column: int(p.pos)}, msg)
} }
func (p *parser) init(r io.Reader, pCfg *ParserConfig) { func (p *parser) init(r io.Reader, pCfg *ParserConfig) error {
p.errors = ParserErrorList{} p.errors = ParserErrorList{}
if pCfg == nil { if pCfg == nil {
pCfg = POSIXyParserConfig return fmt.Errorf("nil parser config: %w", Error)
} }
p.cfg = pCfg p.cfg = pCfg
@ -52,6 +55,8 @@ func (p *parser) init(r io.Reader, pCfg *ParserConfig) {
p.s = NewScanner(r, pCfg.ScannerConfig) p.s = NewScanner(r, pCfg.ScannerConfig)
p.next() p.next()
return nil
} }
func (p *parser) parseArgs() (*ParseTree, error) { func (p *parser) parseArgs() (*ParseTree, error) {
@ -179,6 +184,13 @@ func (p *parser) parseCommand(cCfg *CommandConfig) Node {
node.Values = values node.Values = values
} }
if cCfg.On != nil {
tracef("parseCommand(...) calling command config handler for node=%+#v", node)
cCfg.On(*node)
} else {
tracef("parseCommand(...) no command config handler for node=%+#v", node)
}
tracef("parseCommand(...) returning node=%+#v", node) tracef("parseCommand(...) returning node=%+#v", node)
return node return node
} }
@ -209,12 +221,12 @@ func (p *parser) parseShortFlag(flags *Flags) Node {
flCfg, ok := flags.Get(node.Name) flCfg, ok := flags.Get(node.Name)
if !ok { if !ok {
p.addError(fmt.Sprintf("unknown flag %q", node.Name)) p.addError(fmt.Sprintf("unknown flag %[1]q", node.Name))
return node return node
} }
return p.parseConfiguredFlag(node, flCfg) return p.parseConfiguredFlag(node, flCfg, nil)
} }
func (p *parser) parseLongFlag(flags *Flags) Node { func (p *parser) parseLongFlag(flags *Flags) Node {
@ -222,48 +234,98 @@ func (p *parser) parseLongFlag(flags *Flags) Node {
flCfg, ok := flags.Get(node.Name) flCfg, ok := flags.Get(node.Name)
if !ok { if !ok {
p.addError(fmt.Sprintf("unknown flag %q", node.Name)) p.addError(fmt.Sprintf("unknown flag %[1]q", node.Name))
return node return node
} }
return p.parseConfiguredFlag(node, flCfg) return p.parseConfiguredFlag(node, flCfg, nil)
} }
func (p *parser) parseCompoundShortFlag(flags *Flags) Node { func (p *parser) parseCompoundShortFlag(flags *Flags) Node {
flagNodes := []Node{} unparsedFlags := []*Flag{}
unparsedFlagConfigs := []FlagConfig{}
withoutFlagPrefix := p.lit[1:] withoutFlagPrefix := p.lit[1:]
for i, r := range withoutFlagPrefix { for _, r := range withoutFlagPrefix {
node := &Flag{Name: string(r)} node := &Flag{Name: string(r)}
if i == len(withoutFlagPrefix)-1 { flCfg, ok := flags.Get(node.Name)
flCfg, ok := flags.Get(node.Name) if !ok {
if !ok { p.addError(fmt.Sprintf("unknown flag %[1]q", node.Name))
p.addError(fmt.Sprintf("unknown flag %q", node.Name))
continue continue
}
unparsedFlags = append(unparsedFlags, node)
unparsedFlagConfigs = append(unparsedFlagConfigs, flCfg)
}
flagNodes := []Node{}
for i, node := range unparsedFlags {
flCfg := unparsedFlagConfigs[i]
if i != len(unparsedFlags)-1 {
// NOTE: if a compound short flag is configured to accept
// more than zero values but is not the last flag in the
// group, it will be parsed with an override NValue of
// ZeroValue so that it does not consume the next token.
if flCfg.NValue.Required() {
p.addError(
fmt.Sprintf(
"short flag %[1]q before end of compound group expects value",
node.Name,
),
)
} }
flagNodes = append(flagNodes, p.parseConfiguredFlag(node, flCfg)) flagNodes = append(
flagNodes,
p.parseConfiguredFlag(node, flCfg, zeroValuePtr),
)
continue continue
} }
flagNodes = append(flagNodes, node) flagNodes = append(flagNodes, p.parseConfiguredFlag(node, flCfg, nil))
} }
return &CompoundShortFlag{Nodes: flagNodes} return &CompoundShortFlag{Nodes: flagNodes}
} }
func (p *parser) parseConfiguredFlag(node *Flag, flCfg FlagConfig) Node { func (p *parser) parseConfiguredFlag(node *Flag, flCfg FlagConfig, nValueOverride *NValue) Node {
values := map[string]string{} values := map[string]string{}
nodes := []Node{} nodes := []Node{}
atExit := func() *Flag {
if len(nodes) > 0 {
node.Nodes = nodes
}
if len(values) > 0 {
node.Values = values
}
if flCfg.On != nil {
tracef("parseConfiguredFlag(...) calling flag config handler for node=%+#[1]v", node)
flCfg.On(*node)
} else {
tracef("parseConfiguredFlag(...) no flag config handler for node=%+#[1]v", node)
}
return node
}
identIndex := 0 identIndex := 0
for i := 0; p.tok != EOL; i++ { for i := 0; p.tok != EOL; i++ {
if nValueOverride != nil && !(*nValueOverride).Contains(identIndex) {
tracef("parseConfiguredFlag(...) identIndex=%d exceeds expected=%v; breaking", identIndex, *nValueOverride)
break
}
if !flCfg.NValue.Contains(identIndex) { if !flCfg.NValue.Contains(identIndex) {
tracef("parseConfiguredFlag(...) identIndex=%d exceeds expected=%v; breaking", identIndex, flCfg.NValue) tracef("parseConfiguredFlag(...) identIndex=%d exceeds expected=%v; breaking", identIndex, flCfg.NValue)
break break
@ -308,27 +370,11 @@ func (p *parser) parseConfiguredFlag(node *Flag, flCfg FlagConfig) Node {
tracef("parseConfiguredFlag(...) breaking on %s %q %v; setting buffered=true", p.tok, p.lit, p.pos) tracef("parseConfiguredFlag(...) breaking on %s %q %v; setting buffered=true", p.tok, p.lit, p.pos)
p.buffered = true p.buffered = true
if len(nodes) > 0 { return atExit()
node.Nodes = nodes
}
if len(values) > 0 {
node.Values = values
}
return node
} }
} }
if len(nodes) > 0 { return atExit()
node.Nodes = nodes
}
if len(values) > 0 {
node.Values = values
}
return node
} }
func (p *parser) parsePassthrough() Node { func (p *parser) parsePassthrough() Node {

@ -7,11 +7,22 @@ const (
) )
var ( var (
POSIXyParserConfig = NewParserConfig() zeroValuePtr = func() *NValue {
v := ZeroValue
return &v
}()
) )
type NValue int type NValue int
func (nv NValue) Required() bool {
if nv == OneOrMoreValue {
return true
}
return int(nv) >= 1
}
func (nv NValue) Contains(i int) bool { func (nv NValue) Contains(i int) bool {
tracef("NValue.Contains(%v)", i) tracef("NValue.Contains(%v)", i)
@ -60,6 +71,8 @@ type CommandConfig struct {
ValueNames []string ValueNames []string
Flags *Flags Flags *Flags
Commands *Commands Commands *Commands
On func(Command)
} }
func (cCfg *CommandConfig) init() { func (cCfg *CommandConfig) init() {
@ -100,6 +113,8 @@ type FlagConfig struct {
NValue NValue NValue NValue
Persist bool Persist bool
ValueNames []string ValueNames []string
On func(Flag)
} }
type Flags struct { type Flags struct {

@ -9,6 +9,14 @@ import (
) )
func TestParser(t *testing.T) { func TestParser(t *testing.T) {
traceOnFlag := func(fl argh.Flag) {
t.Logf("Flag.On: %+#[1]v", fl)
}
traceOnCommand := func(cmd argh.Command) {
t.Logf("Command.On: %+#[1]v", cmd)
}
for _, tc := range []struct { for _, tc := range []struct {
name string name string
args []string args []string
@ -27,10 +35,10 @@ func TestParser(t *testing.T) {
Prog: &argh.CommandConfig{ Prog: &argh.CommandConfig{
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"e": {}, "e": {On: traceOnFlag},
"a": {}, "a": {On: traceOnFlag},
"t": {}, "t": {On: traceOnFlag},
"wat": {}, "wat": {On: traceOnFlag},
}, },
}, },
Commands: &argh.Commands{ Commands: &argh.Commands{
@ -38,9 +46,11 @@ func TestParser(t *testing.T) {
"hello": argh.CommandConfig{ "hello": argh.CommandConfig{
NValue: 1, NValue: 1,
ValueNames: []string{"name"}, ValueNames: []string{"name"},
On: traceOnCommand,
}, },
}, },
}, },
On: traceOnCommand,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
@ -102,12 +112,13 @@ func TestParser(t *testing.T) {
cmdCfg := &argh.CommandConfig{ cmdCfg := &argh.CommandConfig{
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"e": {Persist: true}, "e": {Persist: true, On: traceOnFlag},
"a": {Persist: true}, "a": {Persist: true, On: traceOnFlag},
"t": {Persist: true}, "t": {Persist: true, On: traceOnFlag},
"wat": {}, "wat": {On: traceOnFlag},
}, },
}, },
On: traceOnCommand,
} }
cmdCfg.Commands = &argh.Commands{ cmdCfg.Commands = &argh.Commands{
@ -119,6 +130,7 @@ func TestParser(t *testing.T) {
Parent: cmdCfg.Flags, Parent: cmdCfg.Flags,
Map: map[string]argh.FlagConfig{}, Map: map[string]argh.FlagConfig{},
}, },
On: traceOnCommand,
}, },
}, },
} }
@ -193,7 +205,7 @@ func TestParser(t *testing.T) {
name: "one positional arg", name: "one positional arg",
args: []string{"pizzas", "excel"}, args: []string{"pizzas", "excel"},
cfg: &argh.ParserConfig{ cfg: &argh.ParserConfig{
Prog: &argh.CommandConfig{NValue: 1}, Prog: &argh.CommandConfig{NValue: 1, On: traceOnCommand},
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.Command{ &argh.Command{
@ -222,6 +234,7 @@ func TestParser(t *testing.T) {
Prog: &argh.CommandConfig{ Prog: &argh.CommandConfig{
NValue: argh.OneOrMoreValue, NValue: argh.OneOrMoreValue,
ValueNames: []string{"word"}, ValueNames: []string{"word"},
On: traceOnCommand,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
@ -270,11 +283,12 @@ func TestParser(t *testing.T) {
Prog: &argh.CommandConfig{ Prog: &argh.CommandConfig{
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"tasty": {}, "tasty": {On: traceOnFlag},
"fresh": {}, "fresh": {On: traceOnFlag},
"super-hot-right-now": {}, "super-hot-right-now": {On: traceOnFlag},
}, },
}, },
On: traceOnCommand,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
@ -316,13 +330,14 @@ func TestParser(t *testing.T) {
Commands: &argh.Commands{Map: map[string]argh.CommandConfig{}}, Commands: &argh.Commands{Map: map[string]argh.CommandConfig{}},
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"tasty": {}, "tasty": {On: traceOnFlag},
"fresh": argh.FlagConfig{NValue: 1}, "fresh": argh.FlagConfig{NValue: 1, On: traceOnFlag},
"super-hot-right-now": {}, "super-hot-right-now": {On: traceOnFlag},
"box": argh.FlagConfig{NValue: argh.OneOrMoreValue}, "box": argh.FlagConfig{NValue: argh.OneOrMoreValue, On: traceOnFlag},
"please": {}, "please": {On: traceOnFlag},
}, },
}, },
On: traceOnCommand,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
@ -394,11 +409,12 @@ func TestParser(t *testing.T) {
Prog: &argh.CommandConfig{ Prog: &argh.CommandConfig{
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"t": {}, "t": {On: traceOnFlag},
"f": {}, "f": {On: traceOnFlag},
"s": {}, "s": {On: traceOnFlag},
}, },
}, },
On: traceOnCommand,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
@ -432,13 +448,14 @@ func TestParser(t *testing.T) {
Prog: &argh.CommandConfig{ Prog: &argh.CommandConfig{
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"a": {}, "a": {On: traceOnFlag},
"b": {}, "b": {On: traceOnFlag},
"c": {}, "c": {On: traceOnFlag},
"l": {}, "l": {On: traceOnFlag},
"o": {}, "o": {On: traceOnFlag},
}, },
}, },
On: traceOnCommand,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
@ -488,13 +505,14 @@ func TestParser(t *testing.T) {
Commands: &argh.Commands{Map: map[string]argh.CommandConfig{}}, Commands: &argh.Commands{Map: map[string]argh.CommandConfig{}},
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"a": {}, "a": {On: traceOnFlag},
"b": argh.FlagConfig{NValue: 1}, "b": argh.FlagConfig{NValue: 1, On: traceOnFlag},
"ca": {}, "ca": {On: traceOnFlag},
"l": {}, "l": {On: traceOnFlag},
"o": {}, "o": {On: traceOnFlag},
}, },
}, },
On: traceOnCommand,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
@ -558,7 +576,7 @@ func TestParser(t *testing.T) {
"fry": argh.CommandConfig{ "fry": argh.CommandConfig{
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"forever": {}, "forever": {On: traceOnFlag},
}, },
}, },
}, },
@ -568,6 +586,7 @@ func TestParser(t *testing.T) {
}, },
}, },
Flags: &argh.Flags{Map: map[string]argh.FlagConfig{}}, Flags: &argh.Flags{Map: map[string]argh.FlagConfig{}},
On: traceOnCommand,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
@ -635,15 +654,16 @@ func TestParser(t *testing.T) {
Prog: &argh.CommandConfig{ Prog: &argh.CommandConfig{
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"a": {NValue: argh.ZeroOrMoreValue}, "a": {NValue: argh.ZeroOrMoreValue, On: traceOnFlag},
"d": {NValue: argh.OneOrMoreValue}, "d": {NValue: argh.OneOrMoreValue, On: traceOnFlag},
"e": {}, "e": {On: traceOnFlag},
"l": {}, "l": {On: traceOnFlag},
"n": {}, "n": {On: traceOnFlag},
"o": {NValue: 1, ValueNames: []string{"level"}}, "o": {NValue: 1, ValueNames: []string{"level"}, On: traceOnFlag},
"s": {NValue: argh.ZeroOrMoreValue}, "s": {NValue: argh.ZeroOrMoreValue, On: traceOnFlag},
}, },
}, },
On: traceOnCommand,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
@ -741,7 +761,7 @@ func TestParser(t *testing.T) {
"fly": argh.CommandConfig{ "fly": argh.CommandConfig{
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"freely": {}, "freely": {On: traceOnFlag},
}, },
}, },
Commands: &argh.Commands{ Commands: &argh.Commands{
@ -749,10 +769,10 @@ func TestParser(t *testing.T) {
"fry": argh.CommandConfig{ "fry": argh.CommandConfig{
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"deeply": {}, "deeply": {On: traceOnFlag},
"w": {}, "w": {On: traceOnFlag},
"A": {}, "A": {On: traceOnFlag},
"t": argh.FlagConfig{NValue: 1}, "t": argh.FlagConfig{NValue: 1, On: traceOnFlag},
}, },
}, },
}, },
@ -762,6 +782,7 @@ func TestParser(t *testing.T) {
}, },
}, },
Flags: &argh.Flags{Map: map[string]argh.FlagConfig{}}, Flags: &argh.Flags{Map: map[string]argh.FlagConfig{}},
On: traceOnCommand,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
@ -842,7 +863,7 @@ func TestParser(t *testing.T) {
NValue: 1, NValue: 1,
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"FIERCENESS": argh.FlagConfig{NValue: 1}, "FIERCENESS": argh.FlagConfig{NValue: 1, On: traceOnFlag},
}, },
}, },
}, },
@ -850,12 +871,13 @@ func TestParser(t *testing.T) {
}, },
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"w": argh.FlagConfig{}, "w": {On: traceOnFlag},
"A": argh.FlagConfig{}, "A": {On: traceOnFlag},
"T": argh.FlagConfig{NValue: 1}, "T": {NValue: 1, On: traceOnFlag},
"hecKing": argh.FlagConfig{}, "hecKing": {On: traceOnFlag},
}, },
}, },
On: traceOnCommand,
}, },
ScannerConfig: &argh.ScannerConfig{ ScannerConfig: &argh.ScannerConfig{
AssignmentOperator: '@', AssignmentOperator: '@',
@ -913,9 +935,9 @@ func TestParser(t *testing.T) {
Prog: &argh.CommandConfig{ Prog: &argh.CommandConfig{
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"f": {}, "f": {On: traceOnFlag},
"L": {}, "L": {On: traceOnFlag},
"o": argh.FlagConfig{NValue: 1}, "o": argh.FlagConfig{NValue: 1, On: traceOnFlag},
}, },
}, },
Commands: &argh.Commands{ Commands: &argh.Commands{
@ -923,6 +945,7 @@ func TestParser(t *testing.T) {
"hats": {}, "hats": {},
}, },
}, },
On: traceOnCommand,
}, },
ScannerConfig: &argh.ScannerConfig{ ScannerConfig: &argh.ScannerConfig{
AssignmentOperator: ':', AssignmentOperator: ':',
@ -960,9 +983,10 @@ func TestParser(t *testing.T) {
Prog: &argh.CommandConfig{ Prog: &argh.CommandConfig{
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"wat": {}, "wat": {On: traceOnFlag},
}, },
}, },
On: traceOnCommand,
}, },
}, },
expErr: argh.ParserErrorList{ expErr: argh.ParserErrorList{
@ -987,7 +1011,12 @@ func TestParser(t *testing.T) {
return return
} }
pt, err := argh.ParseArgs(tc.args, tc.cfg) pCfg := tc.cfg
if pCfg == nil {
pCfg = argh.NewParserConfig()
}
pt, err := argh.ParseArgs(tc.args, pCfg)
if err != nil || tc.expErr != nil { if err != nil || tc.expErr != nil {
if !assert.ErrorIs(ct, err, tc.expErr) { if !assert.ErrorIs(ct, err, tc.expErr) {
spew.Dump(err, tc.expErr) spew.Dump(err, tc.expErr)
@ -1009,7 +1038,12 @@ func TestParser(t *testing.T) {
return return
} }
pt, err := argh.ParseArgs(tc.args, tc.cfg) pCfg := tc.cfg
if pCfg == nil {
pCfg = argh.NewParserConfig()
}
pt, err := argh.ParseArgs(tc.args, pCfg)
if err != nil || tc.expErr != nil { if err != nil || tc.expErr != nil {
if !assert.ErrorIs(ct, err, tc.expErr) { if !assert.ErrorIs(ct, err, tc.expErr) {
spew.Dump(pt) spew.Dump(pt)
@ -1017,7 +1051,7 @@ func TestParser(t *testing.T) {
return return
} }
ast := argh.NewQuerier(pt.Nodes).AST() ast := argh.ToAST(pt.Nodes)
if !assert.Equal(ct, tc.expAST, ast) { if !assert.Equal(ct, tc.expAST, ast) {
spew.Dump(ast) spew.Dump(ast)

@ -1,94 +0,0 @@
package argh
type Querier interface {
Program() (*Command, bool)
AST() []Node
}
func NewQuerier(nodes []Node) Querier {
return &defaultQuerier{nodes: nodes}
}
type defaultQuerier struct {
nodes []Node
}
func (dq *defaultQuerier) Program() (*Command, bool) {
if len(dq.nodes) == 0 {
tracef("Program nodes are empty")
return nil, false
}
tracef("Program node[0] is %T", dq.nodes[0])
v, ok := dq.nodes[0].(*Command)
if ok && v.Name == "" {
return v, false
}
return v, ok
}
func (dq *defaultQuerier) AST() []Node {
ret := []Node{}
for i, node := range dq.nodes {
tracef("AST i=%d node type=%T", i, node)
if _, ok := node.(*ArgDelimiter); ok {
continue
}
if _, ok := node.(*StopFlag); ok {
continue
}
if v, ok := node.(*CompoundShortFlag); ok {
if v.Nodes != nil {
ret = append(ret, NewQuerier(v.Nodes).AST()...)
}
continue
}
if v, ok := node.(*Command); ok {
astNodes := NewQuerier(v.Nodes).AST()
if len(astNodes) == 0 {
astNodes = nil
}
ret = append(
ret,
&Command{
Name: v.Name,
Values: v.Values,
Nodes: astNodes,
})
continue
}
if v, ok := node.(*Flag); ok {
astNodes := NewQuerier(v.Nodes).AST()
if len(astNodes) == 0 {
astNodes = nil
}
ret = append(
ret,
&Flag{
Name: v.Name,
Values: v.Values,
Nodes: astNodes,
})
continue
}
ret = append(ret, node)
}
return ret
}

@ -1,60 +0,0 @@
package argh_test
import (
"testing"
"git.meatballhat.com/x/argh"
"github.com/stretchr/testify/require"
)
func TestQuerier_Program(t *testing.T) {
for _, tc := range []struct {
name string
args []string
cfg *argh.ParserConfig
exp string
expOK bool
}{
{
name: "typical",
args: []string{"pizzas", "ahoy", "--treatsa", "fun"},
cfg: &argh.ParserConfig{
Prog: &argh.CommandConfig{
Commands: &argh.Commands{
Map: map[string]argh.CommandConfig{
"ahoy": argh.CommandConfig{
Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{
"treatsa": argh.FlagConfig{NValue: 1},
},
},
},
},
},
},
},
exp: "pizzas",
expOK: true,
},
{
name: "minimal",
args: []string{"pizzas"},
exp: "pizzas",
expOK: true,
},
{
name: "invalid",
args: []string{},
expOK: false,
},
} {
t.Run(tc.name, func(ct *testing.T) {
pt, err := argh.ParseArgs(tc.args, tc.cfg)
require.Nil(ct, err)
prog, ok := argh.NewQuerier(pt.Nodes).Program()
require.Equal(ct, tc.expOK, ok)
require.Equal(ct, tc.exp, prog.Name)
})
}
}
Loading…
Cancel
Save