From e3872e316d2da9ff93afb9cf85dc9141dc1568af Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sat, 4 Jun 2022 17:38:24 -0400 Subject: [PATCH] Making more messes with parser config --- cmd/{argh => argh-example}/main.go | 11 +++++- parser_config.go | 55 ++++++++++++++++++++++++++---- 2 files changed, 58 insertions(+), 8 deletions(-) rename cmd/{argh => argh-example}/main.go (67%) diff --git a/cmd/argh/main.go b/cmd/argh-example/main.go similarity index 67% rename from cmd/argh/main.go rename to cmd/argh-example/main.go index e99ff48..325c7ec 100644 --- a/cmd/argh/main.go +++ b/cmd/argh-example/main.go @@ -15,7 +15,16 @@ func main() { log.SetFlags(0) - pt, err := argh.ParseArgs(os.Args, nil) + pt, err := argh.ParseArgs(os.Args, argh.NewParserConfig( + &argh.CommandConfig{ + NValue: argh.OneOrMoreValue, + ValueNames: []string{"topping"}, + Flags: &argh.Flags{ + Automatic: true, + }, + }, + nil, + )) if err != nil { log.Fatal(err) } diff --git a/parser_config.go b/parser_config.go index 78d7277..62ea57d 100644 --- a/parser_config.go +++ b/parser_config.go @@ -7,10 +7,10 @@ const ( ) var ( - POSIXyParserConfig = &ParserConfig{ - Prog: CommandConfig{}, - ScannerConfig: POSIXyScannerConfig, - } + POSIXyParserConfig = NewParserConfig( + nil, + POSIXyScannerConfig, + ) ) type NValue int @@ -35,6 +35,25 @@ type ParserConfig struct { ScannerConfig *ScannerConfig } +func NewParserConfig(prog *CommandConfig, sCfg *ScannerConfig) *ParserConfig { + if sCfg == nil { + sCfg = POSIXyScannerConfig + } + + if prog == nil { + prog = &CommandConfig{} + } + + prog.init() + + pCfg := &ParserConfig{ + Prog: *prog, + ScannerConfig: sCfg, + } + + return pCfg +} + type CommandConfig struct { NValue NValue ValueNames []string @@ -42,6 +61,20 @@ type CommandConfig struct { Commands *Commands } +func (cCfg *CommandConfig) init() { + if cCfg.ValueNames == nil { + cCfg.ValueNames = []string{} + } + + if cCfg.Flags == nil { + cCfg.Flags = &Flags{} + } + + if cCfg.Commands == nil { + cCfg.Commands = &Commands{} + } +} + func (cCfg *CommandConfig) GetCommandConfig(name string) (CommandConfig, bool) { tracef("CommandConfig.GetCommandConfig(%q)", name) @@ -71,6 +104,8 @@ type FlagConfig struct { type Flags struct { Parent *Flags Map map[string]FlagConfig + + Automatic bool } func (fl *Flags) Get(name string) (FlagConfig, bool) { @@ -81,9 +116,15 @@ func (fl *Flags) Get(name string) (FlagConfig, bool) { } flCfg, ok := fl.Map[name] - if !ok && fl.Parent != nil { - flCfg, ok = fl.Parent.Get(name) - return flCfg, ok && flCfg.Persist + if !ok { + if fl.Automatic { + return FlagConfig{}, true + } + + if fl.Parent != nil { + flCfg, ok = fl.Parent.Get(name) + return flCfg, ok && flCfg.Persist + } } return flCfg, ok