-
Notifications
You must be signed in to change notification settings - Fork 82
/
command.go
90 lines (71 loc) · 2.01 KB
/
command.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
package gowrap
import (
"flag"
"io"
"text/template"
)
var version string = "dev"
// Command interface represents gowrap subcommand
type Command interface {
//FlagSet returns command specific flag set. If command doesn't have any flags nil should be returned.
FlagSet() *flag.FlagSet
//Run runs command
Run(args []string, stdout io.Writer) error
//Description returns short description of a command that is shown in the help message
ShortDescription() string
UsageLine() string
HelpMessage(w io.Writer) error
}
// BaseCommand implements Command interface
type BaseCommand struct {
Flags *flag.FlagSet
Short string
Usage string
Help string
}
// ShortDescription implements Command
func (b BaseCommand) ShortDescription() string {
return b.Short
}
// UsageLine implements Command
func (b BaseCommand) UsageLine() string {
return b.Usage
}
// FlagSet implements Command
func (b BaseCommand) FlagSet() *flag.FlagSet {
return b.Flags
}
// HelpMessage implements Command
func (b BaseCommand) HelpMessage(w io.Writer) error {
_, err := w.Write([]byte(b.Help))
return err
}
var commands = map[string]Command{}
// RegisterCommand adds command to the global Commands map
func RegisterCommand(name string, cmd Command) {
commands[name] = cmd
if fs := cmd.FlagSet(); fs != nil {
fs.Init("", flag.ContinueOnError)
fs.SetOutput(io.Discard)
}
}
// GetCommand returns command from the global Commands map
func GetCommand(name string) Command {
return commands[name]
}
// Usage writes gowrap usage message to w
func Usage(w io.Writer) error {
return usageTemplate.Execute(w, struct {
Commands map[string]Command
Version string
}{commands, version})
}
var usageTemplate = template.Must(template.New("usage").Parse(`GoWrap({{.Version}}) is a tool for generating decorators for the Go interfaces
Usage:
gowrap command [arguments]
The commands are:
{{ range $name, $cmd := .Commands }}
{{ printf "%-10s" $name }}{{ $cmd.ShortDescription }}
{{ end }}
Use "gowrap help [command]" for more information about a command.
`))