diff --git a/client/writer.go b/client/writer.go index c8eb5b6..f68e3dd 100644 --- a/client/writer.go +++ b/client/writer.go @@ -8,6 +8,8 @@ import ( "strconv" "strings" "text/tabwriter" + + "github.com/howardjohn/kubectl-resources/util" ) const ( @@ -33,7 +35,8 @@ func Write(response map[string]*PodResource, args *Args) error { } sortPodResources(resources) if !args.Verbose { - simplifyNames(resources) + simplifyPodNames(resources) + simplifyNodeNames(resources) } w := getNewTabWriter(os.Stdout) @@ -138,7 +141,7 @@ func formatMemory(i int64) string { return strconv.FormatInt(mb, 10) + "Mi" } -func simplifyNames(resources []*PodResource) { +func simplifyPodNames(resources []*PodResource) { names := map[string]int{} for _, pod := range resources { parts := strings.Split(pod.Name, "-") @@ -147,6 +150,10 @@ func simplifyNames(resources []*PodResource) { } for _, pod := range resources { parts := strings.Split(pod.Name, "-") + // Skip pods that don't follow assumptions + if len(parts) < 3 { + continue + } shortName := strings.Join(parts[:len(parts)-2], "-") if names[shortName] > 1 { pod.Name = shortName + "-" + parts[len(parts)-1] @@ -156,6 +163,17 @@ func simplifyNames(resources []*PodResource) { } } +func simplifyNodeNames(resources []*PodResource) { + var nameParts []util.Part + for _, pod := range resources { + nameParts = append(nameParts, strings.Split(pod.Node, "-")) + } + lcp := strings.Join(util.LongestCommonPrefix(nameParts), "-") + "-" + for _, pod := range resources { + pod.Node = strings.TrimPrefix(pod.Node, lcp) + } +} + // GetNewTabWriter returns a tabwriter that translates tabbed columns in input into properly aligned text. func getNewTabWriter(output io.Writer) *tabwriter.Writer { return tabwriter.NewWriter(output, tabwriterMinWidth, tabwriterWidth, tabwriterPadding, tabwriterPadChar, 0) diff --git a/util/names.go b/util/names.go new file mode 100644 index 0000000..3b33fe5 --- /dev/null +++ b/util/names.go @@ -0,0 +1,31 @@ +package util + +type Part []string + +func LongestCommonPrefix(parts []Part) Part { + var result Part + + maxIndex := 0 + for i, part := range parts { + strLen := len(part) + if i == 0 { + maxIndex = strLen - 1 + result = part + continue + } + + if strLen-1 < maxIndex { + maxIndex = strLen - 1 + result = result[:strLen] + } + + for j := 0; j <= maxIndex && j < strLen; j++ { + if part[j] != result[j] { + maxIndex = j - 1 + result = part[:j] + } + } + } + + return result +}