-
-
Notifications
You must be signed in to change notification settings - Fork 816
/
Copy pathmodule_validator.go
81 lines (65 loc) · 1.83 KB
/
module_validator.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
package app
import (
"fmt"
"os"
"github.com/logrusorgru/aurora/v4"
"github.com/wtfutil/wtf/cfg"
"github.com/wtfutil/wtf/wtf"
)
// ModuleValidator is responsible for validating the state of a module's configuration
type ModuleValidator struct{}
type widgetError struct {
name string
validationErrors []cfg.Validatable
}
// NewModuleValidator creates and returns an instance of ModuleValidator
func NewModuleValidator() *ModuleValidator {
return &ModuleValidator{}
}
// Validate rolls through all the enabled widgets and looks for configuration errors.
// If it finds any it stringifies them, writes them to the console, and kills the app gracefully
func (val *ModuleValidator) Validate(widgets []wtf.Wtfable) {
validationErrors := validate(widgets)
if len(validationErrors) > 0 {
fmt.Println()
for _, error := range validationErrors {
for _, message := range error.errorMessages() {
fmt.Println(message)
}
}
fmt.Println()
os.Exit(1)
}
}
func validate(widgets []wtf.Wtfable) (widgetErrors []widgetError) {
for _, widget := range widgets {
err := widgetError{name: widget.Name()}
for _, val := range widget.CommonSettings().Validations() {
if val.HasError() {
err.validationErrors = append(err.validationErrors, val)
}
}
if len(err.validationErrors) > 0 {
widgetErrors = append(widgetErrors, err)
}
}
return widgetErrors
}
func (err widgetError) errorMessages() (messages []string) {
widgetMessage := fmt.Sprintf(
"%s in %s configuration",
aurora.Red("Errors"),
aurora.Yellow(
fmt.Sprintf(
"%s.position",
err.name,
),
),
)
messages = append(messages, widgetMessage)
for _, e := range err.validationErrors {
configMessage := fmt.Sprintf(" - %s\t%s %v", e.String(), aurora.Red("Error:"), e.Error())
messages = append(messages, configMessage)
}
return messages
}