From c382bc403f8bdeca950b32cc4df468e45df08792 Mon Sep 17 00:00:00 2001 From: surdeus Date: Fri, 24 Mar 2023 10:33:13 +0300 Subject: [PATCH] More unified argument to the tool processing function. --- src/cmd/test/main.go | 14 +++++++++----- src/mtool/main.go | 19 ++++++++++++++++--- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/cmd/test/main.go b/src/cmd/test/main.go index 7208213..93a5698 100644 --- a/src/cmd/test/main.go +++ b/src/cmd/test/main.go @@ -9,18 +9,22 @@ import( var( tools = mtool.Tools{ "echo" : mtool.Tool{ - func(args []string, flags *mtool.Flags) { + func(flags *mtool.Flags) { var b bool flags.BoolVar(&b, "b", false, "the check flag") - flags.Parse(args) - fmt.Println(flags.Args()) + flags.Parse() + + args := flags.Args() + + fmt.Println(args) }, "print string to standard output string", "[str1 str2 ... strN]", }, "sum" : mtool.Tool{ - func(args []string, flags *mtool.Flags) { - flags.Parse(args) + func(flags *mtool.Flags) { + flags.Parse() + args := flags.Args() one, _ := strconv.Atoi(args[1]) two, _ := strconv.Atoi(args[2]) fmt.Println(one + two) diff --git a/src/mtool/main.go b/src/mtool/main.go index 0f6fd7f..d3baf82 100644 --- a/src/mtool/main.go +++ b/src/mtool/main.go @@ -10,9 +10,11 @@ import( type Flags struct { *flag.FlagSet + args []string + parsedArgs []string } -type Handler func(args []string, flags *Flags) +type Handler func(*Flags) type Tool struct { Handler Handler @@ -21,6 +23,15 @@ type Tool struct { type Tools map[string] Tool +func (flags *Flags) Parse() { + flags.FlagSet.Parse(flags.args) + flags.parsedArgs = flags.FlagSet.Args() +} + +func (flags *Flags) Args() []string { + return flags.parsedArgs +} + func Main(name string, m Tools) { var( utilName string @@ -65,6 +76,8 @@ func Main(name string, m Tools) { flagSet := flag.NewFlagSet(arg1, flag.ExitOnError) flags := &Flags{ flagSet, + []string{}, + []string{}, } flags.Usage = func() { out := flags.Output() @@ -102,8 +115,8 @@ func Main(name string, m Tools) { os.Exit(1) } - args = args[1:] + flags.args = args[1:] - util.Handler(args, flags) + util.Handler(flags) }