istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/test/framework/components/echo/namespacedname.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 echo 16 17 import ( 18 "sort" 19 "strings" 20 21 "istio.io/istio/pkg/test/framework/components/namespace" 22 "istio.io/istio/pkg/util/sets" 23 ) 24 25 // NamespacedName represents the full name of a service. 26 type NamespacedName struct { 27 // Namespace of the echo Instance. If not provided, a default namespace "apps" is used. 28 Namespace namespace.Instance 29 30 // Name of the service within the Namespace. 31 Name string 32 } 33 34 // NamespaceName returns the string name of the namespace, or "" if Namespace is nil. 35 func (n NamespacedName) NamespaceName() string { 36 if n.Namespace != nil { 37 return n.Namespace.Name() 38 } 39 return "" 40 } 41 42 // String returns the Istio-formatted service name in the form of <namespace>/<name>. 43 func (n NamespacedName) String() string { 44 return n.NamespaceName() + "/" + n.Name 45 } 46 47 // PrefixString returns a string in the form of <name>.<prefix>. This is helpful for 48 // providing more stable test names. 49 func (n NamespacedName) PrefixString() string { 50 if n.Namespace == nil { 51 return n.Name 52 } 53 return n.Name + "." + n.Namespace.Prefix() 54 } 55 56 var _ sort.Interface = NamespacedNames{} 57 58 // NamespacedNames is a list of NamespacedName. 59 type NamespacedNames []NamespacedName 60 61 func (n NamespacedNames) Less(i, j int) bool { 62 return strings.Compare(n[i].PrefixString(), n[j].PrefixString()) < 0 63 } 64 65 func (n NamespacedNames) Swap(i, j int) { 66 n[i], n[j] = n[j], n[i] 67 } 68 69 func (n NamespacedNames) Len() int { 70 return len(n) 71 } 72 73 // Names returns the list of service names without any namespace appended. 74 func (n NamespacedNames) Names() []string { 75 return n.uniqueSortedNames(func(nn NamespacedName) string { 76 return nn.Name 77 }) 78 } 79 80 func (n NamespacedNames) NamesWithNamespacePrefix() []string { 81 return n.uniqueSortedNames(func(nn NamespacedName) string { 82 if nn.Namespace == nil { 83 return nn.Name 84 } 85 return nn.Name + "." + nn.Namespace.Prefix() 86 }) 87 } 88 89 func (n NamespacedNames) uniqueSortedNames(getName func(NamespacedName) string) []string { 90 set := sets.NewWithLength[string](n.Len()) 91 for _, nn := range n { 92 name := getName(nn) 93 set.Insert(name) 94 } 95 return sets.SortedList(set) 96 }