Skip to content

Commit

Permalink
Simplify node name
Browse files Browse the repository at this point in the history
  • Loading branch information
howardjohn committed Jun 28, 2019
1 parent 618f363 commit ec5c19c
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
22 changes: 20 additions & 2 deletions client/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"strconv"
"strings"
"text/tabwriter"

"github.com/howardjohn/kubectl-resources/util"
)

const (
Expand All @@ -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)
Expand Down Expand Up @@ -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, "-")
Expand All @@ -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]
Expand All @@ -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)
Expand Down
31 changes: 31 additions & 0 deletions util/names.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit ec5c19c

Please sign in to comment.