istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/config/analysis/diag/messages.go (about) 1 // Copyright Istio Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package diag 16 17 import ( 18 "sort" 19 ) 20 21 // Messages is a slice of Message items. 22 type Messages []Message 23 24 // Add a new message to the messages 25 func (ms *Messages) Add(m ...Message) { 26 *ms = append(*ms, m...) 27 } 28 29 // Sort the message lexicographically by level, code, resource origin name, then string. 30 func (ms *Messages) Sort() { 31 sort.Slice(*ms, func(i, j int) bool { 32 a, b := (*ms)[i], (*ms)[j] 33 switch { 34 case a.Type.Level() != b.Type.Level(): 35 return a.Type.Level().sortOrder < b.Type.Level().sortOrder 36 case a.Type.Code() != b.Type.Code(): 37 return a.Type.Code() < b.Type.Code() 38 case a.Resource == nil && b.Resource != nil: 39 return true 40 case a.Resource != nil && b.Resource == nil: 41 return false 42 case a.Resource != nil && b.Resource != nil && a.Resource.Origin.Comparator() != b.Resource.Origin.Comparator(): 43 return a.Resource.Origin.Comparator() < b.Resource.Origin.Comparator() 44 default: 45 return a.String() < b.String() 46 } 47 }) 48 } 49 50 // SortedDedupedCopy returns a different sorted (and deduped) Messages struct. 51 func (ms *Messages) SortedDedupedCopy() Messages { 52 newMs := append((*ms)[:0:0], *ms...) 53 newMs.Sort() 54 55 // Take advantage of the fact that the list is already sorted to dedupe 56 // messages (any duplicates should be adjacent). 57 var deduped Messages 58 for _, m := range newMs { 59 // Two messages are duplicates if they have the same string representation. 60 if len(deduped) != 0 && deduped[len(deduped)-1].String() == m.String() { 61 continue 62 } 63 deduped = append(deduped, m) 64 } 65 return deduped 66 } 67 68 // SetDocRef sets the doc URL reference tracker for the messages 69 func (ms *Messages) SetDocRef(docRef string) *Messages { 70 for i := range *ms { 71 (*ms)[i].DocRef = docRef 72 } 73 return ms 74 } 75 76 // FilterOutLowerThan only keeps messages at or above the specified output level 77 func (ms *Messages) FilterOutLowerThan(outputLevel Level) Messages { 78 outputMessages := Messages{} 79 for _, m := range *ms { 80 if m.Type.Level().IsWorseThanOrEqualTo(outputLevel) { 81 outputMessages = append(outputMessages, m) 82 } 83 } 84 return outputMessages 85 }