Compare commits

..

1 Commits

Author SHA1 Message Date
c713d85bd3
Like what would urfave/cli integration look 2022-10-11 09:46:35 -04:00
15 changed files with 572 additions and 524 deletions

View File

@ -1,5 +1,3 @@
BENCHTIME ?= 10s
.PHONY: all .PHONY: all
all: test all: test
@ -11,10 +9,6 @@ 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

View File

@ -20,7 +20,6 @@ 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

View File

@ -1,7 +1,6 @@
package argh package argh
import ( import (
"errors"
"fmt" "fmt"
"log" "log"
"os" "os"
@ -12,8 +11,6 @@ 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() {

View File

@ -3,26 +3,12 @@ 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() {
@ -36,16 +22,7 @@ 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,
@ -64,118 +41,23 @@ 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": {},
On: func(fl argh.CommandFlag) { "dur": {},
okFlag = ptrTo(true) "f64": {},
}, "i": {},
}, "i64": {},
"dur": { "s": {},
NValue: 1, "u": {},
On: func(fl argh.CommandFlag) { "u64": {},
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.CommandFlag) {
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.CommandFlag) {
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.CommandFlag) {
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.CommandFlag) {
if v, ok := fl.Values["0"]; ok {
sFlag = ptrTo(v)
}
},
},
"u": {
NValue: 1,
On: func(fl argh.CommandFlag) {
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.CommandFlag) {
if v, ok := fl.Values["0"]; ok {
if u, err := strconv.ParseUint(v, 10, 64); err == nil {
u64Flag = ptrTo(u)
}
}
},
},
}, },
}, },
} }
_, _ = argh.ParseArgs([]string{ _, _ = argh.ParseArgs([]string{}, pCfg)
"--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),
)
}() }()
} }
} }

50
ast.go
View File

@ -1,50 +0,0 @@
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.(*CommandFlag); ok {
astNodes := ToAST(v.Nodes)
if len(astNodes) == 0 {
astNodes = nil
}
ret = append(
ret,
&CommandFlag{
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) log.Fatal(err)
} }
ast := argh.ToAST(pt.Nodes) ast := argh.NewQuerier(pt.Nodes).AST()
if asJSON { if asJSON {
b, err := json.MarshalIndent(ast, "", " ") b, err := json.MarshalIndent(ast, "", " ")

View File

@ -0,0 +1,121 @@
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"git.meatballhat.com/x/argh"
"github.com/urfave/cli/v2"
)
func main() {
pc := argh.NewParserConfig()
app := &cli.App{
Name: "argh-from-urfave-cli",
Flags: []cli.Flag{
&cli.StringFlag{Name: "name", Aliases: []string{"n"}},
&cli.BoolFlag{Name: "happy", Aliases: []string{"H"}},
},
Action: func(cCtx *cli.Context) error {
return dumpAST(cCtx.App.Writer, os.Args, pc)
},
Commands: []*cli.Command{
{
Name: "poof",
Flags: []cli.Flag{
&cli.StringFlag{Name: "like", Aliases: []string{"L"}},
&cli.BoolFlag{Name: "loudly", Aliases: []string{"l"}},
},
Action: func(cCtx *cli.Context) error {
return dumpAST(cCtx.App.Writer, os.Args, pc)
},
Subcommands: []*cli.Command{
{
Name: "immediately",
Flags: []cli.Flag{
&cli.BoolFlag{Name: "really", Aliases: []string{"X"}},
},
Action: func(cCtx *cli.Context) error {
return dumpAST(cCtx.App.Writer, os.Args, pc)
},
},
},
},
},
}
mapFlags(pc.Prog.Flags, app.Flags, true)
mapCommands(pc.Prog, app.Commands)
app.RunContext(context.Background(), os.Args)
}
func dumpAST(w io.Writer, args []string, pc *argh.ParserConfig) error {
pt, err := argh.ParseArgs(args, pc)
if err != nil {
return err
}
q := argh.NewQuerier(pt.Nodes)
jsonBytes, err := json.MarshalIndent(
map[string]any{
"ast": q.AST(),
"config": pc,
},
"", " ",
)
if err != nil {
return err
}
_, err = fmt.Fprintln(w, string(jsonBytes))
return err
}
func mapFlags(cmdFlags *argh.Flags, flags []cli.Flag, persist bool) {
for _, fl := range flags {
nValue := argh.ZeroValue
if df, ok := fl.(cli.DocGenerationFlag); ok {
if df.TakesValue() {
if dsf, ok := df.(cli.DocGenerationSliceFlag); ok && dsf.IsSliceFlag() {
nValue = argh.OneOrMoreValue
} else {
nValue = argh.NValue(1)
}
}
}
flCfg := argh.FlagConfig{
NValue: nValue,
Persist: persist,
ValueNames: []string{fl.Names()[0]},
}
for _, flAlias := range fl.Names() {
cmdFlags.Set(flAlias, flCfg)
}
}
}
func mapCommands(cCfg *argh.CommandConfig, cmds []*cli.Command) {
for _, cmd := range cmds {
// TODO: vary nValue if/when cli.Command accepts positional args?
cmdCfg := argh.NewCommandConfig()
mapFlags(cmdCfg.Flags, cmd.Flags, false)
cCfg.Commands.Set(cmd.Name, *cmdCfg)
if len(cmd.Subcommands) == 0 {
return
}
mapCommands(cmdCfg, cmd.Subcommands)
}
}

4
go.mod
View File

@ -8,6 +8,10 @@ require (
) )
require ( require (
github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/urfave/cli/v2 v2.19.2 // indirect
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
) )

