github.com/wtfutil/wtf@v0.43.0/app/module_validator.go (about) 1 package app 2 3 import ( 4 "fmt" 5 "os" 6 7 "github.com/logrusorgru/aurora/v4" 8 "github.com/wtfutil/wtf/cfg" 9 "github.com/wtfutil/wtf/wtf" 10 ) 11 12 // ModuleValidator is responsible for validating the state of a module's configuration 13 type ModuleValidator struct{} 14 15 type widgetError struct { 16 name string 17 validationErrors []cfg.Validatable 18 } 19 20 // NewModuleValidator creates and returns an instance of ModuleValidator 21 func NewModuleValidator() *ModuleValidator { 22 return &ModuleValidator{} 23 } 24 25 // Validate rolls through all the enabled widgets and looks for configuration errors. 26 // If it finds any it stringifies them, writes them to the console, and kills the app gracefully 27 func (val *ModuleValidator) Validate(widgets []wtf.Wtfable) { 28 validationErrors := validate(widgets) 29 30 if len(validationErrors) > 0 { 31 fmt.Println() 32 for _, error := range validationErrors { 33 for _, message := range error.errorMessages() { 34 fmt.Println(message) 35 } 36 } 37 fmt.Println() 38 39 os.Exit(1) 40 } 41 } 42 43 func validate(widgets []wtf.Wtfable) (widgetErrors []widgetError) { 44 for _, widget := range widgets { 45 err := widgetError{name: widget.Name()} 46 47 for _, val := range widget.CommonSettings().Validations() { 48 if val.HasError() { 49 err.validationErrors = append(err.validationErrors, val) 50 } 51 } 52 53 if len(err.validationErrors) > 0 { 54 widgetErrors = append(widgetErrors, err) 55 } 56 } 57 58 return widgetErrors 59 } 60 61 func (err widgetError) errorMessages() (messages []string) { 62 widgetMessage := fmt.Sprintf( 63 "%s in %s configuration", 64 aurora.Red("Errors"), 65 aurora.Yellow( 66 fmt.Sprintf( 67 "%s.position", 68 err.name, 69 ), 70 ), 71 ) 72 messages = append(messages, widgetMessage) 73 74 for _, e := range err.validationErrors { 75 configMessage := fmt.Sprintf(" - %s\t%s %v", e.String(), aurora.Red("Error:"), e.Error()) 76 77 messages = append(messages, configMessage) 78 } 79 80 return messages 81 }