forked from tcnksm/gcli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
executable.go
130 lines (101 loc) · 2.45 KB
/
executable.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
package skeleton
import (
"fmt"
"reflect"
)
const (
// DefaultVersion is default appliaction version.
DefaultVersion = "0.1.0"
// DefaultDescription is default application description.
DefaultDescription = ""
)
// Executable store executable meta information.
type Executable struct {
// Name is executable name.
Name string
// Owner is owner of the executable.
Owner string
// Commands are commands of the executable.
Commands []*Command
// Flags are flags of the executable.
Flags []*Flag
// Version is initial version.
Version string
// Description is description of the executable.
Description string
// FrameworkStr is framework name to use.
FrameworkStr string `toml:"Framework"`
}
// NewExecutable is constructor of Executable struct.
func NewExecutable() *Executable {
return &Executable{
Version: DefaultVersion,
Description: DefaultDescription,
}
}
// Fix fixes user inputs for using
func (e *Executable) Fix() error {
for _, c := range e.Commands {
if err := c.Fix(); err != nil {
return err
}
}
for _, f := range e.Flags {
if err := f.Fix(); err != nil {
return err
}
}
return nil
}
// Validate validates Executalbe has required field or not.
// If not returns, errors as slice.
func (e *Executable) Validate() (errs []error) {
if e.Name == "" {
errs = append(errs, fmt.Errorf("`Name` cannot be blank"))
}
if e.Owner == "" {
errs = append(errs, fmt.Errorf("`Owner` cannot be blank"))
}
if len(e.Commands) == 0 && len(e.Flags) == 0 {
// can be blank ?
}
if len(e.Commands) > 0 {
for _, c := range e.Commands {
if c.Name == "" {
errs = append(errs, fmt.Errorf("`Command.Name` cannot be blank"))
}
}
}
if len(e.Flags) > 0 {
for _, f := range e.Flags {
if f.LongName == "" {
errs = append(errs, fmt.Errorf("`Flag.LongName` cannot be blank"))
}
if f.TypeString == "" {
errs = append(errs, fmt.Errorf("`Flag.TypeString` cannot be blank. Select from bool|int|string"))
}
}
}
if e.Version == "" {
// can be blank
}
if e.Description == "" {
// can be blank
}
if e.FrameworkStr == "" {
// can be blank
}
return errs
}
// Overwrite overwrites provided value with default value.
func (e *Executable) Overwrite(key string, v interface{}) error {
// Check
switch v.(type) {
case string, []*Command, []*Flag:
default:
return fmt.Errorf("unexpected value: %#v", v)
}
rve := reflect.ValueOf(e)
rve.Elem().FieldByName(key).Set(reflect.ValueOf(v))
return nil
}