github.com/grahambrereton-form3/tilt@v0.10.18/internal/k8s/names.go (about) 1 package k8s 2 3 import ( 4 "fmt" 5 "strings" 6 ) 7 8 // Calculates names for workloads by using the shortest uniquely matching identifiers 9 func UniqueNames(es []K8sEntity, minComponents int) []string { 10 ret := make([]string, len(es)) 11 // how many resources potentially map to a given name 12 counts := make(map[string]int) 13 14 // count how many entities want each potential name 15 for _, e := range es { 16 for _, name := range potentialNames(e, minComponents) { 17 counts[name]++ 18 } 19 } 20 21 // for each entity, take the shortest name that is uniquely wanted by that entity 22 for i, e := range es { 23 names := potentialNames(e, minComponents) 24 for _, name := range names { 25 if counts[name] == 1 { 26 ret[i] = name 27 break 28 } 29 } 30 31 if ret[i] == "" { 32 // If we hit this case, this means we have two resources with the same 33 // name/kind/namespace/group This usually means the user is trying to 34 // deploy the same resource twice. Kubernetes will not treat these as 35 // unique. 36 // 37 // We should surface a warning or error about this somewhere else that has 38 // more context on how to fix it. 39 // https://github.com/windmilleng/tilt/issues/1852 40 // 41 // But for now, append the index to the name to make it unique 42 ret[i] = fmt.Sprintf("%s:%d", names[len(names)-1], i) 43 } 44 } 45 46 return ret 47 } 48 49 // returns a list of potential names, in order of preference 50 func potentialNames(e K8sEntity, minComponents int) []string { 51 gvk := e.GVK() 52 components := []string{ 53 e.Name(), 54 gvk.Kind, 55 e.Namespace().String(), 56 gvk.Group, 57 } 58 var ret []string 59 for i := minComponents - 1; i < len(components); i++ { 60 ret = append(ret, strings.ToLower(strings.Join(components[:i+1], ":"))) 61 } 62 return ret 63 }