cli/src/mtool/main.go

110 lines
1.5 KiB
Go
Raw Normal View History

2023-03-24 10:05:50 +03:00
package mtool
2022-06-16 09:02:24 +03:00
import(
"fmt"
"os"
2023-02-16 15:05:23 +03:00
path "path/filepath"
2023-03-23 12:32:52 +03:00
"flag"
"sort"
2022-06-16 09:02:24 +03:00
)
2023-03-23 12:32:52 +03:00
type Flags struct {
*flag.FlagSet
2022-10-11 15:38:48 +03:00
}
2023-03-23 12:32:52 +03:00
type Handler func(args []string, flags *Flags)
type Tool struct {
Handler Handler
Desc, Usage string
}
2022-06-16 09:02:24 +03:00
2022-10-11 15:38:48 +03:00
type Tools map[string] Tool
2022-06-16 09:02:24 +03:00
func Main(name string, m Tools) {
var(
utilName string
args []string
)
2023-03-23 12:32:52 +03:00
arg0 := os.Args[0]
binBase := path.Base(arg0) ;
binBase = binBase[:len(binBase)-len(path.Ext(binBase))]
if binBase != name {
2022-06-16 09:02:24 +03:00
utilName = binBase
args = os.Args[:]
} else {
if len(os.Args)<2 {
keys := make([]string, len(m))
i := 0
for k, _ := range m {
keys[i] = k
i++
2022-06-16 09:02:24 +03:00
}
sort.Strings(keys)
for _, k := range keys {
tool := m[k]
fmt.Printf("%s: %s\n", k, tool.Desc)
}
2022-06-16 09:02:24 +03:00
os.Exit(0)
}
utilName = os.Args[1]
args = os.Args[1:]
}
if _, ok := m[utilName] ; !ok {
2023-03-23 12:32:52 +03:00
fmt.Printf("%s: No such uitl as '%s'.\n", arg0, utilName )
2022-06-16 09:02:24 +03:00
os.Exit(1)
}
2023-03-23 12:32:52 +03:00
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)
2022-06-16 09:02:24 +03:00
}