-
Notifications
You must be signed in to change notification settings - Fork 69
/
form.go
186 lines (163 loc) · 4.39 KB
/
form.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
package tui
import (
"bufio"
"encoding/json"
"fmt"
"os"
"strings"
)
// A ComplexValue represents some thing that needs to be displayed
// one way to a human operator, and another way to a machine (API)
type ComplexValue interface {
HumanReadable() string // Used to display information to the human operator
MachineReadable() interface{} // Used for API requests
}
// A FieldProcessor is any function that validates, transforms, or
// replaces a value entered by the operator into a different value.
// For example, entering a duration as a string, i.e. "4d", might
// result in a FieldProcessor creating a Duration object representing
// four days worth of time.
type FieldProcessor func(name string, value string) (interface{}, error)
// A Form represents a set of Fields that an operator must fill out
// in order to change some piece of data elsewhere inside of SHIELD.
type Form struct {
Fields []*Field
}
// A Field represents a single piece of information that the operator
// must enter, usually in the larger context of a Form. Each Field has
// its own prompt label, internal field name, stored value and
// processor function for validation / data manipulation.
type Field struct {
Label string
Name string
ShowAs string
Value interface{}
Processor FieldProcessor
Hidden bool
}
// NewForm creates and returns a pointer to a new Form object.
func NewForm() *Form {
return &Form{}
}
// NewField appends a new Field to the Form.
func (f *Form) NewField(label string, name string, value interface{}, showas string, fn FieldProcessor) (*Field, error) {
tmpField := Field{
Label: label,
Name: name,
ShowAs: showas,
Value: value,
Processor: fn,
Hidden: false,
}
f.Fields = append(f.Fields, &tmpField)
return &tmpField, nil
}
//GetField retrieves the reference to the Field with the Name attribute given
//to this function. Returns nil if no such Field was found.
func (f *Form) GetField(name string) *Field {
for _, field := range f.Fields {
if field.Name == name {
return field
}
}
return nil
}
func (field *Field) PromptString() string {
if field.ShowAs != "" {
return fmt.Sprintf("%s (%s)", field.Label, field.ShowAs)
}
if field.Value != nil {
if s, ok := field.Value.(string); !ok || s != "" {
return fmt.Sprintf("%s (%v)", field.Label, field.Value)
}
}
return field.Label
}
func (field *Field) Prompt() error {
in := bufio.NewReader(os.Stdin)
for {
fmt.Printf("%s: ", field.PromptString())
v, err := in.ReadString('\n')
if err != nil {
return err
}
v = field.OrDefault(strings.TrimSpace(v))
final, err := field.Processor(field.Name, v)
if err != nil {
fmt.Printf("!! %s\n", err)
continue
}
field.Value = final
return nil
}
}
func (field *Field) OrDefault(v string) string {
if v == "" {
return fmt.Sprintf("%v", field.Value)
}
return v
}
func (f *Form) Show() error {
for _, field := range f.Fields {
if !field.Hidden {
err := field.Prompt()
if err != nil {
return fmt.Errorf("%s", err)
}
}
}
return nil
}
func (f *Form) Confirm(prompt string) bool {
r := NewReport()
for _, field := range f.Fields {
if !field.Hidden {
if v, ok := field.Value.(ComplexValue); ok {
r.Add(field.Label, v.HumanReadable())
} else {
r.Add(field.Label, fmt.Sprintf("%v", field.Value))
}
}
}
fmt.Printf("\n\n")
r.Output(os.Stdout)
fmt.Printf("\n\n")
return Confirm(prompt)
}
func FieldIsRequired(name string, value string) (interface{}, error) {
if len(value) < 1 {
return value, fmt.Errorf("Field %s is a required field.\n", name)
}
return value, nil
}
func FieldIsOptional(name string, value string) (interface{}, error) {
return value, nil
}
func FieldIsBoolean(name string, value string) (interface{}, error) {
switch strings.ToLower(value) {
case "y":
fallthrough
case "yes":
return true, nil
case "n":
case "no":
return false, nil
}
return "", fmt.Errorf("'%s' is not a boolean value. Acceptable values are (y)es or (n)o.", value)
}
func (f *Form) BuildContent() (string, error) {
c := make(map[string]interface{})
for z := 0; z < len(f.Fields); z++ {
field := f.Fields[z]
if v, ok := field.Value.(ComplexValue); ok {
c[field.Name] = v.MachineReadable()
} else {
c[field.Name] = field.Value
}
}
j, err := json.Marshal(c)
if err != nil {
return "", fmt.Errorf("Could not marshal into JSON\nmapped input:%v\nerror:%s", c, err)
}
return string(j), nil
}