-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcontext.go
73 lines (65 loc) · 1.77 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
package guinea
import (
"flag"
)
// OptionValue stores the value of a parsed option as returned by the standard
// library flag package. The helper methods can be used to cast the value
// quickly but they will only succeed if the defined type of the option matches
// the called method.
type OptionValue struct {
Value interface{}
}
// Bool casts a value to a bool and panics on failure.
func (v OptionValue) Bool() bool {
return *v.Value.(*bool)
}
// Int casts a value to an int and panics on failure.
func (v OptionValue) Int() int {
return *v.Value.(*int)
}
// Str casts a value to a string and panics on failure.
func (v OptionValue) Str() string {
return *v.Value.(*string)
}
// Context holds the options and arguments provided by the user.
type Context struct {
Options map[string]OptionValue
Arguments []string
}
func makeContext(c Command, args []string) (*Context, error) {
context := &Context{
Options: make(map[string]OptionValue),
}
flagset := flag.NewFlagSet("sth", flag.ContinueOnError)
flagset.Usage = func() {}
for _, option := range c.Options {
switch option.Type {
case String:
if option.Default == nil {
option.Default = ""
}
context.Options[option.Name] = OptionValue{
Value: flagset.String(option.Name, option.Default.(string), ""),
}
case Bool:
if option.Default == nil {
option.Default = false
}
context.Options[option.Name] = OptionValue{
Value: flagset.Bool(option.Name, option.Default.(bool), ""),
}
case Int:
if option.Default == nil {
option.Default = 0
}
context.Options[option.Name] = OptionValue{
Value: flagset.Int(option.Name, option.Default.(int), ""),
}
}
}
if err := flagset.Parse(args); err != nil {
return nil, err
}
context.Arguments = flagset.Args()
return context, nil
}