8
go.sum
View File

@ -1,13 +1,21 @@
github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/urfave/cli/v2 v2.19.2 h1:eXu5089gqqiDQKSnFW+H/FhjrxRGztwSxlTsVK7IuqQ=
github.com/urfave/cli/v2 v2.19.2/go.mod h1:1CNUng3PtjQMtRzJO4FMXBQvkGtuYRxxiR9xMa7jMwI=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

10
node.go
View File

@ -25,9 +25,13 @@ type BadArg struct {
To Pos To Pos
} }
// CommandFlag is a Node with a name, a slice of child Nodes, and type Command struct {
// potentially a map of named values derived from the child Nodes Name string
type CommandFlag struct { Values map[string]string
Nodes []Node
}
type Flag struct {
Name string Name string
Values map[string]string Values map[string]string
Nodes []Node Nodes []Node

120
parser.go
View File

@ -26,13 +26,10 @@ 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)
@ -43,11 +40,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) error { func (p *parser) init(r io.Reader, pCfg *ParserConfig) {
p.errors = ParserErrorList{} p.errors = ParserErrorList{}
if pCfg == nil { if pCfg == nil {
return fmt.Errorf("nil parser config: %w", Error) pCfg = POSIXyParserConfig
} }
p.cfg = pCfg p.cfg = pCfg
@ -55,8 +52,6 @@ func (p *parser) init(r io.Reader, pCfg *ParserConfig) error {
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) {
@ -92,7 +87,7 @@ func (p *parser) next() {
func (p *parser) parseCommand(cCfg *CommandConfig) Node { func (p *parser) parseCommand(cCfg *CommandConfig) Node {
tracef("parseCommand(%+#v)", cCfg) tracef("parseCommand(%+#v)", cCfg)
node := &CommandFlag{ node := &Command{
Name: p.lit, Name: p.lit,
} }
values := map[string]string{} values := map[string]string{}
@ -184,13 +179,6 @@ 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
} }
@ -217,115 +205,65 @@ func (p *parser) parseFlag(flags *Flags) Node {
} }
func (p *parser) parseShortFlag(flags *Flags) Node { func (p *parser) parseShortFlag(flags *Flags) Node {
node := &CommandFlag{Name: string(p.lit[1])} node := &Flag{Name: string(p.lit[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))
return node return node
} }
return p.parseConfiguredFlag(node, flCfg, nil) return p.parseConfiguredFlag(node, flCfg)
} }
func (p *parser) parseLongFlag(flags *Flags) Node { func (p *parser) parseLongFlag(flags *Flags) Node {
node := &CommandFlag{Name: string(p.lit[2:])} node := &Flag{Name: string(p.lit[2:])}
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))
return node return node
} }
return p.parseConfiguredFlag(node, flCfg, nil) return p.parseConfiguredFlag(node, flCfg)
} }
func (p *parser) parseCompoundShortFlag(flags *Flags) Node { func (p *parser) parseCompoundShortFlag(flags *Flags) Node {
unparsedFlags := []*CommandFlag{} flagNodes := []Node{}
unparsedFlagConfigs := []FlagConfig{}
withoutFlagPrefix := p.lit[1:] withoutFlagPrefix := p.lit[1:]
for _, r := range withoutFlagPrefix { for i, r := range withoutFlagPrefix {
node := &CommandFlag{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) flagNodes = append(flagNodes, p.parseConfiguredFlag(node, flCfg))
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 continue
} }
flagNodes = append(flagNodes, p.parseConfiguredFlag(node, flCfg, nil)) flagNodes = append(flagNodes, node)
} }
return &CompoundShortFlag{Nodes: flagNodes} return &CompoundShortFlag{Nodes: flagNodes}
} }
func (p *parser) parseConfiguredFlag(node *CommandFlag, flCfg FlagConfig, nValueOverride *NValue) Node { func (p *parser) parseConfiguredFlag(node *Flag, flCfg FlagConfig) Node {
values := map[string]string{} values := map[string]string{}
nodes := []Node{} nodes := []Node{}
atExit := func() *CommandFlag {
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
@ -370,11 +308,27 @@ func (p *parser) parseConfiguredFlag(node *CommandFlag, flCfg FlagConfig, nValue
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
return atExit() 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
} }
func (p *parser) parsePassthrough() Node { func (p *parser) parsePassthrough() Node {

View File

@ -7,22 +7,11 @@ const (
) )
var ( var (
zeroValuePtr = func() *NValue { POSIXyParserConfig = NewParserConfig()
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)
@ -55,8 +44,7 @@ func NewParserConfig(opts ...ParserOption) *ParserConfig {
} }
if pCfg.Prog == nil { if pCfg.Prog == nil {
pCfg.Prog = &CommandConfig{} pCfg.Prog = NewCommandConfig()
pCfg.Prog.init()
} }
if pCfg.ScannerConfig == nil { if pCfg.ScannerConfig == nil {
@ -71,8 +59,13 @@ type CommandConfig struct {
ValueNames []string ValueNames []string
Flags *Flags Flags *Flags
Commands *Commands Commands *Commands
}
On func(CommandFlag) func NewCommandConfig() *CommandConfig {
cmdCfg := &CommandConfig{}
cmdCfg.init()
return cmdCfg
} }
func (cCfg *CommandConfig) init() { func (cCfg *CommandConfig) init() {
@ -113,8 +106,6 @@ type FlagConfig struct {
NValue NValue NValue NValue
Persist bool Persist bool
ValueNames []string ValueNames []string
On func(CommandFlag)
} }
type Flags struct { type Flags struct {
@ -146,6 +137,16 @@ func (fl *Flags) Get(name string) (FlagConfig, bool) {
return flCfg, ok return flCfg, ok
} }
func (fl *Flags) Set(name string, flCfg FlagConfig) {
tracef("Flags.Set(%[1]q, %+#[2]v)", name, flCfg)
if fl.Map == nil {
fl.Map = map[string]FlagConfig{}
}
fl.Map[name] = flCfg
}
type Commands struct { type Commands struct {
Map map[string]CommandConfig Map map[string]CommandConfig
} }
@ -160,3 +161,13 @@ func (cmd *Commands) Get(name string) (CommandConfig, bool) {
cmdCfg, ok := cmd.Map[name] cmdCfg, ok := cmd.Map[name]
return cmdCfg, ok return cmdCfg, ok
} }
func (cmd *Commands) Set(name string, cmdCfg CommandConfig) {
tracef("Commands.Set(%[1]q, %+#[2]v)", name, cmdCfg)
if cmd.Map == nil {
cmd.Map = map[string]CommandConfig{}
}
cmd.Map[name] = cmdCfg
}

View File

@ -9,10 +9,6 @@ import (
) )
func TestParser(t *testing.T) { func TestParser(t *testing.T) {
traceOnCommandFlag := func(cmd argh.CommandFlag) {
t.Logf("CommandFlag.On: %+#[1]v", cmd)
}
for _, tc := range []struct { for _, tc := range []struct {
name string name string
args []string args []string
@ -31,10 +27,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": {On: traceOnCommandFlag}, "e": {},
"a": {On: traceOnCommandFlag}, "a": {},
"t": {On: traceOnCommandFlag}, "t": {},
"wat": {On: traceOnCommandFlag}, "wat": {},
}, },
}, },
Commands: &argh.Commands{ Commands: &argh.Commands{
@ -42,29 +38,27 @@ func TestParser(t *testing.T) {
"hello": argh.CommandConfig{ "hello": argh.CommandConfig{
NValue: 1, NValue: 1,
ValueNames: []string{"name"}, ValueNames: []string{"name"},
On: traceOnCommandFlag,
}, },
}, },
}, },
On: traceOnCommandFlag,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pies", Name: "pies",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CompoundShortFlag{ &argh.CompoundShortFlag{
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "e"}, &argh.Flag{Name: "e"},
&argh.CommandFlag{Name: "a"}, &argh.Flag{Name: "a"},
&argh.CommandFlag{Name: "t"}, &argh.Flag{Name: "t"},
}, },
}, },
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "wat"}, &argh.Flag{Name: "wat"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{ &argh.Command{
Name: "hello", Name: "hello",
Values: map[string]string{ Values: map[string]string{
"name": "mario", "name": "mario",
@ -78,14 +72,14 @@ func TestParser(t *testing.T) {
}, },
}, },
expAST: []argh.Node{ expAST: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pies", Name: "pies",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "e"}, &argh.Flag{Name: "e"},
&argh.CommandFlag{Name: "a"}, &argh.Flag{Name: "a"},
&argh.CommandFlag{Name: "t"}, &argh.Flag{Name: "t"},
&argh.CommandFlag{Name: "wat"}, &argh.Flag{Name: "wat"},
&argh.CommandFlag{ &argh.Command{
Name: "hello", Name: "hello",
Values: map[string]string{ Values: map[string]string{
"name": "mario", "name": "mario",
@ -108,13 +102,12 @@ 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, On: traceOnCommandFlag}, "e": {Persist: true},
"a": {Persist: true, On: traceOnCommandFlag}, "a": {Persist: true},
"t": {Persist: true, On: traceOnCommandFlag}, "t": {Persist: true},
"wat": {On: traceOnCommandFlag}, "wat": {},
}, },
}, },
On: traceOnCommandFlag,
} }
cmdCfg.Commands = &argh.Commands{ cmdCfg.Commands = &argh.Commands{
@ -126,7 +119,6 @@ func TestParser(t *testing.T) {
Parent: cmdCfg.Flags, Parent: cmdCfg.Flags,
Map: map[string]argh.FlagConfig{}, Map: map[string]argh.FlagConfig{},
}, },
On: traceOnCommandFlag,
}, },
}, },
} }
@ -135,13 +127,13 @@ func TestParser(t *testing.T) {
}(), }(),
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pies", Name: "pies",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "wat"}, &argh.Flag{Name: "wat"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{ &argh.Command{
Name: "hello", Name: "hello",
Values: map[string]string{ Values: map[string]string{
"name": "mario", "name": "mario",
@ -152,9 +144,9 @@ func TestParser(t *testing.T) {
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CompoundShortFlag{ &argh.CompoundShortFlag{
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "e"}, &argh.Flag{Name: "e"},
&argh.CommandFlag{Name: "a"}, &argh.Flag{Name: "a"},
&argh.CommandFlag{Name: "t"}, &argh.Flag{Name: "t"},
}, },
}, },
}, },
@ -163,20 +155,20 @@ func TestParser(t *testing.T) {
}, },
}, },
expAST: []argh.Node{ expAST: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pies", Name: "pies",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "wat"}, &argh.Flag{Name: "wat"},
&argh.CommandFlag{ &argh.Command{
Name: "hello", Name: "hello",
Values: map[string]string{ Values: map[string]string{
"name": "mario", "name": "mario",
}, },
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.Ident{Literal: "mario"}, &argh.Ident{Literal: "mario"},
&argh.CommandFlag{Name: "e"}, &argh.Flag{Name: "e"},
&argh.CommandFlag{Name: "a"}, &argh.Flag{Name: "a"},
&argh.CommandFlag{Name: "t"}, &argh.Flag{Name: "t"},
}, },
}, },
}, },
@ -187,12 +179,12 @@ func TestParser(t *testing.T) {
name: "bare", name: "bare",
args: []string{"pizzas"}, args: []string{"pizzas"},
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
}, },
}, },
expAST: []argh.Node{ expAST: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
}, },
}, },
@ -201,10 +193,10 @@ 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, On: traceOnCommandFlag}, Prog: &argh.CommandConfig{NValue: 1},
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Values: map[string]string{"0": "excel"}, Values: map[string]string{"0": "excel"},
Nodes: []argh.Node{ Nodes: []argh.Node{
@ -214,7 +206,7 @@ func TestParser(t *testing.T) {
}, },
}, },
expAST: []argh.Node{ expAST: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Values: map[string]string{"0": "excel"}, Values: map[string]string{"0": "excel"},
Nodes: []argh.Node{ Nodes: []argh.Node{
@ -230,11 +222,10 @@ func TestParser(t *testing.T) {
Prog: &argh.CommandConfig{ Prog: &argh.CommandConfig{
NValue: argh.OneOrMoreValue, NValue: argh.OneOrMoreValue,
ValueNames: []string{"word"}, ValueNames: []string{"word"},
On: traceOnCommandFlag,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Values: map[string]string{ Values: map[string]string{
"word": "excel", "word": "excel",
@ -255,7 +246,7 @@ func TestParser(t *testing.T) {
}, },
}, },
expAST: []argh.Node{ expAST: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Values: map[string]string{ Values: map[string]string{
"word": "excel", "word": "excel",
@ -279,34 +270,33 @@ 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": {On: traceOnCommandFlag}, "tasty": {},
"fresh": {On: traceOnCommandFlag}, "fresh": {},
"super-hot-right-now": {On: traceOnCommandFlag}, "super-hot-right-now": {},
}, },
}, },
On: traceOnCommandFlag,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "tasty"}, &argh.Flag{Name: "tasty"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "fresh"}, &argh.Flag{Name: "fresh"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "super-hot-right-now"}, &argh.Flag{Name: "super-hot-right-now"},
}, },
}, },
}, },
expAST: []argh.Node{ expAST: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "tasty"}, &argh.Flag{Name: "tasty"},
&argh.CommandFlag{Name: "fresh"}, &argh.Flag{Name: "fresh"},
&argh.CommandFlag{Name: "super-hot-right-now"}, &argh.Flag{Name: "super-hot-right-now"},
}, },
}, },
}, },
@ -326,24 +316,23 @@ 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": {On: traceOnCommandFlag}, "tasty": {},
"fresh": argh.FlagConfig{NValue: 1, On: traceOnCommandFlag}, "fresh": argh.FlagConfig{NValue: 1},
"super-hot-right-now": {On: traceOnCommandFlag}, "super-hot-right-now": {},
"box": argh.FlagConfig{NValue: argh.OneOrMoreValue, On: traceOnCommandFlag}, "box": argh.FlagConfig{NValue: argh.OneOrMoreValue},
"please": {On: traceOnCommandFlag}, "please": {},
}, },
}, },
On: traceOnCommandFlag,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "tasty"}, &argh.Flag{Name: "tasty"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{ &argh.Flag{
Name: "fresh", Name: "fresh",
Values: map[string]string{"0": "soon"}, Values: map[string]string{"0": "soon"},
Nodes: []argh.Node{ Nodes: []argh.Node{
@ -352,9 +341,9 @@ func TestParser(t *testing.T) {
}, },
}, },
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "super-hot-right-now"}, &argh.Flag{Name: "super-hot-right-now"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{ &argh.Flag{
Name: "box", Name: "box",
Values: map[string]string{"0": "square", "1": "shaped", "2": "hot"}, Values: map[string]string{"0": "square", "1": "shaped", "2": "hot"},
Nodes: []argh.Node{ Nodes: []argh.Node{
@ -367,24 +356,24 @@ func TestParser(t *testing.T) {
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
}, },
}, },
&argh.CommandFlag{Name: "please"}, &argh.Flag{Name: "please"},
}, },
}, },
}, },
expAST: []argh.Node{ expAST: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "tasty"}, &argh.Flag{Name: "tasty"},
&argh.CommandFlag{ &argh.Flag{
Name: "fresh", Name: "fresh",
Values: map[string]string{"0": "soon"}, Values: map[string]string{"0": "soon"},
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.Ident{Literal: "soon"}, &argh.Ident{Literal: "soon"},
}, },
}, },
&argh.CommandFlag{Name: "super-hot-right-now"}, &argh.Flag{Name: "super-hot-right-now"},
&argh.CommandFlag{ &argh.Flag{
Name: "box", Name: "box",
Values: map[string]string{"0": "square", "1": "shaped", "2": "hot"}, Values: map[string]string{"0": "square", "1": "shaped", "2": "hot"},
Nodes: []argh.Node{ Nodes: []argh.Node{
@ -393,7 +382,7 @@ func TestParser(t *testing.T) {
&argh.Ident{Literal: "hot"}, &argh.Ident{Literal: "hot"},
}, },
}, },
&argh.CommandFlag{Name: "please"}, &argh.Flag{Name: "please"},
}, },
}, },
}, },
@ -405,34 +394,33 @@ 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": {On: traceOnCommandFlag}, "t": {},
"f": {On: traceOnCommandFlag}, "f": {},
"s": {On: traceOnCommandFlag}, "s": {},
}, },
}, },
On: traceOnCommandFlag,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "t"}, &argh.Flag{Name: "t"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "f"}, &argh.Flag{Name: "f"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "s"}, &argh.Flag{Name: "s"},
}, },
}, },
}, },
expAST: []argh.Node{ expAST: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "t"}, &argh.Flag{Name: "t"},
&argh.CommandFlag{Name: "f"}, &argh.Flag{Name: "f"},
&argh.CommandFlag{Name: "s"}, &argh.Flag{Name: "s"},
}, },
}, },
}, },
@ -444,51 +432,50 @@ 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": {On: traceOnCommandFlag}, "a": {},
"b": {On: traceOnCommandFlag}, "b": {},
"c": {On: traceOnCommandFlag}, "c": {},
"l": {On: traceOnCommandFlag}, "l": {},
"o": {On: traceOnCommandFlag}, "o": {},
}, },
}, },
On: traceOnCommandFlag,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CompoundShortFlag{ &argh.CompoundShortFlag{
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "a"}, &argh.Flag{Name: "a"},
&argh.CommandFlag{Name: "c"}, &argh.Flag{Name: "c"},
&argh.CommandFlag{Name: "a"}, &argh.Flag{Name: "a"},
}, },
}, },
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CompoundShortFlag{ &argh.CompoundShortFlag{
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "b"}, &argh.Flag{Name: "b"},
&argh.CommandFlag{Name: "l"}, &argh.Flag{Name: "l"},
&argh.CommandFlag{Name: "o"}, &argh.Flag{Name: "o"},
&argh.CommandFlag{Name: "l"}, &argh.Flag{Name: "l"},
}, },
}, },
}, },
}, },
}, },
expAST: []argh.Node{ expAST: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "a"}, &argh.Flag{Name: "a"},
&argh.CommandFlag{Name: "c"}, &argh.Flag{Name: "c"},
&argh.CommandFlag{Name: "a"}, &argh.Flag{Name: "a"},
&argh.CommandFlag{Name: "b"}, &argh.Flag{Name: "b"},
&argh.CommandFlag{Name: "l"}, &argh.Flag{Name: "l"},
&argh.CommandFlag{Name: "o"}, &argh.Flag{Name: "o"},
&argh.CommandFlag{Name: "l"}, &argh.Flag{Name: "l"},
}, },
}, },
}, },
@ -501,26 +488,25 @@ 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": {On: traceOnCommandFlag}, "a": {},
"b": argh.FlagConfig{NValue: 1, On: traceOnCommandFlag}, "b": argh.FlagConfig{NValue: 1},
"ca": {On: traceOnCommandFlag}, "ca": {},
"l": {On: traceOnCommandFlag}, "l": {},
"o": {On: traceOnCommandFlag}, "o": {},
}, },
}, },
On: traceOnCommandFlag,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "a"}, &argh.Flag{Name: "a"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "ca"}, &argh.Flag{Name: "ca"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{ &argh.Flag{
Name: "b", Name: "b",
Values: map[string]string{"0": "1312"}, Values: map[string]string{"0": "1312"},
Nodes: []argh.Node{ Nodes: []argh.Node{
@ -531,30 +517,30 @@ func TestParser(t *testing.T) {
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CompoundShortFlag{ &argh.CompoundShortFlag{
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "l"}, &argh.Flag{Name: "l"},
&argh.CommandFlag{Name: "o"}, &argh.Flag{Name: "o"},
&argh.CommandFlag{Name: "l"}, &argh.Flag{Name: "l"},
}, },
}, },
}, },
}, },
}, },
expAST: []argh.Node{ expAST: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "a"}, &argh.Flag{Name: "a"},
&argh.CommandFlag{Name: "ca"}, &argh.Flag{Name: "ca"},
&argh.CommandFlag{ &argh.Flag{
Name: "b", Name: "b",
Values: map[string]string{"0": "1312"}, Values: map[string]string{"0": "1312"},
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.Ident{Literal: "1312"}, &argh.Ident{Literal: "1312"},
}, },
}, },
&argh.CommandFlag{Name: "l"}, &argh.Flag{Name: "l"},
&argh.CommandFlag{Name: "o"}, &argh.Flag{Name: "o"},
&argh.CommandFlag{Name: "l"}, &argh.Flag{Name: "l"},
}, },
}, },
}, },
@ -572,7 +558,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": {On: traceOnCommandFlag}, "forever": {},
}, },
}, },
}, },
@ -582,15 +568,14 @@ func TestParser(t *testing.T) {
}, },
}, },
Flags: &argh.Flags{Map: map[string]argh.FlagConfig{}}, Flags: &argh.Flags{Map: map[string]argh.FlagConfig{}},
On: traceOnCommandFlag,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{ &argh.Command{
Name: "fly", Name: "fly",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
@ -604,13 +589,13 @@ func TestParser(t *testing.T) {
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.Ident{Literal: "times"}, &argh.Ident{Literal: "times"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{ &argh.Command{
Name: "fry", Name: "fry",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.Ident{Literal: "deeply"}, &argh.Ident{Literal: "deeply"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "forever"}, &argh.Flag{Name: "forever"},
}, },
}, },
}, },
@ -619,10 +604,10 @@ func TestParser(t *testing.T) {
}, },
}, },
expAST: []argh.Node{ expAST: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "fly", Name: "fly",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.Ident{Literal: "freely"}, &argh.Ident{Literal: "freely"},
@ -630,11 +615,11 @@ func TestParser(t *testing.T) {
&argh.Ident{Literal: "and"}, &argh.Ident{Literal: "and"},
&argh.Ident{Literal: "other"}, &argh.Ident{Literal: "other"},
&argh.Ident{Literal: "times"}, &argh.Ident{Literal: "times"},
&argh.CommandFlag{ &argh.Command{
Name: "fry", Name: "fry",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.Ident{Literal: "deeply"}, &argh.Ident{Literal: "deeply"},
&argh.CommandFlag{Name: "forever"}, &argh.Flag{Name: "forever"},
}, },
}, },
}, },
@ -650,29 +635,28 @@ 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, On: traceOnCommandFlag}, "a": {NValue: argh.ZeroOrMoreValue},
"d": {NValue: argh.OneOrMoreValue, On: traceOnCommandFlag}, "d": {NValue: argh.OneOrMoreValue},
"e": {On: traceOnCommandFlag}, "e": {},
"l": {On: traceOnCommandFlag}, "l": {},
"n": {On: traceOnCommandFlag}, "n": {},
"o": {NValue: 1, ValueNames: []string{"level"}, On: traceOnCommandFlag}, "o": {NValue: 1, ValueNames: []string{"level"}},
"s": {NValue: argh.ZeroOrMoreValue, On: traceOnCommandFlag}, "s": {NValue: argh.ZeroOrMoreValue},
}, },
}, },
On: traceOnCommandFlag,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CompoundShortFlag{ &argh.CompoundShortFlag{
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "n"}, &argh.Flag{Name: "n"},
&argh.CommandFlag{Name: "e"}, &argh.Flag{Name: "e"},
&argh.CommandFlag{Name: "e"}, &argh.Flag{Name: "e"},
&argh.CommandFlag{ &argh.Flag{
Name: "d", Name: "d",
Values: map[string]string{ Values: map[string]string{
"0": "sauce", "0": "sauce",
@ -693,10 +677,10 @@ func TestParser(t *testing.T) {
}, },
&argh.CompoundShortFlag{ &argh.CompoundShortFlag{
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "a"}, &argh.Flag{Name: "a"},
&argh.CommandFlag{Name: "l"}, &argh.Flag{Name: "l"},
&argh.CommandFlag{Name: "s"}, &argh.Flag{Name: "s"},
&argh.CommandFlag{ &argh.Flag{
Name: "o", Name: "o",
Values: map[string]string{ Values: map[string]string{
"level": "over9000", "level": "over9000",
@ -712,13 +696,13 @@ func TestParser(t *testing.T) {
}, },
}, },
expAST: []argh.Node{ expAST: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "n"}, &argh.Flag{Name: "n"},
&argh.CommandFlag{Name: "e"}, &argh.Flag{Name: "e"},
&argh.CommandFlag{Name: "e"}, &argh.Flag{Name: "e"},
&argh.CommandFlag{ &argh.Flag{
Name: "d", Name: "d",
Values: map[string]string{ Values: map[string]string{
"0": "sauce", "0": "sauce",
@ -731,10 +715,10 @@ func TestParser(t *testing.T) {
&argh.Ident{Literal: "love"}, &argh.Ident{Literal: "love"},
}, },
}, },
&argh.CommandFlag{Name: "a"}, &argh.Flag{Name: "a"},
&argh.CommandFlag{Name: "l"}, &argh.Flag{Name: "l"},
&argh.CommandFlag{Name: "s"}, &argh.Flag{Name: "s"},
&argh.CommandFlag{ &argh.Flag{
Name: "o", Name: "o",
Values: map[string]string{ Values: map[string]string{
"level": "over9000", "level": "over9000",
@ -757,7 +741,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": {On: traceOnCommandFlag}, "freely": {},
}, },
}, },
Commands: &argh.Commands{ Commands: &argh.Commands{
@ -765,10 +749,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": {On: traceOnCommandFlag}, "deeply": {},
"w": {On: traceOnCommandFlag}, "w": {},
"A": {On: traceOnCommandFlag}, "A": {},
"t": argh.FlagConfig{NValue: 1, On: traceOnCommandFlag}, "t": argh.FlagConfig{NValue: 1},
}, },
}, },
}, },
@ -778,31 +762,30 @@ func TestParser(t *testing.T) {
}, },
}, },
Flags: &argh.Flags{Map: map[string]argh.FlagConfig{}}, Flags: &argh.Flags{Map: map[string]argh.FlagConfig{}},
On: traceOnCommandFlag,
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{ &argh.Command{
Name: "fly", Name: "fly",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "freely"}, &argh.Flag{Name: "freely"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{ &argh.Command{
Name: "fry", Name: "fry",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "deeply"}, &argh.Flag{Name: "deeply"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CompoundShortFlag{ &argh.CompoundShortFlag{
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "w"}, &argh.Flag{Name: "w"},
&argh.CommandFlag{Name: "A"}, &argh.Flag{Name: "A"},
&argh.CommandFlag{ &argh.Flag{
Name: "t", Name: "t",
Values: map[string]string{"0": "hugs"}, Values: map[string]string{"0": "hugs"},
Nodes: []argh.Node{ Nodes: []argh.Node{
@ -820,20 +803,20 @@ func TestParser(t *testing.T) {
}, },
}, },
expAST: []argh.Node{ expAST: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "fly", Name: "fly",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "freely"}, &argh.Flag{Name: "freely"},
&argh.CommandFlag{ &argh.Command{
Name: "fry", Name: "fry",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "deeply"}, &argh.Flag{Name: "deeply"},
&argh.CommandFlag{Name: "w"}, &argh.Flag{Name: "w"},
&argh.CommandFlag{Name: "A"}, &argh.Flag{Name: "A"},
&argh.CommandFlag{ &argh.Flag{
Name: "t", Name: "t",
Values: map[string]string{"0": "hugs"}, Values: map[string]string{"0": "hugs"},
Nodes: []argh.Node{ Nodes: []argh.Node{
@ -859,7 +842,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, On: traceOnCommandFlag}, "FIERCENESS": argh.FlagConfig{NValue: 1},
}, },
}, },
}, },
@ -867,13 +850,12 @@ func TestParser(t *testing.T) {
}, },
Flags: &argh.Flags{ Flags: &argh.Flags{
Map: map[string]argh.FlagConfig{ Map: map[string]argh.FlagConfig{
"w": {On: traceOnCommandFlag}, "w": argh.FlagConfig{},
"A": {On: traceOnCommandFlag}, "A": argh.FlagConfig{},
"T": {NValue: 1, On: traceOnCommandFlag}, "T": argh.FlagConfig{NValue: 1},
"hecKing": {On: traceOnCommandFlag}, "hecKing": argh.FlagConfig{},
}, },
}, },
On: traceOnCommandFlag,
}, },
ScannerConfig: &argh.ScannerConfig{ ScannerConfig: &argh.ScannerConfig{
AssignmentOperator: '@', AssignmentOperator: '@',
@ -882,15 +864,15 @@ func TestParser(t *testing.T) {
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "PIZZAs", Name: "PIZZAs",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CompoundShortFlag{ &argh.CompoundShortFlag{
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.CommandFlag{Name: "w"}, &argh.Flag{Name: "w"},
&argh.CommandFlag{Name: "A"}, &argh.Flag{Name: "A"},
&argh.CommandFlag{ &argh.Flag{
Name: "T", Name: "T",
Values: map[string]string{"0": "golf"}, Values: map[string]string{"0": "golf"},
Nodes: []argh.Node{ Nodes: []argh.Node{
@ -901,16 +883,16 @@ func TestParser(t *testing.T) {
}, },
}, },
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "hecKing"}, &argh.Flag{Name: "hecKing"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{ &argh.Command{
Name: "goose", Name: "goose",
Values: map[string]string{"0": "bonk"}, Values: map[string]string{"0": "bonk"},
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.Ident{Literal: "bonk"}, &argh.Ident{Literal: "bonk"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{ &argh.Flag{
Name: "FIERCENESS", Name: "FIERCENESS",
Values: map[string]string{"0": "-2"}, Values: map[string]string{"0": "-2"},
Nodes: []argh.Node{ Nodes: []argh.Node{
@ -931,9 +913,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": {On: traceOnCommandFlag}, "f": {},
"L": {On: traceOnCommandFlag}, "L": {},
"o": argh.FlagConfig{NValue: 1, On: traceOnCommandFlag}, "o": argh.FlagConfig{NValue: 1},
}, },
}, },
Commands: &argh.Commands{ Commands: &argh.Commands{
@ -941,7 +923,6 @@ func TestParser(t *testing.T) {
"hats": {}, "hats": {},
}, },
}, },
On: traceOnCommandFlag,
}, },
ScannerConfig: &argh.ScannerConfig{ ScannerConfig: &argh.ScannerConfig{
AssignmentOperator: ':', AssignmentOperator: ':',
@ -950,15 +931,15 @@ func TestParser(t *testing.T) {
}, },
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "hotdog", Name: "hotdog",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "f"}, &argh.Flag{Name: "f"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "L"}, &argh.Flag{Name: "L"},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{ &argh.Flag{
Name: "o", Name: "o",
Values: map[string]string{"0": "ppy"}, Values: map[string]string{"0": "ppy"},
Nodes: []argh.Node{ Nodes: []argh.Node{
@ -967,7 +948,7 @@ func TestParser(t *testing.T) {
}, },
}, },
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "hats"}, &argh.Command{Name: "hats"},
}, },
}, },
}, },
@ -979,22 +960,21 @@ 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": {On: traceOnCommandFlag}, "wat": {},
}, },
}, },
On: traceOnCommandFlag,
}, },
}, },
expErr: argh.ParserErrorList{ expErr: argh.ParserErrorList{
&argh.ParserError{Pos: argh.Position{Column: 8}, Msg: "invalid bare assignment"}, &argh.ParserError{Pos: argh.Position{Column: 8}, Msg: "invalid bare assignment"},
}, },
expPT: []argh.Node{ expPT: []argh.Node{
&argh.CommandFlag{ &argh.Command{
Name: "pizzas", Name: "pizzas",
Nodes: []argh.Node{ Nodes: []argh.Node{
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.ArgDelimiter{}, &argh.ArgDelimiter{},
&argh.CommandFlag{Name: "wat"}, &argh.Flag{Name: "wat"},
}, },
}, },
}, },
@ -1007,12 +987,7 @@ func TestParser(t *testing.T) {
return return
} }
pCfg := tc.cfg pt, err := argh.ParseArgs(tc.args, 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)
@ -1034,12 +1009,7 @@ func TestParser(t *testing.T) {
return return
} }
pCfg := tc.cfg pt, err := argh.ParseArgs(tc.args, 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)
@ -1047,7 +1017,7 @@ func TestParser(t *testing.T) {
return return
} }
ast := argh.ToAST(pt.Nodes) ast := argh.NewQuerier(pt.Nodes).AST()
if !assert.Equal(ct, tc.expAST, ast) { if !assert.Equal(ct, tc.expAST, ast) {
spew.Dump(ast) spew.Dump(ast)

94
querier.go Normal file
View File

@ -0,0 +1,94 @@
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
}

60
querier_test.go Normal file
View File

@ -0,0 +1,60 @@
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)
})
}
}