From 3274f31b648a2017fd71e14f340444fba8364649 Mon Sep 17 00:00:00 2001 From: surdeus Date: Mon, 23 Sep 2024 01:14:45 +0500 Subject: [PATCH] feat: added custom args to be able to call the tools in more flexablie way. --- mtool/main.go | 19 +++++++++++-------- mtool/tool.go | 26 +++++++++++++------------- 2 files changed, 24 insertions(+), 21 deletions(-) diff --git a/mtool/main.go b/mtool/main.go index 1679bb4..488e94d 100644 --- a/mtool/main.go +++ b/mtool/main.go @@ -9,21 +9,25 @@ import ( "time" ) - type Flags struct { *flag.FlagSet - tool *Tool - args []string + tool *Tool + args []string parsedArgs []string - envNameMap map[string] []string - envMap map[string]string + customArgs []any + envNameMap map[string][]string + envMap map[string]string } -type ToolMap map[string] *Tool +type ToolMap map[string]*Tool + +func (flags *Flags) CustomArgs() []any { + return flags.customArgs +} func (flags *Flags) wasPassed(name string) bool { found := false - flags.Visit(func(f *flag.Flag){ + flags.Visit(func(f *flag.Flag) { if f.Name == name { found = true } @@ -150,4 +154,3 @@ func (flags *Flags) Args() []string { func (flags *Flags) Tool() *Tool { return flags.tool } - diff --git a/mtool/tool.go b/mtool/tool.go index 7115bed..f1ee9cd 100644 --- a/mtool/tool.go +++ b/mtool/tool.go @@ -1,13 +1,13 @@ package mtool import ( - "text/tabwriter" - "strings" "flag" - "sort" "fmt" "io" "os" + "sort" + "strings" + "text/tabwriter" ) type Tool struct { @@ -107,7 +107,7 @@ func (t *Tool) PrintSubs(out io.Writer) { } } -func (t *Tool) Run(args []string) { +func (t *Tool) Run(args []string, customArgs ...any) { var( usageTool *Tool ) @@ -120,6 +120,7 @@ func (t *Tool) Run(args []string) { FlagSet : flagSet, envMap: make(map[string]string), envNameMap: make(map[string] []string), + customArgs: customArgs, } out := flags.Output() flags.Usage = func() { @@ -150,7 +151,7 @@ func (t *Tool) Run(args []string) { usageTool.FullName(), FormatInCode(t.desc, true), ) } - + // Usage fmt.Fprintf( @@ -160,7 +161,7 @@ func (t *Tool) Run(args []string) { if hasOptions { fmt.Fprintf(out, " [options]") } - + if usageTool.usage != "" { fmt.Fprintf( out, @@ -178,16 +179,16 @@ func (t *Tool) Run(args []string) { FormatInCode(usageTool.ldesc, true), ) } - + // Options if hasOptions { fmt.Fprintln(out, "\nOptions:") fmt.Fprintln(out, " -- option terminator") flags.PrintDefaults() } - + } - + flags.args = args // If the tool has its own handler run it. @@ -234,12 +235,12 @@ func (t *Tool) Run(args []string) { fmt.Fprint(out, "\nCommands:\n") t.PrintSubs(out) } - + os.Exit(1) } toolName := args[0] args = args[1:] - + if _, ok := t.subs[toolName] ; !ok { fmt.Fprintf( out, @@ -253,7 +254,7 @@ func (t *Tool) Run(args []string) { sub := t.subs[toolName] usageTool = sub - sub.Run(args) + sub.Run(args, customArgs...) } // Returns the built-in @@ -278,4 +279,3 @@ func FormatInCode( } return desc } -