-
Notifications
You must be signed in to change notification settings - Fork 6
/
cli.go
85 lines (74 loc) · 1.77 KB
/
cli.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
package kibelasync
import (
"context"
"flag"
"fmt"
"io"
"log"
"golang.org/x/xerrors"
)
const cmdName = "kibelasync"
// Run the kibelasync
func Run(argv []string, outStream, errStream io.Writer) error {
log.SetOutput(errStream)
log.SetPrefix(fmt.Sprintf("[%s] ", cmdName))
nameAndVer := fmt.Sprintf("%s (v%s rev:%s)", cmdName, version, revision)
fs := flag.NewFlagSet(nameAndVer, flag.ContinueOnError)
fs.SetOutput(errStream)
fs.Usage = func() {
fmt.Fprintf(fs.Output(), "Usage of %s:\n", nameAndVer)
fs.PrintDefaults()
fmt.Fprintf(fs.Output(), "\nCommands:\n")
formatCommands(fs.Output())
}
ver := fs.Bool("version", false, "display version")
if err := fs.Parse(argv); err != nil {
return err
}
if *ver {
return printVersion(outStream)
}
argv = fs.Args()
if len(argv) < 1 {
return xerrors.New("no subcommand specified")
}
rnr, ok := dispatch[argv[0]]
if !ok {
return xerrors.Errorf("unknown subcommand: %s", argv[0])
}
return rnr.run(context.Background(), argv[1:], outStream, errStream)
}
func printVersion(out io.Writer) error {
_, err := fmt.Fprintf(out, "%s v%s (rev:%s)\n", cmdName, version, revision)
return err
}
var (
subCommands = []runner{
&cmdPublish{},
&cmdPull{},
&cmdPush{},
}
dispatch = make(map[string]runner, len(subCommands))
maxSubcommandName int
)
func init() {
for _, r := range subCommands {
n := r.name()
l := len(n)
if l > maxSubcommandName {
maxSubcommandName = l
}
dispatch[n] = r
}
}
func formatCommands(out io.Writer) {
format := fmt.Sprintf(" %%-%ds %%s\n", maxSubcommandName)
for _, r := range subCommands {
fmt.Fprintf(out, format, r.name(), r.description())
}
}
type runner interface {
name() string
description() string
run(context.Context, []string, io.Writer, io.Writer) error
}