-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
244 lines (210 loc) · 5.73 KB
/
app.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package cli
import (
"errors"
"fmt"
"io"
"os"
"os/signal"
"path"
"time"
)
// App is the main structure of a cli application. It is recommended that
// an app be created with the cli.NewApp() function
type App struct {
// The name of the program. Defaults to path.Base(os.Args[0])
Name string
// A short description of the usage of this command
Usage string
// Custom text to show on USAGE section of help
UsageText string
// A longer explanation of how the command works
Description string
// A short description of the arguments of this command
ArgsUsage string
// Compilation date
Compiled time.Time
// List of all authors who contributed
Authors []*Author
// Copyright of the binary if any
Copyright string
// Full name of command for help, defaults to full command name, including parent commands.
HelpName string
// Boolean to hide built-in help command
HideHelp bool
// Version of the program
Version string
// Boolean to hide built-in version flag and the VERSION section of help
HideVersion bool
// Signals are the signals that we want to handle
Signals []os.Signal
// List of commands to execute
Commands []*Command
// List of flags to parse
Flags []Flag
// Providers contains a list of all providers
Providers []Provider
// An action to execute before any subcommands are run, but after the context is ready
// If a non-nil error is returned, no subcommands are run
Before BeforeFunc
// An action to execute after any subcommands are run, but after the subcommand has finished
// It is run even if Action() panics
After AfterFunc
// An action to execute before provider execution
BeforeInit BeforeFunc
// An action to execute after provider execution
AfterInit AfterFunc
// The action to execute when no subcommands are specified
// Expects a `cli.ActionFunc` but will accept the *deprecated* signature of `func(*cli.Context) {}`
Action ActionFunc
// Strategy enables comman retry logic
Strategy BackOffStrategy
// OnSignal occurs on system signal
OnSignal SignalFunc
// Execute this function if a usage error occurs.
OnUsageError UsageErrorFunc
// OnCommandNotFound is executed if the proper command cannot be found
OnCommandNotFound CommandNotFoundFunc
// Execute this function to handle ExitErrors. If not provided, HandleExitCoder is provided to
// function as a default, so this is optional.
OnExitError ExitErrorHandlerFunc
// Exit is the function used when the app exits. If not set defaults to os.Exit.
Exit ExitFunc
// Writer writer to write output to
Writer io.Writer
// ErrWriter writes error output
ErrWriter io.Writer
}
// Run is the entry point to the cli app. Parses the arguments slice and routes
// to the proper flag/args combination
func (app *App) Run(args []string) {
args = app.prepare(args)
cmd := &Command{
Name: app.Name,
Usage: app.Usage,
UsageText: app.UsageText,
HideHelp: app.HideHelp,
HelpName: app.HelpName,
Commands: app.Commands,
Description: app.Description,
ArgsUsage: app.ArgsUsage,
Flags: app.Flags,
Before: app.Before,
After: app.After,
BeforeInit: app.BeforeInit,
AfterInit: app.AfterInit,
Action: app.Action,
Strategy: app.Strategy,
Providers: app.Providers,
OnUsageError: app.OnUsageError,
OnCommandNotFound: app.OnCommandNotFound,
Metadata: Map{
"HideVersion": app.HideVersion,
"Version": app.Version,
"Authors": app.Authors,
"Copyright": app.Copyright,
},
}
ctx := &Context{
Command: cmd,
Args: args[1:],
Writer: app.Writer,
ErrWriter: app.ErrWriter,
Metadata: make(map[string]interface{}),
}
app.notify(ctx)
app.error(cmd.RunWithContext(ctx))
}
func (app *App) notify(ctx *Context) {
if len(app.Signals) == 0 {
return
}
if app.OnSignal == nil {
return
}
ch := make(chan os.Signal, 1)
signal.Notify(ch, app.Signals...)
go func() {
signal := <-ch
err := app.OnSignal(ctx, signal)
app.error(err)
}()
}
func (app *App) prepare(args []string) []string {
app.flags()
app.commands()
return app.app(args)
}
func (app *App) app(args []string) []string {
if len(args) == 0 {
args = []string{"unknown"}
}
if app.Name == "" {
app.Name = path.Base(args[0])
}
if app.Compiled.IsZero() {
info, err := os.Stat(args[0])
if err != nil {
app.Compiled = time.Now()
} else {
app.Compiled = info.ModTime()
}
}
if app.Writer == nil {
app.Writer = os.Stdout
}
if app.ErrWriter == nil {
app.ErrWriter = os.Stderr
}
if app.Exit == nil {
app.Exit = os.Exit
}
return args
}
func (app *App) flags() {
if !app.HideVersion {
version := &BoolFlag{
Name: "version, v",
Usage: "prints the version",
}
app.Flags = append(app.Flags, version)
}
}
func (app *App) commands() {
if !app.HideVersion {
version := NewVersionCommand()
app.Commands = append(app.Commands, version)
}
}
func (app *App) error(err error) {
if err == nil {
return
}
if app.OnExitError != nil {
err = app.OnExitError(err)
}
fmt.Fprintln(app.ErrWriter, err)
var errx *ExitError
if !errors.As(err, &errx) {
errx = WrapError(err)
}
app.Exit(errx.Code())
}
// Author represents someone who has contributed to a cli project.
type Author struct {
// Name of the author
Name string
// Email of the author
Email string
}
// String makes Author comply to the Stringer interface, to allow an easy print in the templating process
func (author *Author) String() string {
value := ""
if author.Email != "" {
value = fmt.Sprintf(" <%s>", author.Email)
}
return fmt.Sprintf("%v%v", author.Name, value)
}
// Copyright creates a copyright message
func Copyright(name string) string {
return fmt.Sprintf("%s (C) %d", name, time.Now().Year())
}