From a4bb5d703e4cb9d27e505c98049a0a27c85808f2 Mon Sep 17 00:00:00 2001 From: surdeus Date: Thu, 23 Mar 2023 12:32:52 +0300 Subject: [PATCH] More flags standartization. --- .gitignore | 1 + mkconfig | 5 ++++ mkfile | 3 ++ src/cmd/test/main.go | 22 +++++++++------ src/multitool/main.go | 65 +++++++++++++++++++++++++++++++++++++++---- 5 files changed, 82 insertions(+), 14 deletions(-) create mode 100644 .gitignore create mode 100644 mkconfig create mode 100644 mkfile diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..86daf54 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +exe diff --git a/mkconfig b/mkconfig new file mode 100644 index 0000000..b3be456 --- /dev/null +++ b/mkconfig @@ -0,0 +1,5 @@ +MKSHELL = sh +<$(MKINCDIR)/config +PKG_NAME = goblin +CC = cc + diff --git a/mkfile b/mkfile new file mode 100644 index 0000000..0c5baf7 --- /dev/null +++ b/mkfile @@ -0,0 +1,3 @@ + ", }, } ) func main() { - multitool.Main("test", tools) + mtool.Main("test", tools) } diff --git a/src/multitool/main.go b/src/multitool/main.go index 3162ade..69ac86f 100644 --- a/src/multitool/main.go +++ b/src/multitool/main.go @@ -4,13 +4,19 @@ import( "fmt" "os" path "path/filepath" + "flag" ) -type Tool struct { - Handler func(args []string) - Desc string +type Flags struct { + *flag.FlagSet } +type Handler func(args []string, flags *Flags) + +type Tool struct { + Handler Handler + Desc, Usage string +} type Tools map[string] Tool @@ -19,7 +25,9 @@ func Main(name string, m Tools) { utilName string args []string ) - binBase := path.Base(os.Args[0]) ; + + arg0 := os.Args[0] + binBase := path.Base(arg0) ; binBase = binBase[:len(binBase)-len(path.Ext(binBase))] if binBase != name { utilName = binBase @@ -36,10 +44,55 @@ func Main(name string, m Tools) { } if _, ok := m[utilName] ; !ok { - fmt.Printf("%s: No such uitl as '%s'.\n", os.Args[0], utilName ) + fmt.Printf("%s: No such uitl as '%s'.\n", arg0, utilName ) os.Exit(1) } - m[utilName].Handler(args) + util := m[utilName] + + arg1 := os.Args[1] + flagSet := flag.NewFlagSet(arg1, flag.ExitOnError) + flags := &Flags{ + flagSet, + } + flags.Usage = func() { + out := flags.Output() + n := 0 + flags.VisitAll(func(f *flag.Flag){ + n++ + }) + + hasOptions := n != 0 + + fmt.Fprintf( + out, + "Usage of %s:\n\t%s", + arg1, arg1, + ) + if hasOptions { + fmt.Fprintf(out, " [options]") + } + + if util.Usage != "" { + fmt.Fprintf( + out, + " %s", + util.Usage, + ) + } + + fmt.Fprintln(out, "") + + if hasOptions { + fmt.Fprintln(out, "Options:") + flags.PrintDefaults() + } + + os.Exit(1) + } + + args = args[1:] + + util.Handler(args, flags) }