cli/main.go

137 lines
2 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
2023-03-24 19:35:14 +03:00
progName string
utilName string
args []string
parsedArgs []string
2022-10-11 15:38:48 +03:00
}
type Handler func(*Flags)
2023-03-23 12:32:52 +03:00
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 (flags *Flags) Parse() []string {
flags.FlagSet.Parse(flags.args)
flags.parsedArgs = flags.FlagSet.Args()
return flags.parsedArgs
}
2023-03-24 20:36:29 +03:00
func (flags *Flags) AllArgs() []string {
return flags.args
}
func (flags *Flags) Args() []string {
return flags.parsedArgs
}
2023-03-24 19:35:14 +03:00
func (flags *Flags) ProgName() string {
return flags.progName
}
func (flags *Flags) UtilName() string {
return flags.utilName
}
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
2023-03-24 20:18:04 +03:00
args = os.Args
2022-06-16 09:02:24 +03:00
} 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]
2023-03-24 20:18:04 +03:00
flagSet := flag.NewFlagSet(utilName, flag.ExitOnError)
2023-03-23 12:32:52 +03:00
flags := &Flags{
2023-03-24 19:35:14 +03:00
FlagSet : flagSet,
2023-03-23 12:32:52 +03:00
}
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",
2023-03-24 20:18:04 +03:00
utilName, utilName,
2023-03-23 12:32:52 +03:00
)
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)
}
2023-03-24 19:35:14 +03:00
flags.progName = name
2023-03-24 20:18:04 +03:00
flags.utilName = utilName
flags.args = args[1:]
2023-03-23 12:32:52 +03:00
util.Handler(flags)
2022-06-16 09:02:24 +03:00
}