Add support for "event"-like interface to parsing

and drop the querier
This commit is contained in:
Dan Buch 2022-11-08 19:26:23 -05:00
parent c93d1cd4f0
commit b97681c710
Signed by: meatballhat
GPG Key ID: A12F782281063434
11 changed files with 398 additions and 260 deletions

View File

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

View File

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

View File

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

View File

@ -3,12 +3,26 @@ package argh_test
import (
"flag"
"fmt"
"strconv"
"testing"
"time"
"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) {
for i := 0; i < b.N; i++ {
func() {
@ -22,7 +36,16 @@ func BenchmarkStdlibFlag(b *testing.B) {
uFlag := fl.Uint("u", 11, "")
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(
"fl", fl,
"okFlag", *okFlag,
@ -41,23 +64,118 @@ func BenchmarkStdlibFlag(b *testing.B) {
func BenchmarkArgh(b *testing.B) {
for i := 0; i < b.N; i++ {
func() {
var (
okFlag *bool
durFlag *time.Duration
f64Flag *float64
iFlag *int
i64Flag *int64
sFlag *string
uFlag *uint
u64Flag *uint64
)
pCfg := argh.NewParserConfig()
pCfg.Prog = &argh.CommandConfig{
Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{
"ok": {},
"dur": {},
"f64": {},
"i": {},
"i64": {},
"s": {},
"u": {},
"u64": {},
"ok": {
On: func(fl argh.Flag) {
okFlag = ptrTo(true)
},
},
"dur": {
NValue: 1,
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),
)
}()
}
}

69
ast.go Normal file
View File

@ -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
}

View File

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

124
parser.go
View File

@ -26,10 +26,13 @@ type ParseTree struct {
func ParseArgs(args []string, pCfg *ParserConfig) (*ParseTree, error) {
p := &parser{}
p.init(
if err := p.init(
strings.NewReader(strings.Join(args, string(nul))),
pCfg,
)
); err != nil {
return nil, err
}
tracef("ParseArgs(...) parser=%+#v", p)
@ -40,11 +43,11 @@ func (p *parser) addError(msg string) {
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{}
if pCfg == nil {
pCfg = POSIXyParserConfig
return fmt.Errorf("nil parser config: %w", Error)
}
p.cfg = pCfg
@ -52,6 +55,8 @@ func (p *parser) init(r io.Reader, pCfg *ParserConfig) {
p.s = NewScanner(r, pCfg.ScannerConfig)
p.next()
return nil
}
func (p *parser) parseArgs() (*ParseTree, error) {
@ -179,6 +184,13 @@ func (p *parser) parseCommand(cCfg *CommandConfig) Node {
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)
return node
}
@ -209,12 +221,12 @@ func (p *parser) parseShortFlag(flags *Flags) Node {
flCfg, ok := flags.Get(node.Name)
if !ok {
p.addError(fmt.Sprintf("unknown flag %q", node.Name))
p.addError(fmt.Sprintf("unknown flag %[1]q", node.Name))
return node
}
return p.parseConfiguredFlag(node, flCfg)
return p.parseConfiguredFlag(node, flCfg, nil)
}
func (p *parser) parseLongFlag(flags *Flags) Node {
@ -222,48 +234,98 @@ func (p *parser) parseLongFlag(flags *Flags) Node {
flCfg, ok := flags.Get(node.Name)
if !ok {
p.addError(fmt.Sprintf("unknown flag %q", node.Name))
p.addError(fmt.Sprintf("unknown flag %[1]q", node.Name))
return node
}
return p.parseConfiguredFlag(node, flCfg)
return p.parseConfiguredFlag(node, flCfg, nil)
}
func (p *parser) parseCompoundShortFlag(flags *Flags) Node {
flagNodes := []Node{}
unparsedFlags := []*Flag{}
unparsedFlagConfigs := []FlagConfig{}
withoutFlagPrefix := p.lit[1:]
for i, r := range withoutFlagPrefix {
for _, r := range withoutFlagPrefix {
node := &Flag{Name: string(r)}
if i == len(withoutFlagPrefix)-1 {
flCfg, ok := flags.Get(node.Name)
if !ok {
p.addError(fmt.Sprintf("unknown flag %q", node.Name))
continue
}
flagNodes = append(flagNodes, p.parseConfiguredFlag(node, flCfg))
flCfg, ok := flags.Get(node.Name)
if !ok {
p.addError(fmt.Sprintf("unknown flag %[1]q", node.Name))
continue
}
flagNodes = append(flagNodes, node)
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, zeroValuePtr),
)
continue
}
flagNodes = append(flagNodes, p.parseConfiguredFlag(node, flCfg, nil))
}
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{}
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
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) {
tracef("parseConfiguredFlag(...) identIndex=%d exceeds expected=%v; breaking", identIndex, flCfg.NValue)
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)
p.buffered = true
if len(nodes) > 0 {
node.Nodes = nodes
}
if len(values) > 0 {
node.Values = values
}
return node
return atExit()
}
}
if len(nodes) > 0 {
node.Nodes = nodes
}
if len(values) > 0 {
node.Values = values
}
return node
return atExit()
}
func (p *parser) parsePassthrough() Node {

View File

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

View File

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

View File

@ -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
}

View File

@ -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)
})
}
}