forked from fgeller/kt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
92 lines (77 loc) · 1.88 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"flag"
"fmt"
"os"
)
type command interface {
addFlags(*flag.FlagSet)
environFlags() map[string]string
run(args []string) error
}
var usageMessage = `hkt is a tool for Kafka.
Usage:
hkt command [arguments]
The commands are:
consume consume messages.
produce produce messages.
topic topic information.
group consumer group information and modification.
admin basic cluster administration.
Use "hkt [command] -help" for for information about the command.
More at https://github.com/heetch/hkt
`
var commands = map[string]command{
"consume": &consumeCmd{},
"produce": &produceCmd{},
"topic": &topicCmd{},
"group": &groupCmd{},
"admin": &adminCmd{},
}
var errSilent = fmt.Errorf("silent error; you should not be seeing this")
func main() {
os.Exit(main1())
}
func main1() int {
if err := main2(); err != nil {
if err != errSilent && err != flag.ErrHelp {
fmt.Fprintf(os.Stderr, "hkt: %v\n", err)
return 1
}
}
return 0
}
func main2() error {
c, args, err := parseCmd(os.Args...)
if err != nil {
return err
}
return c.run(args)
}
func parseCmd(args ...string) (command, []string, error) {
flags := flag.NewFlagSet(args[0], flag.ContinueOnError)
flags.Usage = func() {
fmt.Fprint(os.Stderr, usageMessage)
}
if err := flags.Parse(args[1:]); err != nil {
return nil, nil, errSilent
}
if flags.NArg() < 1 {
flags.Usage()
return nil, nil, errSilent
}
cmdName := flags.Arg(0)
c := commands[cmdName]
if c == nil {
return nil, nil, fmt.Errorf("unknown command %q; use `hkt -help` for help", cmdName)
}
subcmdFlags := flag.NewFlagSet("hkt "+cmdName, flag.ContinueOnError)
c.addFlags(subcmdFlags)
if err := subcmdFlags.Parse(flags.Args()[1:]); err != nil {
return nil, nil, err
}
if err := setFlagsFromEnv(subcmdFlags, c.environFlags()); err != nil {
return nil, nil, err
}
return c, subcmdFlags.Args(), nil
}