github.com/grafana/tanka@v0.26.1-0.20240506093700-c22cfc35c21a/pkg/kubernetes/manifest/errors.go (about) 1 package manifest 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/fatih/color" 8 ) 9 10 // SchemaError means that some expected fields were missing 11 type SchemaError struct { 12 Fields map[string]error 13 Name string 14 Manifest Manifest 15 } 16 17 var ( 18 redf = color.New(color.FgRed, color.Bold, color.Underline).Sprintf 19 yellowf = color.New(color.FgYellow).Sprintf 20 bluef = color.New(color.FgBlue, color.Bold).Sprintf 21 ) 22 23 // Error returns the fields the manifest at the path is missing 24 func (s *SchemaError) Error() string { 25 if s.Name == "" { 26 s.Name = "Resource" 27 } 28 29 msg := fmt.Sprintf("%s has missing or invalid fields:\n", redf(s.Name)) 30 31 for k, err := range s.Fields { 32 if err == nil { 33 continue 34 } 35 36 msg += fmt.Sprintf(" - %s: %s\n", yellowf(k), err) 37 } 38 39 if s.Manifest != nil { 40 msg += bluef("\nPlease check below object:\n") 41 msg += SampleString(s.Manifest.String()).Indent(2) 42 } 43 44 return msg 45 } 46 47 // SampleString is used for displaying code samples for error messages. It 48 // truncates the output to 10 lines 49 type SampleString string 50 51 func (s SampleString) String() string { 52 lines := strings.Split(strings.TrimSpace(string(s)), "\n") 53 truncate := len(lines) >= 10 54 if truncate { 55 lines = lines[0:10] 56 } 57 out := strings.Join(lines, "\n") 58 if truncate { 59 out += "\n..." 60 } 61 return out 62 } 63 64 func (s SampleString) Indent(n int) string { 65 indent := strings.Repeat(" ", n) 66 lines := strings.Split(s.String(), "\n") 67 return indent + strings.Join(lines, "\n"+indent) 68 } 69 70 // ErrorDuplicateName means two resources share the same name using the given 71 // nameFormat. 72 type ErrorDuplicateName struct { 73 name string 74 format string 75 } 76 77 func (e ErrorDuplicateName) Error() string { 78 return fmt.Sprintf("Two resources share the same name '%s'. Please adapt the name template '%s'.", e.name, e.format) 79 }