More flags standartization.

This commit is contained in:
Andrey Parhomenko 2023-03-23 12:32:52 +03:00
parent b00a31dd98
commit a4bb5d703e
5 changed files with 82 additions and 14 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
exe

5
mkconfig Normal file
View file

@ -0,0 +1,5 @@
MKSHELL = sh
<$(MKINCDIR)/config
PKG_NAME = goblin
CC = cc

3
mkfile Normal file
View file

@ -0,0 +1,3 @@
<mkconfig
<$MKINCDIR/gobuild

View file

@ -1,31 +1,37 @@
package main
import(
"github.com/surdeus/gomtool/src/multitool"
mtool "github.com/surdeus/gomtool/src/multitool"
"strconv"
"fmt"
)
var(
tools = multitool.Tools{
"echo" : multitool.Tool{
func(args []string) {
fmt.Println(args)
tools = mtool.Tools{
"echo" : mtool.Tool{
func(args []string, flags *mtool.Flags) {
var b bool
flags.BoolVar(&b, "b", false, "the check flag")
flags.Parse(args)
fmt.Println(flags.Args())
},
"print string to standard output string",
"[str1 str2 ... strN]",
},
"sum" : multitool.Tool{
func(args []string) {
"sum" : mtool.Tool{
func(args []string, flags *mtool.Flags) {
flags.Parse(args)
one, _ := strconv.Atoi(args[1])
two, _ := strconv.Atoi(args[2])
fmt.Println(one + two)
},
"add one value to another",
"<int1> <int2>",
},
}
)
func main() {
multitool.Main("test", tools)
mtool.Main("test", tools)
}

View file

@ -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)
}