Skip to content

Commit

Permalink
feat(watch): Adding --show-labels support
Browse files Browse the repository at this point in the history
Signed-off-by: Vincent Boutour <bob@vibioh.fr>
  • Loading branch information
ViBiOh committed May 3, 2024
1 parent 9efc804 commit 8bd39cc
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ Usage:
Flags:
-o, --output string Output format. One of: (wide)
-l, --selector stringToString Labels to filter pods (default [])
--show-labels Show all labels as the last column
```

### `restart`
Expand Down
30 changes: 29 additions & 1 deletion cmd/watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"sort"
"strings"
"syscall"
"time"

Expand All @@ -26,13 +27,17 @@ type watchPod struct {
v1.Pod `json:"pod"`
}

var outputFormat string
var (
outputFormat string
showLabels bool
)

func initWatch() {
flags := watchCmd.Flags()

flags.StringVarP(&outputFormat, "output", "o", "", "Output format. One of: (wide)")
flags.StringToStringVarP(&labelsSelector, "selector", "l", nil, "Labels to filter pods")
flags.BoolVarP(&showLabels, "show-labels", "", false, "Show all labels as the last column")
}

var watchCmd = &cobra.Command{
Expand Down Expand Up @@ -108,6 +113,11 @@ func initWatchTable() *table.Table {
)
}

if showLabels {
defaultWidths = append(defaultWidths, 12)
content = append(content, table.NewCell("LABELS"))
}

watchTable := table.New(defaultWidths)
output.Std("", watchTable.Format(content))

Expand Down Expand Up @@ -228,6 +238,10 @@ func outputWatch(watchTable *table.Table, contextName string, pod v1.Pod) {
)
}

if showLabels {
content = append(content, table.NewCell(labelsAsString(pod.GetLabels())))
}

output.Std("", watchTable.Format(content))
}

Expand All @@ -246,6 +260,20 @@ func getPhaseCell(phase string) table.Cell {
}
}

func labelsAsString(labels map[string]string) string {
values := make([]string, len(labels))

var index int
for key, value := range labels {
values[index] = fmt.Sprintf("%s=%s", key, value)
index++
}

sort.Strings(values)

return strings.Join(values, ",")
}

// from https://github.com/kubernetes/kubernetes/blob/v1.24.3/pkg/printers/internalversion/printers.go#L743
func getPodStatus(pod v1.Pod) (string, uint, uint, time.Time) {
var ready uint
Expand Down

0 comments on commit 8bd39cc

Please sign in to comment.