Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"flag"
"fmt"
"os"
"strings"
)
type Cli struct {
cmds map[string]*flag.FlagSet
cb *func()
}
func NewCli(callback *func()) *Cli {
return &Cli{map[string]*flag.FlagSet{}, callback}
}
func (r *Cli) AddSub(name string) *flag.FlagSet {
name = strings.TrimSpace(name)
cmd := flag.NewFlagSet(name, flag.ExitOnError)
r.cmds[name] = cmd
return cmd
}
func (r *Cli) Parse() (string, *flag.FlagSet) {
names := []string{}
for name, _ := range r.cmds {
names = append(names, name)
}
if len(os.Args) < 2 {
fmt.Printf("expected subcommands: %s\n", strings.Join(names, ", "))
if r.cb != nil {
(*r.cb)()
}
os.Exit(1)
}
if cmd, ok := r.cmds[os.Args[1]]; ok {
cmd.Parse(os.Args[2:])
return os.Args[1], cmd
} else {
fmt.Printf("expected subcommands: %s\n", strings.Join(names, ", "))
if r.cb != nil {
(*r.cb)()
}
os.Exit(1)
}
return "", nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment