forked from mkideal/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
257 lines (225 loc) · 5.82 KB
/
context.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
245
246
247
248
249
250
251
252
253
254
255
256
257
package cli
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"github.com/labstack/gommon/color"
"github.com/mattn/go-colorable"
)
type (
// Context provides running context
Context struct {
router []string
path string
argvList []interface{}
nativeArgs []string
flagSet *flagSet
command *Command
writer io.Writer
color color.Color
HTTPRequest *http.Request
HTTPResponse http.ResponseWriter
}
// Validator validates flag before running command
Validator interface {
Validate(*Context) error
}
// AutoHelper represents interface for showing help information automatically
AutoHelper interface {
AutoHelp() bool
}
)
func newContext(path string, router, args []string, argvList []interface{}, clr color.Color) (*Context, error) {
ctx := &Context{
path: path,
router: router,
argvList: argvList,
nativeArgs: args,
color: clr,
flagSet: newFlagSet(),
}
if !isEmptyArgvList(argvList) {
ctx.flagSet = parseArgvList(args, argvList, ctx.color)
if ctx.flagSet.err != nil {
return ctx, ctx.flagSet.err
}
}
return ctx, nil
}
// Path returns full command name
// `./app hello world -a --xyz=1` will returns "hello world"
func (ctx *Context) Path() string {
return ctx.path
}
// Router returns full command name with string array
// `./app hello world -a --xyz=1` will returns ["hello" "world"]
func (ctx *Context) Router() []string {
return ctx.router
}
// NativeArgs returns native args
// `./app hello world -a --xyz=1` will return ["-a" "--xyz=1"]
func (ctx *Context) NativeArgs() []string {
return ctx.nativeArgs
}
// Args returns free args
// `./app hello world -a=1 abc xyz` will return ["abc" "xyz"]
func (ctx *Context) Args() []string {
return ctx.flagSet.args
}
// NArg returns length of Args
func (ctx *Context) NArg() int {
return len(ctx.flagSet.args)
}
// NOpt returns num of options
func (ctx *Context) NOpt() int {
if ctx.flagSet == nil || ctx.flagSet.flagSlice == nil {
return 0
}
n := 0
for _, fl := range ctx.flagSet.flagSlice {
if fl.isSet {
n++
}
}
return n
}
// Argv returns parsed args object
func (ctx *Context) Argv() interface{} {
if ctx.argvList == nil || len(ctx.argvList) == 0 {
return nil
}
return ctx.argvList[0]
}
// RootArgv returns parsed root args object
func (ctx *Context) RootArgv() interface{} {
if isEmptyArgvList(ctx.argvList) {
return nil
}
index := len(ctx.argvList) - 1
return ctx.argvList[index]
}
// GetArgvList gets argv objects
func (ctx *Context) GetArgvList(curr interface{}, parents ...interface{}) error {
if isEmptyArgvList(ctx.argvList) {
return argvError{isEmpty: true}
}
for i, argv := range append([]interface{}{curr}, parents...) {
if argv == nil {
continue
}
if i >= len(ctx.argvList) {
return argvError{isOutOfRange: true}
}
if ctx.argvList[i] == nil {
return argvError{ith: i, msg: "source is nil"}
}
buf := bytes.NewBufferString("")
if err := json.NewEncoder(buf).Encode(ctx.argvList[i]); err != nil {
return err
}
if err := json.NewDecoder(buf).Decode(argv); err != nil {
return err
}
}
return nil
}
// GetArgvAt gets the i-th argv object
func (ctx *Context) GetArgvAt(argv interface{}, i int) error {
if isEmptyArgvList(ctx.argvList) {
return argvError{isEmpty: true}
}
if argv == nil {
return errors.New("argv is nil")
}
if i >= len(ctx.argvList) {
return argvError{isOutOfRange: true}
}
if ctx.argvList[i] == nil {
return argvError{ith: i, msg: "source is nil"}
}
buf := bytes.NewBufferString("")
if err := json.NewEncoder(buf).Encode(ctx.argvList[i]); err != nil {
return err
}
return json.NewDecoder(buf).Decode(argv)
}
// IsSet determins whether `flag` is set
func (ctx *Context) IsSet(flag string, aliasFlags ...string) bool {
fl, ok := ctx.flagSet.flagMap[flag]
if ok {
return fl.isSet
}
for _, alias := range aliasFlags {
if fl, ok := ctx.flagSet.flagMap[alias]; ok {
return fl.isSet
}
}
return false
}
// FormValues returns parsed args as url.Values
func (ctx *Context) FormValues() url.Values {
if ctx.flagSet == nil {
panic("ctx.flagSet == nil")
}
return ctx.flagSet.values
}
// Command returns current command instance
func (ctx *Context) Command() *Command {
return ctx.command
}
// Usage returns current command's usage with current context
func (ctx *Context) Usage() string {
return ctx.command.Usage(ctx)
}
// WriteUsage writes usage to writer
func (ctx *Context) WriteUsage() {
ctx.String(ctx.Usage())
}
// Writer returns writer
func (ctx *Context) Writer() io.Writer {
if ctx.writer == nil {
ctx.writer = colorable.NewColorableStdout()
}
return ctx.writer
}
// Write implements io.Writer
func (ctx *Context) Write(data []byte) (n int, err error) {
return ctx.Writer().Write(data)
}
// Color returns color instance
func (ctx *Context) Color() *color.Color {
return &ctx.color
}
// String writes formatted string to writer
func (ctx *Context) String(format string, args ...interface{}) *Context {
fmt.Fprintf(ctx.Writer(), format, args...)
return ctx
}
// JSON writes json string of obj to writer
func (ctx *Context) JSON(obj interface{}) *Context {
data, err := json.Marshal(obj)
if err == nil {
fmt.Fprint(ctx.Writer(), string(data))
}
return ctx
}
// JSONln writes json string of obj end with "\n" to writer
func (ctx *Context) JSONln(obj interface{}) *Context {
return ctx.JSON(obj).String("\n")
}
// JSONIndent writes pretty json string of obj to writer
func (ctx *Context) JSONIndent(obj interface{}, prefix, indent string) *Context {
data, err := json.MarshalIndent(obj, prefix, indent)
if err == nil {
fmt.Fprint(ctx.Writer(), string(data))
}
return ctx
}
// JSONIndentln writes pretty json string of obj end with "\n" to writer
func (ctx *Context) JSONIndentln(obj interface{}, prefix, indent string) *Context {
return ctx.JSONIndent(obj, prefix, indent).String("\n")
}