-
Notifications
You must be signed in to change notification settings - Fork 113
/
option.go
75 lines (65 loc) · 1.4 KB
/
option.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
package diagnostics
import (
"fmt"
"strconv"
"strings"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
var ErrInvalidOption = errors.New("Invalid option")
type Option struct {
Key string
Value string
}
func OptionsFromStrings(options []string) ([]*Option, error) {
out := make([]*Option, len(options))
for i, o := range options {
opt, err := OptionFromString(o)
if err != nil {
return nil, errors.Wrapf(err, "%q is not a valid option", o)
}
out[i] = opt
}
return out, nil
}
func OptionFromString(option string) (*Option, error) {
parts := strings.SplitN(option, ":", 2)
if len(parts) == 0 {
return nil, ErrInvalidOption
}
return &Option{
Key: parts[0],
Value: parts[1],
}, nil
}
func (o *Option) AsString(defaultVal string) string {
if o == nil || o.Value == "" {
return defaultVal
}
return o.Value
}
func (o *Option) AsInt(defaultVal int) int {
if o == nil || o.Value == "" {
return defaultVal
}
i, err := strconv.Atoi(o.Value)
if err != nil {
logrus.WithError(err).Warnf("could not parse int (%s)", o.Value)
return defaultVal
}
return i
}
func (o *Option) MarshalText() (text []byte, err error) {
if o == nil {
return nil, ErrInvalidOption
}
return []byte(fmt.Sprintf("%s:%s", o.Key, o.Value)), nil
}
func (o *Option) UnmarshalText(text []byte) error {
opt, err := OptionFromString(string(text))
if err != nil {
return err
}
*o = *opt
return nil
}