repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/crd_test.go
internal/render/crd_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestCustomResourceDefinitionRender(t *testing.T) { c := render.CustomResourceDefinition{} r := model1.NewRow(2) require.NoError(t, c.Render(load(t, "crd"), "", &r)) assert.Equal(t, "-/adapters.config.istio.io", r.ID) assert.Equal(t, "adapters", r.Fields[0]) assert.Equal(t, "config.istio.io", r.Fields[1]) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/cr_test.go
internal/render/cr_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestClusterRoleRender(t *testing.T) { c := render.ClusterRole{} r := model1.NewRow(2) require.NoError(t, c.Render(load(t, "cr"), "-", &r)) assert.Equal(t, "-/blee", r.ID) assert.Equal(t, model1.Fields{"blee"}, r.Fields[:1]) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/subject.go
internal/render/subject.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "github.com/derailed/k9s/internal/model1" "github.com/derailed/tcell/v2" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) // Subject renders a rbac to screen. type Subject struct { Base } // ColorerFunc colors a resource row. func (Subject) ColorerFunc() model1.ColorerFunc { return func(string, model1.Header, *model1.RowEvent) tcell.Color { return tcell.ColorMediumSpringGreen } } // Header returns a header row. func (Subject) Header(string) model1.Header { return model1.Header{ model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "KIND"}, model1.HeaderColumn{Name: "FIRST LOCATION"}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, } } // Render renders a K8s resource to screen. func (s Subject) Render(o any, _ string, r *model1.Row) error { res, ok := o.(SubjectRes) if !ok { return fmt.Errorf("expected SubjectRes, but got %T", s) } r.ID = res.Name r.Fields = model1.Fields{ res.Name, res.Kind, res.FirstLocation, "", } return nil } // ---------------------------------------------------------------------------- // Helpers... // SubjectRes represents a subject rule. type SubjectRes struct { Name, Kind, FirstLocation string } // GetObjectKind returns a schema object. func (SubjectRes) GetObjectKind() schema.ObjectKind { return nil } // DeepCopyObject returns a container copy. func (s SubjectRes) DeepCopyObject() runtime.Object { return s } // Subjects represents a collection of RBAC policies. type Subjects []SubjectRes // Upsert adds a new subject. func (ss Subjects) Upsert(s SubjectRes) Subjects { idx, ok := ss.find(s.Name) if !ok { return append(ss, s) } ss[idx] = s return ss } // Find locates a row by id. Returns false is not found. func (ss Subjects) find(res string) (int, bool) { for i, s := range ss { if s.Name == res { return i, true } } return 0, false }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/rob_test.go
internal/render/rob_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestRoleBindingRender(t *testing.T) { c := render.RoleBinding{} r := model1.NewRow(6) require.NoError(t, c.Render(load(t, "rb"), "", &r)) assert.Equal(t, "default/blee", r.ID) assert.Equal(t, model1.Fields{"default", "blee", "blee", "SvcAcct", "fernand"}, r.Fields[:5]) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/ro.go
internal/render/ro.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" rbacv1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) // Role renders a K8s Role to screen. type Role struct { Base } // Header returns a header row. func (r Role) Header(_ string) model1.Header { return r.doHeader(defaultROHeader) } var defaultROHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // Render renders a K8s resource to screen. func (r Role) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := r.defaultRow(raw, row); err != nil { return err } if r.specs.isEmpty() { return nil } cols, err := r.specs.realize(raw, defaultROHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } func (Role) defaultRow(raw *unstructured.Unstructured, row *model1.Row) error { var ro rbacv1.Role err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &ro) if err != nil { return err } row.ID = client.MetaFQN(&ro.ObjectMeta) row.Fields = model1.Fields{ ro.Namespace, ro.Name, mapToStr(ro.Labels), "", ToAge(ro.GetCreationTimestamp()), } return nil }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/context_test.go
internal/render/context_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "k8s.io/client-go/tools/clientcmd/api" ) func TestContextHeader(t *testing.T) { var c render.Context assert.Len(t, c.Header(""), 4) } func TestContextRender(t *testing.T) { uu := map[string]struct { ctx *render.NamedContext e model1.Row }{ "active": { ctx: &render.NamedContext{ Name: "c1", Context: &api.Context{ LocationOfOrigin: "fred", Cluster: "c1", AuthInfo: "u1", Namespace: "ns1", }, Config: &config{}, }, e: model1.Row{ ID: "c1", Fields: model1.Fields{"c1", "c1", "u1", "ns1"}, }, }, } var r render.Context for k := range uu { uc := uu[k] t.Run(k, func(t *testing.T) { row := model1.NewRow(4) err := r.Render(uc.ctx, "", &row) require.NoError(t, err) assert.Equal(t, uc.e, row) }) } } // ---------------------------------------------------------------------------- // Helpers... type config struct{} func (config) CurrentContextName() (string, error) { return "fred", nil }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/crd.go
internal/render/crd.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "errors" "fmt" "log/slog" "strings" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/slogs" v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) var defaultCRDHeader = model1.Header{ model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "GROUP"}, model1.HeaderColumn{Name: "KIND"}, model1.HeaderColumn{Name: "VERSIONS"}, model1.HeaderColumn{Name: "SCOPE"}, model1.HeaderColumn{Name: "ALIASES", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // CustomResourceDefinition renders a K8s CustomResourceDefinition to screen. type CustomResourceDefinition struct { Base } // Header returns a header row. func (c CustomResourceDefinition) Header(_ string) model1.Header { return c.doHeader(defaultCRDHeader) } // Render renders a K8s resource to screen. func (c CustomResourceDefinition) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := c.defaultRow(raw, row); err != nil { return err } if c.specs.isEmpty() { return nil } cols, err := c.specs.realize(raw, defaultCRDHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } // Render renders a K8s resource to screen. func (c CustomResourceDefinition) defaultRow(raw *unstructured.Unstructured, r *model1.Row) error { var crd v1.CustomResourceDefinition err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &crd) if err != nil { return err } versions := make([]string, 0, len(crd.Spec.Versions)) for _, v := range crd.Spec.Versions { if v.Served { n := v.Name if v.Deprecated { n += "!" } versions = append(versions, n) } } if len(versions) == 0 { slog.Warn("Unable to assert CRD versions", slogs.FQN, crd.Name) } r.ID = client.MetaFQN(&crd.ObjectMeta) r.Fields = model1.Fields{ crd.Spec.Names.Plural, crd.Spec.Group, crd.Spec.Names.Kind, naStrings(versions), string(crd.Spec.Scope), naStrings(crd.Spec.Names.ShortNames), mapToIfc(crd.GetLabels()), AsStatus(c.diagnose(crd.Name, crd.Spec.Versions)), ToAge(crd.GetCreationTimestamp()), } return nil } func (CustomResourceDefinition) diagnose(n string, vv []v1.CustomResourceDefinitionVersion) error { if len(vv) == 0 { return fmt.Errorf("unable to assert CRD servers versions for %s", n) } var ( ee []error served bool ) for _, v := range vv { if v.Served { served = true } if v.Deprecated { if v.DeprecationWarning != nil { ee = append(ee, fmt.Errorf("%s", *v.DeprecationWarning)) } else { ee = append(ee, fmt.Errorf("%s[%s] is deprecated", n, v.Name)) } } } if !served { ee = append(ee, fmt.Errorf("CRD %s is no longer served by the api server", n)) } if len(ee) == 0 { return nil } errs := make([]string, 0, len(ee)) for _, e := range ee { errs = append(errs, e.Error()) } return errors.New(strings.Join(errs, " - ")) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/benchmark.go
internal/render/benchmark.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "errors" "fmt" "os" "regexp" "strconv" "strings" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" "github.com/derailed/tcell/v2" "github.com/derailed/tview" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) var ( totalRx = regexp.MustCompile(`Total:\s+([0-9.]+)\ssecs`) reqRx = regexp.MustCompile(`Requests/sec:\s+([0-9.]+)`) okRx = regexp.MustCompile(`\[2\d{2}\]\s+(\d+)\s+responses`) errRx = regexp.MustCompile(`\[[45]\d{2}\]\s+(\d+)\s+responses`) toastRx = regexp.MustCompile(`Error distribution`) ) // Benchmark renders a benchmarks to screen. type Benchmark struct { Base } // ColorerFunc colors a resource row. func (Benchmark) ColorerFunc() model1.ColorerFunc { return func(ns string, h model1.Header, re *model1.RowEvent) tcell.Color { if !model1.IsValid(ns, h, re.Row) { return model1.ErrColor } return tcell.ColorPaleGreen } } // Header returns a header row. func (Benchmark) Header(string) model1.Header { return model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "STATUS"}, model1.HeaderColumn{Name: "TIME"}, model1.HeaderColumn{Name: "REQ/S", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "2XX", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "4XX/5XX", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "REPORT"}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } } // Render renders a K8s resource to screen. func (b Benchmark) Render(o any, ns string, r *model1.Row) error { bench, ok := o.(BenchInfo) if !ok { return fmt.Errorf("no benchmarks available %T", o) } data, err := b.readFile(bench.Path) if err != nil { return fmt.Errorf("unable to load bench file %s", bench.Path) } r.ID = bench.Path r.Fields = make(model1.Fields, len(b.Header(ns))) if err := b.initRow(r.Fields, bench.File); err != nil { return err } b.augmentRow(r.Fields, data) r.Fields[8] = AsStatus(b.diagnose(ns, r.Fields)) return nil } // Happy returns true if resource is happy, false otherwise. func (Benchmark) diagnose(ns string, ff model1.Fields) error { statusCol := 3 if !client.IsAllNamespaces(ns) { statusCol-- } if len(ff) < statusCol { return nil } if ff[statusCol] != "pass" { return errors.New("failed benchmark") } return nil } // ---------------------------------------------------------------------------- // Helpers... func (Benchmark) readFile(file string) (string, error) { data, err := os.ReadFile(file) if err != nil { return "", err } return string(data), nil } func (Benchmark) initRow(row model1.Fields, f os.FileInfo) error { tokens := strings.Split(f.Name(), "_") if len(tokens) < 2 { return fmt.Errorf("invalid file name %s", f.Name()) } row[0] = tokens[0] row[1] = tokens[1] row[7] = f.Name() row[9] = ToAge(metav1.Time{Time: f.ModTime()}) return nil } func (b Benchmark) augmentRow(fields model1.Fields, data string) { if data == "" { return } col := 2 fields[col] = "pass" mf := toastRx.FindAllStringSubmatch(data, 1) if len(mf) > 0 { fields[col] = "fail" } col++ mt := totalRx.FindAllStringSubmatch(data, 1) if len(mt) > 0 { fields[col] = mt[0][1] } col++ mr := reqRx.FindAllStringSubmatch(data, 1) if len(mr) > 0 { fields[col] = mr[0][1] } col++ ms := okRx.FindAllStringSubmatch(data, -1) fields[col] = b.countReq(ms) col++ me := errRx.FindAllStringSubmatch(data, -1) fields[col] = b.countReq(me) } func (Benchmark) countReq(rr [][]string) string { if len(rr) == 0 { return "0" } var sum int for _, m := range rr { if m, err := strconv.Atoi(m[1]); err == nil { sum += m } } return AsThousands(int64(sum)) } // BenchInfo represents benchmark run info. type BenchInfo struct { File os.FileInfo Path string } // GetObjectKind returns a schema object. func (BenchInfo) GetObjectKind() schema.ObjectKind { return nil } // DeepCopyObject returns a container copy. func (b BenchInfo) DeepCopyObject() runtime.Object { return b }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/pod.go
internal/render/pod.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "context" "fmt" "log/slog" "strconv" "strings" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/config" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/slogs" "github.com/derailed/tcell/v2" "github.com/derailed/tview" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/sets" mv1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1" ) const ( // NodeUnreachablePodReason is reason and message set on a pod when its state // cannot be confirmed as kubelet is unresponsive on the node it is (was) running. NodeUnreachablePodReason = "NodeLost" // k8s.io/kubernetes/pkg/util/node.NodeUnreachablePodReason vulIdx = 2 ) const ( PhaseTerminating = "Terminating" PhaseInitialized = "Initialized" PhaseRunning = "Running" PhaseNotReady = "NoReady" PhaseCompleted = "Completed" PhaseContainerCreating = "ContainerCreating" PhasePodInitializing = "PodInitializing" PhaseUnknown = "Unknown" PhaseCrashLoop = "CrashLoopBackOff" PhaseError = "Error" PhaseImagePullBackOff = "ImagePullBackOff" PhaseOOMKilled = "OOMKilled" PhasePending = "Pending" PhaseContainerStatusUnknown = "ContainerStatusUnknown" PhaseEvicted = "Evicted" ) var defaultPodHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "VS", Attrs: model1.Attrs{VS: true}}, model1.HeaderColumn{Name: "PF"}, model1.HeaderColumn{Name: "READY"}, model1.HeaderColumn{Name: "STATUS"}, model1.HeaderColumn{Name: "RESTARTS", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "LAST RESTART", Attrs: model1.Attrs{Align: tview.AlignRight, Time: true, Wide: true}}, model1.HeaderColumn{Name: "CPU", Attrs: model1.Attrs{Align: tview.AlignRight, MX: true}}, model1.HeaderColumn{Name: "CPU/RL", Attrs: model1.Attrs{Align: tview.AlignRight, Wide: true}}, model1.HeaderColumn{Name: "%CPU/R", Attrs: model1.Attrs{Align: tview.AlignRight, MX: true}}, model1.HeaderColumn{Name: "%CPU/L", Attrs: model1.Attrs{Align: tview.AlignRight, MX: true}}, model1.HeaderColumn{Name: "MEM", Attrs: model1.Attrs{Align: tview.AlignRight, MX: true}}, model1.HeaderColumn{Name: "MEM/RL", Attrs: model1.Attrs{Align: tview.AlignRight, Wide: true}}, model1.HeaderColumn{Name: "%MEM/R", Attrs: model1.Attrs{Align: tview.AlignRight, MX: true}}, model1.HeaderColumn{Name: "%MEM/L", Attrs: model1.Attrs{Align: tview.AlignRight, MX: true}}, model1.HeaderColumn{Name: "GPU/RL", Attrs: model1.Attrs{Align: tview.AlignRight, Wide: true}}, model1.HeaderColumn{Name: "IP"}, model1.HeaderColumn{Name: "NODE"}, model1.HeaderColumn{Name: "SERVICE-ACCOUNT", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "NOMINATED NODE", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "READINESS GATES", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "QOS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // Pod renders a K8s Pod to screen. type Pod struct { *Base } // NewPod returns a new instance. func NewPod() *Pod { return &Pod{ Base: new(Base), } } // ColorerFunc colors a resource row. func (*Pod) ColorerFunc() model1.ColorerFunc { return func(ns string, h model1.Header, re *model1.RowEvent) tcell.Color { c := model1.DefaultColorer(ns, h, re) idx, ok := h.IndexOf("STATUS", true) if !ok { return c } status := strings.TrimSpace(re.Row.Fields[idx]) switch status { case Pending, ContainerCreating: c = model1.PendingColor case PodInitializing: c = model1.AddColor case Initialized: c = model1.HighlightColor case Completed: c = model1.CompletedColor case Running: if c != model1.ErrColor { c = model1.StdColor } case Terminating: c = model1.KillColor } return c } } // Header returns a header row. func (p *Pod) Header(string) model1.Header { return p.doHeader(defaultPodHeader) } // Render renders a K8s resource to screen. func (p *Pod) Render(o any, _ string, row *model1.Row) error { pwm, ok := o.(*PodWithMetrics) if !ok { return fmt.Errorf("expected PodWithMetrics, but got %T", o) } if err := p.defaultRow(pwm, row); err != nil { return err } if p.specs.isEmpty() { return nil } cols, err := p.specs.realize(pwm.Raw.DeepCopy(), defaultPodHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } func (p *Pod) defaultRow(pwm *PodWithMetrics, row *model1.Row) error { var st v1.PodStatus if err := runtime.DefaultUnstructuredConverter.FromUnstructured(pwm.Raw.Object["status"].(map[string]any), &st); err != nil { return err } spec := new(v1.PodSpec) if err := runtime.DefaultUnstructuredConverter.FromUnstructured(pwm.Raw.Object["spec"].(map[string]any), spec); err != nil { return err } dt := pwm.Raw.GetDeletionTimestamp() cReady, _, cRestarts, lastRestart := p.ContainerStats(st.ContainerStatuses) iReady, iTerminated, iRestarts := p.initContainerStats(spec.InitContainers, st.InitContainerStatuses) cReady += iReady allCounts := len(spec.Containers) + iTerminated rgr, rgt := p.readinessGateStats(spec, &st) ready := hasPodReadyCondition(st.Conditions) var ccmx []mv1beta1.ContainerMetrics if pwm.MX != nil { ccmx = pwm.MX.Containers } c, r := gatherPodMX(spec, ccmx) phase := p.Phase(dt, spec, &st) ns, n := pwm.Raw.GetNamespace(), pwm.Raw.GetName() row.ID = client.FQN(ns, n) row.Fields = model1.Fields{ ns, n, computeVulScore(ns, pwm.Raw.GetLabels(), spec), "●", strconv.Itoa(cReady) + "/" + strconv.Itoa(allCounts), phase, strconv.Itoa(cRestarts + iRestarts), ToAge(lastRestart), toMc(c.cpu), toMc(r.cpu) + ":" + toMc(r.lcpu), client.ToPercentageStr(c.cpu, r.cpu), client.ToPercentageStr(c.cpu, r.lcpu), toMi(c.mem), toMi(r.mem) + ":" + toMi(r.lmem), client.ToPercentageStr(c.mem, r.mem), client.ToPercentageStr(c.mem, r.lmem), toMc(r.gpu) + ":" + toMc(r.lgpu), na(st.PodIP), na(spec.NodeName), na(spec.ServiceAccountName), asNominated(st.NominatedNodeName), asReadinessGate(spec, &st), p.mapQOS(st.QOSClass), mapToStr(pwm.Raw.GetLabels()), AsStatus(p.diagnose(phase, cReady, allCounts, ready, rgr, rgt)), ToAge(pwm.Raw.GetCreationTimestamp()), } return nil } // Healthy checks component health. func (p *Pod) Healthy(_ context.Context, o any) error { pwm, ok := o.(*PodWithMetrics) if !ok { slog.Error("Expected *PodWithMetrics", slogs.Type, fmt.Sprintf("%T", o)) return nil } var st v1.PodStatus if err := runtime.DefaultUnstructuredConverter.FromUnstructured(pwm.Raw.Object["status"].(map[string]any), &st); err != nil { slog.Error("Failed to convert unstructured to PodState", slogs.Error, err) return nil } spec := new(v1.PodSpec) if err := runtime.DefaultUnstructuredConverter.FromUnstructured(pwm.Raw.Object["spec"].(map[string]any), spec); err != nil { slog.Error("Failed to convert unstructured to PodSpec", slogs.Error, err) return nil } dt := pwm.Raw.GetDeletionTimestamp() phase := p.Phase(dt, spec, &st) cr, _, _, _ := p.ContainerStats(st.ContainerStatuses) ct := len(st.ContainerStatuses) icr, ict, _ := p.initContainerStats(spec.InitContainers, st.InitContainerStatuses) cr += icr ct += ict ready := hasPodReadyCondition(st.Conditions) rgr, rgt := p.readinessGateStats(spec, &st) return p.diagnose(phase, cr, ct, ready, rgr, rgt) } func (*Pod) diagnose(phase string, cr, ct int, ready bool, rgr, rgt int) error { if phase == Completed { return nil } if cr != ct || ct == 0 { return fmt.Errorf("container ready check failed: %d of %d", cr, ct) } if rgt > 0 && rgr != rgt { return fmt.Errorf("readiness gate check failed: %d of %d", rgr, rgt) } if !ready { return fmt.Errorf("pod condition ready is false") } if phase == Terminating { return fmt.Errorf("pod is terminating") } return nil } // ---------------------------------------------------------------------------- // Helpers... func asNominated(n string) string { if n == "" { return MissingValue } return n } func asReadinessGate(spec *v1.PodSpec, st *v1.PodStatus) string { if len(spec.ReadinessGates) == 0 { return MissingValue } var trueConditions int for _, readinessGate := range spec.ReadinessGates { conditionType := readinessGate.ConditionType for _, condition := range st.Conditions { if condition.Type == conditionType { if condition.Status == "True" { trueConditions++ } break } } } return strconv.Itoa(trueConditions) + "/" + strconv.Itoa(len(spec.ReadinessGates)) } // PodWithMetrics represents a pod and its metrics. type PodWithMetrics struct { Raw *unstructured.Unstructured MX *mv1beta1.PodMetrics } // GetObjectKind returns a schema object. func (*PodWithMetrics) GetObjectKind() schema.ObjectKind { return nil } // DeepCopyObject returns a container copy. func (p *PodWithMetrics) DeepCopyObject() runtime.Object { return p } func gatherPodMX(spec *v1.PodSpec, ccmx []mv1beta1.ContainerMetrics) (c, r metric) { cc := make([]v1.Container, 0, len(spec.InitContainers)+len(spec.Containers)) cc = append(cc, filterSidecarCO(spec.InitContainers)...) cc = append(cc, spec.Containers...) rcpu, rmem, rgpu := cosRequests(cc) r.cpu, r.mem, r.gpu = rcpu.MilliValue(), rmem.Value(), rgpu.Value() lcpu, lmem, lgpu := cosLimits(cc) r.lcpu, r.lmem, r.lgpu = lcpu.MilliValue(), lmem.Value(), lgpu.Value() ccpu, cmem := currentRes(ccmx) c.cpu, c.mem = ccpu.MilliValue(), cmem.Value() return } func cosLimits(cc []v1.Container) (cpuQ, memQ, gpuQ *resource.Quantity) { cpuQ, gpuQ, memQ = new(resource.Quantity), new(resource.Quantity), new(resource.Quantity) for i := range cc { limits := cc[i].Resources.Limits if len(limits) == 0 { continue } if q := limits.Cpu(); q != nil { cpuQ.Add(*q) } if q := limits.Memory(); q != nil { memQ.Add(*q) } if q := extractGPU(limits); q != nil { gpuQ.Add(*q) } } return } func cosRequests(cc []v1.Container) (cpuQ, memQ, gpuQ *resource.Quantity) { cpuQ, gpuQ, memQ = new(resource.Quantity), new(resource.Quantity), new(resource.Quantity) for i := range cc { co := cc[i] rl := containerRequests(&co) if q := rl.Cpu(); q != nil { cpuQ.Add(*q) } if q := rl.Memory(); q != nil { memQ.Add(*q) } if q := extractGPU(rl); q != nil { gpuQ.Add(*q) } } return } func extractGPU(rl v1.ResourceList) *resource.Quantity { for _, v := range config.KnownGPUVendors { if q, ok := rl[v1.ResourceName(v)]; ok { return &q } } return &resource.Quantity{Format: resource.DecimalSI} } func currentRes(ccmx []mv1beta1.ContainerMetrics) (cpuQ, memQ *resource.Quantity) { cpuQ = new(resource.Quantity) memQ = new(resource.Quantity) if ccmx == nil { return } for _, co := range ccmx { c, m := co.Usage.Cpu(), co.Usage.Memory() cpuQ.Add(*c) memQ.Add(*m) } return } func (*Pod) mapQOS(class v1.PodQOSClass) string { //nolint:exhaustive switch class { case v1.PodQOSGuaranteed: return "GA" case v1.PodQOSBurstable: return "BU" default: return "BE" } } // ContainerStats reports pod container stats. func (*Pod) ContainerStats(cc []v1.ContainerStatus) (readyCnt, terminatedCnt, restartCnt int, latest metav1.Time) { for i := range cc { if cc[i].State.Terminated != nil { terminatedCnt++ } if cc[i].Ready { readyCnt++ } restartCnt += int(cc[i].RestartCount) if t := cc[i].LastTerminationState.Terminated; t != nil { ts := cc[i].LastTerminationState.Terminated.FinishedAt if latest.IsZero() || ts.After(latest.Time) { latest = ts } } } return } func (*Pod) initContainerStats(cc []v1.Container, cos []v1.ContainerStatus) (ready, total, restart int) { for i := range cos { if !isSideCarContainer(cc[i].RestartPolicy) { continue } total++ if cos[i].Ready { ready++ } restart += int(cos[i].RestartCount) } return } func (*Pod) readinessGateStats(spec *v1.PodSpec, st *v1.PodStatus) (ready, total int) { total = len(spec.ReadinessGates) for _, readinessGate := range spec.ReadinessGates { for _, condition := range st.Conditions { if condition.Type == readinessGate.ConditionType { if condition.Status == "True" { ready++ } } } } return } // Phase reports the given pod phase. func (p *Pod) Phase(dt *metav1.Time, spec *v1.PodSpec, st *v1.PodStatus) string { status := string(st.Phase) if st.Reason != "" { if dt != nil && st.Reason == NodeUnreachablePodReason { return "Unknown" } status = st.Reason } status, ok := p.initContainerPhase(spec, st, status) if ok { return status } status, ok = p.containerPhase(st, status) if ok && status == Completed { status = Running } if dt == nil { return status } return Terminating } func (*Pod) containerPhase(st *v1.PodStatus, status string) (string, bool) { var running bool for i := len(st.ContainerStatuses) - 1; i >= 0; i-- { cs := st.ContainerStatuses[i] switch { case cs.State.Waiting != nil && cs.State.Waiting.Reason != "": status = cs.State.Waiting.Reason case cs.State.Terminated != nil && cs.State.Terminated.Reason != "": status = cs.State.Terminated.Reason case cs.State.Terminated != nil: if cs.State.Terminated.Signal != 0 { status = "Signal:" + strconv.Itoa(int(cs.State.Terminated.Signal)) } else { status = "ExitCode:" + strconv.Itoa(int(cs.State.Terminated.ExitCode)) } case cs.Ready && cs.State.Running != nil: running = true } } return status, running } func (*Pod) initContainerPhase(spec *v1.PodSpec, pst *v1.PodStatus, status string) (string, bool) { count := len(spec.InitContainers) sidecars := sets.New[string]() for i := range spec.InitContainers { co := spec.InitContainers[i] if isSideCarContainer(co.RestartPolicy) { sidecars.Insert(co.Name) } } for i := range pst.InitContainerStatuses { if s := checkInitContainerStatus(&pst.InitContainerStatuses[i], i, count, sidecars.Has(pst.InitContainerStatuses[i].Name)); s != "" { return s, true } } return status, false } // ---------------------------------------------------------------------------- // Helpers.. func checkInitContainerStatus(cs *v1.ContainerStatus, count, initCount int, restartable bool) string { switch { case cs.State.Terminated != nil: if cs.State.Terminated.ExitCode == 0 { return "" } if cs.State.Terminated.Reason != "" { return "Init:" + cs.State.Terminated.Reason } if cs.State.Terminated.Signal != 0 { return "Init:Signal:" + strconv.Itoa(int(cs.State.Terminated.Signal)) } return "Init:ExitCode:" + strconv.Itoa(int(cs.State.Terminated.ExitCode)) case restartable && cs.Started != nil && *cs.Started: if cs.Ready { return "" } case cs.State.Waiting != nil && cs.State.Waiting.Reason != "" && cs.State.Waiting.Reason != "PodInitializing": return "Init:" + cs.State.Waiting.Reason } return "Init:" + strconv.Itoa(count) + "/" + strconv.Itoa(initCount) } // PodStatus computes pod status. func PodStatus(pod *v1.Pod) string { reason := string(pod.Status.Phase) if pod.Status.Reason != "" { reason = pod.Status.Reason } for _, condition := range pod.Status.Conditions { if condition.Type == v1.PodScheduled && condition.Reason == v1.PodReasonSchedulingGated { reason = v1.PodReasonSchedulingGated } } var initializing bool for i := range pod.Status.InitContainerStatuses { container := pod.Status.InitContainerStatuses[i] switch { case container.State.Terminated != nil && container.State.Terminated.ExitCode == 0: continue case container.State.Terminated != nil: if container.State.Terminated.Reason == "" { if container.State.Terminated.Signal != 0 { reason = fmt.Sprintf("Init:Signal:%d", container.State.Terminated.Signal) } else { reason = fmt.Sprintf("Init:ExitCode:%d", container.State.Terminated.ExitCode) } } else { reason = "Init:" + container.State.Terminated.Reason } initializing = true case container.State.Waiting != nil && container.State.Waiting.Reason != "" && container.State.Waiting.Reason != "PodInitializing": reason = "Init:" + container.State.Waiting.Reason initializing = true default: reason = fmt.Sprintf("Init:%d/%d", i, len(pod.Spec.InitContainers)) initializing = true } break } if !initializing { var hasRunning bool for i := len(pod.Status.ContainerStatuses) - 1; i >= 0; i-- { container := pod.Status.ContainerStatuses[i] switch { case container.State.Waiting != nil && container.State.Waiting.Reason != "": reason = container.State.Waiting.Reason case container.State.Terminated != nil && container.State.Terminated.Reason != "": reason = container.State.Terminated.Reason case container.State.Terminated != nil && container.State.Terminated.Reason == "": if container.State.Terminated.Signal != 0 { reason = fmt.Sprintf("Signal:%d", container.State.Terminated.Signal) } else { reason = fmt.Sprintf("ExitCode:%d", container.State.Terminated.ExitCode) } case container.Ready && container.State.Running != nil: hasRunning = true } } if reason == PhaseCompleted && hasRunning { if hasPodReadyCondition(pod.Status.Conditions) { reason = PhaseRunning } else { reason = PhaseNotReady } } } if pod.DeletionTimestamp != nil && pod.Status.Reason == NodeUnreachablePodReason { reason = PhaseUnknown } else if pod.DeletionTimestamp != nil { reason = PhaseTerminating } return reason } func hasPodReadyCondition(conditions []v1.PodCondition) bool { for _, condition := range conditions { if condition.Type == v1.PodReady && condition.Status == v1.ConditionTrue { return true } } return false } func isSideCarContainer(p *v1.ContainerRestartPolicy) bool { return p != nil && *p == v1.ContainerRestartPolicyAlways } func filterSidecarCO(cc []v1.Container) []v1.Container { rcc := make([]v1.Container, 0, len(cc)) for i := range cc { if isSideCarContainer(cc[i].RestartPolicy) { rcc = append(rcc, cc[i]) } } return rcc }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/rob.go
internal/render/rob.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "strings" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" rbacv1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) var defaultROBHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "ROLE"}, model1.HeaderColumn{Name: "KIND"}, model1.HeaderColumn{Name: "SUBJECTS"}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // RoleBinding renders a K8s RoleBinding to screen. type RoleBinding struct { Base } // Header returns a header row. func (r RoleBinding) Header(_ string) model1.Header { return r.doHeader(defaultROBHeader) } // Render renders a K8s resource to screen. func (r RoleBinding) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := r.defaultRow(raw, row); err != nil { return err } if r.specs.isEmpty() { return nil } cols, err := r.specs.realize(raw, defaultROBHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } func (RoleBinding) defaultRow(raw *unstructured.Unstructured, row *model1.Row) error { var rb rbacv1.RoleBinding err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &rb) if err != nil { return err } kind, ss := renderSubjects(rb.Subjects) row.ID = client.MetaFQN(&rb.ObjectMeta) row.Fields = model1.Fields{ rb.Namespace, rb.Name, rb.RoleRef.Name, kind, ss, mapToStr(rb.Labels), "", ToAge(rb.GetCreationTimestamp()), } return nil } // ---------------------------------------------------------------------------- // Helpers... func renderSubjects(ss []rbacv1.Subject) (kind, subjects string) { if len(ss) == 0 { return NAValue, "" } tt := make([]string, 0, len(ss)) for _, s := range ss { kind = toSubjectAlias(s.Kind) tt = append(tt, s.Name) } return kind, strings.Join(tt, ",") } func toSubjectAlias(s string) string { if s == "" { return s } switch s { case rbacv1.UserKind: return "User" case rbacv1.GroupKind: return "Group" case rbacv1.ServiceAccountKind: return "SvcAcct" default: return strings.ToUpper(s) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/container_test.go
internal/render/container_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "fmt" "testing" "time" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" mv1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1" ) func TestContainer(t *testing.T) { var c render.Container cres := render.ContainerRes{ Container: makeContainer(), Status: makeContainerStatus(), MX: makeContainerMetrics(), Age: makeAge(), } var r model1.Row require.NoError(t, c.Render(cres, "blee", &r)) assert.Equal(t, "fred", r.ID) assert.Equal(t, model1.Fields{ "", "fred", "●", "img", "false", "Running", "0", "off:off:off", "10", "20:20", "50", "50", "20", "100:100", "20", "20", "0:0", "", "container is not ready", }, r.Fields[:len(r.Fields)-1], ) } func BenchmarkContainerRender(b *testing.B) { var ( c render.Container r model1.Row cres = render.ContainerRes{ Container: makeContainer(), Status: makeContainerStatus(), MX: makeContainerMetrics(), Age: makeAge(), } ) b.ReportAllocs() b.ResetTimer() for range b.N { _ = c.Render(cres, "blee", &r) } } // ---------------------------------------------------------------------------- // Helpers... func toQty(s string) resource.Quantity { q, _ := resource.ParseQuantity(s) return q } func makeContainerMetrics() *mv1beta1.ContainerMetrics { return &mv1beta1.ContainerMetrics{ Name: "fred", Usage: v1.ResourceList{ v1.ResourceCPU: toQty("10m"), v1.ResourceMemory: toQty("20Mi"), }, } } func makeAge() metav1.Time { return metav1.Time{Time: testTime()} } func makeContainer() *v1.Container { return &v1.Container{ Name: "fred", Image: "img", Resources: v1.ResourceRequirements{ Limits: v1.ResourceList{ v1.ResourceCPU: toQty("20m"), v1.ResourceMemory: toQty("100Mi"), }, }, Env: []v1.EnvVar{ { Name: "fred", Value: "1", ValueFrom: &v1.EnvVarSource{ ConfigMapKeyRef: &v1.ConfigMapKeySelector{Key: "blee"}, }, }, }, } } func makeContainerStatus() *v1.ContainerStatus { return &v1.ContainerStatus{ Name: "fred", State: v1.ContainerState{Running: &v1.ContainerStateRunning{}}, RestartCount: 0, } } func testTime() time.Time { t, err := time.Parse(time.RFC3339, "2018-12-14T10:36:43.326972-07:00") if err != nil { fmt.Println("TestTime Failed", err) } return t }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/ep.go
internal/render/ep.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "strconv" "strings" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) var defaultEPHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "ENDPOINTS"}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // Endpoints renders a K8s Endpoints to screen. type Endpoints struct { Base } // Header returns a header row. func (e Endpoints) Header(_ string) model1.Header { return e.doHeader(defaultEPHeader) } // Render renders a K8s resource to screen. func (e Endpoints) Render(o any, ns string, row *model1.Row) error { if err := e.defaultRow(o, ns, row); err != nil { return err } if e.specs.isEmpty() { return nil } cols, err := e.specs.realize(o.(*unstructured.Unstructured), defaultEPHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } func (e Endpoints) defaultRow(o any, ns string, r *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } var ep v1.Endpoints err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &ep) if err != nil { return err } r.ID = client.MetaFQN(&ep.ObjectMeta) r.Fields = make(model1.Fields, 0, len(e.Header(ns))) r.Fields = model1.Fields{ ep.Namespace, ep.Name, missing(toEPs(ep.Subsets)), ToAge(ep.GetCreationTimestamp()), } return nil } // ---------------------------------------------------------------------------- // Helpers... func toEPs(ss []v1.EndpointSubset) string { aa := make([]string, 0, len(ss)) for _, s := range ss { pp := make([]string, len(s.Ports)) portsToStrs(s.Ports, pp) a := make([]string, len(s.Addresses)) processIPs(a, pp, s.Addresses) aa = append(aa, strings.Join(a, ",")) } return strings.Join(aa, ",") } func portsToStrs(pp []v1.EndpointPort, ss []string) { for i := range pp { ss[i] = strconv.Itoa(int(pp[i].Port)) } } func processIPs(aa, pp []string, addrs []v1.EndpointAddress) { const maxIPs = 3 var i int for _, a := range addrs { if a.IP == "" { continue } if len(pp) == 0 { aa[i], i = a.IP, i+1 continue } if len(pp) > maxIPs { aa[i], i = a.IP+":"+strings.Join(pp[:maxIPs], ",")+"...", i+1 } else { aa[i], i = a.IP+":"+strings.Join(pp, ","), i+1 } } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/ns_test.go
internal/render/ns_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/derailed/tcell/v2" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNSColorer(t *testing.T) { uu := map[string]struct { re model1.RowEvent e tcell.Color }{ "add": { re: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ Fields: model1.Fields{ "blee", "Active", }, }, }, e: model1.AddColor, }, "update": { re: model1.RowEvent{ Kind: model1.EventUpdate, Row: model1.Row{ Fields: model1.Fields{ "blee", "Active", }, }, }, e: model1.StdColor, }, "decorator": { re: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ Fields: model1.Fields{ "blee*", "Active", }, }, }, e: model1.HighlightColor, }, } h := model1.Header{ model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "STATUS"}, } var r render.Namespace for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, r.ColorerFunc()("", h, &u.re)) }) } } func TestNamespaceRender(t *testing.T) { c := render.Namespace{} r := model1.NewRow(3) require.NoError(t, c.Render(load(t, "ns"), "-", &r)) assert.Equal(t, "-/kube-system", r.ID) assert.Equal(t, model1.Fields{"kube-system", "Active"}, r.Fields[:2]) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/dp.go
internal/render/dp.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "strconv" "strings" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" "github.com/derailed/tcell/v2" "github.com/derailed/tview" appsv1 "k8s.io/api/apps/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) var defaultDPHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "VS", Attrs: model1.Attrs{VS: true}}, model1.HeaderColumn{Name: "READY", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "UP-TO-DATE", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "AVAILABLE", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // Deployment renders a K8s Deployment to screen. type Deployment struct { Base } // ColorerFunc colors a resource row. func (Deployment) ColorerFunc() model1.ColorerFunc { return func(ns string, h model1.Header, re *model1.RowEvent) tcell.Color { c := model1.DefaultColorer(ns, h, re) idx, ok := h.IndexOf("READY", true) if !ok { return c } ready := strings.TrimSpace(re.Row.Fields[idx]) tt := strings.Split(ready, "/") if len(tt) == 2 && tt[1] == "0" { return model1.PendingColor } return c } } // Header returns a header row. func (d Deployment) Header(_ string) model1.Header { return d.doHeader(defaultDPHeader) } // Render renders a K8s resource to screen. func (d Deployment) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := d.defaultRow(raw, row); err != nil { return err } if d.specs.isEmpty() { return nil } cols, err := d.specs.realize(raw, defaultDPHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } // Render renders a K8s resource to screen. func (d Deployment) defaultRow(raw *unstructured.Unstructured, r *model1.Row) error { var dp appsv1.Deployment err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &dp) if err != nil { return err } var desired int32 if dp.Spec.Replicas != nil { desired = *dp.Spec.Replicas } r.ID = client.MetaFQN(&dp.ObjectMeta) r.Fields = model1.Fields{ dp.Namespace, dp.Name, computeVulScore(dp.Namespace, dp.Labels, &dp.Spec.Template.Spec), strconv.Itoa(int(dp.Status.AvailableReplicas)) + "/" + strconv.Itoa(int(desired)), strconv.Itoa(int(dp.Status.UpdatedReplicas)), strconv.Itoa(int(dp.Status.AvailableReplicas)), mapToStr(dp.Labels), AsStatus(d.diagnose(dp.Status.Replicas, dp.Status.AvailableReplicas)), ToAge(dp.GetCreationTimestamp()), } return nil } func (Deployment) diagnose(desired, avail int32) error { if desired != avail { return fmt.Errorf("desiring %d replicas got %d available", desired, avail) } return nil }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/pvc_test.go
internal/render/pvc_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestPersistentVolumeClaimRender(t *testing.T) { c := render.PersistentVolumeClaim{} r := model1.NewRow(8) require.NoError(t, c.Render(load(t, "pvc"), "", &r)) assert.Equal(t, "default/www-nginx-sts-0", r.ID) assert.Equal(t, model1.Fields{"default", "www-nginx-sts-0", "Bound", "pvc-fbabd470-8725-11e9-a8e8-42010a80015b", "1Gi", "RWO", "standard"}, r.Fields[:7]) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/screen_dump.go
internal/render/screen_dump.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "os" "path/filepath" "time" "github.com/derailed/k9s/internal/model1" "github.com/derailed/tcell/v2" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/duration" ) // ScreenDump renders a screendumps to screen. type ScreenDump struct { Base } // ColorerFunc colors a resource row. func (ScreenDump) ColorerFunc() model1.ColorerFunc { return func(string, model1.Header, *model1.RowEvent) tcell.Color { return tcell.ColorNavajoWhite } } // Header returns a header row. func (ScreenDump) Header(string) model1.Header { return model1.Header{ model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "DIR"}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } } // Render renders a K8s resource to screen. func (ScreenDump) Render(o any, _ string, r *model1.Row) error { f, ok := o.(FileRes) if !ok { return fmt.Errorf("expecting screendumper, but got %T", o) } r.ID = filepath.Join(f.Dir, f.File.Name()) r.Fields = model1.Fields{ f.File.Name(), f.Dir, "", timeToAge(f.File.ModTime()), } return nil } // ---------------------------------------------------------------------------- // Helpers... func timeToAge(timestamp time.Time) string { return duration.HumanDuration(time.Since(timestamp)) } // FileRes represents a file resource. type FileRes struct { File os.FileInfo Dir string } // GetObjectKind returns a schema object. func (FileRes) GetObjectKind() schema.ObjectKind { return nil } // DeepCopyObject returns a container copy. func (c FileRes) DeepCopyObject() runtime.Object { return c }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/ep_test.go
internal/render/ep_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestEndpointsRender(t *testing.T) { c := render.Endpoints{} r := model1.NewRow(4) require.NoError(t, c.Render(load(t, "ep"), "", &r)) assert.Equal(t, "ns-1/blee", r.ID) assert.Equal(t, model1.Fields{"ns-1", "blee", "10.0.0.67:8080"}, r.Fields[:3]) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/ds.go
internal/render/ds.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "strconv" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" "github.com/derailed/tview" appsv1 "k8s.io/api/apps/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) var defaultDSHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "VS", Attrs: model1.Attrs{VS: true}}, model1.HeaderColumn{Name: "DESIRED", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "CURRENT", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "READY", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "UP-TO-DATE", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "AVAILABLE", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // DaemonSet renders a K8s DaemonSet to screen. type DaemonSet struct { Base } // Header returns a header row. func (d DaemonSet) Header(_ string) model1.Header { return d.doHeader(defaultDSHeader) } // Render renders a K8s resource to screen. func (d DaemonSet) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := d.defaultRow(raw, row); err != nil { return err } if d.specs.isEmpty() { return nil } cols, err := d.specs.realize(raw, defaultDSHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } // Render renders a K8s resource to screen. func (d DaemonSet) defaultRow(raw *unstructured.Unstructured, r *model1.Row) error { var ds appsv1.DaemonSet err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &ds) if err != nil { return err } r.ID = client.MetaFQN(&ds.ObjectMeta) r.Fields = model1.Fields{ ds.Namespace, ds.Name, computeVulScore(ds.Namespace, ds.Labels, &ds.Spec.Template.Spec), strconv.Itoa(int(ds.Status.DesiredNumberScheduled)), strconv.Itoa(int(ds.Status.CurrentNumberScheduled)), strconv.Itoa(int(ds.Status.NumberReady)), strconv.Itoa(int(ds.Status.UpdatedNumberScheduled)), strconv.Itoa(int(ds.Status.NumberAvailable)), mapToStr(ds.Labels), AsStatus(d.diagnose(ds.Status.DesiredNumberScheduled, ds.Status.NumberReady)), ToAge(ds.GetCreationTimestamp()), } return nil } // Happy returns true if resource is happy, false otherwise. func (DaemonSet) diagnose(d, r int32) error { if d != r { return fmt.Errorf("desiring %d replicas but %d ready", d, r) } return nil }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/node_test.go
internal/render/node_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" mv1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1" ) func TestNodeRender(t *testing.T) { pom := render.NodeWithMetrics{ Raw: load(t, "no"), MX: makeNodeMX("n1", "10m", "20Mi"), } var no render.Node r := model1.NewRow(14) err := no.Render(&pom, "", &r) require.NoError(t, err) assert.Equal(t, "minikube", r.ID) e := model1.Fields{"minikube", "Ready", "master", "amd64", "0", "v1.15.2", "Buildroot 2018.05.3", "4.15.0", "192.168.64.107", "<none>", "0", "10", "4000", "0", "20", "7874", "0", "n/a", "n/a"} assert.Equal(t, e, r.Fields[:19]) } func BenchmarkNodeRender(b *testing.B) { var ( no render.Node r = model1.NewRow(14) pom = render.NodeWithMetrics{ Raw: load(b, "no"), MX: makeNodeMX("n1", "10m", "10Mi"), } ) b.ResetTimer() b.ReportAllocs() for range b.N { _ = no.Render(&pom, "", &r) } } // ---------------------------------------------------------------------------- // Helpers... func makeNodeMX(name, cpu, mem string) *mv1beta1.NodeMetrics { return &mv1beta1.NodeMetrics{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: "default", }, Usage: makeRes(cpu, mem), } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/eps_test.go
internal/render/eps_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestEndpointSliceRender(t *testing.T) { c := render.EndpointSlice{} r := model1.NewRow(4) require.NoError(t, c.Render(load(t, "eps"), "", &r)) assert.Equal(t, "blee/fred", r.ID) assert.Equal(t, model1.Fields{"blee", "fred", "IPv4", "4244", "172.20.0.2,172.20.0.3"}, r.Fields[:5]) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/helpers_test.go
internal/render/helpers_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "encoding/json" "fmt" "os" "testing" "time" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" "k8s.io/apimachinery/pkg/runtime" ) func TestTableGenericHydrate(t *testing.T) { raw := load(t, "p1") tt := metav1beta1.Table{ ColumnDefinitions: []metav1beta1.TableColumnDefinition{ {Name: "c1"}, {Name: "c2"}, }, Rows: []metav1beta1.TableRow{ { Cells: []any{"fred", 10}, Object: runtime.RawExtension{Object: raw}, }, { Cells: []any{"blee", 20}, Object: runtime.RawExtension{Object: raw}, }, }, } rr := make([]model1.Row, 2) var re Table re.SetTable("blee", &tt) require.NoError(t, model1.GenericHydrate("blee", &tt, rr, &re)) assert.Len(t, rr, 2) assert.Len(t, rr[0].Fields, 2) } func TestTableHydrate(t *testing.T) { oo := []runtime.Object{ &PodWithMetrics{Raw: load(t, "p1")}, } rr := make([]model1.Row, 1) re := NewPod() require.NoError(t, model1.Hydrate("blee", oo, rr, re)) assert.Len(t, rr, 1) assert.Len(t, rr[0].Fields, 26) } func TestToAge(t *testing.T) { uu := map[string]struct { t time.Time e string }{ "zero": { t: time.Time{}, e: UnknownValue, }, } for k := range uu { uc := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, uc.e, ToAge(metav1.Time{Time: uc.t})) }) } } func TestToAgeHuman(t *testing.T) { uu := map[string]struct { t, e string }{ "blank": { t: "", e: UnknownValue, }, "good": { t: time.Now().Add(-10 * time.Second).Format(time.RFC3339Nano), e: "10s", }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, toAgeHuman(u.t)) }) } } func TestJoin(t *testing.T) { uu := map[string]struct { i []string e string }{ "zero": {[]string{}, ""}, "std": {[]string{"a", "b", "c"}, "a,b,c"}, "blank": {[]string{"", "", ""}, ""}, "sparse": {[]string{"a", "", "c"}, "a,c"}, "withBlank": {[]string{"", "a", "c"}, "a,c"}, } for k := range uu { uc := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, uc.e, join(uc.i, ",")) }) } } func TestBoolPtrToStr(t *testing.T) { tv, fv := true, false uu := []struct { p *bool e string }{ {nil, "false"}, {&tv, "true"}, {&fv, "false"}, } for _, u := range uu { assert.Equal(t, u.e, boolPtrToStr(u.p)) } } func TestNamespaced(t *testing.T) { uu := []struct { p, ns, n string }{ {"fred/blee", "fred", "blee"}, } for _, u := range uu { ns, n := client.Namespaced(u.p) assert.Equal(t, u.ns, ns) assert.Equal(t, u.n, n) } } func TestMissing(t *testing.T) { uu := []struct { i, e string }{ {"fred", "fred"}, {"", MissingValue}, } for _, u := range uu { assert.Equal(t, u.e, missing(u.i)) } } func TestBoolToStr(t *testing.T) { uu := []struct { i bool e string }{ {true, "true"}, {false, "false"}, } for _, u := range uu { assert.Equal(t, u.e, boolToStr(u.i)) } } func TestNa(t *testing.T) { uu := []struct { i, e string }{ {"fred", "fred"}, {"", NAValue}, } for _, u := range uu { assert.Equal(t, u.e, na(u.i)) } } func TestTruncate(t *testing.T) { uu := map[string]struct { data string size int e string }{ "same": { data: "fred", size: 4, e: "fred", }, "small": { data: "fred", size: 10, e: "fred", }, "larger": { data: "fred", size: 3, e: "fr…", }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, Truncate(u.data, u.size)) }) } } func TestToSelector(t *testing.T) { uu := map[string]struct { m map[string]string e []string }{ "cool": { map[string]string{"app": "fred", "env": "test"}, []string{"app=fred,env=test", "env=test,app=fred"}, }, "empty": { map[string]string{}, []string{""}, }, } for k := range uu { uc := uu[k] t.Run(k, func(t *testing.T) { s := toSelector(uc.m) var match bool for _, e := range uc.e { if e == s { match = true } } assert.True(t, match) }) } } func TestBlank(t *testing.T) { uu := map[string]struct { a []string e bool }{ "full": { a: []string{"fred", "blee"}, }, "empty": { e: true, }, "blank": { a: []string{"fred", ""}, }, } for k := range uu { uc := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, uc.e, blank(uc.a)) }) } } func TestMetaFQN(t *testing.T) { uu := map[string]struct { m metav1.ObjectMeta e string }{ "full": {metav1.ObjectMeta{Namespace: "fred", Name: "blee"}, "fred/blee"}, "nons": {metav1.ObjectMeta{Name: "blee"}, "-/blee"}, } for k := range uu { uc := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, uc.e, client.MetaFQN(&uc.m)) }) } } func TestFQN(t *testing.T) { uu := map[string]struct { ns, n string e string }{ "full": {ns: "fred", n: "blee", e: "fred/blee"}, "nons": {n: "blee", e: "blee"}, } for k := range uu { uc := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, uc.e, client.FQN(uc.ns, uc.n)) }) } } func TestMapToStr(t *testing.T) { uu := []struct { i map[string]string e string }{ {map[string]string{"blee": "duh", "aa": "bb"}, "aa=bb,blee=duh"}, {map[string]string{}, ""}, } for _, u := range uu { assert.Equal(t, u.e, mapToStr(u.i)) } } func BenchmarkMapToStr(b *testing.B) { ll := map[string]string{ "blee": "duh", "aa": "bb", } b.ReportAllocs() b.ResetTimer() for range b.N { mapToStr(ll) } } func TestRunesToNum(t *testing.T) { uu := map[string]struct { rr []rune e int64 }{ "0": { rr: []rune(""), e: 0, }, "100": { rr: []rune("100"), e: 100, }, "64": { rr: []rune("64"), e: 64, }, "52640": { rr: []rune("52640"), e: 52640, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, runesToNum(u.rr)) }) } } func BenchmarkRunesToNum(b *testing.B) { rr := []rune("5465") b.ReportAllocs() b.ResetTimer() for range b.N { runesToNum(rr) } } func TestToMc(t *testing.T) { uu := []struct { v int64 e string }{ {0, "0"}, {2, "2"}, {1_000, "1000"}, } for _, u := range uu { assert.Equal(t, u.e, toMc(u.v)) } } func TestToMi(t *testing.T) { uu := []struct { v int64 e string }{ {0, "0"}, {2 * client.MegaByte, "2"}, {1_000 * client.MegaByte, "1000"}, } for _, u := range uu { assert.Equal(t, u.e, toMi(u.v)) } } func TestIntToStr(t *testing.T) { uu := []struct { v int e string }{ {0, "0"}, {10, "10"}, } for _, u := range uu { assert.Equal(t, u.e, IntToStr(u.v)) } } func BenchmarkIntToStr(b *testing.B) { v := 10 b.ResetTimer() b.ReportAllocs() for range b.N { IntToStr(v) } } // Helpers... func load(t *testing.T, n string) *unstructured.Unstructured { raw, err := os.ReadFile(fmt.Sprintf("testdata/%s.json", n)) require.NoError(t, err) var o unstructured.Unstructured err = json.Unmarshal(raw, &o) require.NoError(t, err) return &o }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/crb_test.go
internal/render/crb_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestClusterRoleBindingRender(t *testing.T) { c := render.ClusterRoleBinding{} r := model1.NewRow(5) require.NoError(t, c.Render(load(t, "crb"), "-", &r)) assert.Equal(t, "-/blee", r.ID) assert.Equal(t, model1.Fields{"blee", "blee", "User", "fernand"}, r.Fields[:4]) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/ns.go
internal/render/ns.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "context" "errors" "fmt" "strings" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/slogs" "github.com/derailed/tcell/v2" "golang.org/x/exp/slog" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) var defaultNSHeader = model1.Header{ model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "STATUS"}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // Namespace renders a K8s Namespace to screen. type Namespace struct { Base } // ColorerFunc colors a resource row. func (Namespace) ColorerFunc() model1.ColorerFunc { return func(ns string, h model1.Header, re *model1.RowEvent) tcell.Color { c := model1.DefaultColorer(ns, h, re) if c == model1.ErrColor { return c } if re.Kind == model1.EventUpdate { c = model1.StdColor } if strings.Contains(strings.TrimSpace(re.Row.Fields[0]), "*") { c = model1.HighlightColor } return c } } // Header returns a header row. func (n Namespace) Header(_ string) model1.Header { return n.doHeader(defaultNSHeader) } // Render renders a K8s resource to screen. func (n Namespace) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := n.defaultRow(raw, row); err != nil { return err } if n.specs.isEmpty() { return nil } cols, err := n.specs.realize(raw, defaultNSHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } func (n Namespace) defaultRow(raw *unstructured.Unstructured, r *model1.Row) error { var ns v1.Namespace err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &ns) if err != nil { return err } r.ID = client.MetaFQN(&ns.ObjectMeta) r.Fields = model1.Fields{ ns.Name, string(ns.Status.Phase), mapToStr(ns.Labels), AsStatus(n.diagnose(ns.Status.Phase)), ToAge(ns.GetCreationTimestamp()), } return nil } // Healthy checks component health. func (n Namespace) Healthy(_ context.Context, o any) error { res, ok := o.(*unstructured.Unstructured) if !ok { slog.Error("Expected *Unstructured, but got", slogs.Type, fmt.Sprintf("%T", o)) return nil } var ns v1.Namespace err := runtime.DefaultUnstructuredConverter.FromUnstructured(res.Object, &ns) if err != nil { slog.Error("Failed to convert Unstructured to Namespace", slogs.Type, fmt.Sprintf("%T", o), slog.String("error", err.Error())) return nil } return n.diagnose(ns.Status.Phase) } func (Namespace) diagnose(phase v1.NamespacePhase) error { if phase != v1.NamespaceActive && phase != v1.NamespaceTerminating { return errors.New("namespace not ready") } return nil }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/node_int_test.go
internal/render/node_int_test.go
package render import ( "testing" "github.com/stretchr/testify/assert" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" mv1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1" ) func Test_extractNodeGPU(t *testing.T) { uu := map[string]struct { rl v1.ResourceList main *resource.Quantity shared *resource.Quantity }{ "empty": {}, "nvidia": { rl: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("3"), v1.ResourceMemory: resource.MustParse("4Gi"), v1.ResourceName("nvidia.com/gpu"): resource.MustParse("2"), }, main: makeQ(t, "2"), }, "nvidia-shared": { rl: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("3"), v1.ResourceMemory: resource.MustParse("4Gi"), v1.ResourceName("nvidia.com/gpu.shared"): resource.MustParse("2"), }, shared: makeQ(t, "2"), }, "nvidia-both": { rl: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("3"), v1.ResourceMemory: resource.MustParse("4Gi"), v1.ResourceName("nvidia.com/gpu.shared"): resource.MustParse("2"), v1.ResourceName("nvidia.com/gpu"): resource.MustParse("5"), }, main: makeQ(t, "5"), shared: makeQ(t, "2"), }, "intel": { rl: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("3"), v1.ResourceMemory: resource.MustParse("4Gi"), v1.ResourceName("gpu.intel.com/i915"): resource.MustParse("5"), }, main: makeQ(t, "5"), }, "unknown-vendor": { rl: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("3"), v1.ResourceMemory: resource.MustParse("4Gi"), v1.ResourceName("bozo/gpu"): resource.MustParse("2"), }, }, } for k, u := range uu { t.Run(k, func(t *testing.T) { m, s := extractNodeGPU(u.rl) assert.Equal(t, u.main, m) assert.Equal(t, u.shared, s) }) } } func Test_gatherNodeMX(t *testing.T) { uu := map[string]struct { node v1.Node nMX *mv1beta1.NodeMetrics ec, ea metric }{ "empty": {}, "nvidia": { node: v1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "nvidia", }, Status: v1.NodeStatus{ Capacity: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("3"), v1.ResourceMemory: resource.MustParse("4Gi"), v1.ResourceName("nvidia.com/gpu"): resource.MustParse("2"), }, Allocatable: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("8"), v1.ResourceMemory: resource.MustParse("8Gi"), v1.ResourceName("nvidia.com/gpu"): resource.MustParse("4"), }, }, }, nMX: &mv1beta1.NodeMetrics{ ObjectMeta: metav1.ObjectMeta{ Name: "nvidia", }, Usage: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("3"), v1.ResourceMemory: resource.MustParse("4Gi"), v1.ResourceName("nvidia.com/gpu"): resource.MustParse("2"), }, }, ea: metric{ cpu: 8000, mem: 8589934592, gpu: 4, }, ec: metric{ cpu: 3000, mem: 4294967296, gpu: 2, }, }, "intel": { node: v1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "intel", }, Status: v1.NodeStatus{ Capacity: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("3"), v1.ResourceMemory: resource.MustParse("4Gi"), v1.ResourceName("gpu.intel.com/i915"): resource.MustParse("2"), }, Allocatable: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("8"), v1.ResourceMemory: resource.MustParse("8Gi"), v1.ResourceName("gpu.intel.com/i915"): resource.MustParse("4"), }, }, }, ea: metric{ cpu: 8000, mem: 8589934592, gpu: 4, }, ec: metric{ cpu: 0, mem: 0, gpu: 2, }, }, "unknown-vendor": { node: v1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "amd", }, Status: v1.NodeStatus{ Capacity: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("3"), v1.ResourceMemory: resource.MustParse("4Gi"), v1.ResourceName("bozo/gpu"): resource.MustParse("2"), }, Allocatable: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("8"), v1.ResourceMemory: resource.MustParse("8Gi"), v1.ResourceName("bozo/gpu"): resource.MustParse("4"), }, }, }, ea: metric{ cpu: 8000, mem: 8589934592, gpu: 0, }, ec: metric{ gpu: 0, }, }, } for k, u := range uu { t.Run(k, func(t *testing.T) { c, a := gatherNodeMX(&u.node, u.nMX) assert.Equal(t, u.ec, c) assert.Equal(t, u.ea, a) }) } } func makeQ(t *testing.T, v string) *resource.Quantity { q, err := resource.ParseQuantity(v) if err != nil { t.Fatal(err) } return &q }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/port_forward_test.go
internal/render/port_forward_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "time" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestPortForwardRender(t *testing.T) { o := render.ForwardRes{ Forwarder: fwd{}, Config: render.BenchCfg{ C: 1, N: 1, Host: "0.0.0.0", Path: "/", }, } var p render.PortForward var r model1.Row require.NoError(t, p.Render(o, "fred", &r)) assert.Equal(t, "blee/fred", r.ID) assert.Equal(t, model1.Fields{ "blee", "fred", "co", "p1:p2", "http://0.0.0.0:p1/", "1", "1", "", }, r.Fields[:8]) } // Helpers... type fwd struct{} func (fwd) ID() string { return "blee/fred" } func (fwd) Path() string { return "blee/fred" } func (fwd) Container() string { return "co" } func (fwd) Port() string { return "p1:p2" } func (fwd) Active() bool { return true } func (fwd) Age() time.Time { return testTime() } func (fwd) Address() string { return "" }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/hpa.go
internal/render/hpa.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "strconv" "strings" "github.com/derailed/k9s/internal/model1" "github.com/derailed/tcell/v2" ) // HorizontalPodAutoscaler renders a K8s HorizontalPodAutoscaler to screen. type HorizontalPodAutoscaler struct { Table } // ColorerFunc colors a resource row. func (*HorizontalPodAutoscaler) ColorerFunc() model1.ColorerFunc { return func(ns string, h model1.Header, re *model1.RowEvent) tcell.Color { c := model1.DefaultColorer(ns, h, re) maxPodsIndex, ok := h.IndexOf("MAXPODS", true) if !ok || maxPodsIndex >= len(re.Row.Fields) { return c } replicasIndex, ok := h.IndexOf("REPLICAS", true) if !ok || replicasIndex >= len(re.Row.Fields) { return c } maxPodsS := strings.TrimSpace(re.Row.Fields[maxPodsIndex]) currentReplicasS := strings.TrimSpace(re.Row.Fields[replicasIndex]) maxPods, err := strconv.Atoi(maxPodsS) if err != nil { return c } currentReplicas, err := strconv.Atoi(currentReplicasS) if err != nil { return c } if currentReplicas >= maxPods { c = model1.ErrColor } return c } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/alias_test.go
internal/render/alias_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/derailed/tcell/v2" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestAliasColorer(t *testing.T) { var a render.Alias h := model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B"}, model1.HeaderColumn{Name: "C"}, } r := model1.Row{ID: "g/v/r", Fields: model1.Fields{"r", "blee", "g"}} uu := map[string]struct { ns string re model1.RowEvent e tcell.Color }{ "addAll": { ns: client.NamespaceAll, re: model1.RowEvent{Kind: model1.EventAdd, Row: r}, e: tcell.ColorBlue, }, "deleteAll": { ns: client.NamespaceAll, re: model1.RowEvent{Kind: model1.EventDelete, Row: r}, e: tcell.ColorGray, }, "updateAll": { ns: client.NamespaceAll, re: model1.RowEvent{Kind: model1.EventUpdate, Row: r}, e: tcell.ColorDefault, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, a.ColorerFunc()(u.ns, h, &u.re)) }) } } func TestAliasHeader(t *testing.T) { h := model1.Header{ model1.HeaderColumn{Name: "RESOURCE"}, model1.HeaderColumn{Name: "GROUP"}, model1.HeaderColumn{Name: "VERSION"}, model1.HeaderColumn{Name: "COMMAND"}, } var a render.Alias assert.Equal(t, h, a.Header("ns-1")) assert.Equal(t, h, a.Header(client.NamespaceAll)) } func TestAliasRender(t *testing.T) { var a render.Alias o := render.AliasRes{ GVR: client.NewGVR("fred/v1/blee"), Aliases: []string{"a", "b", "c"}, } var r model1.Row require.NoError(t, a.Render(o, "fred/v1/blee", &r)) assert.Equal(t, model1.Row{ ID: "fred/v1/blee", Fields: model1.Fields{"blee", "fred", "v1", "a b c"}, }, r) } func BenchmarkAlias(b *testing.B) { o := render.AliasRes{ GVR: client.NewGVR("fred/v1/blee"), Aliases: []string{"a", "b", "c"}, } var a render.Alias b.ResetTimer() b.ReportAllocs() for range b.N { var r model1.Row _ = a.Render(o, "ns-1", &r) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/pod_int_test.go
internal/render/pod_int_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "testing" "time" "github.com/derailed/k9s/internal/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" v1 "k8s.io/api/core/v1" res "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" mv1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1" ) func Test_checkInitContainerStatus(t *testing.T) { trueVal := true uu := map[string]struct { status v1.ContainerStatus e string count, total int restart bool }{ "none": { e: "Init:0/0", }, "restart": { status: v1.ContainerStatus{ Name: "ic1", Started: &trueVal, State: v1.ContainerState{}, }, restart: true, e: "Init:0/0", }, "no-restart": { status: v1.ContainerStatus{ Name: "ic1", Started: &trueVal, State: v1.ContainerState{}, }, e: "Init:0/0", }, "terminated-reason": { status: v1.ContainerStatus{ Name: "ic1", State: v1.ContainerState{ Terminated: &v1.ContainerStateTerminated{ ExitCode: 1, Reason: "blah", }, }, }, e: "Init:blah", }, "terminated-signal": { status: v1.ContainerStatus{ Name: "ic1", State: v1.ContainerState{ Terminated: &v1.ContainerStateTerminated{ ExitCode: 1, Signal: 9, }, }, }, e: "Init:Signal:9", }, "terminated-code": { status: v1.ContainerStatus{ Name: "ic1", State: v1.ContainerState{ Terminated: &v1.ContainerStateTerminated{ ExitCode: 1, }, }, }, e: "Init:ExitCode:1", }, "terminated-restart": { status: v1.ContainerStatus{ Name: "ic1", State: v1.ContainerState{ Terminated: &v1.ContainerStateTerminated{ Reason: "blah", }, }, }, }, "waiting": { status: v1.ContainerStatus{ Name: "ic1", State: v1.ContainerState{ Waiting: &v1.ContainerStateWaiting{ Reason: "blah", }, }, }, e: "Init:blah", }, "waiting-init": { status: v1.ContainerStatus{ Name: "ic1", State: v1.ContainerState{ Waiting: &v1.ContainerStateWaiting{ Reason: "PodInitializing", }, }, }, e: "Init:0/0", }, "running": { status: v1.ContainerStatus{ Name: "ic1", State: v1.ContainerState{ Running: &v1.ContainerStateRunning{}, }, }, e: "Init:0/0", }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, checkInitContainerStatus(&u.status, u.count, u.total, u.restart)) }) } } func Test_containerPhase(t *testing.T) { uu := map[string]struct { status v1.PodStatus e string ok bool }{ "none": {}, "empty": { status: v1.PodStatus{ Phase: PhaseUnknown, }, }, "waiting": { status: v1.PodStatus{ Phase: PhaseUnknown, InitContainerStatuses: []v1.ContainerStatus{ { Name: "ic1", State: v1.ContainerState{ Running: &v1.ContainerStateRunning{}, }, }, }, ContainerStatuses: []v1.ContainerStatus{ { Name: "c1", State: v1.ContainerState{ Waiting: &v1.ContainerStateWaiting{ Reason: "waiting", }, }, }, }, }, e: "waiting", }, "terminated": { status: v1.PodStatus{ Phase: PhaseUnknown, InitContainerStatuses: []v1.ContainerStatus{ { Name: "ic1", State: v1.ContainerState{ Running: &v1.ContainerStateRunning{}, }, }, }, ContainerStatuses: []v1.ContainerStatus{ { Name: "c1", State: v1.ContainerState{ Terminated: &v1.ContainerStateTerminated{ Reason: "done", }, }, }, }, }, e: "done", }, "terminated-sig": { status: v1.PodStatus{ Phase: PhaseUnknown, InitContainerStatuses: []v1.ContainerStatus{ { Name: "ic1", State: v1.ContainerState{ Running: &v1.ContainerStateRunning{}, }, }, }, ContainerStatuses: []v1.ContainerStatus{ { Name: "c1", State: v1.ContainerState{ Terminated: &v1.ContainerStateTerminated{ Signal: 9, }, }, }, }, }, e: "Signal:9", }, "terminated-code": { status: v1.PodStatus{ Phase: PhaseUnknown, InitContainerStatuses: []v1.ContainerStatus{ { Name: "ic1", State: v1.ContainerState{ Running: &v1.ContainerStateRunning{}, }, }, }, ContainerStatuses: []v1.ContainerStatus{ { Name: "c1", State: v1.ContainerState{ Terminated: &v1.ContainerStateTerminated{ ExitCode: 2, }, }, }, }, }, e: "ExitCode:2", }, "running": { status: v1.PodStatus{ Phase: PhaseUnknown, InitContainerStatuses: []v1.ContainerStatus{ { Name: "ic1", State: v1.ContainerState{ Running: &v1.ContainerStateRunning{}, }, }, }, ContainerStatuses: []v1.ContainerStatus{ { Name: "c1", Ready: true, State: v1.ContainerState{ Running: &v1.ContainerStateRunning{}, }, }, }, }, ok: true, }, } var p Pod for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { s, ok := p.containerPhase(&u.status, "") assert.Equal(t, u.ok, ok) assert.Equal(t, u.e, s) }) } } func Test_isSideCarContainer(t *testing.T) { always, never := v1.ContainerRestartPolicyAlways, v1.ContainerRestartPolicy("never") uu := map[string]struct { p *v1.ContainerRestartPolicy e bool }{ "empty": {}, "sidecar": { p: &always, e: true, }, "no-sidecar": { p: &never, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, isSideCarContainer(u.p)) }) } } func Test_filterSidecarCO(t *testing.T) { always := v1.ContainerRestartPolicyAlways uu := map[string]struct { cc, ecc []v1.Container }{ "empty": { cc: []v1.Container{}, ecc: []v1.Container{}, }, "restartable": { cc: []v1.Container{ { Name: "c1", RestartPolicy: &always, }, }, ecc: []v1.Container{ { Name: "c1", RestartPolicy: &always, }, }, }, "not-restartable": { cc: []v1.Container{ { Name: "c1", }, }, ecc: []v1.Container{}, }, "mixed": { cc: []v1.Container{ { Name: "c1", }, { Name: "c2", RestartPolicy: &always, }, }, ecc: []v1.Container{ { Name: "c2", RestartPolicy: &always, }, }, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.ecc, filterSidecarCO(u.cc)) }) } } func Test_lastRestart(t *testing.T) { uu := map[string]struct { containerStatuses []v1.ContainerStatus expected metav1.Time }{ "no-restarts": { containerStatuses: []v1.ContainerStatus{ { Name: "c1", LastTerminationState: v1.ContainerState{}, }, }, expected: metav1.Time{}, }, "single-container-restart": { containerStatuses: []v1.ContainerStatus{ { Name: "c1", LastTerminationState: v1.ContainerState{ Terminated: &v1.ContainerStateTerminated{ FinishedAt: metav1.Time{Time: testTime()}, }, }, }, }, expected: metav1.Time{Time: testTime()}, }, "multiple-container-restarts": { containerStatuses: []v1.ContainerStatus{ { Name: "c1", LastTerminationState: v1.ContainerState{ Terminated: &v1.ContainerStateTerminated{ FinishedAt: metav1.Time{Time: testTime().Add(-1 * time.Hour)}, }, }, }, { Name: "c2", LastTerminationState: v1.ContainerState{ Terminated: &v1.ContainerStateTerminated{ FinishedAt: metav1.Time{Time: testTime()}, }, }, }, }, expected: metav1.Time{Time: testTime()}, }, "mixed-termination-states": { containerStatuses: []v1.ContainerStatus{ { Name: "c1", LastTerminationState: v1.ContainerState{}, }, { Name: "c2", LastTerminationState: v1.ContainerState{ Terminated: &v1.ContainerStateTerminated{ FinishedAt: metav1.Time{Time: testTime()}, }, }, }, }, expected: metav1.Time{Time: testTime()}, }, } var p Pod for name, u := range uu { t.Run(name, func(t *testing.T) { _, _, _, lr := p.ContainerStats(u.containerStatuses) assert.Equal(t, u.expected, lr) }) } } func Test_gatherPodMX(t *testing.T) { uu := map[string]struct { spec *v1.PodSpec mx []mv1beta1.ContainerMetrics c, r metric perc string }{ "single": { spec: &v1.PodSpec{ Containers: []v1.Container{ makeContainer("c1", false, "10m", "1Mi", "20m", "2Mi"), }, }, mx: []mv1beta1.ContainerMetrics{ makeCoMX("c1", "1m", "22Mi"), }, c: metric{ cpu: 1, mem: 22 * client.MegaByte, gpu: 1, }, r: metric{ cpu: 10, mem: 1 * client.MegaByte, gpu: 1, lcpu: 20, lmem: 2 * client.MegaByte, lgpu: 1, }, perc: "10", }, "multi": { spec: &v1.PodSpec{ Containers: []v1.Container{ makeContainer("c1", false, "11m", "22Mi", "111m", "44Mi"), makeContainer("c2", false, "93m", "1402Mi", "0m", "2804Mi"), makeContainer("c3", false, "11m", "34Mi", "0m", "69Mi"), }, }, r: metric{ cpu: 11 + 93 + 11, gpu: 1, mem: (22 + 1402 + 34) * client.MegaByte, lcpu: 111 + 0 + 0, lgpu: 1, lmem: (44 + 2804 + 69) * client.MegaByte, }, mx: []mv1beta1.ContainerMetrics{ makeCoMX("c1", "1m", "22Mi"), makeCoMX("c2", "51m", "1275Mi"), makeCoMX("c3", "1m", "27Mi"), }, c: metric{ cpu: 1 + 51 + 1, gpu: 1, mem: (22 + 1275 + 27) * client.MegaByte, }, perc: "46", }, "sidecar": { spec: &v1.PodSpec{ Containers: []v1.Container{ makeContainer("c1", false, "11m", "22Mi", "111m", "44Mi"), }, InitContainers: []v1.Container{ makeContainer("c2", true, "93m", "1402Mi", "0m", "2804Mi"), }, }, r: metric{ cpu: 11 + 93, gpu: 1, mem: (22 + 1402) * client.MegaByte, lcpu: 111 + 0, lgpu: 1, lmem: (44 + 2804) * client.MegaByte, }, mx: []mv1beta1.ContainerMetrics{ makeCoMX("c1", "1m", "22Mi"), makeCoMX("c2", "51m", "1275Mi"), }, c: metric{ cpu: 1 + 51, gpu: 1, mem: (22 + 1275) * client.MegaByte, }, perc: "50", }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { c, r := gatherPodMX(u.spec, u.mx) assert.Equal(t, u.c.cpu, c.cpu) assert.Equal(t, u.c.mem, c.mem) assert.Equal(t, u.c.lcpu, c.lcpu) assert.Equal(t, u.c.lmem, c.lmem) assert.Equal(t, u.c.lgpu, c.lgpu) assert.Equal(t, u.r.cpu, r.cpu) assert.Equal(t, u.r.mem, r.mem) assert.Equal(t, u.r.lcpu, r.lcpu) assert.Equal(t, u.r.lmem, r.lmem) assert.Equal(t, u.r.gpu, r.gpu) assert.Equal(t, u.r.lgpu, r.lgpu) assert.Equal(t, u.perc, client.ToPercentageStr(c.cpu, r.cpu)) }) } } func Test_podLimits(t *testing.T) { uu := map[string]struct { cc []v1.Container l v1.ResourceList }{ "plain": { cc: []v1.Container{ makeContainer("c1", false, "10m", "1Mi", "20m", "2Mi"), }, l: makeRes("20m", "2Mi"), }, "multi-co": { cc: []v1.Container{ makeContainer("c1", false, "10m", "1Mi", "20m", "2Mi"), makeContainer("c2", false, "10m", "1Mi", "40m", "4Mi"), }, l: makeRes("60m", "6Mi"), }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { c, m, g := cosLimits(u.cc) assert.True(t, c.Equal(*u.l.Cpu())) assert.True(t, m.Equal(*u.l.Memory())) assert.True(t, g.Equal(*extractGPU(u.l))) }) } } func Test_podRequests(t *testing.T) { uu := map[string]struct { cc []v1.Container e v1.ResourceList }{ "plain": { cc: []v1.Container{ makeContainer("c1", false, "10m", "1Mi", "20m", "2Mi"), }, e: makeRes("10m", "1Mi"), }, "multi-co": { cc: []v1.Container{ makeContainer("c1", false, "10m", "1Mi", "20m", "2Mi"), makeContainer("c2", false, "10m", "1Mi", "40m", "4Mi"), }, e: makeRes("20m", "2Mi"), }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { c, m, g := cosRequests(u.cc) assert.True(t, c.Equal(*u.e.Cpu())) assert.True(t, m.Equal(*u.e.Memory())) assert.True(t, g.Equal(*extractGPU(u.e))) }) } } func Test_readinessGateStats(t *testing.T) { const ( gate1 = "k9s.derailed.com/gate1" gate2 = "k9s.derailed.com/gate2" ) uu := map[string]struct { spec *v1.PodSpec st *v1.PodStatus r int t int }{ "empty": { spec: &v1.PodSpec{}, st: &v1.PodStatus{ Conditions: []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue}}, }, r: 0, t: 0, }, "single": { spec: &v1.PodSpec{ ReadinessGates: []v1.PodReadinessGate{{ConditionType: gate1}}, }, st: &v1.PodStatus{ Conditions: []v1.PodCondition{{Type: gate1, Status: v1.ConditionTrue}}, }, r: 1, t: 1, }, "multiple": { spec: &v1.PodSpec{ ReadinessGates: []v1.PodReadinessGate{{ConditionType: gate1}, {ConditionType: gate2}}, }, st: &v1.PodStatus{ Conditions: []v1.PodCondition{{Type: gate1, Status: v1.ConditionTrue}, {Type: gate2, Status: v1.ConditionTrue}, {Type: v1.PodReady, Status: v1.ConditionFalse}}, }, r: 2, t: 2, }, "mixed": { spec: &v1.PodSpec{ ReadinessGates: []v1.PodReadinessGate{{ConditionType: gate1}, {ConditionType: gate2}}, }, st: &v1.PodStatus{ Conditions: []v1.PodCondition{{Type: gate1, Status: v1.ConditionTrue}, {Type: gate2, Status: v1.ConditionFalse}, {Type: v1.PodReady, Status: v1.ConditionTrue}}, }, r: 1, t: 2, }, "missing": { spec: &v1.PodSpec{ ReadinessGates: []v1.PodReadinessGate{{ConditionType: gate1}, {ConditionType: gate2}}, }, st: &v1.PodStatus{ Conditions: []v1.PodCondition{{Type: gate1, Status: v1.ConditionTrue}, {Type: v1.PodReady, Status: v1.ConditionTrue}}, }, r: 1, t: 2, }, } var p Pod for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { ready, total := p.readinessGateStats(u.spec, u.st) assert.Equal(t, u.r, ready) assert.Equal(t, u.t, total) }) } } func Test_diagnose(t *testing.T) { uu := map[string]struct { phase string cr, ct int ready bool rgr, rgt int err string }{ "completed": { phase: Completed, cr: 0, ct: 1, ready: true, rgr: 0, rgt: 0, err: "", }, "container-ready-check-failed": { phase: "Running", cr: 1, ct: 2, ready: true, rgr: 1, rgt: 2, err: "container ready check failed: 1 of 2", }, "readiness-gate-check-failed": { phase: "Running", cr: 1, ct: 1, ready: true, rgr: 1, rgt: 2, err: "readiness gate check failed: 1 of 2", }, "pod-condition-ready-false": { phase: "Running", cr: 1, ct: 1, ready: false, rgr: 0, rgt: 0, err: "pod condition ready is false", }, "pod-terminating": { phase: "Terminating", cr: 1, ct: 1, ready: true, rgr: 1, rgt: 1, err: "pod is terminating", }, } var p Pod for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { err := p.diagnose(u.phase, u.cr, u.ct, u.ready, u.rgr, u.rgt) if u.err == "" { assert.NoError(t, err) } else { require.Error(t, err) assert.Contains(t, err.Error(), u.err) } }) } } // Helpers... func makeContainer(n string, restartable bool, rc, rm, lc, lm string) v1.Container { always := v1.ContainerRestartPolicyAlways rq := v1.ResourceRequirements{ Requests: makeRes(rc, rm), Limits: makeRes(lc, lm), } var rp *v1.ContainerRestartPolicy if restartable { rp = &always } return v1.Container{Name: n, Resources: rq, RestartPolicy: rp} } func makeRes(c, m string) v1.ResourceList { cpu, _ := res.ParseQuantity(c) mem, _ := res.ParseQuantity(m) gpu, _ := res.ParseQuantity(c) return v1.ResourceList{ v1.ResourceCPU: cpu, v1.ResourceMemory: mem, v1.ResourceName("nvidia.com/gpu"): gpu, } } func makeCoMX(n, c, m string) mv1beta1.ContainerMetrics { return mv1beta1.ContainerMetrics{ Name: n, Usage: makeRes(c, m), } } func testTime() time.Time { t, err := time.Parse(time.RFC3339, "2018-12-14T10:36:43.326972-07:00") if err != nil { fmt.Println("TestTime Failed", err) } return t }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/svc.go
internal/render/svc.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "sort" "strconv" "strings" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) // Header returns a header row. var defaultSVCHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "TYPE"}, model1.HeaderColumn{Name: "CLUSTER-IP"}, model1.HeaderColumn{Name: "EXTERNAL-IP"}, model1.HeaderColumn{Name: "SELECTOR", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "PORTS", Attrs: model1.Attrs{Wide: false}}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // Service renders a K8s Service to screen. type Service struct { Base } // Header returns a header row. func (s Service) Header(_ string) model1.Header { return s.doHeader(defaultSVCHeader) } // Render renders a K8s resource to screen. func (s Service) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := s.defaultRow(raw, row); err != nil { return err } if s.specs.isEmpty() { return nil } cols, err := s.specs.realize(raw, defaultSVCHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } func (s Service) defaultRow(raw *unstructured.Unstructured, r *model1.Row) error { var svc v1.Service err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &svc) if err != nil { return err } r.ID = client.MetaFQN(&svc.ObjectMeta) r.Fields = model1.Fields{ svc.Namespace, svc.Name, string(svc.Spec.Type), toIP(svc.Spec.ClusterIP), toIPs(svc.Spec.Type, getSvcExtIPS(&svc)), mapToStr(svc.Spec.Selector), ToPorts(svc.Spec.Ports), mapToStr(svc.Labels), AsStatus(s.diagnose()), ToAge(svc.GetCreationTimestamp()), } return nil } func (Service) diagnose() error { return nil } // ---------------------------------------------------------------------------- // Helpers... func toIP(ip string) string { if ip == "" || ip == "None" { return "" } return ip } func getSvcExtIPS(svc *v1.Service) []string { results := []string{} switch svc.Spec.Type { case v1.ServiceTypeNodePort, v1.ServiceTypeClusterIP: return svc.Spec.ExternalIPs case v1.ServiceTypeLoadBalancer: lbIps := lbIngressIP(svc.Status.LoadBalancer) if len(svc.Spec.ExternalIPs) > 0 { if lbIps != "" { results = append(results, lbIps) } return append(results, svc.Spec.ExternalIPs...) } if lbIps != "" { results = append(results, lbIps) } case v1.ServiceTypeExternalName: results = append(results, svc.Spec.ExternalName) } return results } func lbIngressIP(s v1.LoadBalancerStatus) string { ingress := s.Ingress result := []string{} for i := range ingress { if ingress[i].IP != "" { result = append(result, ingress[i].IP) } else if ingress[i].Hostname != "" { result = append(result, ingress[i].Hostname) } } return strings.Join(result, ",") } func toIPs(svcType v1.ServiceType, ips []string) string { if len(ips) == 0 { if svcType == v1.ServiceTypeLoadBalancer { return "<pending>" } return "" } sort.Strings(ips) return strings.Join(ips, ",") } // ToPorts returns service ports as a string. func ToPorts(pp []v1.ServicePort) string { ports := make([]string, len(pp)) for i, p := range pp { if p.Name != "" { ports[i] = p.Name + ":" } ports[i] += strconv.Itoa(int(p.Port)) + "►" + strconv.Itoa(int(p.NodePort)) if p.Protocol != "TCP" { ports[i] += "╱" + string(p.Protocol) } } return strings.Join(ports, " ") }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/sa.go
internal/render/sa.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "strconv" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) var defaultSAHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "SECRET"}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // ServiceAccount renders a K8s ServiceAccount to screen. type ServiceAccount struct { Base } // Header returns a header row. func (s ServiceAccount) Header(_ string) model1.Header { return s.doHeader(defaultSAHeader) } // Render renders a K8s resource to screen. func (s ServiceAccount) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := s.defaultRow(raw, row); err != nil { return err } if s.specs.isEmpty() { return nil } cols, err := s.specs.realize(raw, defaultSAHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } func (ServiceAccount) defaultRow(raw *unstructured.Unstructured, r *model1.Row) error { var sa v1.ServiceAccount err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &sa) if err != nil { return err } r.ID = client.MetaFQN(&sa.ObjectMeta) r.Fields = model1.Fields{ sa.Namespace, sa.Name, strconv.Itoa(len(sa.Secrets)), mapToStr(sa.Labels), "", ToAge(sa.GetCreationTimestamp()), } return nil }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/secret.go
internal/render/secret.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "strconv" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) var defaultSECHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "TYPE"}, model1.HeaderColumn{Name: "DATA"}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // Secret renders a K8s Secret to screen. type Secret struct { Base } // Header returns a header row. func (s Secret) Header(_ string) model1.Header { return s.doHeader(defaultSECHeader) } // Render renders a K8s resource to screen. func (s Secret) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := s.defaultRow(raw, row); err != nil { return err } if s.specs.isEmpty() { return nil } cols, err := s.specs.realize(raw, defaultSECHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } func (Secret) defaultRow(raw *unstructured.Unstructured, r *model1.Row) error { var sec v1.Secret err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &sec) if err != nil { return err } r.ID = client.FQN(sec.Namespace, sec.Name) r.Fields = model1.Fields{ sec.Namespace, sec.Name, string(sec.Type), strconv.Itoa(len(sec.Data)), "", ToAge(raw.GetCreationTimestamp()), } return nil }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/reference_test.go
internal/render/reference_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestReferenceRender(t *testing.T) { o := render.ReferenceRes{ Namespace: "ns1", Name: "blee", GVR: client.SecGVR.String(), } var ( ref = render.Reference{} r model1.Row ) require.NoError(t, ref.Render(o, "fred", &r)) assert.Equal(t, "ns1/blee", r.ID) assert.Equal(t, model1.Fields{ "ns1", "blee", client.SecGVR.String(), }, r.Fields) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/benchmark_int_test.go
internal/render/benchmark_int_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "log/slog" "os" "testing" "github.com/derailed/k9s/internal/model1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func init() { slog.SetDefault(slog.New(slog.DiscardHandler)) } func TestAugmentRow(t *testing.T) { uu := map[string]struct { file string e model1.Fields }{ "cool": { "testdata/b1.txt", model1.Fields{"pass", "3.3544", "29.8116", "100", "0"}, }, "2XX": { "testdata/b4.txt", model1.Fields{"pass", "3.3544", "29.8116", "160", "0"}, }, "4XX/5XX": { "testdata/b2.txt", model1.Fields{"pass", "3.3544", "29.8116", "100", "12"}, }, "toast": { "testdata/b3.txt", model1.Fields{"fail", "2.3688", "35.4606", "0", "0"}, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { data, err := os.ReadFile(u.file) require.NoError(t, err) fields := make(model1.Fields, 8) b := Benchmark{} b.augmentRow(fields, string(data)) assert.Equal(t, u.e, fields[2:7]) }) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/img_scan.go
internal/render/img_scan.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "strings" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/vul" "github.com/derailed/tcell/v2" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) const ( CVEParseIdx = 5 sevColName = "SEVERITY" ) // ImageScan renders scans report table. type ImageScan struct { Base } // ColorerFunc colors a resource row. func (ImageScan) ColorerFunc() model1.ColorerFunc { return func(ns string, h model1.Header, re *model1.RowEvent) tcell.Color { c := model1.DefaultColorer(ns, h, re) idx, ok := h.IndexOf(sevColName, true) if !ok { return c } sev := strings.TrimSpace(re.Row.Fields[idx]) switch sev { case vul.Sev1: c = tcell.ColorRed case vul.Sev2: c = tcell.ColorDarkOrange case vul.Sev3: c = tcell.ColorYellow case vul.Sev4: c = tcell.ColorDeepSkyBlue case vul.Sev5: c = tcell.ColorCadetBlue default: c = tcell.ColorDarkOliveGreen } return c } } // Header returns a header row. func (ImageScan) Header(string) model1.Header { return model1.Header{ model1.HeaderColumn{Name: "SEVERITY"}, model1.HeaderColumn{Name: "VULNERABILITY"}, model1.HeaderColumn{Name: "IMAGE"}, model1.HeaderColumn{Name: "LIBRARY"}, model1.HeaderColumn{Name: "VERSION"}, model1.HeaderColumn{Name: "FIXED-IN"}, model1.HeaderColumn{Name: "TYPE"}, } } // Render renders a K8s resource to screen. func (ImageScan) Render(o any, _ string, r *model1.Row) error { res, ok := o.(ImageScanRes) if !ok { return fmt.Errorf("expected ImageScanRes, but got %T", o) } r.ID = fmt.Sprintf("%s|%s", res.Image, strings.Join(res.Row, "|")) r.Fields = model1.Fields{ res.Row.Severity(), res.Row.Vulnerability(), res.Image, res.Row.Name(), res.Row.Version(), res.Row.Fix(), res.Row.Type(), } return nil } // ---------------------------------------------------------------------------- // Helpers... // ImageScanRes represents a container and its metrics. type ImageScanRes struct { Image string Row vul.Row } // GetObjectKind returns a schema object. func (ImageScanRes) GetObjectKind() schema.ObjectKind { return nil } // DeepCopyObject returns a container copy. func (is ImageScanRes) DeepCopyObject() runtime.Object { return is }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/sc.go
internal/render/sc.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" storagev1 "k8s.io/api/storage/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/kubectl/pkg/util/storage" ) var defaultSCHeader = model1.Header{ model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "PROVISIONER"}, model1.HeaderColumn{Name: "RECLAIMPOLICY"}, model1.HeaderColumn{Name: "VOLUMEBINDINGMODE"}, model1.HeaderColumn{Name: "ALLOWVOLUMEEXPANSION"}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // StorageClass renders a K8s StorageClass to screen. type StorageClass struct { Base } // Header returns a header row. func (s StorageClass) Header(_ string) model1.Header { return s.doHeader(defaultSCHeader) } // Render renders a K8s resource to screen. func (s StorageClass) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := s.defaultRow(raw, row); err != nil { return err } if s.specs.isEmpty() { return nil } cols, err := s.specs.realize(raw, defaultSCHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } func (s StorageClass) defaultRow(raw *unstructured.Unstructured, r *model1.Row) error { var sc storagev1.StorageClass err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &sc) if err != nil { return err } r.ID = client.FQN(client.ClusterScope, sc.Name) r.Fields = model1.Fields{ s.nameWithDefault(&sc.ObjectMeta), sc.Provisioner, strPtrToStr((*string)(sc.ReclaimPolicy)), strPtrToStr((*string)(sc.VolumeBindingMode)), boolPtrToStr(sc.AllowVolumeExpansion), mapToStr(sc.Labels), "", ToAge(sc.GetCreationTimestamp()), } return nil } func (StorageClass) nameWithDefault(meta *metav1.ObjectMeta) string { if storage.IsDefaultAnnotationText(*meta) == "Yes" { return meta.Name + " (default)" } return meta.Name }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/table_int_test.go
internal/render/table_int_test.go
package render import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/stretchr/testify/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func Test_defaultHeader(t *testing.T) { uu := map[string]struct { cdefs []metav1.TableColumnDefinition e model1.Header }{ "empty": { e: make(model1.Header, 0), }, "plain": { cdefs: []metav1.TableColumnDefinition{ {Name: "A"}, {Name: "B"}, {Name: "C"}, }, e: model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B"}, model1.HeaderColumn{Name: "C"}, }, }, "age": { cdefs: []metav1.TableColumnDefinition{ {Name: "Fred"}, {Name: "Blee"}, {Name: "Age"}, }, e: model1.Header{ model1.HeaderColumn{Name: "FRED"}, model1.HeaderColumn{Name: "BLEE"}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, }, }, "time-cols": { cdefs: []metav1.TableColumnDefinition{ {Name: "Last Seen"}, {Name: "Fred"}, {Name: "Blee"}, {Name: "Age"}, {Name: "First Seen"}, }, e: model1.Header{ model1.HeaderColumn{Name: "LAST SEEN", Attrs: model1.Attrs{Time: true}}, model1.HeaderColumn{Name: "FRED"}, model1.HeaderColumn{Name: "BLEE"}, model1.HeaderColumn{Name: "FIRST SEEN", Attrs: model1.Attrs{Time: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, }, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { var ta Table ta.SetTable("ns-1", &metav1.Table{ColumnDefinitions: u.cdefs}) assert.Equal(t, u.e, ta.defaultHeader()) }) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/pdb.go
internal/render/pdb.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "strconv" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" "github.com/derailed/tview" v1 "k8s.io/api/policy/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" ) var defaultPDBHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "MIN-AVAILABLE", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "MAX-UNAVAILABLE", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "ALLOWED-DISRUPTIONS", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "CURRENT", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "DESIRED", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "EXPECTED", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // PodDisruptionBudget renders a K8s PodDisruptionBudget to screen. type PodDisruptionBudget struct { Base } // Header returns a header row. func (p PodDisruptionBudget) Header(_ string) model1.Header { return p.doHeader(defaultPDBHeader) } // Render renders a K8s resource to screen. func (p PodDisruptionBudget) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := p.defaultRow(raw, row); err != nil { return err } if p.specs.isEmpty() { return nil } cols, err := p.specs.realize(raw, defaultPDBHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } func (p PodDisruptionBudget) defaultRow(raw *unstructured.Unstructured, r *model1.Row) error { var pdb v1.PodDisruptionBudget err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &pdb) if err != nil { return err } r.ID = client.MetaFQN(&pdb.ObjectMeta) r.Fields = model1.Fields{ pdb.Namespace, pdb.Name, numbToStr(pdb.Spec.MinAvailable), numbToStr(pdb.Spec.MaxUnavailable), strconv.Itoa(int(pdb.Status.DisruptionsAllowed)), strconv.Itoa(int(pdb.Status.CurrentHealthy)), strconv.Itoa(int(pdb.Status.DesiredHealthy)), strconv.Itoa(int(pdb.Status.ExpectedPods)), mapToStr(pdb.Labels), AsStatus(p.diagnose(pdb.Spec.MinAvailable, pdb.Status.CurrentHealthy)), ToAge(pdb.GetCreationTimestamp()), } return nil } func (PodDisruptionBudget) diagnose(v *intstr.IntOrString, healthy int32) error { if v == nil { return nil } if v.IntVal > healthy { return fmt.Errorf("expected %d but got %d", v.IntVal, healthy) } return nil } // Helpers... func numbToStr(n *intstr.IntOrString) string { if n == nil { return NAValue } if n.Type == intstr.Int { return strconv.Itoa(int(n.IntVal)) } return n.StrVal }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/pdb_test.go
internal/render/pdb_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestPodDisruptionBudgetRender(t *testing.T) { c := render.PodDisruptionBudget{} r := model1.NewRow(9) require.NoError(t, c.Render(load(t, "pdb"), "", &r)) assert.Equal(t, "default/fred", r.ID) assert.Equal(t, model1.Fields{"default", "fred", "2", render.NAValue, "0", "0", "2", "0"}, r.Fields[:8]) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/context.go
internal/render/context.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "log/slog" "os" "strings" "github.com/derailed/k9s/internal/model1" "github.com/derailed/tcell/v2" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/tools/clientcmd/api" ) // Context renders a K8s ConfigMap to screen. type Context struct { Base } // ColorerFunc colors a resource row. func (Context) ColorerFunc() model1.ColorerFunc { return func(ns string, h model1.Header, r *model1.RowEvent) tcell.Color { c := model1.DefaultColorer(ns, h, r) if strings.Contains(strings.TrimSpace(r.Row.Fields[0]), "*") { return model1.HighlightColor } return c } } // Header returns a header row. func (Context) Header(string) model1.Header { return model1.Header{ model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "CLUSTER"}, model1.HeaderColumn{Name: "AUTHINFO"}, model1.HeaderColumn{Name: "NAMESPACE"}, } } // Render renders a K8s resource to screen. func (Context) Render(o any, _ string, r *model1.Row) error { ctx, ok := o.(*NamedContext) if !ok { return fmt.Errorf("expected *NamedContext, but got %T", o) } name := ctx.Name if ctx.IsCurrentContext(ctx.Name) { name += "(*)" } r.ID = ctx.Name r.Fields = model1.Fields{ name, ctx.Context.Cluster, ctx.Context.AuthInfo, ctx.Context.Namespace, } return nil } // Helpers... // NamedContext represents a named cluster context. type NamedContext struct { Name string Context *api.Context Config ContextNamer } // ContextNamer represents a named context. type ContextNamer interface { CurrentContextName() (string, error) } // NewNamedContext returns a new named context. func NewNamedContext(c ContextNamer, n string, ctx *api.Context) *NamedContext { return &NamedContext{Name: n, Context: ctx, Config: c} } // IsCurrentContext return the active context name. func (c *NamedContext) IsCurrentContext(n string) bool { cl, err := c.Config.CurrentContextName() if err != nil { slog.Error("Fail to retrieve current context. Exiting!") os.Exit(1) } return cl == n } // GetObjectKind returns a schema object. func (*NamedContext) GetObjectKind() schema.ObjectKind { return nil } // DeepCopyObject returns a container copy. func (c *NamedContext) DeepCopyObject() runtime.Object { return c }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/section.go
internal/render/section.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render // Level tracks lint check level. type Level int const ( // OkLevel denotes no linting issues. OkLevel Level = iota // InfoLevel denotes FIY linting issues. InfoLevel // WarnLevel denotes a warning issue. WarnLevel // ErrorLevel denotes a serious issue. ErrorLevel ) type ( // Sections represents a collection of sections. Sections []Section // Section represents a sanitizer pass. Section struct { Title string `json:"sanitizer" yaml:"sanitizer"` GVR string `yaml:"gvr" json:"gvr"` Outcome Outcome `json:"issues,omitempty" yaml:"issues,omitempty"` } // Outcome represents a classification of reports outcome. Outcome map[string]Issues // Issues represents a collection of issues. Issues []Issue // Issue represents a sanitization issue. Issue struct { Group string `yaml:"group" json:"group"` GVR string `yaml:"gvr" json:"gvr"` Level Level `yaml:"level" json:"level"` Message string `yaml:"message" json:"message"` } )
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/dp_test.go
internal/render/dp_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDpRender(t *testing.T) { c := render.Deployment{} r := model1.NewRow(7) require.NoError(t, c.Render(load(t, "dp"), "", &r)) assert.Equal(t, "icx/icx-db", r.ID) assert.Equal(t, model1.Fields{"icx", "icx-db", "n/a", "1/1", "1", "1"}, r.Fields[:6]) } func BenchmarkDpRender(b *testing.B) { var ( c = render.Deployment{} r = model1.NewRow(7) o = load(b, "dp") ) b.ResetTimer() b.ReportAllocs() for range b.N { _ = c.Render(o, "", &r) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/svc_test.go
internal/render/svc_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestServiceRender(t *testing.T) { c := render.Service{} r := model1.NewRow(4) require.NoError(t, c.Render(load(t, "svc"), "", &r)) assert.Equal(t, "default/dictionary1", r.ID) assert.Equal(t, model1.Fields{"default", "dictionary1", "ClusterIP", "10.47.248.116", "", "app=dictionary1", "http:4001►0"}, r.Fields[:7]) } func BenchmarkSvcRender(b *testing.B) { var ( svc render.Service r = model1.NewRow(4) s = load(b, "svc") ) b.ResetTimer() b.ReportAllocs() for range b.N { _ = svc.Render(s, "", &r) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/sc_test.go
internal/render/sc_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestStorageClassRender(t *testing.T) { c := render.StorageClass{} r := model1.NewRow(4) require.NoError(t, c.Render(load(t, "sc"), "", &r)) assert.Equal(t, "-/standard", r.ID) assert.Equal(t, model1.Fields{"standard (default)", "kubernetes.io/gce-pd", "Delete", "Immediate", "true"}, r.Fields[:5]) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/np.go
internal/render/np.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "strings" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" netv1 "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) var defaultNPHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "POD-SELECTOR"}, model1.HeaderColumn{Name: "ING-SELECTOR", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "ING-PORTS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "ING-BLOCK", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "EGR-SELECTOR", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "EGR-PORTS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "EGR-BLOCK", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // NetworkPolicy renders a K8s NetworkPolicy to screen. type NetworkPolicy struct { Base } // Header returns a header row. func (p NetworkPolicy) Header(_ string) model1.Header { return p.doHeader(defaultNPHeader) } // Render renders a K8s resource to screen. func (p NetworkPolicy) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := p.defaultRow(raw, row); err != nil { return err } if p.specs.isEmpty() { return nil } cols, err := p.specs.realize(raw, defaultNPHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } func (NetworkPolicy) defaultRow(raw *unstructured.Unstructured, r *model1.Row) error { var np netv1.NetworkPolicy err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &np) if err != nil { return err } ip, is, ib := ingress(np.Spec.Ingress) ep, es, eb := egress(np.Spec.Egress) var podSel string if len(np.Spec.PodSelector.MatchLabels) > 0 { podSel = mapToStr(np.Spec.PodSelector.MatchLabels) } if len(np.Spec.PodSelector.MatchExpressions) > 0 { podSel += "::" + expToStr(np.Spec.PodSelector.MatchExpressions) } r.ID = client.MetaFQN(&np.ObjectMeta) r.Fields = model1.Fields{ np.Namespace, np.Name, podSel, is, ip, ib, es, ep, eb, mapToStr(np.Labels), "", ToAge(np.GetCreationTimestamp()), } return nil } // Helpers... func ingress(ii []netv1.NetworkPolicyIngressRule) (port, selector, block string) { var ports, sels, blocks []string for _, i := range ii { if p := portsToStr(i.Ports); p != "" { ports = append(ports, p) } ll, pp := peersToStr(i.From) if ll != "" { sels = append(sels, ll) } if pp != "" { blocks = append(blocks, pp) } } return strings.Join(ports, ","), strings.Join(sels, ","), strings.Join(blocks, ",") } func egress(ee []netv1.NetworkPolicyEgressRule) (port, selector, block string) { var ports, sels, blocks []string for _, e := range ee { if p := portsToStr(e.Ports); p != "" { ports = append(ports, p) } ll, pp := peersToStr(e.To) if ll != "" { sels = append(sels, ll) } if pp != "" { blocks = append(blocks, pp) } } return strings.Join(ports, ","), strings.Join(sels, ","), strings.Join(blocks, ",") } func portsToStr(pp []netv1.NetworkPolicyPort) string { ports := make([]string, 0, len(pp)) for _, p := range pp { proto, port := NAValue, NAValue if p.Protocol != nil { proto = string(*p.Protocol) } if p.Port != nil { port = p.Port.String() } ports = append(ports, proto+":"+port) } return strings.Join(ports, ",") } func peersToStr(pp []netv1.NetworkPolicyPeer) (selector, ip string) { sels := make([]string, 0, len(pp)) ips := make([]string, 0, len(pp)) for _, p := range pp { if peer := renderPeer(p); peer != "" { sels = append(sels, peer) } if p.IPBlock == nil { continue } if b := renderBlock(p.IPBlock); b != "" { ips = append(ips, b) } } return strings.Join(sels, ","), strings.Join(ips, ",") } func renderBlock(b *netv1.IPBlock) string { s := b.CIDR if len(b.Except) == 0 { return s } e, more := b.Except, false if len(b.Except) > 2 { e, more = e[:2], true } if more { return s + "[" + strings.Join(e, ",") + "...]" } return s + "[" + strings.Join(b.Except, ",") + "]" } func renderPeer(i netv1.NetworkPolicyPeer) string { var s string if i.PodSelector != nil { if m := mapToStr(i.PodSelector.MatchLabels); m != "" { s += "po:" + m } if e := expToStr(i.PodSelector.MatchExpressions); e != "" { s += "--" + e } } if i.NamespaceSelector != nil { if m := mapToStr(i.NamespaceSelector.MatchLabels); m != "" { s += "ns:" + m } if e := expToStr(i.NamespaceSelector.MatchExpressions); e != "" { s += "--" + e } } return s } func expToStr(ee []metav1.LabelSelectorRequirement) string { ss := make([]string, len(ee)) for i, e := range ee { ss[i] = labToStr(e) } return strings.Join(ss, ",") } func labToStr(e metav1.LabelSelectorRequirement) string { return fmt.Sprintf("%s-%s%s", e.Key, e.Operator, strings.Join(e.Values, ",")) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/np_test.go
internal/render/np_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNetworkPolicyRender(t *testing.T) { c := render.NetworkPolicy{} r := model1.NewRow(9) require.NoError(t, c.Render(load(t, "np"), "", &r)) assert.Equal(t, "default/fred", r.ID) assert.Equal(t, model1.Fields{"default", "fred", "app=nginx", "ns:app=blee,po:app=fred", "TCP:6379", "172.17.0.0/16[172.17.1.0/24,172.17.3.0/24...]", "", "TCP:5978", "10.0.0.0/24"}, r.Fields[:9]) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/cust_cols_test.go
internal/render/cust_cols_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "errors" "fmt" "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/tview" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "k8s.io/client-go/util/jsonpath" ) func TestParseSpecs(t *testing.T) { uu := map[string]struct { cols ColsSpecs err error e ColumnSpecs }{ "empty": { e: ColumnSpecs{}, }, "plain": { cols: ColsSpecs{ "a", "b", "c", }, e: ColumnSpecs{ { Header: model1.HeaderColumn{ Name: "a", }, }, { Header: model1.HeaderColumn{ Name: "b", }, }, { Header: model1.HeaderColumn{ Name: "c", }, }, }, }, "with-spec-plain": { cols: ColsSpecs{ "a", "b:.metadata.name", "c", }, e: ColumnSpecs{ { Header: model1.HeaderColumn{ Name: "a", }, }, { Header: model1.HeaderColumn{ Name: "b", }, Spec: "{.metadata.name}", }, { Header: model1.HeaderColumn{ Name: "c", }, }, }, }, "with-spec-fq": { cols: ColsSpecs{ "a", "b:.metadata.name|NW", "c", }, e: ColumnSpecs{ { Header: model1.HeaderColumn{ Name: "a", }, }, { Header: model1.HeaderColumn{ Name: "b", Attrs: model1.Attrs{ Wide: true, Capacity: true, Align: tview.AlignRight, }, }, Spec: "{.metadata.name}", }, { Header: model1.HeaderColumn{ Name: "c", }, }, }, }, "spec-type-no-wide": { cols: ColsSpecs{ "a", "b:.metadata.name|T", "c", }, e: ColumnSpecs{ { Header: model1.HeaderColumn{ Name: "a", }, }, { Header: model1.HeaderColumn{ Name: "b", Attrs: model1.Attrs{ Time: true, }, }, Spec: "{.metadata.name}", }, { Header: model1.HeaderColumn{ Name: "c", }, }, }, }, "plain-wide": { cols: ColsSpecs{ "a", "b|W", "c", }, e: ColumnSpecs{ { Header: model1.HeaderColumn{ Name: "a", }, }, { Header: model1.HeaderColumn{ Name: "b", Attrs: model1.Attrs{Wide: true}, }, }, { Header: model1.HeaderColumn{ Name: "c", }, }, }, }, "no-spec-kind-wide": { cols: ColsSpecs{ "a", "b|NW", "c", }, e: ColumnSpecs{ { Header: model1.HeaderColumn{ Name: "a", }, }, { Header: model1.HeaderColumn{ Name: "b", Attrs: model1.Attrs{ Align: tview.AlignRight, Capacity: true, Wide: true, }, }, }, { Header: model1.HeaderColumn{ Name: "c", }, }, }, }, "toast-spec": { cols: ColsSpecs{ "a", "b:{{crap.bozo}}|NW", "c", }, err: errors.New(`unexpected path string, expected a 'name1.name2' or '.name1.name2' or '{name1.name2}' or '{.name1.name2}'`), }, "no-spec": { cols: ColsSpecs{ "a", "b|NW", "c", }, e: ColumnSpecs{ { Header: model1.HeaderColumn{ Name: "a", }, }, { Header: model1.HeaderColumn{ Name: "b", Attrs: model1.Attrs{Align: tview.AlignRight, Capacity: true, Wide: true}, }, }, { Header: model1.HeaderColumn{ Name: "c", }, }, }, }, } for k, u := range uu { t.Run(k, func(t *testing.T) { cols, err := u.cols.parseSpecs() assert.Equal(t, u.err, err) assert.Equal(t, u.e, cols) }) } } func TestHydrateNilObject(t *testing.T) { cc := ColumnSpecs{ { Header: model1.HeaderColumn{Name: "test"}, Spec: "{.metadata.name}", }, } parser := jsonpath.New(fmt.Sprintf("column%d", 0)).AllowMissingKeys(true) err := parser.Parse("{.metadata.name}") require.NoError(t, err) parsers := []*jsonpath.JSONPath{parser} rh := model1.Header{ {Name: "test"}, } row := &model1.Row{ Fields: model1.Fields{"value1"}, } // Test with nil object - should not panic cols, err := hydrate(nil, cc, parsers, rh, row) require.NoError(t, err) assert.Len(t, cols, 1) assert.Equal(t, NAValue, cols[0].Value) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/sts.go
internal/render/sts.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "strconv" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" appsv1 "k8s.io/api/apps/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) var defaultSTSHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "VS", Attrs: model1.Attrs{VS: true}}, model1.HeaderColumn{Name: "READY"}, model1.HeaderColumn{Name: "SELECTOR", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "SERVICE"}, model1.HeaderColumn{Name: "CONTAINERS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "IMAGES", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // StatefulSet renders a K8s StatefulSet to screen. type StatefulSet struct { Base } // Header returns a header row. func (s StatefulSet) Header(_ string) model1.Header { return s.doHeader(defaultSTSHeader) } // Render renders a K8s resource to screen. func (s StatefulSet) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := s.defaultRow(raw, row); err != nil { return err } if s.specs.isEmpty() { return nil } cols, err := s.specs.realize(raw, defaultSTSHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } func (s StatefulSet) defaultRow(raw *unstructured.Unstructured, r *model1.Row) error { var sts appsv1.StatefulSet err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &sts) if err != nil { return err } var desired int32 if sts.Spec.Replicas != nil { desired = *sts.Spec.Replicas } r.ID = client.MetaFQN(&sts.ObjectMeta) r.Fields = model1.Fields{ sts.Namespace, sts.Name, computeVulScore(sts.Namespace, sts.Labels, &sts.Spec.Template.Spec), strconv.Itoa(int(sts.Status.ReadyReplicas)) + "/" + strconv.Itoa(int(desired)), asSelector(sts.Spec.Selector), na(sts.Spec.ServiceName), podContainerNames(&sts.Spec.Template.Spec, true), podImageNames(&sts.Spec.Template.Spec, true), mapToStr(sts.Labels), AsStatus(s.diagnose(desired, sts.Status.Replicas, sts.Status.ReadyReplicas)), ToAge(sts.GetCreationTimestamp()), } return nil } func (StatefulSet) diagnose(d, c, r int32) error { if c != r { return fmt.Errorf("desired %d replicas got %d available", c, r) } if d != r { return fmt.Errorf("want %d replicas got %d available", d, r) } return nil }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/eps.go
internal/render/eps.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "strconv" "strings" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" discoveryv1 "k8s.io/api/discovery/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) var defaultEPsHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "ADDRESSTYPE"}, model1.HeaderColumn{Name: "PORTS"}, model1.HeaderColumn{Name: "ENDPOINTS"}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // EndpointSlice renders a K8s EndpointSlice to screen. type EndpointSlice struct { Base } // Header returns a header row. func (e EndpointSlice) Header(_ string) model1.Header { return e.doHeader(defaultEPsHeader) } // Render renders a K8s resource to screen. func (e EndpointSlice) Render(o any, ns string, row *model1.Row) error { if err := e.defaultRow(o, ns, row); err != nil { return err } if e.specs.isEmpty() { return nil } cols, err := e.specs.realize(o.(*unstructured.Unstructured), defaultEPsHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } func (e EndpointSlice) defaultRow(o any, ns string, r *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } var eps discoveryv1.EndpointSlice err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &eps) if err != nil { return err } r.ID = client.MetaFQN(&eps.ObjectMeta) r.Fields = make(model1.Fields, 0, len(e.Header(ns))) r.Fields = model1.Fields{ eps.Namespace, eps.Name, string(eps.AddressType), toPorts(eps.Ports), toEPss(eps.Endpoints), ToAge(eps.GetCreationTimestamp()), } return nil } // ---------------------------------------------------------------------------- // Helpers... func toEPss(ee []discoveryv1.Endpoint) string { if len(ee) == 0 { return UnsetValue } aa := make([]string, 0, len(ee)) for _, e := range ee { aa = append(aa, e.Addresses...) } return strings.Join(aa, ",") } func toPorts(ee []discoveryv1.EndpointPort) string { if len(ee) == 0 { return UnsetValue } aa := make([]string, 0, len(ee)) for _, e := range ee { if e.Port != nil { aa = append(aa, strconv.Itoa(int(*e.Port))) } } return strings.Join(aa, ",") }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/container_int_test.go
internal/render/container_int_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "testing" "github.com/stretchr/testify/assert" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" mv1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1" ) func Test_gatherContainerMX(t *testing.T) { uu := map[string]struct { container v1.Container mx *mv1beta1.ContainerMetrics c, r metric }{ "empty": {}, "amd-request": { container: v1.Container{ Name: "fred", Image: "img", Resources: v1.ResourceRequirements{ Requests: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("10m"), v1.ResourceMemory: resource.MustParse("20Mi"), "nvidia.com/gpu": resource.MustParse("1"), }, }, }, mx: &mv1beta1.ContainerMetrics{ Name: "fred", Usage: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("10m"), v1.ResourceMemory: resource.MustParse("20Mi"), }, }, c: metric{ cpu: 10, mem: 20971520, }, r: metric{ cpu: 10, gpu: 1, mem: 20971520, }, }, "amd-both": { container: v1.Container{ Name: "fred", Image: "img", Resources: v1.ResourceRequirements{ Requests: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("10m"), v1.ResourceMemory: resource.MustParse("20Mi"), "nvidia.com/gpu": resource.MustParse("1"), }, Limits: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("50m"), v1.ResourceMemory: resource.MustParse("100Mi"), "nvidia.com/gpu": resource.MustParse("2"), }, }, }, mx: &mv1beta1.ContainerMetrics{ Name: "fred", Usage: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("10m"), v1.ResourceMemory: resource.MustParse("20Mi"), }, }, c: metric{ cpu: 10, mem: 20971520, }, r: metric{ cpu: 10, gpu: 1, mem: 20971520, lcpu: 50, lgpu: 2, lmem: 104857600, }, }, "amd-limits": { container: v1.Container{ Name: "fred", Image: "img", Resources: v1.ResourceRequirements{ Limits: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("50m"), v1.ResourceMemory: resource.MustParse("100Mi"), "nvidia.com/gpu": resource.MustParse("2"), }, }, }, mx: &mv1beta1.ContainerMetrics{ Name: "fred", Usage: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("10m"), v1.ResourceMemory: resource.MustParse("20Mi"), }, }, c: metric{ cpu: 10, mem: 20971520, }, r: metric{ cpu: 50, gpu: 2, mem: 104857600, lcpu: 50, lgpu: 2, lmem: 104857600, }, }, "amd-no-mx": { container: v1.Container{ Name: "fred", Image: "img", Resources: v1.ResourceRequirements{ Requests: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("10m"), v1.ResourceMemory: resource.MustParse("20Mi"), "nvidia.com/gpu": resource.MustParse("1"), }, Limits: v1.ResourceList{ v1.ResourceCPU: resource.MustParse("50m"), v1.ResourceMemory: resource.MustParse("100Mi"), "nvidia.com/gpu": resource.MustParse("2"), }, }, }, r: metric{ cpu: 10, gpu: 1, mem: 20971520, lcpu: 50, lgpu: 2, lmem: 104857600, }, }, } for k, u := range uu { t.Run(k, func(t *testing.T) { c, r := gatherContainerMX(&u.container, u.mx) assert.Equal(t, u.c, c) assert.Equal(t, u.r, r) }) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/pv.go
internal/render/pv.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "path" "strings" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" "github.com/derailed/tcell/v2" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) const terminatingPhase = "Terminating" // PersistentVolume renders a K8s PersistentVolume to screen. type PersistentVolume struct { Base } // ColorerFunc colors a resource row. func (PersistentVolume) ColorerFunc() model1.ColorerFunc { return func(ns string, h model1.Header, re *model1.RowEvent) tcell.Color { c := model1.DefaultColorer(ns, h, re) idx, ok := h.IndexOf("STATUS", true) if !ok { return c } switch strings.TrimSpace(re.Row.Fields[idx]) { case string(v1.VolumeBound): return model1.StdColor case string(v1.VolumeAvailable): return tcell.ColorGreen case string(v1.VolumePending): return model1.PendingColor case terminatingPhase: return model1.CompletedColor } return c } } // Header returns a header row. func (p PersistentVolume) Header(_ string) model1.Header { return p.doHeader(defaultPVHeader) } var defaultPVHeader = model1.Header{ model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "CAPACITY", Attrs: model1.Attrs{Capacity: true}}, model1.HeaderColumn{Name: "ACCESS MODES"}, model1.HeaderColumn{Name: "RECLAIM POLICY"}, model1.HeaderColumn{Name: "STATUS"}, model1.HeaderColumn{Name: "CLAIM"}, model1.HeaderColumn{Name: "STORAGECLASS"}, model1.HeaderColumn{Name: "REASON"}, model1.HeaderColumn{Name: "VOLUMEMODE", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // Render renders a K8s resource to screen. func (p PersistentVolume) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := p.defaultRow(raw, row); err != nil { return err } if p.specs.isEmpty() { return nil } cols, err := p.specs.realize(raw, defaultPVHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } func (p PersistentVolume) defaultRow(raw *unstructured.Unstructured, r *model1.Row) error { var pv v1.PersistentVolume err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &pv) if err != nil { return err } phase := pv.Status.Phase if pv.DeletionTimestamp != nil { phase = terminatingPhase } var claim string if pv.Spec.ClaimRef != nil { claim = path.Join(pv.Spec.ClaimRef.Namespace, pv.Spec.ClaimRef.Name) } class, found := pv.Annotations[v1.BetaStorageClassAnnotation] if !found { class = pv.Spec.StorageClassName } size := pv.Spec.Capacity[v1.ResourceStorage] r.ID = client.MetaFQN(&pv.ObjectMeta) r.Fields = model1.Fields{ pv.Name, size.String(), accessMode(pv.Spec.AccessModes), string(pv.Spec.PersistentVolumeReclaimPolicy), string(phase), claim, class, pv.Status.Reason, p.volumeMode(pv.Spec.VolumeMode), mapToStr(pv.Labels), AsStatus(p.diagnose(phase)), ToAge(pv.GetCreationTimestamp()), } return nil } func (PersistentVolume) diagnose(phase v1.PersistentVolumePhase) error { if phase == v1.VolumeFailed { return fmt.Errorf("failed to delete or recycle") } return nil } func (PersistentVolume) volumeMode(m *v1.PersistentVolumeMode) string { if m == nil { return MissingValue } return string(*m) } // ---------------------------------------------------------------------------- // Helpers... func accessMode(aa []v1.PersistentVolumeAccessMode) string { dd := accessDedup(aa) s := make([]string, 0, len(dd)) for _, am := range dd { switch am { case v1.ReadWriteOnce: s = append(s, "RWO") case v1.ReadOnlyMany: s = append(s, "ROX") case v1.ReadWriteMany: s = append(s, "RWX") case v1.ReadWriteOncePod: s = append(s, "RWOP") } } return strings.Join(s, ",") } func accessContains(cc []v1.PersistentVolumeAccessMode, a v1.PersistentVolumeAccessMode) bool { for _, c := range cc { if c == a { return true } } return false } func accessDedup(cc []v1.PersistentVolumeAccessMode) []v1.PersistentVolumeAccessMode { set := []v1.PersistentVolumeAccessMode{} for _, c := range cc { if !accessContains(set, c) { set = append(set, c) } } return set }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/cronjob_test.go
internal/render/cronjob_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestCronJobRender(t *testing.T) { c := render.CronJob{} r := model1.NewRow(6) require.NoError(t, c.Render(load(t, "cj"), "", &r)) assert.Equal(t, "default/hello", r.ID) assert.Equal(t, model1.Fields{"default", "hello", "n/a", "*/1 * * * *", "false", "0"}, r.Fields[:6]) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/cronjob.go
internal/render/cronjob.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "strconv" "strings" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" batchv1 "k8s.io/api/batch/v1" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) var defaultCJHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "VS", Attrs: model1.Attrs{VS: true}}, model1.HeaderColumn{Name: "SCHEDULE"}, model1.HeaderColumn{Name: "SUSPEND"}, model1.HeaderColumn{Name: "ACTIVE"}, model1.HeaderColumn{Name: "LAST_SCHEDULE", Attrs: model1.Attrs{Time: true}}, model1.HeaderColumn{Name: "SELECTOR", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "CONTAINERS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "IMAGES", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // CronJob renders a K8s CronJob to screen. type CronJob struct { Base } // Header returns a header row. func (c CronJob) Header(_ string) model1.Header { return c.doHeader(defaultCJHeader) } // Render renders a K8s resource to screen. func (c CronJob) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := c.defaultRow(raw, row); err != nil { return err } if c.specs.isEmpty() { return nil } cols, err := c.specs.realize(raw, defaultCJHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } // Render renders a K8s resource to screen. func (CronJob) defaultRow(raw *unstructured.Unstructured, r *model1.Row) error { var cj batchv1.CronJob err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &cj) if err != nil { return err } lastScheduled := "<none>" if cj.Status.LastScheduleTime != nil { lastScheduled = ToAge(*cj.Status.LastScheduleTime) } r.ID = client.MetaFQN(&cj.ObjectMeta) r.Fields = model1.Fields{ cj.Namespace, cj.Name, computeVulScore(cj.Namespace, cj.Labels, &cj.Spec.JobTemplate.Spec.Template.Spec), cj.Spec.Schedule, boolPtrToStr(cj.Spec.Suspend), strconv.Itoa(len(cj.Status.Active)), lastScheduled, jobSelector(&cj.Spec.JobTemplate.Spec), podContainerNames(&cj.Spec.JobTemplate.Spec.Template.Spec, true), podImageNames(&cj.Spec.JobTemplate.Spec.Template.Spec, true), mapToStr(cj.Labels), "", ToAge(cj.GetCreationTimestamp()), } return nil } // Helpers func jobSelector(spec *batchv1.JobSpec) string { if spec.Selector == nil { return MissingValue } if len(spec.Selector.MatchLabels) > 0 { return mapToStr(spec.Selector.MatchLabels) } if len(spec.Selector.MatchExpressions) == 0 { return "" } ss := make([]string, 0, len(spec.Selector.MatchExpressions)) for _, e := range spec.Selector.MatchExpressions { ss = append(ss, e.String()) } return strings.Join(ss, " ") } func podContainerNames(spec *v1.PodSpec, includeInit bool) string { cc := make([]string, 0, len(spec.Containers)+len(spec.InitContainers)) if includeInit { for i := range spec.InitContainers { cc = append(cc, spec.InitContainers[i].Name) } } for i := range spec.Containers { cc = append(cc, spec.Containers[i].Name) } return strings.Join(cc, ",") } func podImageNames(spec *v1.PodSpec, includeInit bool) string { cc := make([]string, 0, len(spec.Containers)+len(spec.InitContainers)) if includeInit { for i := range spec.InitContainers { cc = append(cc, spec.InitContainers[i].Image) } } for i := range spec.Containers { cc = append(cc, spec.Containers[i].Image) } return strings.Join(cc, ",") }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/policy_int_test.go
internal/render/policy_int_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "testing" "github.com/stretchr/testify/assert" ) func Test_cleanseResource(t *testing.T) { uu := map[string]struct { r, e string }{ "empty": {}, "single": { r: "fred", e: "fred", }, "grp/res": { r: "fred/blee", e: "blee", }, "grp/res/sub": { r: "fred/blee/bob", e: "blee/bob", }, } for k, u := range uu { t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, cleanseResource(u.r)) }) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/helpers.go
internal/render/helpers.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "context" "log/slog" "sort" "strconv" "strings" "time" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/slogs" "github.com/derailed/k9s/internal/vul" "github.com/derailed/tview" "github.com/mattn/go-runewidth" "golang.org/x/text/language" "golang.org/x/text/message" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/duration" ) // ExtractImages returns a collection of container images. // !!BOZO!! If this has any legs?? enable scans on other container types. func ExtractImages(spec *v1.PodSpec) []string { ii := make([]string, 0, len(spec.Containers)) for i := range spec.Containers { ii = append(ii, spec.Containers[i].Image) } return ii } func computeVulScore(ns string, lbls map[string]string, spec *v1.PodSpec) string { if vul.ImgScanner == nil || !vul.ImgScanner.IsInitialized() || vul.ImgScanner.ShouldExcludes(ns, lbls) { return NAValue } ii := ExtractImages(spec) vul.ImgScanner.Enqueue(context.Background(), ii...) sc := vul.ImgScanner.Score(ii...) return sc } func runesToNum(rr []rune) int64 { var r int64 var m int64 = 1 for i := len(rr) - 1; i >= 0; i-- { v := int64(rr[i] - '0') r += v * m m *= 10 } return r } // AsThousands prints a number with thousand separator. func AsThousands(n int64) string { p := message.NewPrinter(language.English) return p.Sprintf("%d", n) } // AsStatus returns error as string. func AsStatus(err error) string { if err == nil { return "" } return err.Error() } func asSelector(s *metav1.LabelSelector) string { sel, err := metav1.LabelSelectorAsSelector(s) if err != nil { slog.Error("Selector conversion failed", slogs.Error, err) return NAValue } return sel.String() } // ToSelector flattens a map selector to a string selector. func toSelector(m map[string]string) string { s := make([]string, 0, len(m)) for k, v := range m { s = append(s, k+"="+v) } return strings.Join(s, ",") } // Blank checks if a collection is empty or all values are blank. func blank(ss []string) bool { for _, s := range ss { if s != "" { return false } } return true } // Join a slice of strings, skipping blanks. func join(ss []string, sep string) string { switch len(ss) { case 0: return "" case 1: return ss[0] } b := make([]string, 0, len(ss)) for _, s := range ss { if s != "" { b = append(b, s) } } if len(b) == 0 { return "" } n := len(sep) * (len(b) - 1) for i := range b { n += len(ss[i]) } var buff strings.Builder buff.Grow(n) buff.WriteString(b[0]) for _, s := range b[1:] { buff.WriteString(sep) buff.WriteString(s) } return buff.String() } // AsPerc prints a number as percentage with parens. func AsPerc(p string) string { return "(" + p + ")" } // PrintPerc prints a number as percentage. func PrintPerc(p int) string { return strconv.Itoa(p) + "%" } // IntToStr converts an int to a string. func IntToStr(p int) string { return strconv.Itoa(p) } func missing(s string) string { return check(s, MissingValue) } func naStrings(ss []string) string { if len(ss) == 0 { return NAValue } return strings.Join(ss, ",") } func na(s string) string { return check(s, NAValue) } func check(s, sub string) string { if s == "" { return sub } return s } func boolToStr(b bool) string { switch b { case true: return "true" default: return "false" } } // ToAge converts time to human duration. func ToAge(t metav1.Time) string { if t.IsZero() { return UnknownValue } return duration.HumanDuration(time.Since(t.Time)) } func toAgeHuman(s string) string { if s == "" { return UnknownValue } t, err := time.Parse(time.RFC3339, s) if err != nil { return NAValue } return duration.HumanDuration(time.Since(t)) } // Truncate a string to the given l and suffix ellipsis if needed. func Truncate(str string, width int) string { return runewidth.Truncate(str, width, string(tview.SemigraphicsHorizontalEllipsis)) } func mapToStr(m map[string]string) string { if len(m) == 0 { return "" } kk := make([]string, 0, len(m)) for k := range m { kk = append(kk, k) } sort.Strings(kk) bb := make([]byte, 0, 100) for i, k := range kk { bb = append(bb, k+"="+m[k]...) if i < len(kk)-1 { bb = append(bb, ',') } } return string(bb) } func mapToIfc(m any) (s string) { if m == nil { return "" } mm, ok := m.(map[string]any) if !ok { return "" } if len(mm) == 0 { return "" } kk := make([]string, 0, len(mm)) for k := range mm { kk = append(kk, k) } sort.Strings(kk) for i, k := range kk { str, ok := mm[k].(string) if !ok { continue } s += k + "=" + str if i < len(kk)-1 { s += " " } } return } func toMu(v int64) string { if v == 0 { return NAValue } return strconv.Itoa(int(v)) } func toMc(v int64) string { if v == 0 { return ZeroValue } return strconv.Itoa(int(v)) } func toMi(v int64) string { if v == 0 { return ZeroValue } return strconv.Itoa(int(client.ToMB(v))) } func boolPtrToStr(b *bool) string { if b == nil { return "false" } return boolToStr(*b) } func strPtrToStr(s *string) string { if s == nil { return "" } return *s } // Pad a string up to the given length or truncates if greater than length. func Pad(s string, width int) string { if len(s) == width { return s } if len(s) > width { return Truncate(s, width) } return s + strings.Repeat(" ", width-len(s)) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/cr.go
internal/render/cr.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" rbacv1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) // ClusterRole renders a K8s ClusterRole to screen. type ClusterRole struct { Base } // Header returns a header row. func (c ClusterRole) Header(_ string) model1.Header { return c.doHeader(defaultCRHeader) } // Header returns a header rbw. var defaultCRHeader = model1.Header{ model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "LABELS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // Render renders a K8s resource to screen. func (p ClusterRole) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expecting Unstructured, but got %T", o) } if err := p.defaultRow(raw, row); err != nil { return err } if p.specs.isEmpty() { return nil } cols, err := p.specs.realize(raw, defaultCRHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } // Render renders a K8s resource to screen. func (ClusterRole) defaultRow(raw *unstructured.Unstructured, r *model1.Row) error { var cr rbacv1.ClusterRole err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &cr) if err != nil { return err } r.ID = client.FQN("-", cr.Name) r.Fields = model1.Fields{ cr.Name, mapToStr(cr.Labels), ToAge(cr.GetCreationTimestamp()), } return nil }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/rs.go
internal/render/rs.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "strconv" "strings" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" "github.com/derailed/tview" appsv1 "k8s.io/api/apps/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) // ReplicaSet renders a K8s ReplicaSet to screen. type ReplicaSet struct { Base } // ColorerFunc colors a resource row. func (ReplicaSet) ColorerFunc() model1.ColorerFunc { return model1.DefaultColorer } // Header returns a header row. func (r ReplicaSet) Header(_ string) model1.Header { return r.doHeader(defaultRSHeader) } var defaultRSHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "VS", Attrs: model1.Attrs{VS: true}}, model1.HeaderColumn{Name: "DESIRED", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "CURRENT", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "READY", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "CONTAINERS", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "IMAGES", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "SELECTOR", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // Render renders a K8s resource to screen. func (r ReplicaSet) Render(o any, _ string, row *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected Unstructured, but got %T", o) } if err := r.defaultRow(raw, row); err != nil { return err } if r.specs.isEmpty() { return nil } cols, err := r.specs.realize(raw, defaultRSHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } func (r ReplicaSet) defaultRow(raw *unstructured.Unstructured, row *model1.Row) error { var rs appsv1.ReplicaSet err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &rs) if err != nil { return err } var ( cc = rs.Spec.Template.Spec.Containers cos, imgs = make([]string, 0, len(cc)), make([]string, 0, len(cc)) ) for i := range cc { cos, imgs = append(cos, cc[i].Name), append(imgs, cc[i].Image) } row.ID = client.MetaFQN(&rs.ObjectMeta) row.Fields = model1.Fields{ rs.Namespace, rs.Name, computeVulScore(rs.Namespace, rs.Labels, &rs.Spec.Template.Spec), strconv.Itoa(int(*rs.Spec.Replicas)), strconv.Itoa(int(rs.Status.Replicas)), strconv.Itoa(int(rs.Status.ReadyReplicas)), strings.Join(cos, ","), strings.Join(imgs, ","), mapToStr(rs.Labels), AsStatus(r.diagnose(&rs)), ToAge(rs.GetCreationTimestamp()), } return nil } func (ReplicaSet) diagnose(rs *appsv1.ReplicaSet) error { if rs.Status.Replicas != rs.Status.ReadyReplicas { if rs.Status.Replicas == 0 { return fmt.Errorf("did not phase down correctly expecting 0 replicas but got %d", rs.Status.ReadyReplicas) } return fmt.Errorf("mismatch desired(%d) vs ready(%d)", rs.Status.Replicas, rs.Status.ReadyReplicas) } return nil }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/pv_test.go
internal/render/pv_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestPersistentVolumeRender(t *testing.T) { c := render.PersistentVolume{} r := model1.NewRow(9) require.NoError(t, c.Render(load(t, "pv"), "-", &r)) assert.Equal(t, "-/pvc-07aa4e2c-8726-11e9-a8e8-42010a80015b", r.ID) assert.Equal(t, model1.Fields{"pvc-07aa4e2c-8726-11e9-a8e8-42010a80015b", "1Gi", "RWO", "Delete", "Bound", "default/www-nginx-sts-1", "standard"}, r.Fields[:7]) } func TestTerminatingPersistentVolumeRender(t *testing.T) { c := render.PersistentVolume{} r := model1.NewRow(9) require.NoError(t, c.Render(load(t, "pv_terminating"), "-", &r)) assert.Equal(t, "-/pvc-a4d86f51-916c-476b-83af-b551c91a8ac0", r.ID) assert.Equal(t, model1.Fields{"pvc-a4d86f51-916c-476b-83af-b551c91a8ac0", "1Gi", "RWO", "Delete", "Terminating", "default/www-nginx-sts-2", "standard"}, r.Fields[:7]) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/dir.go
internal/render/dir.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "context" "fmt" "os" "github.com/derailed/k9s/internal/config" "github.com/derailed/k9s/internal/model1" "github.com/derailed/tcell/v2" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) // Dir renders a directory entry to screen. type Dir struct{} // IsGeneric identifies a generic handler. func (Dir) IsGeneric() bool { return false } // Healthy checks if the resource is healthy. func (Dir) Healthy(context.Context, any) error { return nil } // ColorerFunc colors a resource row. func (Dir) ColorerFunc() model1.ColorerFunc { return func(string, model1.Header, *model1.RowEvent) tcell.Color { return tcell.ColorCadetBlue } } func (Dir) SetViewSetting(*config.ViewSetting) {} // Header returns a header row. func (Dir) Header(string) model1.Header { return model1.Header{ model1.HeaderColumn{Name: "NAME"}, } } // Render renders a K8s resource to screen. // BOZO!! Pass in a row with pre-alloc fields?? func (Dir) Render(o any, _ string, r *model1.Row) error { d, ok := o.(DirRes) if !ok { return fmt.Errorf("expected DirRes, but got %T", o) } name := "🦄 " if d.Entry.IsDir() { name = "📁 " } name += d.Entry.Name() r.ID, r.Fields = d.Path, append(r.Fields, name) return nil } // ---------------------------------------------------------------------------- // Helpers... // DirRes represents an alias resource. type DirRes struct { Entry os.DirEntry Path string } // GetObjectKind returns a schema object. func (DirRes) GetObjectKind() schema.ObjectKind { return nil } // DeepCopyObject returns a container copy. func (d DirRes) DeepCopyObject() runtime.Object { return d }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/reference.go
internal/render/reference.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" "github.com/derailed/tcell/v2" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) // Reference renders a reference to screen. type Reference struct { Base } // ColorerFunc colors a resource row. func (Reference) ColorerFunc() model1.ColorerFunc { return func(string, model1.Header, *model1.RowEvent) tcell.Color { return tcell.ColorCadetBlue } } // Header returns a header row. func (Reference) Header(string) model1.Header { return model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "GVR"}, } } // Render renders a K8s resource to screen. // BOZO!! Pass in a row with pre-alloc fields?? func (Reference) Render(o any, _ string, r *model1.Row) error { ref, ok := o.(ReferenceRes) if !ok { return fmt.Errorf("expected ReferenceRes, but got %T", o) } r.ID = client.FQN(ref.Namespace, ref.Name) r.Fields = append(r.Fields, ref.Namespace, ref.Name, ref.GVR, ) return nil } // ---------------------------------------------------------------------------- // Helpers... // ReferenceRes represents a reference resource. type ReferenceRes struct { Namespace string Name string GVR string } // GetObjectKind returns a schema object. func (ReferenceRes) GetObjectKind() schema.ObjectKind { return nil } // DeepCopyObject returns a container copy. func (a ReferenceRes) DeepCopyObject() runtime.Object { return a }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/sts_test.go
internal/render/sts_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestStatefulSetRender(t *testing.T) { c := render.StatefulSet{} r := model1.NewRow(4) require.NoError(t, c.Render(load(t, "sts"), "", &r)) assert.Equal(t, "default/nginx-sts", r.ID) assert.Equal(t, model1.Fields{"default", "nginx-sts", "n/a", "4/4", "app=nginx-sts", "nginx-sts", "nginx", "k8s.gcr.io/nginx-slim:0.8", "app=nginx-sts", ""}, r.Fields[:len(r.Fields)-1]) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/hpa_test.go
internal/render/hpa_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/tcell/v2" "github.com/derailed/tview" "github.com/stretchr/testify/assert" ) func TestHorizontalPodAutoscalerColorer(t *testing.T) { hpaHeader := model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "REFERENCE"}, model1.HeaderColumn{Name: "TARGETS%"}, model1.HeaderColumn{Name: "MINPODS", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "MAXPODS", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "REPLICAS", Attrs: model1.Attrs{Align: tview.AlignRight}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } uu := map[string]struct { h model1.Header re *model1.RowEvent e tcell.Color }{ "when replicas = maxpods": { h: hpaHeader, re: &model1.RowEvent{ Kind: model1.EventUnchanged, Row: model1.Row{ Fields: model1.Fields{"blee", "fred", "fred", "100%", "1", "5", "5", "1d"}, }, }, e: model1.ErrColor, }, "when replicas > maxpods, for some reason": { h: hpaHeader, re: &model1.RowEvent{ Kind: model1.EventUnchanged, Row: model1.Row{ Fields: model1.Fields{"blee", "fred", "fred", "100%", "1", "5", "6", "1d"}, }, }, e: model1.ErrColor, }, "when replicas < maxpods": { h: hpaHeader, re: &model1.RowEvent{ Kind: model1.EventUnchanged, Row: model1.Row{ Fields: model1.Fields{"blee", "fred", "fred", "100%", "1", "5", "1", "1d"}, }, }, e: model1.StdColor, }, } var r HorizontalPodAutoscaler for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, r.ColorerFunc()("", u.h, u.re)) }) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/cm.go
internal/render/cm.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package render import ( "fmt" "strconv" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/model1" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" ) // ConfigMap renders a K8s ConfigMap to screen. type ConfigMap struct { Base } // Header returns a header row. func (m ConfigMap) Header(_ string) model1.Header { return m.doHeader(defaultCMHeader) } var defaultCMHeader = model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "DATA"}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } // Render renders a K8s resource to screen. func (m ConfigMap) Render(o any, _ string, row *model1.Row) error { if err := m.defaultRow(o, row); err != nil { return err } if m.specs.isEmpty() { return nil } cols, err := m.specs.realize(o.(*unstructured.Unstructured), defaultCMHeader, row) if err != nil { return err } cols.hydrateRow(row) return nil } // Render renders a K8s resource to screen. func (ConfigMap) defaultRow(o any, r *model1.Row) error { raw, ok := o.(*unstructured.Unstructured) if !ok { return fmt.Errorf("expected *Unstructured, but got %T", o) } var cm v1.ConfigMap err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw.Object, &cm) if err != nil { return err } r.ID = client.FQN(cm.Namespace, cm.Name) r.Fields = model1.Fields{ cm.Namespace, cm.Name, strconv.Itoa(len(cm.Data)), "", ToAge(cm.GetCreationTimestamp()), } return nil }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/helm/chart.go
internal/render/helm/chart.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package helm import ( "context" "fmt" "log/slog" "strconv" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/config" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" "github.com/derailed/k9s/internal/slogs" "helm.sh/helm/v3/pkg/release" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) // Chart renders a helm chart to screen. type Chart struct{} // IsGeneric identifies a generic handler. func (Chart) IsGeneric() bool { return false } func (Chart) SetViewSetting(*config.ViewSetting) {} // ColorerFunc colors a resource row. func (Chart) ColorerFunc() model1.ColorerFunc { return model1.DefaultColorer } // Header returns a header row. func (Chart) Header(_ string) model1.Header { return model1.Header{ model1.HeaderColumn{Name: "NAMESPACE"}, model1.HeaderColumn{Name: "NAME"}, model1.HeaderColumn{Name: "REVISION"}, model1.HeaderColumn{Name: "STATUS"}, model1.HeaderColumn{Name: "CHART"}, model1.HeaderColumn{Name: "APP VERSION"}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, } } // Render renders a chart to screen. func (c Chart) Render(o any, _ string, r *model1.Row) error { h, ok := o.(ReleaseRes) if !ok { return fmt.Errorf("expected ReleaseRes, but got %T", o) } r.ID = client.FQN(h.Release.Namespace, h.Release.Name) r.Fields = model1.Fields{ h.Release.Namespace, h.Release.Name, strconv.Itoa(h.Release.Version), h.Release.Info.Status.String(), h.Release.Chart.Metadata.Name + "-" + h.Release.Chart.Metadata.Version, h.Release.Chart.Metadata.AppVersion, render.AsStatus(c.diagnose(h.Release.Info.Status.String())), render.ToAge(metav1.Time{Time: h.Release.Info.LastDeployed.Time}), } return nil } // Healthy checks component health. func (c Chart) Healthy(_ context.Context, o any) error { h, ok := o.(*ReleaseRes) if !ok { slog.Error("Expected *ReleaseRes, but got", slogs.Type, fmt.Sprintf("%T", o)) } return c.diagnose(h.Release.Info.Status.String()) } func (Chart) diagnose(s string) error { if s != "deployed" { return fmt.Errorf("chart is in an invalid state") } return nil } // ---------------------------------------------------------------------------- // Helpers... // ReleaseRes represents a helm chart resource. type ReleaseRes struct { Release *release.Release } // GetObjectKind returns a schema object. func (ReleaseRes) GetObjectKind() schema.ObjectKind { return nil } // DeepCopyObject returns a container copy. func (h ReleaseRes) DeepCopyObject() runtime.Object { return h }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/render/helm/history.go
internal/render/helm/history.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package helm import ( "context" "fmt" "strconv" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/config" "github.com/derailed/k9s/internal/model1" "github.com/derailed/k9s/internal/render" ) // History renders a History chart to screen. type History struct{} func (History) SetViewSetting(*config.ViewSetting) {} // IsGeneric identifies a generic handler. func (History) IsGeneric() bool { return false } // ColorerFunc colors a resource row. func (History) ColorerFunc() model1.ColorerFunc { return model1.DefaultColorer } // Header returns a header row. func (History) Header(_ string) model1.Header { return model1.Header{ model1.HeaderColumn{Name: "REVISION"}, model1.HeaderColumn{Name: "STATUS"}, model1.HeaderColumn{Name: "CHART"}, model1.HeaderColumn{Name: "APP VERSION"}, model1.HeaderColumn{Name: "DESCRIPTION"}, model1.HeaderColumn{Name: "VALID", Attrs: model1.Attrs{Wide: true}}, } } // Render renders a chart to screen. func (c History) Render(o any, _ string, r *model1.Row) error { h, ok := o.(ReleaseRes) if !ok { return fmt.Errorf("expected HistoryRes, but got %T", o) } r.ID = client.FQN(h.Release.Namespace, h.Release.Name) r.ID += ":" + strconv.Itoa(h.Release.Version) r.Fields = model1.Fields{ strconv.Itoa(h.Release.Version), h.Release.Info.Status.String(), h.Release.Chart.Metadata.Name + "-" + h.Release.Chart.Metadata.Version, h.Release.Chart.Metadata.AppVersion, h.Release.Info.Description, render.AsStatus(c.diagnose(h.Release.Info.Status.String())), } return nil } // Healthy checks component health. func (History) Healthy(context.Context, any) error { return nil } func (History) diagnose(string) error { return nil }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/row_test.go
internal/model1/row_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1_test import ( "fmt" "reflect" "testing" "time" "github.com/derailed/k9s/internal/model1" "github.com/stretchr/testify/assert" ) func BenchmarkRowCustomize(b *testing.B) { row := model1.Row{ID: "fred", Fields: model1.Fields{"f1", "f2", "f3"}} cols := []int{0, 1, 2} b.ReportAllocs() b.ResetTimer() for range b.N { _ = row.Customize(cols) } } func TestFieldCustomize(t *testing.T) { uu := map[string]struct { fields model1.Fields cols []int e model1.Fields }{ "empty": { fields: model1.Fields{}, cols: []int{0, 1, 2}, e: model1.Fields{"", "", ""}, }, "no-cols": { fields: model1.Fields{"f1", "f2", "f3"}, cols: []int{}, e: model1.Fields{}, }, "reverse": { fields: model1.Fields{"f1", "f2", "f3"}, cols: []int{1, 0}, e: model1.Fields{"f2", "f1"}, }, "missing": { fields: model1.Fields{"f1", "f2", "f3"}, cols: []int{10, 0}, e: model1.Fields{"", "f1"}, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { ff := make(model1.Fields, len(u.cols)) u.fields.Customize(u.cols, ff) assert.Equal(t, u.e, ff) }) } } func TestFieldClone(t *testing.T) { f := model1.Fields{"a", "b", "c"} f1 := f.Clone() assert.True(t, reflect.DeepEqual(f, f1)) assert.NotEqual(t, fmt.Sprintf("%p", f), fmt.Sprintf("%p", f1)) } func TestRowLabelize(t *testing.T) { uu := map[string]struct { row model1.Row cols []int e model1.Row }{ "empty": { row: model1.Row{}, cols: []int{0, 1, 2}, e: model1.Row{ID: "", Fields: model1.Fields{"", "", ""}}, }, "no-cols-no-data": { row: model1.Row{}, cols: []int{}, e: model1.Row{ID: "", Fields: model1.Fields{}}, }, "no-cols-data": { row: model1.Row{ID: "fred", Fields: model1.Fields{"f1", "f2", "f3"}}, cols: []int{}, e: model1.Row{ID: "fred", Fields: model1.Fields{}}, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { row := u.row.Customize(u.cols) assert.Equal(t, u.e, row) }) } } func TestRowCustomize(t *testing.T) { uu := map[string]struct { row model1.Row cols []int e model1.Row }{ "empty": { row: model1.Row{}, cols: []int{0, 1, 2}, e: model1.Row{ID: "", Fields: model1.Fields{"", "", ""}}, }, "no-cols-no-data": { row: model1.Row{}, cols: []int{}, e: model1.Row{ID: "", Fields: model1.Fields{}}, }, "no-cols-data": { row: model1.Row{ID: "fred", Fields: model1.Fields{"f1", "f2", "f3"}}, cols: []int{}, e: model1.Row{ID: "fred", Fields: model1.Fields{}}, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { row := u.row.Customize(u.cols) assert.Equal(t, u.e, row) }) } } func TestRowsDelete(t *testing.T) { uu := map[string]struct { rows model1.Rows id string e model1.Rows }{ "first": { rows: model1.Rows{ {ID: "a", Fields: []string{"blee", "duh"}}, {ID: "b", Fields: []string{"albert", "blee"}}, }, id: "a", e: model1.Rows{ {ID: "b", Fields: []string{"albert", "blee"}}, }, }, "last": { rows: model1.Rows{ {ID: "a", Fields: []string{"blee", "duh"}}, {ID: "b", Fields: []string{"albert", "blee"}}, }, id: "b", e: model1.Rows{ {ID: "a", Fields: []string{"blee", "duh"}}, }, }, "middle": { rows: model1.Rows{ {ID: "a", Fields: []string{"blee", "duh"}}, {ID: "b", Fields: []string{"albert", "blee"}}, {ID: "c", Fields: []string{"fred", "zorg"}}, }, id: "b", e: model1.Rows{ {ID: "a", Fields: []string{"blee", "duh"}}, {ID: "c", Fields: []string{"fred", "zorg"}}, }, }, "missing": { rows: model1.Rows{ {ID: "a", Fields: []string{"blee", "duh"}}, {ID: "b", Fields: []string{"albert", "blee"}}, }, id: "zorg", e: model1.Rows{ {ID: "a", Fields: []string{"blee", "duh"}}, {ID: "b", Fields: []string{"albert", "blee"}}, }, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { rows := u.rows.Delete(u.id) assert.Equal(t, u.e, rows) }) } } func TestRowsUpsert(t *testing.T) { uu := map[string]struct { rows model1.Rows row model1.Row e model1.Rows }{ "add": { rows: model1.Rows{ {ID: "a", Fields: []string{"blee", "duh"}}, {ID: "b", Fields: []string{"albert", "blee"}}, }, row: model1.Row{ID: "c", Fields: []string{"f1", "f2"}}, e: model1.Rows{ {ID: "a", Fields: []string{"blee", "duh"}}, {ID: "b", Fields: []string{"albert", "blee"}}, {ID: "c", Fields: []string{"f1", "f2"}}, }, }, "update": { rows: model1.Rows{ {ID: "a", Fields: []string{"blee", "duh"}}, {ID: "b", Fields: []string{"albert", "blee"}}, }, row: model1.Row{ID: "a", Fields: []string{"f1", "f2"}}, e: model1.Rows{ {ID: "a", Fields: []string{"f1", "f2"}}, {ID: "b", Fields: []string{"albert", "blee"}}, }, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { rows := u.rows.Upsert(u.row) assert.Equal(t, u.e, rows) }) } } func TestRowsSortText(t *testing.T) { uu := map[string]struct { rows model1.Rows col int asc, num bool e model1.Rows }{ "plainAsc": { rows: model1.Rows{ {Fields: []string{"blee", "duh"}}, {Fields: []string{"albert", "blee"}}, }, col: 0, asc: true, e: model1.Rows{ {Fields: []string{"albert", "blee"}}, {Fields: []string{"blee", "duh"}}, }, }, "plainDesc": { rows: model1.Rows{ {Fields: []string{"blee", "duh"}}, {Fields: []string{"albert", "blee"}}, }, col: 0, asc: false, e: model1.Rows{ {Fields: []string{"blee", "duh"}}, {Fields: []string{"albert", "blee"}}, }, }, "numericAsc": { rows: model1.Rows{ {Fields: []string{"10", "duh"}}, {Fields: []string{"1", "blee"}}, }, col: 0, num: true, asc: true, e: model1.Rows{ {Fields: []string{"1", "blee"}}, {Fields: []string{"10", "duh"}}, }, }, "numericDesc": { rows: model1.Rows{ {Fields: []string{"10", "duh"}}, {Fields: []string{"1", "blee"}}, }, col: 0, num: true, asc: false, e: model1.Rows{ {Fields: []string{"10", "duh"}}, {Fields: []string{"1", "blee"}}, }, }, "composite": { rows: model1.Rows{ {Fields: []string{"blee-duh", "duh"}}, {Fields: []string{"blee", "blee"}}, }, col: 0, asc: true, e: model1.Rows{ {Fields: []string{"blee", "blee"}}, {Fields: []string{"blee-duh", "duh"}}, }, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { u.rows.Sort(u.col, u.asc, u.num, false, false) assert.Equal(t, u.e, u.rows) }) } } func TestRowsSortDuration(t *testing.T) { uu := map[string]struct { rows model1.Rows col int asc bool e model1.Rows }{ "fred": { rows: model1.Rows{ {Fields: []string{"2m24s", "blee"}}, {Fields: []string{"2m12s", "duh"}}, }, col: 0, asc: true, e: model1.Rows{ {Fields: []string{"2m12s", "duh"}}, {Fields: []string{"2m24s", "blee"}}, }, }, "years": { rows: model1.Rows{ {Fields: []string{testTime().Add(-365 * 24 * time.Hour).String(), "blee"}}, {Fields: []string{testTime().String(), "duh"}}, }, col: 0, asc: true, e: model1.Rows{ {Fields: []string{testTime().String(), "duh"}}, {Fields: []string{testTime().Add(-365 * 24 * time.Hour).String(), "blee"}}, }, }, "durationAsc": { rows: model1.Rows{ {Fields: []string{testTime().Add(10 * time.Second).String(), "duh"}}, {Fields: []string{testTime().String(), "blee"}}, }, col: 0, asc: true, e: model1.Rows{ {Fields: []string{testTime().String(), "blee"}}, {Fields: []string{testTime().Add(10 * time.Second).String(), "duh"}}, }, }, "durationDesc": { rows: model1.Rows{ {Fields: []string{testTime().Add(10 * time.Second).String(), "duh"}}, {Fields: []string{testTime().String(), "blee"}}, }, col: 0, e: model1.Rows{ {Fields: []string{testTime().Add(10 * time.Second).String(), "duh"}}, {Fields: []string{testTime().String(), "blee"}}, }, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { u.rows.Sort(u.col, u.asc, false, true, false) assert.Equal(t, u.e, u.rows) }) } } func TestRowsSortMetrics(t *testing.T) { uu := map[string]struct { rows model1.Rows col int asc bool e model1.Rows }{ "metricAsc": { rows: model1.Rows{ {Fields: []string{"10m", "duh"}}, {Fields: []string{"1m", "blee"}}, }, col: 0, asc: true, e: model1.Rows{ {Fields: []string{"1m", "blee"}}, {Fields: []string{"10m", "duh"}}, }, }, "metricDesc": { rows: model1.Rows{ {Fields: []string{"10000m", "1000Mi"}}, {Fields: []string{"1m", "50Mi"}}, }, col: 1, asc: false, e: model1.Rows{ {Fields: []string{"10000m", "1000Mi"}}, {Fields: []string{"1m", "50Mi"}}, }, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { u.rows.Sort(u.col, u.asc, true, false, false) assert.Equal(t, u.e, u.rows) }) } } func TestRowsSortCapacity(t *testing.T) { uu := map[string]struct { rows model1.Rows col int asc bool e model1.Rows }{ "capacityAsc": { rows: model1.Rows{ {Fields: []string{"10Gi", "duh"}}, {Fields: []string{"10G", "blee"}}, }, col: 0, asc: true, e: model1.Rows{ {Fields: []string{"10G", "blee"}}, {Fields: []string{"10Gi", "duh"}}, }, }, "capacityDesc": { rows: model1.Rows{ {Fields: []string{"10000m", "1000Mi"}}, {Fields: []string{"1m", "50Mi"}}, }, col: 1, asc: false, e: model1.Rows{ {Fields: []string{"10000m", "1000Mi"}}, {Fields: []string{"1m", "50Mi"}}, }, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { u.rows.Sort(u.col, u.asc, false, false, true) assert.Equal(t, u.e, u.rows) }) } } func TestLess(t *testing.T) { uu := map[string]struct { isNumber bool isDuration bool isCapacity bool id1, id2 string v1, v2 string e bool }{ "years": { isNumber: false, isDuration: true, isCapacity: false, id1: "id1", id2: "id2", v1: "2y263d", v2: "1y179d", }, "hours": { isNumber: false, isDuration: true, isCapacity: false, id1: "id1", id2: "id2", v1: "2y263d", v2: "19h", }, "capacity1": { isNumber: false, isDuration: false, isCapacity: true, id1: "id1", id2: "id2", v1: "1Gi", v2: "1G", e: false, }, "capacity2": { isNumber: false, isDuration: false, isCapacity: true, id1: "id1", id2: "id2", v1: "1Gi", v2: "1Ti", e: true, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, model1.Less(u.isNumber, u.isDuration, u.isCapacity, u.id1, u.id2, u.v1, u.v2)) }) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/pool_test.go
internal/model1/pool_test.go
package model1_test import ( "context" "fmt" "sync/atomic" "testing" "github.com/derailed/k9s/internal/model1" "github.com/stretchr/testify/assert" ) func TestWorkerPoolPlain(t *testing.T) { p := model1.NewWorkerPool(context.Background(), 2) var c atomic.Int32 for range 10 { p.Add(func(ctx context.Context) error { select { case <-ctx.Done(): fmt.Println("Worker canceled") return nil default: c.Add(1) return nil } }) } errs := p.Drain() assert.Equal(t, 10, int(c.Load())) assert.Empty(t, errs) } func TestWorkerPoolWithError(t *testing.T) { ctx := context.Background() p := model1.NewWorkerPool(ctx, 2) var c atomic.Int32 for i := range 10 { p.Add(func(ctx context.Context) error { select { case <-ctx.Done(): fmt.Println("Worker canceled") return nil default: if i%2 == 0 { return fmt.Errorf("BOOM%d", i) } c.Add(1) return nil } }) } errs := p.Drain() assert.Equal(t, 5, int(c.Load())) assert.Len(t, errs, 5) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/row_event.go
internal/model1/row_event.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1 import ( "fmt" "log/slog" "sort" ) type ReRangeFn func(int, RowEvent) bool // ResEvent represents a resource event. type ResEvent int // RowEvent tracks resource instance events. type RowEvent struct { Kind ResEvent Row Row Deltas DeltaRow } // NewRowEvent returns a new row event. func NewRowEvent(kind ResEvent, row Row) RowEvent { return RowEvent{ Kind: kind, Row: row, } } // NewRowEventWithDeltas returns a new row event with deltas. func NewRowEventWithDeltas(row Row, delta DeltaRow) RowEvent { return RowEvent{ Kind: EventUpdate, Row: row, Deltas: delta, } } // Clone returns a row event deep copy. func (r RowEvent) Clone() RowEvent { return RowEvent{ Kind: r.Kind, Row: r.Row.Clone(), Deltas: r.Deltas.Clone(), } } // Customize returns a new subset based on the given column indices. func (r RowEvent) Customize(cols []int) RowEvent { delta := r.Deltas if !r.Deltas.IsBlank() { delta = make(DeltaRow, len(cols)) r.Deltas.Customize(cols, delta) } return RowEvent{ Kind: r.Kind, Deltas: delta, Row: r.Row.Customize(cols), } } // ExtractHeaderLabels extract collection of fields into header. func (r RowEvent) ExtractHeaderLabels(labelCol int) []string { hh, _ := sortLabels(labelize(r.Row.Fields[labelCol])) return hh } // Labelize returns a new row event based on labels. func (r RowEvent) Labelize(cols []int, labelCol int, labels []string) RowEvent { return RowEvent{ Kind: r.Kind, Deltas: r.Deltas.Labelize(cols, labelCol), Row: r.Row.Labelize(cols, labelCol, labels), } } // Diff returns true if the row changed. func (r RowEvent) Diff(re RowEvent, ageCol int) bool { if r.Kind != re.Kind { return true } if r.Deltas.Diff(re.Deltas, ageCol) { return true } return r.Row.Diff(re.Row, ageCol) } // ---------------------------------------------------------------------------- type reIndex map[string]int // RowEvents a collection of row events. type RowEvents struct { events []RowEvent index reIndex } func NewRowEvents(size int) *RowEvents { return &RowEvents{ events: make([]RowEvent, 0, size), index: make(reIndex, size), } } func NewRowEventsWithEvts(ee ...RowEvent) *RowEvents { re := NewRowEvents(len(ee)) for _, e := range ee { re.Add(e) } return re } func (r *RowEvents) reindex() { for i, e := range r.events { r.index[e.Row.ID] = i } } func (r *RowEvents) At(i int) (RowEvent, bool) { if i < 0 || i > len(r.events) { return RowEvent{}, false } return r.events[i], true } func (r *RowEvents) Set(i int, re RowEvent) { r.events[i] = re r.index[re.Row.ID] = i } func (r *RowEvents) Add(re RowEvent) { r.events = append(r.events, re) r.index[re.Row.ID] = len(r.events) - 1 } // ExtractHeaderLabels extract header labels. func (r *RowEvents) ExtractHeaderLabels(labelCol int) []string { ll := make([]string, 0, 10) for _, re := range r.events { ll = append(ll, re.ExtractHeaderLabels(labelCol)...) } return ll } // Labelize converts labels into a row event. func (r *RowEvents) Labelize(cols []int, labelCol int, labels []string) *RowEvents { out := make([]RowEvent, 0, len(r.events)) for _, re := range r.events { out = append(out, re.Labelize(cols, labelCol, labels)) } return NewRowEventsWithEvts(out...) } // Customize returns custom row events based on columns layout. func (r *RowEvents) Customize(cols []int) *RowEvents { ee := make([]RowEvent, 0, len(cols)) for _, re := range r.events { ee = append(ee, re.Customize(cols)) } return NewRowEventsWithEvts(ee...) } // Diff returns true if the event changed. func (r *RowEvents) Diff(re *RowEvents, ageCol int) bool { if len(r.events) != len(re.events) { return true } for i := range r.events { if r.events[i].Diff(re.events[i], ageCol) { return true } } return false } // Clone returns a deep copy. func (r *RowEvents) Clone() *RowEvents { re := make([]RowEvent, 0, len(r.events)) for _, e := range r.events { re = append(re, e.Clone()) } return NewRowEventsWithEvts(re...) } // Upsert add or update a row if it exists. func (r *RowEvents) Upsert(re RowEvent) { if idx, ok := r.FindIndex(re.Row.ID); ok { r.events[idx] = re } else { r.Add(re) } } // Delete removes an element by id. func (r *RowEvents) Delete(fqn string) error { victim, ok := r.FindIndex(fqn) if !ok { return fmt.Errorf("unable to delete row with fqn: %q", fqn) } r.events = append(r.events[0:victim], r.events[victim+1:]...) delete(r.index, fqn) r.reindex() return nil } func (r *RowEvents) Len() int { return len(r.events) } func (r *RowEvents) Empty() bool { return len(r.events) == 0 } // Clear delete all row events. func (r *RowEvents) Clear() { r.events = r.events[:0] for k := range r.index { delete(r.index, k) } } func (r *RowEvents) Range(f ReRangeFn) { for i, e := range r.events { if !f(i, e) { return } } } func (r *RowEvents) Get(id string) (RowEvent, bool) { i, ok := r.index[id] if !ok { return RowEvent{}, false } return r.At(i) } // FindIndex locates a row index by id. Returns false is not found. func (r *RowEvents) FindIndex(id string) (int, bool) { i, ok := r.index[id] return i, ok } // Sort rows based on column index and order. func (r *RowEvents) Sort(ns string, sortCol int, isDuration, numCol, isCapacity, asc bool) { if sortCol == -1 || r == nil { return } t := RowEventSorter{ NS: ns, Events: r, Index: sortCol, Asc: asc, IsNumber: numCol, IsDuration: isDuration, IsCapacity: isCapacity, } sort.Sort(t) r.reindex() } // For debugging... func (re RowEvents) Dump(msg string) { slog.Debug("[DEBUG] RowEvents" + msg) for _, r := range re.events { slog.Debug(fmt.Sprintf(" %#v", r)) } } // ---------------------------------------------------------------------------- // RowEventSorter sorts row events by a given colon. type RowEventSorter struct { Events *RowEvents Index int NS string IsNumber bool IsDuration bool IsCapacity bool Asc bool } func (r RowEventSorter) Len() int { return len(r.Events.events) } func (r RowEventSorter) Swap(i, j int) { r.Events.events[i], r.Events.events[j] = r.Events.events[j], r.Events.events[i] } func (r RowEventSorter) Less(i, j int) bool { f1, f2 := r.Events.events[i].Row.Fields, r.Events.events[j].Row.Fields id1, id2 := r.Events.events[i].Row.ID, r.Events.events[j].Row.ID less := Less(r.IsNumber, r.IsDuration, r.IsCapacity, id1, id2, f1[r.Index], f2[r.Index]) if r.Asc { return less } return !less }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/types.go
internal/model1/types.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1 import ( "context" "github.com/derailed/k9s/internal/config" "github.com/derailed/tcell/v2" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) const ( NAValue = "na" // EventUnchanged notifies listener resource has not changed. EventUnchanged ResEvent = 1 << iota // EventAdd notifies listener of a resource was added. EventAdd // EventUpdate notifies listener of a resource updated. EventUpdate // EventDelete notifies listener of a resource was deleted. EventDelete // EventClear the stack was reset. EventClear ) // DecoratorFunc decorates a string. type DecoratorFunc func(string) string // ColorerFunc represents a resource row colorer. type ColorerFunc func(ns string, h Header, re *RowEvent) tcell.Color // Renderer represents a resource renderer. type Renderer interface { // IsGeneric identifies a generic handler. IsGeneric() bool // Render converts raw resources to tabular data. Render(o any, ns string, row *Row) error // Header returns the resource header. Header(ns string) Header // ColorerFunc returns a row colorer function. ColorerFunc() ColorerFunc // SetViewSetting sets custom view settings if any. SetViewSetting(vs *config.ViewSetting) // Healthy checks if the resource is healthy. Healthy(ctx context.Context, o any) error } // Generic represents a generic resource. type Generic interface { // SetTable sets up the resource tabular definition. SetTable(ns string, table *metav1.Table) // Header returns a resource header. Header(ns string) Header // Render renders the resource. Render(o any, ns string, row *Row) error }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/delta.go
internal/model1/delta.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1 import "reflect" // DeltaRow represents a collection of row deltas between old and new row. type DeltaRow []string // NewDeltaRow computes the delta between 2 rows. func NewDeltaRow(o, n Row, h Header) DeltaRow { deltas := make(DeltaRow, len(o.Fields)) for i, old := range o.Fields { if i >= len(n.Fields) { continue } if old != "" && old != n.Fields[i] && !h.IsTimeCol(i) { deltas[i] = old } } return deltas } // Labelize returns a new deltaRow based on labels. func (d DeltaRow) Labelize(cols []int, labelCol int) DeltaRow { if len(d) == 0 { return d } _, vals := sortLabels(labelize(d[labelCol])) out := make(DeltaRow, 0, len(cols)+len(vals)) for _, i := range cols { out = append(out, d[i]) } for _, v := range vals { out = append(out, v) } return out } // Diff returns true if deltas differ or false otherwise. func (d DeltaRow) Diff(r DeltaRow, ageCol int) bool { if len(d) != len(r) { return true } if ageCol < 0 || ageCol >= len(d) { return !reflect.DeepEqual(d, r) } if !reflect.DeepEqual(d[:ageCol], r[:ageCol]) { return true } if ageCol+1 >= len(d) { return false } return !reflect.DeepEqual(d[ageCol+1:], r[ageCol+1:]) } // Customize returns a subset of deltas. func (d DeltaRow) Customize(cols []int, out DeltaRow) { if d.IsBlank() { return } for i, c := range cols { if c < 0 { continue } if c < len(d) && i < len(out) { out[i] = d[c] } } } // IsBlank asserts a row has no values in it. func (d DeltaRow) IsBlank() bool { if len(d) == 0 { return true } for _, v := range d { if v != "" { return false } } return true } // Clone returns a delta copy. func (d DeltaRow) Clone() DeltaRow { res := make(DeltaRow, len(d)) copy(res, d) return res }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/table_data_test.go
internal/model1/table_data_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1 import ( "log/slog" "testing" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/config" "github.com/stretchr/testify/assert" "k8s.io/apimachinery/pkg/util/sets" ) func init() { slog.SetDefault(slog.New(slog.DiscardHandler)) } func TestTableDataComputeSortCol(t *testing.T) { uu := map[string]struct { t1 *TableData vs config.ViewSetting sc SortColumn wide, manual bool e SortColumn }{ "same": { t1: NewTableDataWithRows( client.NewGVR("test"), Header{ HeaderColumn{Name: "A"}, HeaderColumn{Name: "B"}, HeaderColumn{Name: "C"}, }, NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), ), vs: config.ViewSetting{Columns: []string{"A", "B", "C"}, SortColumn: "A:asc"}, e: SortColumn{Name: "A", ASC: true}, }, "wide-col": { t1: NewTableDataWithRows( client.NewGVR("test"), Header{ HeaderColumn{Name: "A"}, HeaderColumn{Name: "B", Attrs: Attrs{Wide: true}}, HeaderColumn{Name: "C"}, }, NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), ), vs: config.ViewSetting{Columns: []string{"A", "B", "C"}, SortColumn: "B:desc"}, e: SortColumn{Name: "B"}, }, "wide": { t1: NewTableDataWithRows( client.NewGVR("test"), Header{ HeaderColumn{Name: "A"}, HeaderColumn{Name: "B", Attrs: Attrs{Wide: true}}, HeaderColumn{Name: "C"}, }, NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), ), wide: true, vs: config.ViewSetting{Columns: []string{"A", "C"}, SortColumn: ""}, e: SortColumn{Name: ""}, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { sc := u.t1.ComputeSortCol(&u.vs, u.sc, u.manual) assert.Equal(t, u.e, sc) }) } } func TestTableDataDiff(t *testing.T) { uu := map[string]struct { t1, t2 *TableData e bool }{ "empty": { t1: NewTableDataWithRows( client.NewGVR("test"), Header{ HeaderColumn{Name: "A"}, HeaderColumn{Name: "B"}, HeaderColumn{Name: "C"}, }, NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), ), e: true, }, "same": { t1: NewTableDataWithRows( client.NewGVR("test"), Header{ HeaderColumn{Name: "A"}, HeaderColumn{Name: "B"}, HeaderColumn{Name: "C"}, }, NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), ), t2: NewTableDataWithRows( client.NewGVR("test"), Header{ HeaderColumn{Name: "A"}, HeaderColumn{Name: "B"}, HeaderColumn{Name: "C"}, }, NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), ), }, "ns-diff": { t1: NewTableDataFull( client.NewGVR("test"), "ns1", Header{ HeaderColumn{Name: "A"}, HeaderColumn{Name: "B"}, HeaderColumn{Name: "C"}, }, NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), ), t2: NewTableDataFull( client.NewGVR("test"), "ns-2", Header{ HeaderColumn{Name: "A"}, HeaderColumn{Name: "B"}, HeaderColumn{Name: "C"}, }, NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), ), e: true, }, "header-diff": { t1: NewTableDataWithRows( client.NewGVR("test"), Header{ HeaderColumn{Name: "A"}, HeaderColumn{Name: "D"}, HeaderColumn{Name: "C"}, }, NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), ), t2: NewTableDataWithRows( client.NewGVR("test"), Header{ HeaderColumn{Name: "A"}, HeaderColumn{Name: "B"}, HeaderColumn{Name: "C"}, }, NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), ), e: true, }, "row-diff": { t1: NewTableDataWithRows( client.NewGVR("test"), Header{ HeaderColumn{Name: "A"}, HeaderColumn{Name: "B"}, HeaderColumn{Name: "C"}, }, NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), ), t2: NewTableDataWithRows( client.NewGVR("test"), Header{ HeaderColumn{Name: "A"}, HeaderColumn{Name: "B"}, HeaderColumn{Name: "C"}, }, NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"100", "2", "3"}}}, ), ), e: true, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, u.t1.Diff(u.t2)) }) } } func TestTableDataUpdate(t *testing.T) { uu := map[string]struct { re, e *RowEvents rr Rows }{ "no-change": { re: NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), rr: Rows{ Row{ID: "A", Fields: Fields{"1", "2", "3"}}, Row{ID: "B", Fields: Fields{"0", "2", "3"}}, Row{ID: "C", Fields: Fields{"10", "2", "3"}}, }, e: NewRowEventsWithEvts( RowEvent{Kind: EventUnchanged, Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Kind: EventUnchanged, Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Kind: EventUnchanged, Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), }, "add": { re: NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), rr: Rows{ Row{ID: "A", Fields: Fields{"1", "2", "3"}}, Row{ID: "B", Fields: Fields{"0", "2", "3"}}, Row{ID: "C", Fields: Fields{"10", "2", "3"}}, Row{ID: "D", Fields: Fields{"10", "2", "3"}}, }, e: NewRowEventsWithEvts( RowEvent{Kind: EventUnchanged, Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Kind: EventUnchanged, Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Kind: EventUnchanged, Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, RowEvent{Kind: EventAdd, Row: Row{ID: "D", Fields: Fields{"10", "2", "3"}}}, ), }, "delete": { re: NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), rr: Rows{ Row{ID: "A", Fields: Fields{"1", "2", "3"}}, Row{ID: "C", Fields: Fields{"10", "2", "3"}}, }, e: NewRowEventsWithEvts( RowEvent{Kind: EventUnchanged, Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Kind: EventUnchanged, Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), }, "update": { re: NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), rr: Rows{ Row{ID: "A", Fields: Fields{"10", "2", "3"}}, Row{ID: "B", Fields: Fields{"0", "2", "3"}}, Row{ID: "C", Fields: Fields{"10", "2", "3"}}, }, e: NewRowEventsWithEvts( RowEvent{ Kind: EventUpdate, Row: Row{ID: "A", Fields: Fields{"10", "2", "3"}}, Deltas: DeltaRow{"1", "", ""}, }, RowEvent{Kind: EventUnchanged, Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Kind: EventUnchanged, Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), }, } var table TableData for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { table.SetRowEvents(u.re) table.Update(u.rr) assert.Equal(t, u.e, table.GetRowEvents()) }) } } func TestTableDataDelete(t *testing.T) { uu := map[string]struct { re, e *RowEvents kk sets.Set[string] }{ "ordered": { re: NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), kk: sets.New[string]("A", "C"), e: NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), }, "unordered": { re: NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "B", Fields: Fields{"0", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, RowEvent{Row: Row{ID: "D", Fields: Fields{"10", "2", "3"}}}, ), kk: sets.New[string]("C", "A"), e: NewRowEventsWithEvts( RowEvent{Row: Row{ID: "A", Fields: Fields{"1", "2", "3"}}}, RowEvent{Row: Row{ID: "C", Fields: Fields{"10", "2", "3"}}}, ), }, } var table TableData for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { table.SetRowEvents(u.re) table.Delete(u.kk) assert.Equal(t, u.e, table.GetRowEvents()) }) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/color_test.go
internal/model1/color_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/derailed/tcell/v2" "github.com/stretchr/testify/assert" ) func TestDefaultColorer(t *testing.T) { uu := map[string]struct { re model1.RowEvent e tcell.Color }{ "add": { model1.RowEvent{ Kind: model1.EventAdd, }, model1.AddColor, }, "update": { model1.RowEvent{ Kind: model1.EventUpdate, }, model1.ModColor, }, "delete": { model1.RowEvent{ Kind: model1.EventDelete, }, model1.KillColor, }, "no-change": { model1.RowEvent{ Kind: model1.EventUnchanged, }, model1.StdColor, }, "invalid": { model1.RowEvent{ Kind: model1.EventUnchanged, Row: model1.Row{ Fields: model1.Fields{"", "", "blah"}, }, }, model1.ErrColor, }, } h := model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B"}, model1.HeaderColumn{Name: "VALID"}, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, model1.DefaultColorer("", h, &u.re)) }) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/delta_test.go
internal/model1/delta_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/stretchr/testify/assert" ) func TestDeltaLabelize(t *testing.T) { uu := map[string]struct { o model1.Row n model1.Row e model1.DeltaRow }{ "same": { o: model1.Row{ Fields: model1.Fields{"a", "b", "blee=fred,doh=zorg"}, }, n: model1.Row{ Fields: model1.Fields{"a", "b", "blee=fred1,doh=zorg"}, }, e: model1.DeltaRow{"", "", "fred", "zorg"}, }, } hh := model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B"}, model1.HeaderColumn{Name: "C"}, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { d := model1.NewDeltaRow(u.o, u.n, hh) d = d.Labelize([]int{0, 1}, 2) assert.Equal(t, u.e, d) }) } } func TestDeltaCustomize(t *testing.T) { uu := map[string]struct { r1, r2 model1.Row cols []int e model1.DeltaRow }{ "same": { r1: model1.Row{ Fields: model1.Fields{"a", "b", "c"}, }, r2: model1.Row{ Fields: model1.Fields{"a", "b", "c"}, }, cols: []int{0, 1, 2}, e: model1.DeltaRow{"", "", ""}, }, "empty": { r1: model1.Row{ Fields: model1.Fields{"a", "b", "c"}, }, r2: model1.Row{ Fields: model1.Fields{"a", "b", "c"}, }, e: model1.DeltaRow{}, }, "diff-full": { r1: model1.Row{ Fields: model1.Fields{"a", "b", "c"}, }, r2: model1.Row{ Fields: model1.Fields{"a1", "b1", "c1"}, }, cols: []int{0, 1, 2}, e: model1.DeltaRow{"a", "b", "c"}, }, "diff-reverse": { r1: model1.Row{ Fields: model1.Fields{"a", "b", "c"}, }, r2: model1.Row{ Fields: model1.Fields{"a1", "b1", "c1"}, }, cols: []int{2, 1, 0}, e: model1.DeltaRow{"c", "b", "a"}, }, "diff-skip": { r1: model1.Row{ Fields: model1.Fields{"a", "b", "c"}, }, r2: model1.Row{ Fields: model1.Fields{"a1", "b1", "c1"}, }, cols: []int{2, 0}, e: model1.DeltaRow{"c", "a"}, }, "diff-missing": { r1: model1.Row{ Fields: model1.Fields{"a", "b", "c"}, }, r2: model1.Row{ Fields: model1.Fields{"a1", "b1", "c1"}, }, cols: []int{2, 10, 0}, e: model1.DeltaRow{"c", "", "a"}, }, "diff-negative": { r1: model1.Row{ Fields: model1.Fields{"a", "b", "c"}, }, r2: model1.Row{ Fields: model1.Fields{"a1", "b1", "c1"}, }, cols: []int{2, -1, 0}, e: model1.DeltaRow{"c", "", "a"}, }, } hh := model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B"}, model1.HeaderColumn{Name: "C"}, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { d := model1.NewDeltaRow(u.r1, u.r2, hh) out := make(model1.DeltaRow, len(u.cols)) d.Customize(u.cols, out) assert.Equal(t, u.e, out) }) } } func TestDeltaNew(t *testing.T) { uu := map[string]struct { o model1.Row n model1.Row blank bool e model1.DeltaRow }{ "same": { o: model1.Row{ Fields: model1.Fields{"a", "b", "c"}, }, n: model1.Row{ Fields: model1.Fields{"a", "b", "c"}, }, blank: true, e: model1.DeltaRow{"", "", ""}, }, "diff": { o: model1.Row{ Fields: model1.Fields{"a1", "b", "c"}, }, n: model1.Row{ Fields: model1.Fields{"a", "b", "c"}, }, e: model1.DeltaRow{"a1", "", ""}, }, "diff2": { o: model1.Row{ Fields: model1.Fields{"a", "b", "c"}, }, n: model1.Row{ Fields: model1.Fields{"a", "b1", "c"}, }, e: model1.DeltaRow{"", "b", ""}, }, "diffLast": { o: model1.Row{ Fields: model1.Fields{"a", "b", "c"}, }, n: model1.Row{ Fields: model1.Fields{"a", "b", "c1"}, }, e: model1.DeltaRow{"", "", "c"}, }, } hh := model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B"}, model1.HeaderColumn{Name: "C"}, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { d := model1.NewDeltaRow(u.o, u.n, hh) assert.Equal(t, u.e, d) assert.Equal(t, u.blank, d.IsBlank()) }) } } func TestDeltaBlank(t *testing.T) { uu := map[string]struct { r model1.DeltaRow e bool }{ "empty": { r: model1.DeltaRow{}, e: true, }, "blank": { r: model1.DeltaRow{"", "", ""}, e: true, }, "notblank": { r: model1.DeltaRow{"", "", "z"}, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, u.r.IsBlank()) }) } } func TestDeltaDiff(t *testing.T) { uu := map[string]struct { d1, d2 model1.DeltaRow ageCol int e bool }{ "empty": { d1: model1.DeltaRow{"f1", "f2", "f3"}, ageCol: 2, e: true, }, "same": { d1: model1.DeltaRow{"f1", "f2", "f3"}, d2: model1.DeltaRow{"f1", "f2", "f3"}, ageCol: -1, }, "diff": { d1: model1.DeltaRow{"f1", "f2", "f3"}, d2: model1.DeltaRow{"f1", "f2", "f13"}, ageCol: -1, e: true, }, "diff-age-first": { d1: model1.DeltaRow{"f1", "f2", "f3"}, d2: model1.DeltaRow{"f1", "f2", "f13"}, ageCol: 0, e: true, }, "diff-age-last": { d1: model1.DeltaRow{"f1", "f2", "f3"}, d2: model1.DeltaRow{"f1", "f2", "f13"}, ageCol: 2, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, u.d1.Diff(u.d2, u.ageCol)) }) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/helpers_test.go
internal/model1/helpers_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1 import ( "math" "testing" "github.com/stretchr/testify/assert" ) func TestSortLabels(t *testing.T) { uu := map[string]struct { labels string e [][]string }{ "simple": { labels: "a=b,c=d", e: [][]string{ {"a", "c"}, {"b", "d"}, }, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { hh, vv := sortLabels(labelize(u.labels)) assert.Equal(t, u.e[0], hh) assert.Equal(t, u.e[1], vv) }) } } func TestLabelize(t *testing.T) { uu := map[string]struct { labels string e map[string]string }{ "simple": { labels: "a=b,c=d", e: map[string]string{"a": "b", "c": "d"}, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, labelize(u.labels)) }) } } func TestIsValid(t *testing.T) { uu := map[string]struct { ns string h Header r Row e bool }{ "empty": { ns: "blee", h: Header{}, r: Row{}, e: true, }, "valid": { ns: "blee", h: Header{HeaderColumn{Name: "VALID"}}, r: Row{Fields: Fields{"true"}}, e: true, }, "invalid": { ns: "blee", h: Header{HeaderColumn{Name: "VALID"}}, r: Row{Fields: Fields{"false"}}, e: false, }, "valid_capital_case": { ns: "blee", h: Header{HeaderColumn{Name: "VALID"}}, r: Row{Fields: Fields{"True"}}, e: true, }, "valid_all_caps": { ns: "blee", h: Header{HeaderColumn{Name: "VALID"}}, r: Row{Fields: Fields{"TRUE"}}, e: true, }, } for k, u := range uu { t.Run(k, func(t *testing.T) { valid := IsValid(u.ns, u.h, u.r) assert.Equal(t, u.e, valid) }) } } func TestDurationToSecond(t *testing.T) { uu := map[string]struct { s string e int64 }{ "seconds": {s: "22s", e: 22}, "minutes": {s: "22m", e: 1320}, "hours": {s: "12h", e: 43200}, "days": {s: "3d", e: 259200}, "day_hour": {s: "3d9h", e: 291600}, "day_hour_minute": {s: "2d22h3m", e: 252180}, "day_hour_minute_seconds": {s: "2d22h3m50s", e: 252230}, "year": {s: "3y", e: 94608000}, "year_day": {s: "1y2d", e: 31708800}, "n/a": {s: NAValue, e: math.MaxInt64}, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, durationToSeconds(u.s)) }) } } func BenchmarkDurationToSecond(b *testing.B) { t := "2d22h3m50s" b.ReportAllocs() b.ResetTimer() for range b.N { durationToSeconds(t) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/test_helper_test.go
internal/model1/test_helper_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1_test import ( "fmt" "time" ) func testTime() time.Time { t, err := time.Parse(time.RFC3339, "2018-12-14T10:36:43.326972-07:00") if err != nil { fmt.Println("TestTime Failed", err) } return t }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/row_event_test.go
internal/model1/row_event_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1_test import ( "testing" "time" "github.com/derailed/k9s/internal/model1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestRowEventCustomize(t *testing.T) { uu := map[string]struct { re1, e model1.RowEvent cols []int }{ "empty": { re1: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, }, e: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{}}, }, }, "full": { re1: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, }, e: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, }, cols: []int{0, 1, 2}, }, "deltas": { re1: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, Deltas: model1.DeltaRow{"a", "b", "c"}, }, e: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, Deltas: model1.DeltaRow{"a", "b", "c"}, }, cols: []int{0, 1, 2}, }, "deltas-skip": { re1: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, Deltas: model1.DeltaRow{"a", "b", "c"}, }, e: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"3", "1"}}, Deltas: model1.DeltaRow{"c", "a"}, }, cols: []int{2, 0}, }, "reverse": { re1: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, }, e: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"3", "2", "1"}}, }, cols: []int{2, 1, 0}, }, "skip": { re1: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, }, e: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"3", "1"}}, }, cols: []int{2, 0}, }, "miss": { re1: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, }, e: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"3", "", "1"}}, }, cols: []int{2, 10, 0}, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, u.re1.Customize(u.cols)) }) } } func TestRowEventDiff(t *testing.T) { uu := map[string]struct { re1, re2 model1.RowEvent e bool }{ "same": { re1: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, }, re2: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, }, }, "diff-kind": { re1: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, }, re2: model1.RowEvent{ Kind: model1.EventDelete, Row: model1.Row{ID: "B", Fields: model1.Fields{"1", "2", "3"}}, }, e: true, }, "diff-delta": { re1: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, Deltas: model1.DeltaRow{"1", "2", "3"}, }, re2: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, Deltas: model1.DeltaRow{"10", "2", "3"}, }, e: true, }, "diff-id": { re1: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, }, re2: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "B", Fields: model1.Fields{"1", "2", "3"}}, }, e: true, }, "diff-field": { re1: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}, }, re2: model1.RowEvent{ Kind: model1.EventAdd, Row: model1.Row{ID: "A", Fields: model1.Fields{"10", "2", "3"}}, }, e: true, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, u.re1.Diff(u.re2, -1)) }) } } func TestRowEventsDiff(t *testing.T) { uu := map[string]struct { re1, re2 *model1.RowEvents ageCol int e bool }{ "same": { re1: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), re2: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), ageCol: -1, }, "diff-len": { re1: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), re2: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), ageCol: -1, e: true, }, "diff-id": { re1: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), re2: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "D", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), ageCol: -1, e: true, }, "diff-order": { re1: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), re2: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), ageCol: -1, e: true, }, "diff-withAge": { re1: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), re2: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "13"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), ageCol: 1, e: true, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, u.re1.Diff(u.re2, u.ageCol)) }) } } func TestRowEventsUpsert(t *testing.T) { uu := map[string]struct { ee, e *model1.RowEvents re model1.RowEvent }{ "add": { ee: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), re: model1.RowEvent{ Row: model1.Row{ID: "D", Fields: model1.Fields{"f1", "f2", "f3"}}, }, e: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "D", Fields: model1.Fields{"f1", "f2", "f3"}}}, ), }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { u.ee.Upsert(u.re) assert.Equal(t, u.e, u.ee) }) } } func TestRowEventsCustomize(t *testing.T) { uu := map[string]struct { re, e *model1.RowEvents cols []int }{ "same": { re: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), cols: []int{0, 1, 2}, e: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), }, "reverse": { re: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), cols: []int{2, 1, 0}, e: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"3", "2", "1"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"3", "2", "0"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"3", "2", "10"}}}, ), }, "skip": { re: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), cols: []int{1, 0}, e: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"2", "1"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"2", "0"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"2", "10"}}}, ), }, "missing": { re: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), cols: []int{1, 0, 4}, e: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"2", "1", ""}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"2", "0", ""}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"2", "10", ""}}}, ), }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, u.re.Customize(u.cols)) }) } } func TestRowEventsDelete(t *testing.T) { uu := map[string]struct { re, e *model1.RowEvents id string }{ "first": { re: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), id: "A", e: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), }, "middle": { re: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), id: "B", e: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), }, "last": { re: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), id: "C", e: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, ), }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { require.NoError(t, u.re.Delete(u.id)) assert.Equal(t, u.e, u.re) }) } } func TestRowEventsSort(t *testing.T) { uu := map[string]struct { re, e *model1.RowEvents col int duration, num, asc bool capacity bool }{ "age_time": { re: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", testTime().Add(20 * time.Second).String()}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", testTime().Add(10 * time.Second).String()}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", testTime().String()}}}, ), col: 2, asc: true, duration: true, e: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", testTime().String()}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", testTime().Add(10 * time.Second).String()}}}, model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", testTime().Add(20 * time.Second).String()}}}, ), }, "col0": { re: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), col: 0, asc: true, e: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "B", Fields: model1.Fields{"0", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "A", Fields: model1.Fields{"1", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "C", Fields: model1.Fields{"10", "2", "3"}}}, ), }, "id_preserve": { re: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "ns1/B", Fields: model1.Fields{"B", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "ns1/A", Fields: model1.Fields{"A", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "ns1/C", Fields: model1.Fields{"C", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "ns2/B", Fields: model1.Fields{"B", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "ns2/A", Fields: model1.Fields{"A", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "ns2/C", Fields: model1.Fields{"C", "2", "3"}}}, ), col: 1, asc: true, e: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "ns1/A", Fields: model1.Fields{"A", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "ns1/B", Fields: model1.Fields{"B", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "ns1/C", Fields: model1.Fields{"C", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "ns2/A", Fields: model1.Fields{"A", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "ns2/B", Fields: model1.Fields{"B", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "ns2/C", Fields: model1.Fields{"C", "2", "3"}}}, ), }, "capacity": { re: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "ns1/B", Fields: model1.Fields{"B", "2", "3", "1Gi"}}}, model1.RowEvent{Row: model1.Row{ID: "ns1/A", Fields: model1.Fields{"A", "2", "3", "1.1G"}}}, model1.RowEvent{Row: model1.Row{ID: "ns1/C", Fields: model1.Fields{"C", "2", "3", "0.5Ti"}}}, model1.RowEvent{Row: model1.Row{ID: "ns2/B", Fields: model1.Fields{"B", "2", "3", "12e6"}}}, model1.RowEvent{Row: model1.Row{ID: "ns2/A", Fields: model1.Fields{"A", "2", "3", "1234"}}}, model1.RowEvent{Row: model1.Row{ID: "ns2/C", Fields: model1.Fields{"C", "2", "3", "0.1Ei"}}}, ), col: 3, asc: true, capacity: true, e: model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "ns2/A", Fields: model1.Fields{"A", "2", "3", "1234"}}}, model1.RowEvent{Row: model1.Row{ID: "ns2/B", Fields: model1.Fields{"B", "2", "3", "12e6"}}}, model1.RowEvent{Row: model1.Row{ID: "ns1/B", Fields: model1.Fields{"B", "2", "3", "1Gi"}}}, model1.RowEvent{Row: model1.Row{ID: "ns1/A", Fields: model1.Fields{"A", "2", "3", "1.1G"}}}, model1.RowEvent{Row: model1.Row{ID: "ns1/C", Fields: model1.Fields{"C", "2", "3", "0.5Ti"}}}, model1.RowEvent{Row: model1.Row{ID: "ns2/C", Fields: model1.Fields{"C", "2", "3", "0.1Ei"}}}, ), }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { u.re.Sort("", u.col, u.duration, u.num, u.capacity, u.asc) assert.Equal(t, u.e, u.re) }) } } func TestRowEventsClone(t *testing.T) { uu := map[string]struct { r *model1.RowEvents }{ "empty": { r: model1.NewRowEventsWithEvts(), }, "full": { r: makeRowEvents(), }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { c := u.r.Clone() assert.Equal(t, u.r.Len(), c.Len()) if !u.r.Empty() { r, ok := u.r.At(0) assert.True(t, ok) r.Row.Fields[0] = "blee" cr, ok := c.At(0) assert.True(t, ok) assert.Equal(t, "A", cr.Row.Fields[0]) } }) } } // Helpers... func makeRowEvents() *model1.RowEvents { return model1.NewRowEventsWithEvts( model1.RowEvent{Row: model1.Row{ID: "ns1/A", Fields: model1.Fields{"A", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "ns1/B", Fields: model1.Fields{"B", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "ns1/C", Fields: model1.Fields{"C", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "ns2/A", Fields: model1.Fields{"A", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "ns2/B", Fields: model1.Fields{"B", "2", "3"}}}, model1.RowEvent{Row: model1.Row{ID: "ns2/C", Fields: model1.Fields{"C", "2", "3"}}}, ) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/header.go
internal/model1/header.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1 import ( "fmt" "log/slog" "reflect" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/slogs" "k8s.io/apimachinery/pkg/util/sets" ) const ageCol = "AGE" type Attrs struct { Align int Decorator DecoratorFunc Wide bool Show bool MX bool MXC, MXM bool Time bool Capacity bool VS bool Hide bool } func (a Attrs) Merge(b Attrs) Attrs { a.MX = b.MX a.MXC = b.MXC a.MXM = b.MXM a.Decorator = b.Decorator a.VS = b.VS if a.Align == 0 { a.Align = b.Align } if !a.Hide { a.Hide = b.Hide } if !a.Show && !a.Wide { a.Wide = b.Wide } if !a.Time { a.Time = b.Time } if !a.Capacity { a.Capacity = b.Capacity } return a } // HeaderColumn represent a table header. type HeaderColumn struct { Attrs Name string } func (h HeaderColumn) String() string { return fmt.Sprintf("%s [%d::%t::%t::%t]", h.Name, h.Align, h.Wide, h.MX, h.Time) } // Clone copies a header. func (h HeaderColumn) Clone() HeaderColumn { return h } // ---------------------------------------------------------------------------- // Header represents a table header. type Header []HeaderColumn func (h Header) Clear() Header { h = h[:0] return h } // Clone duplicates a header. func (h Header) Clone() Header { he := make(Header, 0, len(h)) for _, h := range h { he = append(he, h.Clone()) } return he } // Labelize returns a new Header based on labels. func (h Header) Labelize(cols []int, labelCol int, rr *RowEvents) Header { header := make(Header, 0, len(cols)+1) for _, c := range cols { header = append(header, h[c]) } cc := rr.ExtractHeaderLabels(labelCol) for _, c := range cc { header = append(header, HeaderColumn{Name: c}) } return header } // MapIndices returns a collection of mapped column indices based of the requested columns. func (h Header) MapIndices(cols []string, wide bool) []int { ii := make([]int, 0, len(cols)) cc := make(map[int]struct{}, len(cols)) for _, col := range cols { idx, ok := h.IndexOf(col, true) if !ok { slog.Warn("Column not found on resource", slogs.ColName, col) } ii, cc[idx] = append(ii, idx), struct{}{} } if !wide { return ii } for i := range h { if _, ok := cc[i]; ok { continue } ii = append(ii, i) } return ii } // Customize builds a header from custom col definitions. func (h Header) Customize(cols []string, wide bool) Header { if len(cols) == 0 { return h } cc := make(Header, 0, len(h)) xx := make(map[int]struct{}, len(h)) for _, c := range cols { idx, ok := h.IndexOf(c, true) if !ok { slog.Warn("Column is not available on this resource", slogs.ColName, c) cc = append(cc, HeaderColumn{Name: c}) continue } xx[idx] = struct{}{} col := h[idx].Clone() col.Wide = false cc = append(cc, col) } if !wide { return cc } for i, c := range h { if _, ok := xx[i]; ok { continue } col := c.Clone() col.Wide = true cc = append(cc, col) } return cc } // Diff returns true if the header changed. func (h Header) Diff(header Header) bool { if len(h) != len(header) { return true } return !reflect.DeepEqual(h, header) } // FilterColIndices return viewable col header indices. func (h Header) FilterColIndices(ns string, wide bool) sets.Set[int] { if len(h) == 0 { return nil } nsed := client.IsNamespaced(ns) cc := sets.New[int]() for i, c := range h { if c.Name == "AGE" || !wide && c.Wide || c.Hide || (nsed && c.Name == "NAMESPACE") { continue } cc.Insert(i) } return cc } // ColumnNames return header col names func (h Header) ColumnNames(wide bool) []string { if len(h) == 0 { return nil } cc := make([]string, 0, len(h)) for _, c := range h { if !wide && c.Wide { continue } cc = append(cc, c.Name) } return cc } // HasAge returns true if table has an age column. func (h Header) HasAge() bool { _, ok := h.IndexOf(ageCol, true) return ok } // IsMetricsCol checks if given column index represents metrics. func (h Header) IsMetricsCol(col int) bool { if col < 0 || col >= len(h) { return false } return h[col].MX } // IsTimeCol checks if given column index represents a timestamp. func (h Header) IsTimeCol(col int) bool { if col < 0 || col >= len(h) { return false } return h[col].Time } // IsCapacityCol checks if given column index represents a capacity. func (h Header) IsCapacityCol(col int) bool { if col < 0 || col >= len(h) { return false } return h[col].Capacity } // IndexOf returns the col index or -1 if none. func (h Header) IndexOf(colName string, includeWide bool) (int, bool) { for i, c := range h { if c.Wide && !includeWide { continue } if c.Name == colName { return i, true } } return -1, false } // Dump for debugging. func (h Header) Dump() { slog.Debug("HEADER") for i, c := range h { slog.Debug(fmt.Sprintf("%d %q -- %t", i, c.Name, c.Wide)) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/header_test.go
internal/model1/header_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1_test import ( "testing" "github.com/derailed/k9s/internal/model1" "github.com/stretchr/testify/assert" ) func TestHeaderMapIndices(t *testing.T) { uu := map[string]struct { h1 model1.Header cols []string wide bool e []int }{ "all": { h1: makeHeader(), cols: []string{"A", "B", "C"}, e: []int{0, 1, 2}, }, "reverse": { h1: makeHeader(), cols: []string{"C", "B", "A"}, e: []int{2, 1, 0}, }, "missing": { h1: makeHeader(), cols: []string{"Duh", "B", "A"}, e: []int{-1, 1, 0}, }, "skip": { h1: makeHeader(), cols: []string{"C", "A"}, e: []int{2, 0}, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { ii := u.h1.MapIndices(u.cols, u.wide) assert.Equal(t, u.e, ii) }) } } func TestHeaderIndexOf(t *testing.T) { uu := map[string]struct { h model1.Header name string wide, ok bool e int }{ "shown": { h: makeHeader(), name: "A", e: 0, ok: true, }, "hidden": { h: makeHeader(), name: "B", e: -1, }, "hidden-wide": { h: makeHeader(), name: "B", wide: true, e: 1, ok: true, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { idx, ok := u.h.IndexOf(u.name, u.wide) assert.Equal(t, u.ok, ok) assert.Equal(t, u.e, idx) }) } } func TestHeaderCustomize(t *testing.T) { uu := map[string]struct { h model1.Header cols []string wide bool e model1.Header }{ "default": { h: makeHeader(), e: makeHeader(), }, "default-wide": { h: makeHeader(), wide: true, e: makeHeader(), }, "reverse": { h: model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "C"}, }, cols: []string{"C", "A"}, e: model1.Header{ model1.HeaderColumn{Name: "C"}, model1.HeaderColumn{Name: "A"}, }, }, "reverse-wide": { h: model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "C"}, }, cols: []string{"C", "A"}, wide: true, e: model1.Header{ model1.HeaderColumn{Name: "C"}, model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B", Attrs: model1.Attrs{Wide: true}}, }, }, "toggle-wide": { h: model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "C"}, }, cols: []string{"C", "B"}, wide: true, e: model1.Header{ model1.HeaderColumn{Name: "C"}, model1.HeaderColumn{Name: "B", Attrs: model1.Attrs{Wide: false}}, model1.HeaderColumn{Name: "A", Attrs: model1.Attrs{Wide: true}}, }, }, "missing": { h: model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "C"}, }, cols: []string{"BLEE", "A"}, wide: true, e: model1.Header{ model1.HeaderColumn{Name: "BLEE"}, model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "C", Attrs: model1.Attrs{Wide: true}}, }, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, u.h.Customize(u.cols, u.wide)) }) } } func TestHeaderDiff(t *testing.T) { uu := map[string]struct { h1, h2 model1.Header e bool }{ "same": { h1: makeHeader(), h2: makeHeader(), }, "size": { h1: makeHeader(), h2: makeHeader()[1:], e: true, }, "differ-wide": { h1: model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "C"}, }, h2: model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B"}, model1.HeaderColumn{Name: "C"}, }, e: true, }, "differ-order": { h1: model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "C"}, }, h2: model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "C"}, model1.HeaderColumn{Name: "B", Attrs: model1.Attrs{Wide: true}}, }, e: true, }, "differ-name": { h1: model1.Header{ model1.HeaderColumn{Name: "A"}, }, h2: model1.Header{ model1.HeaderColumn{Name: "B"}, }, e: true, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, u.h1.Diff(u.h2)) }) } } func TestHeaderHasAge(t *testing.T) { uu := map[string]struct { h model1.Header age, e bool }{ "no-age": { h: model1.Header{}, }, "age": { h: model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "AGE", Attrs: model1.Attrs{Time: true}}, }, e: true, age: true, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, u.h.HasAge()) assert.Equal(t, u.e, u.h.IsTimeCol(2)) }) } } func TestHeaderColumns(t *testing.T) { uu := map[string]struct { h model1.Header wide bool e []string }{ "empty": { h: model1.Header{}, }, "regular": { h: makeHeader(), e: []string{"A", "C"}, }, "wide": { h: makeHeader(), e: []string{"A", "B", "C"}, wide: true, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, u.h.ColumnNames(u.wide)) }) } } func TestHeaderClone(t *testing.T) { uu := map[string]struct { h model1.Header }{ "empty": { h: model1.Header{}, }, "full": { h: makeHeader(), }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { c := u.h.Clone() assert.Len(t, u.h, len(c)) if len(u.h) > 0 { u.h[0].Name = "blee" assert.Equal(t, "A", c[0].Name) } }) } } // ---------------------------------------------------------------------------- // Helpers... func makeHeader() model1.Header { return model1.Header{ model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B", Attrs: model1.Attrs{Wide: true}}, model1.HeaderColumn{Name: "C"}, } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/color.go
internal/model1/color.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1 import "github.com/derailed/tcell/v2" var ( // ModColor row modified color. ModColor tcell.Color // AddColor row added color. AddColor tcell.Color // PendingColor row added color. PendingColor tcell.Color // ErrColor row err color. ErrColor tcell.Color // StdColor row default color. StdColor tcell.Color // HighlightColor row highlight color. HighlightColor tcell.Color // KillColor row deleted color. KillColor tcell.Color // CompletedColor row completed color. CompletedColor tcell.Color ) // DefaultColorer set the default table row colors. func DefaultColorer(ns string, h Header, re *RowEvent) tcell.Color { if !IsValid(ns, h, re.Row) { return ErrColor } //nolint:exhaustive switch re.Kind { case EventAdd: return AddColor case EventUpdate: return ModColor case EventDelete: return KillColor default: return StdColor } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/pool.go
internal/model1/pool.go
package model1 import ( "context" "log/slog" "sync" "github.com/derailed/k9s/internal/slogs" ) type jobFn func(ctx context.Context) error type WorkerPool struct { semC chan struct{} errC chan error ctx context.Context cancelFn context.CancelFunc mx sync.RWMutex wg sync.WaitGroup wge sync.WaitGroup errs []error } func NewWorkerPool(ctx context.Context, size int) *WorkerPool { _, cancelFn := context.WithCancel(ctx) p := WorkerPool{ semC: make(chan struct{}, size), errC: make(chan error, 1), cancelFn: cancelFn, ctx: ctx, } p.wge.Add(1) go func(wg *sync.WaitGroup) { defer wg.Done() for err := range p.errC { if err != nil { p.mx.Lock() p.errs = append(p.errs, err) p.mx.Unlock() } } }(&p.wge) return &p } func (p *WorkerPool) Add(job jobFn) { p.semC <- struct{}{} p.wg.Add(1) go func(ctx context.Context, wg *sync.WaitGroup, semC <-chan struct{}, errC chan<- error) { defer func() { <-semC wg.Done() }() if err := job(ctx); err != nil { slog.Error("Worker error", slogs.Error, err) errC <- err } }(p.ctx, &p.wg, p.semC, p.errC) } func (p *WorkerPool) Drain() []error { if p.cancelFn != nil { p.cancelFn() p.cancelFn = nil } p.wg.Wait() close(p.semC) close(p.errC) p.wge.Wait() p.mx.RLock() defer p.mx.RUnlock() return p.errs }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/rows.go
internal/model1/rows.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1 import "sort" // Rows represents a collection of rows. type Rows []Row // Delete removes an element by id. func (rr Rows) Delete(id string) Rows { idx, ok := rr.Find(id) if !ok { return rr } if idx == 0 { return rr[1:] } if idx+1 == len(rr) { return rr[:len(rr)-1] } return append(rr[:idx], rr[idx+1:]...) } // Upsert adds a new item. func (rr Rows) Upsert(r Row) Rows { idx, ok := rr.Find(r.ID) if !ok { return append(rr, r) } rr[idx] = r return rr } // Find locates a row by id. Returns false is not found. func (rr Rows) Find(id string) (int, bool) { for i, r := range rr { if r.ID == id { return i, true } } return 0, false } // Sort rows based on column index and order. func (rr Rows) Sort(col int, asc, isNum, isDur, isCapacity bool) { t := RowSorter{ Rows: rr, Index: col, IsNumber: isNum, IsDuration: isDur, IsCapacity: isCapacity, Asc: asc, } sort.Sort(t) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/table_data.go
internal/model1/table_data.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1 import ( "context" "errors" "fmt" "log/slog" "regexp" "strings" "sync" "github.com/derailed/k9s/internal" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/config" "github.com/derailed/k9s/internal/slogs" "github.com/sahilm/fuzzy" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/sets" ) // SortFn represent a function that can sort columnar data. type SortFn func(rows Rows, sortCol SortColumn) // SortColumn represents a sortable column. type SortColumn struct { Name string ASC bool } // IsSet checks if the sort column is set. func (s SortColumn) IsSet() bool { return s.Name != "" } const spacer = " " type FilterOpts struct { Toast bool Filter string Invert bool } // TableData tracks a K8s resource for tabular display. type TableData struct { header Header rowEvents *RowEvents namespace string gvr *client.GVR mx sync.RWMutex } // NewTableData returns a new table. func NewTableData(gvr *client.GVR) *TableData { return &TableData{ gvr: gvr, rowEvents: NewRowEvents(10), } } func NewTableDataFull(gvr *client.GVR, ns string, h Header, re *RowEvents) *TableData { t := NewTableDataWithRows(gvr, h, re) t.namespace = ns return t } func NewTableDataWithRows(gvr *client.GVR, h Header, re *RowEvents) *TableData { t := NewTableData(gvr) t.header, t.rowEvents = h, re return t } func NewTableDataFromTable(td *TableData) *TableData { t := NewTableData(td.gvr) t.header = td.header t.rowEvents = td.rowEvents t.namespace = td.namespace return t } func (t *TableData) AddRow(re RowEvent) { t.rowEvents.Add(re) } func (t *TableData) SetRow(idx int, re RowEvent) { t.rowEvents.Set(idx, re) } func (t *TableData) FindRow(id string) (RowEvent, bool) { return t.rowEvents.Get(id) } func (t *TableData) RowAt(idx int) (RowEvent, bool) { return t.rowEvents.At(idx) } func (t *TableData) RowsRange(f ReRangeFn) { t.rowEvents.Range(f) } func (t *TableData) Sort(sc SortColumn) { col, idx := t.HeadCol(sc.Name, false) if idx < 0 { return } t.rowEvents.Sort( t.GetNamespace(), idx, col.Time, col.MX, col.Capacity, sc.ASC, ) } func (t *TableData) Header() Header { return t.header } // HeaderCount returns the number of header cols. func (t *TableData) HeaderCount() int { t.mx.RLock() defer t.mx.RUnlock() return len(t.header) } func (t *TableData) HeadCol(n string, w bool) (header HeaderColumn, idx int) { idx, ok := t.header.IndexOf(n, w) if !ok { return HeaderColumn{}, -1 } return t.header[idx], idx } func (t *TableData) Filter(f FilterOpts) *TableData { td := NewTableDataFromTable(t) if f.Toast { td.rowEvents = t.filterToast() } if f.Filter == "" || internal.IsLabelSelector(f.Filter) { return td } if f, ok := internal.IsFuzzySelector(f.Filter); ok { td.rowEvents = t.fuzzyFilter(f) return td } rr, err := t.rxFilter(f.Filter, internal.IsInverseSelector(f.Filter)) if err == nil { td.rowEvents = rr } else { slog.Error("RX filter failed", slogs.Error, err) } return td } func (t *TableData) rxFilter(q string, inverse bool) (*RowEvents, error) { if strings.Contains(q, " ") { return t.rowEvents, nil } if inverse { q = q[1:] } rx, err := regexp.Compile(`(?i)(` + q + `)`) if err != nil { return nil, fmt.Errorf("invalid rx filter %q: %w", q, err) } vidx := t.header.FilterColIndices(t.namespace, true) rr := NewRowEvents(t.RowCount() / 2) t.rowEvents.Range(func(_ int, re RowEvent) bool { ff := make([]string, 0, len(re.Row.Fields)) for idx, r := range re.Row.Fields { if !vidx.Has(idx) { continue } ff = append(ff, r) } match := rx.MatchString(strings.Join(ff, spacer)) if (inverse && !match) || (!inverse && match) { rr.Add(re) } return true }) return rr, nil } func (t *TableData) fuzzyFilter(q string) *RowEvents { q = strings.TrimSpace(q) ss := make([]string, 0, t.RowCount()/2) t.rowEvents.Range(func(_ int, re RowEvent) bool { ss = append(ss, re.Row.ID) return true }) mm := fuzzy.Find(q, ss) rr := NewRowEvents(t.RowCount() / 2) for _, m := range mm { if re, ok := t.rowEvents.At(m.Index); !ok { slog.Error("Unable to find event for index in fuzzfilter", slogs.Index, m.Index) } else { rr.Add(re) } } return rr } func (t *TableData) filterToast() *RowEvents { rr := NewRowEvents(10) idx, ok := t.header.IndexOf("VALID", true) if !ok { return rr } t.rowEvents.Range(func(_ int, re RowEvent) bool { if re.Row.Fields[idx] != "" { rr.Add(re) } return true }) return rr } func (t *TableData) GetNamespace() string { t.mx.RLock() defer t.mx.RUnlock() return t.namespace } func (t *TableData) Reset(ns string) { t.mx.Lock() t.namespace = ns t.mx.Unlock() t.Clear() } func (t *TableData) Render(_ context.Context, r Renderer, oo []runtime.Object) error { var rows Rows if len(oo) > 0 { if r.IsGeneric() { table, ok := oo[0].(*metav1.Table) if !ok { return fmt.Errorf("expecting a meta table but got %T", oo[0]) } rows = make(Rows, len(table.Rows)) if err := GenericHydrate(t.namespace, table, rows, r); err != nil { return err } } else { rows = make(Rows, len(oo)) if err := Hydrate(t.namespace, oo, rows, r); err != nil { return err } } } t.Update(rows) t.SetHeader(t.namespace, r.Header(t.namespace)) if t.HeaderCount() == 0 { return fmt.Errorf("no data found for resource %s", t.gvr) } return nil } // Empty checks if there are no entries. func (t *TableData) Empty() bool { t.mx.RLock() defer t.mx.RUnlock() return t.rowEvents.Empty() } func (t *TableData) SetRowEvents(re *RowEvents) { t.rowEvents = re } func (t *TableData) GetRowEvents() *RowEvents { return t.rowEvents } // RowCount returns the number of rows. func (t *TableData) RowCount() int { t.mx.RLock() defer t.mx.RUnlock() return t.rowEvents.Len() } // IndexOfHeader return the index of the header. func (t *TableData) IndexOfHeader(h string) (int, bool) { return t.header.IndexOf(h, false) } // Labelize prints out specific label columns. func (t *TableData) Labelize(labels []string) *TableData { idx, ok := t.header.IndexOf("LABELS", true) if !ok { return t } cols := []int{0, 1} if client.IsNamespaced(t.namespace) { cols = cols[1:] } data := TableData{ namespace: t.namespace, header: t.header.Labelize(cols, idx, t.rowEvents), } data.rowEvents = t.rowEvents.Labelize(cols, idx, labels) return &data } // ComputeSortCol computes the best matched sort column. func (t *TableData) ComputeSortCol(vs *config.ViewSetting, sc SortColumn, manual bool) SortColumn { if vs.IsBlank() { if sc.Name != "" { return sc } if psc, err := t.sortCol(vs); err == nil { return psc } return sc } if manual && sc.IsSet() { return sc } if s, asc, err := vs.SortCol(); err == nil { return SortColumn{Name: s, ASC: asc} } return sc } func (t *TableData) sortCol(vs *config.ViewSetting) (SortColumn, error) { var psc SortColumn if t.HeaderCount() == 0 { return psc, errors.New("no header found") } name, order, _ := vs.SortCol() if _, ok := t.header.IndexOf(name, false); ok { psc.Name, psc.ASC = name, order return psc, nil } if client.IsAllNamespaces(t.GetNamespace()) { if _, ok := t.header.IndexOf("NAMESPACE", false); ok { psc.Name = "NAMESPACE" } else if _, ok := t.header.IndexOf("NAME", false); ok { psc.Name = "NAME" } } else { if _, ok := t.header.IndexOf("NAME", false); ok { psc.Name = "NAME" } else { psc.Name = t.header[0].Name } } psc.ASC = true return psc, nil } // Clear clears out the entire table. func (t *TableData) Clear() { t.mx.Lock() defer t.mx.Unlock() t.header = t.header.Clear() t.rowEvents.Clear() } // Clone returns a copy of the table. func (t *TableData) Clone() *TableData { t.mx.RLock() defer t.mx.RUnlock() return &TableData{ header: t.header.Clone(), rowEvents: t.rowEvents.Clone(), namespace: t.namespace, gvr: t.gvr, } } func (t *TableData) ColumnNames(w bool) []string { t.mx.RLock() defer t.mx.RUnlock() return t.header.ColumnNames(w) } // GetHeader returns table header. func (t *TableData) GetHeader() Header { t.mx.RLock() defer t.mx.RUnlock() return t.header } // SetHeader sets table header. func (t *TableData) SetHeader(ns string, h Header) { t.mx.Lock() defer t.mx.Unlock() t.namespace, t.header = ns, h } // Update computes row deltas and update the table data. func (t *TableData) Update(rows Rows) { empty := t.Empty() kk := sets.New[string]() var blankDelta DeltaRow t.mx.Lock() for _, row := range rows { kk.Insert(row.ID) if empty { t.rowEvents.Add(NewRowEvent(EventAdd, row)) continue } if index, ok := t.rowEvents.FindIndex(row.ID); ok { ev, ok := t.rowEvents.At(index) if !ok { continue } delta := NewDeltaRow(ev.Row, row, t.header) if delta.IsBlank() { ev.Kind, ev.Deltas, ev.Row = EventUnchanged, blankDelta, row t.rowEvents.Set(index, ev) } else { t.rowEvents.Set(index, NewRowEventWithDeltas(row, delta)) } continue } t.rowEvents.Add(NewRowEvent(EventAdd, row)) } t.mx.Unlock() if !empty { t.Delete(kk) } } // Delete removes items in cache that are no longer valid. func (t *TableData) Delete(newKeys sets.Set[string]) { t.mx.Lock() defer t.mx.Unlock() victims := sets.New[string]() t.rowEvents.Range(func(_ int, e RowEvent) bool { if newKeys.Has(e.Row.ID) { delete(newKeys, e.Row.ID) } else { victims.Insert(e.Row.ID) } return true }) for _, id := range victims.UnsortedList() { if err := t.rowEvents.Delete(id); err != nil { slog.Error("Table delete failed", slogs.Error, err, slogs.Message, id, ) } } } // Diff checks if two tables are equal. func (t *TableData) Diff(t2 *TableData) bool { if t2 == nil || t.namespace != t2.namespace || t.header.Diff(t2.header) { return true } idx, ok := t.header.IndexOf("AGE", true) if !ok { idx = -1 } return t.rowEvents.Diff(t2.rowEvents, idx) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/helpers.go
internal/model1/helpers.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1 import ( "context" "fmt" "log/slog" "math" "sort" "strings" "github.com/fvbommel/sortorder" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" ) const poolSize = 10 func Hydrate(ns string, oo []runtime.Object, rr Rows, re Renderer) error { pool := NewWorkerPool(context.Background(), poolSize) for i, o := range oo { pool.Add(func(ctx context.Context) error { select { case <-ctx.Done(): slog.Debug("Worker canceled") return nil default: return re.Render(o, ns, &rr[i]) } }) } errs := pool.Drain() if len(errs) > 0 { return errs[0] } return nil } func GenericHydrate(ns string, table *metav1.Table, rr Rows, re Renderer) error { gr, ok := re.(Generic) if !ok { return fmt.Errorf("expecting generic renderer but got %T", re) } gr.SetTable(ns, table) pool := NewWorkerPool(context.Background(), poolSize) for i, row := range table.Rows { pool.Add(func(ctx context.Context) error { select { case <-ctx.Done(): slog.Debug("Worker canceled") return nil default: return gr.Render(row, ns, &rr[i]) } }) } errs := pool.Drain() if len(errs) > 0 { return errs[0] } return nil } // IsValid returns true if resource is valid, false otherwise. func IsValid(_ string, h Header, r Row) bool { if len(r.Fields) == 0 { return true } idx, ok := h.IndexOf("VALID", true) if !ok || idx >= len(r.Fields) { return true } return strings.TrimSpace(r.Fields[idx]) == "" || strings.ToLower(strings.TrimSpace(r.Fields[idx])) == "true" } func sortLabels(m map[string]string) (keys, vals []string) { for k := range m { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { vals = append(vals, m[k]) } return } // Converts labels string to map. func labelize(labels string) map[string]string { ll := strings.Split(labels, ",") data := make(map[string]string, len(ll)) for _, l := range ll { tokens := strings.Split(l, "=") if len(tokens) == 2 { data[tokens[0]] = tokens[1] } } return data } func durationToSeconds(duration string) int64 { if duration == "" { return 0 } if duration == NAValue { return math.MaxInt64 } num := make([]rune, 0, 5) var n, m int64 for _, r := range duration { switch r { case 'y': m = 365 * 24 * 60 * 60 case 'd': m = 24 * 60 * 60 case 'h': m = 60 * 60 case 'm': m = 60 case 's': m = 1 default: num = append(num, r) continue } n, num = n+runesToNum(num)*m, num[:0] } return n } func runesToNum(rr []rune) int64 { var r int64 var m int64 = 1 for i := len(rr) - 1; i >= 0; i-- { v := int64(rr[i] - '0') r += v * m m *= 10 } return r } func capacityToNumber(capacity string) int64 { quantity := resource.MustParse(capacity) return quantity.Value() } // Less return true if c1 <= c2. func Less(isNumber, isDuration, isCapacity bool, id1, id2, v1, v2 string) bool { var less bool switch { case isNumber: less = lessNumber(v1, v2) case isDuration: less = lessDuration(v1, v2) case isCapacity: less = lessCapacity(v1, v2) default: less = sortorder.NaturalLess(v1, v2) } if v1 == v2 { return sortorder.NaturalLess(id1, id2) } return less } func lessDuration(s1, s2 string) bool { d1, d2 := durationToSeconds(s1), durationToSeconds(s2) return d1 <= d2 } func lessCapacity(s1, s2 string) bool { c1, c2 := capacityToNumber(s1), capacityToNumber(s2) return c1 <= c2 } func lessNumber(s1, s2 string) bool { v1, v2 := strings.ReplaceAll(s1, ",", ""), strings.ReplaceAll(s2, ",", "") return sortorder.NaturalLess(v1, v2) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/fields.go
internal/model1/fields.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1 import "reflect" // Fields represents a collection of row fields. type Fields []string // Customize returns a subset of fields. func (f Fields) Customize(cols []int, out Fields) { for i, c := range cols { if c < 0 { out[i] = NAValue continue } if c < len(f) { out[i] = f[c] } } } // Diff returns true if fields differ or false otherwise. func (f Fields) Diff(ff Fields, ageCol int) bool { if ageCol < 0 { return !reflect.DeepEqual(f[:len(f)-1], ff[:len(ff)-1]) } if !reflect.DeepEqual(f[:ageCol], ff[:ageCol]) { return true } return !reflect.DeepEqual(f[ageCol+1:], ff[ageCol+1:]) } // Clone returns a copy of the fields. func (f Fields) Clone() Fields { cp := make(Fields, len(f)) copy(cp, f) return cp }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/model1/row.go
internal/model1/row.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package model1 // Row represents a collection of columns. type Row struct { ID string Fields Fields } // NewRow returns a new row with initialized fields. func NewRow(size int) Row { return Row{Fields: make([]string, size)} } // Labelize returns a new row based on labels. func (r Row) Labelize(cols []int, labelCol int, labels []string) Row { out := NewRow(len(cols) + len(labels)) for _, col := range cols { out.Fields = append(out.Fields, r.Fields[col]) } m := labelize(r.Fields[labelCol]) for _, label := range labels { out.Fields = append(out.Fields, m[label]) } return out } // Customize returns a row subset based on given col indices. func (r Row) Customize(cols []int) Row { out := NewRow(len(cols)) r.Fields.Customize(cols, out.Fields) out.ID = r.ID return out } // Diff returns true if row differ or false otherwise. func (r Row) Diff(ro Row, ageCol int) bool { if r.ID != ro.ID { return true } return r.Fields.Diff(ro.Fields, ageCol) } // Clone copies a row. func (r Row) Clone() Row { return Row{ ID: r.ID, Fields: r.Fields.Clone(), } } // Len returns the length of the row. func (r Row) Len() int { return len(r.Fields) } // ---------------------------------------------------------------------------- // RowSorter sorts rows. type RowSorter struct { Rows Rows Index int IsNumber bool IsDuration bool IsCapacity bool Asc bool } func (s RowSorter) Len() int { return len(s.Rows) } func (s RowSorter) Swap(i, j int) { s.Rows[i], s.Rows[j] = s.Rows[j], s.Rows[i] } func (s RowSorter) Less(i, j int) bool { v1, v2 := s.Rows[i].Fields[s.Index], s.Rows[j].Fields[s.Index] id1, id2 := s.Rows[i].ID, s.Rows[j].ID less := Less(s.IsNumber, s.IsDuration, s.IsCapacity, id1, id2, v1, v2) if s.Asc { return less } return !less } // ---------------------------------------------------------------------------- // Helpers...
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/files_test.go
internal/config/files_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package config_test import ( "os" "path/filepath" "testing" "github.com/adrg/xdg" "github.com/derailed/k9s/internal/config" "github.com/derailed/k9s/internal/config/data" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestInitLogLoc(t *testing.T) { tmp, err := config.UserTmpDir() require.NoError(t, err) uu := map[string]struct { dir string e string }{ "log-env": { dir: "/tmp/test/k9s/logs", e: "/tmp/test/k9s/logs/k9s.log", }, "xdg-env": { dir: "/tmp/test/xdg-state", e: "/tmp/test/xdg-state/k9s/k9s.log", }, "cfg-env": { dir: "/tmp/test/k9s-test", e: filepath.Join(tmp, "k9s.log"), }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { require.NoError(t, os.Unsetenv(config.K9sEnvLogsDir)) require.NoError(t, os.Unsetenv("XDG_STATE_HOME")) require.NoError(t, os.Unsetenv(config.K9sEnvConfigDir)) switch k { case "log-env": require.NoError(t, os.Setenv(config.K9sEnvLogsDir, u.dir)) case "xdg-env": require.NoError(t, os.Setenv("XDG_STATE_HOME", u.dir)) xdg.Reload() case "cfg-env": require.NoError(t, os.Setenv(config.K9sEnvConfigDir, u.dir)) } err := config.InitLogLoc() require.NoError(t, err) assert.Equal(t, u.e, config.AppLogFile) require.NoError(t, os.RemoveAll(config.AppLogFile)) }) } } func TestEnsureBenchmarkCfg(t *testing.T) { require.NoError(t, os.Setenv(config.K9sEnvConfigDir, "/tmp/test-config")) require.NoError(t, config.InitLocs()) defer require.NoError(t, os.RemoveAll("/tmp/test-config")) require.NoError(t, data.EnsureFullPath("/tmp/test-config/clusters/cl-1/ct-2", data.DefaultDirMod)) require.NoError(t, os.WriteFile("/tmp/test-config/clusters/cl-1/ct-2/benchmarks.yaml", []byte{}, data.DefaultFileMod)) uu := map[string]struct { cluster, context string f, e string }{ "not-exist": { cluster: "cl-1", context: "ct-1", f: "/tmp/test-config/clusters/cl-1/ct-1/benchmarks.yaml", e: "benchmarks:\n defaults:\n concurrency: 2\n requests: 200", }, "exist": { cluster: "cl-1", context: "ct-2", f: "/tmp/test-config/clusters/cl-1/ct-2/benchmarks.yaml", }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { f, err := config.EnsureBenchmarksCfgFile(u.cluster, u.context) require.NoError(t, err) assert.Equal(t, u.f, f) bb, err := os.ReadFile(f) require.NoError(t, err) assert.Equal(t, u.e, string(bb)) }) } } func TestSkinFileFromName(t *testing.T) { config.AppSkinsDir = "/tmp/k9s-test/skins" defer require.NoError(t, os.RemoveAll("/tmp/k9s-test/skins")) uu := map[string]struct { n string e string }{ "empty": { e: "/tmp/k9s-test/skins/stock.yaml", }, "happy": { n: "fred-blee", e: "/tmp/k9s-test/skins/fred-blee.yaml", }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, config.SkinFileFromName(u.n)) }) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/views_int_test.go
internal/config/views_int_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package config import ( "testing" "github.com/derailed/k9s/internal/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestCustomView_getVS(t *testing.T) { uu := map[string]struct { cv *CustomView gvr, ns string e *ViewSetting }{ "empty": {}, "miss": { gvr: "zorg", }, "gvr": { gvr: client.PodGVR.String(), e: &ViewSetting{ Columns: []string{"NAMESPACE", "NAME", "AGE", "IP"}, }, }, "gvr+ns": { gvr: client.PodGVR.String(), ns: "default", e: &ViewSetting{ Columns: []string{"NAME", "IP", "AGE"}, }, }, "rx": { gvr: client.PodGVR.String(), ns: "ns-fred", e: &ViewSetting{ Columns: []string{"AGE", "NAME", "IP"}, }, }, "alias": { gvr: "bozo", e: &ViewSetting{ Columns: []string{"DUH", "BLAH", "BLEE"}, }, }, "toast-no-ns": { gvr: client.PodGVR.String(), ns: "zorg", e: &ViewSetting{ Columns: []string{"NAMESPACE", "NAME", "AGE", "IP"}, }, }, "toast-no-res": { gvr: client.SvcGVR.String(), ns: "zorg", }, } v := NewCustomView() require.NoError(t, v.Load("testdata/views/views.yaml")) for k, u := range uu { t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, v.getVS(u.gvr, u.ns)) }) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/flags.go
internal/config/flags.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package config const ( // DefaultRefreshRate represents the refresh interval. DefaultRefreshRate float32 = 2.0 // secs // DefaultLogLevel represents the default log level. DefaultLogLevel = "info" // DefaultCommand represents the default command to run. DefaultCommand = "" ) // Flags represents K9s configuration flags. type Flags struct { RefreshRate *float32 LogLevel *string LogFile *string Headless *bool Logoless *bool Command *string AllNamespaces *bool ReadOnly *bool Write *bool Crumbsless *bool Splashless *bool ScreenDumpDir *string } // NewFlags returns new configuration flags. func NewFlags() *Flags { return &Flags{ RefreshRate: float32Ptr(DefaultRefreshRate), LogLevel: strPtr(DefaultLogLevel), LogFile: strPtr(AppLogFile), Headless: boolPtr(false), Logoless: boolPtr(false), Command: strPtr(DefaultCommand), AllNamespaces: boolPtr(false), ReadOnly: boolPtr(false), Write: boolPtr(false), Crumbsless: boolPtr(false), Splashless: boolPtr(false), ScreenDumpDir: strPtr(AppDumpsDir), } } func boolPtr(b bool) *bool { return &b } func float32Ptr(f float32) *float32 { return &f } func strPtr(s string) *string { return &s }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/hotkey.go
internal/config/hotkey.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package config import ( "errors" "io/fs" "log/slog" "os" "github.com/derailed/k9s/internal/config/data" "github.com/derailed/k9s/internal/config/json" "github.com/derailed/k9s/internal/slogs" "gopkg.in/yaml.v3" ) // HotKeys represents a collection of plugins. type HotKeys struct { HotKey map[string]HotKey `yaml:"hotKeys"` } // HotKey describes a K9s hotkey. type HotKey struct { ShortCut string `yaml:"shortCut"` Override bool `yaml:"override"` Description string `yaml:"description"` Command string `yaml:"command"` KeepHistory bool `yaml:"keepHistory"` } // NewHotKeys returns a new plugin. func NewHotKeys() HotKeys { return HotKeys{ HotKey: make(map[string]HotKey), } } // Load K9s plugins. func (h HotKeys) Load(path string) error { if err := h.LoadHotKeys(AppHotKeysFile); err != nil { return err } if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) { return nil } return h.LoadHotKeys(path) } // LoadHotKeys loads plugins from a given file. func (h HotKeys) LoadHotKeys(path string) error { if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) { return nil } bb, err := os.ReadFile(path) if err != nil { return err } if err := data.JSONValidator.Validate(json.HotkeysSchema, bb); err != nil { slog.Warn("Validation failed. Please update your config and restart.", slogs.Path, path, slogs.Error, err, ) } var hh HotKeys if err := yaml.Unmarshal(bb, &hh); err != nil { return err } for k, v := range hh.HotKey { h.HotKey[k] = v } return nil }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/k9s_int_test.go
internal/config/k9s_int_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package config import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func Test_k9sOverrides(t *testing.T) { var ( trueVal = true cmd = "po" dir = "/tmp/blee" ) uu := map[string]struct { k *K9s rate float32 ro, hl, cl, sl, ll bool }{ "plain": { k: &K9s{ LiveViewAutoRefresh: false, ScreenDumpDir: "", RefreshRate: 10.0, MaxConnRetry: 0, ReadOnly: false, NoExitOnCtrlC: false, UI: UI{}, SkipLatestRevCheck: false, DisablePodCounting: false, }, rate: 10.0, }, "sub-second": { k: &K9s{ LiveViewAutoRefresh: false, ScreenDumpDir: "", RefreshRate: 0.5, MaxConnRetry: 0, ReadOnly: false, NoExitOnCtrlC: false, UI: UI{}, SkipLatestRevCheck: false, DisablePodCounting: false, }, rate: 2.0, // minimum enforced }, "set": { k: &K9s{ LiveViewAutoRefresh: false, ScreenDumpDir: "", RefreshRate: 10.0, MaxConnRetry: 0, ReadOnly: true, NoExitOnCtrlC: false, UI: UI{ Headless: true, Logoless: true, Crumbsless: true, Splashless: true, }, SkipLatestRevCheck: false, DisablePodCounting: false, }, rate: 10.0, ro: true, hl: true, ll: true, cl: true, sl: true, }, "overrides": { k: &K9s{ LiveViewAutoRefresh: false, ScreenDumpDir: "", RefreshRate: 10.0, MaxConnRetry: 0, ReadOnly: false, NoExitOnCtrlC: false, UI: UI{ Headless: false, Logoless: false, Crumbsless: false, manualHeadless: &trueVal, manualLogoless: &trueVal, manualCrumbsless: &trueVal, manualSplashless: &trueVal, }, SkipLatestRevCheck: false, DisablePodCounting: false, manualRefreshRate: 100.0, manualReadOnly: &trueVal, manualCommand: &cmd, manualScreenDumpDir: &dir, }, rate: 100.0, ro: true, hl: true, ll: true, cl: true, sl: true, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.InDelta(t, u.rate, u.k.GetRefreshRate(), 0.001) assert.Equal(t, u.ro, u.k.IsReadOnly()) assert.Equal(t, u.cl, u.k.IsCrumbsless()) assert.Equal(t, u.sl, u.k.IsSplashless()) assert.Equal(t, u.hl, u.k.IsHeadless()) assert.Equal(t, u.ll, u.k.IsLogoless()) }) } } func Test_screenDumpDirOverride(t *testing.T) { uu := map[string]struct { dir string e string }{ "empty": { e: "/tmp/k9s-test/screen-dumps", }, "override": { dir: "/tmp/k9s-test/sd", e: "/tmp/k9s-test/sd", }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { cfg := NewConfig(nil) require.NoError(t, cfg.Load("testdata/configs/k9s.yaml", true)) cfg.K9s.manualScreenDumpDir = &u.dir assert.Equal(t, u.e, cfg.K9s.AppScreenDumpDir()) }) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/refresh_rate_test.go
internal/config/refresh_rate_test.go
package config import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" ) func TestRefreshRateBackwardCompatibility(t *testing.T) { tests := map[string]struct { yamlContent string expected float32 }{ "integer_value": { yamlContent: `refreshRate: 2`, expected: 2.0, }, "float_value": { yamlContent: `refreshRate: 2.5`, expected: 2.5, }, } for name, test := range tests { t.Run(name, func(t *testing.T) { var k K9s err := yaml.Unmarshal([]byte(test.yamlContent), &k) require.NoError(t, err) assert.InDelta(t, test.expected, k.RefreshRate, 0.001) }) } } func TestGetRefreshRateMinimum(t *testing.T) { tests := map[string]struct { refreshRate float32 manualRefreshRate float32 expected float32 }{ "below_minimum": { refreshRate: 0.5, expected: 2.0, }, "at_minimum": { refreshRate: 2.0, expected: 2.0, }, "above_minimum": { refreshRate: 3.5, expected: 3.5, }, "manual_below_minimum": { refreshRate: 3.0, manualRefreshRate: 0.5, expected: 2.0, }, "manual_above_minimum": { refreshRate: 2.0, manualRefreshRate: 4.0, expected: 4.0, }, } for name, test := range tests { t.Run(name, func(t *testing.T) { k := K9s{ RefreshRate: test.refreshRate, manualRefreshRate: test.manualRefreshRate, } assert.InDelta(t, test.expected, k.GetRefreshRate(), 0.001) }) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/alias.go
internal/config/alias.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package config import ( "errors" "io/fs" "log/slog" "os" "strings" "sync" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/config/data" "github.com/derailed/k9s/internal/config/json" "github.com/derailed/k9s/internal/slogs" "github.com/derailed/k9s/internal/view/cmd" "gopkg.in/yaml.v3" "k8s.io/apimachinery/pkg/util/sets" ) type ( // Alias tracks shortname to GVR mappings. Alias map[string]*client.GVR // ShortNames represents a collection of shortnames for aliases. ShortNames map[*client.GVR][]string // Aliases represents a collection of aliases. Aliases struct { Alias Alias `yaml:"aliases"` mx sync.RWMutex } ) // NewAliases return a new alias. func NewAliases() *Aliases { return &Aliases{ Alias: make(Alias, 50), } } func (a *Aliases) AliasesFor(gvr *client.GVR) sets.Set[string] { a.mx.RLock() defer a.mx.RUnlock() ss := sets.New[string]() for alias, aliasGVR := range a.Alias { if aliasGVR == gvr { ss.Insert(alias) } } return ss } // ShortNames return all shortnames. func (a *Aliases) ShortNames() ShortNames { a.mx.RLock() defer a.mx.RUnlock() m := make(ShortNames, len(a.Alias)) for alias, gvr := range a.Alias { if v, ok := m[gvr]; ok { m[gvr] = append(v, alias) } else { m[gvr] = []string{alias} } } return m } // Clear remove all aliases. func (a *Aliases) Clear() { a.mx.Lock() defer a.mx.Unlock() for k := range a.Alias { delete(a.Alias, k) } } func (a *Aliases) Resolve(p *cmd.Interpreter) (*client.GVR, bool) { gvr, ok := a.Get(p.Cmd()) if !ok { return nil, false } if gvr.IsK8sRes() { p.Reset(strings.Replace(p.GetLine(), p.Cmd(), gvr.String(), 1), p.Cmd()) return gvr, true } for gvr.IsAlias() { ap := cmd.NewInterpreter(gvr.String()) gvr, ok = a.Get(ap.Cmd()) if !ok { return gvr, false } ap.Merge(p) p.Reset(strings.Replace(ap.GetLine(), ap.Cmd(), gvr.String(), 1), ap.Cmd()) } return gvr, true } // Get retrieves an alias. func (a *Aliases) Get(alias string) (*client.GVR, bool) { a.mx.RLock() defer a.mx.RUnlock() gvr, ok := a.Alias[alias] return gvr, ok } // Define declares a new alias. func (a *Aliases) Define(gvr *client.GVR, aliases ...string) { a.mx.Lock() defer a.mx.Unlock() for _, alias := range aliases { if _, ok := a.Alias[alias]; !ok && alias != "" { a.Alias[alias] = gvr } } } // Load K9s aliases. func (a *Aliases) Load(path string) error { a.loadDefaultAliases() f, err := EnsureAliasesCfgFile() if err != nil { slog.Error("Unable to gen config aliases", slogs.Error, err) } // load global alias file if err := a.LoadFile(f); err != nil { return err } // load context specific aliases if any return a.LoadFile(path) } // LoadFile loads alias from a given file. func (a *Aliases) LoadFile(path string) error { if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) { return nil } bb, err := os.ReadFile(path) if err != nil { return err } if err := data.JSONValidator.Validate(json.AliasesSchema, bb); err != nil { slog.Warn("Aliases validation failed", slogs.Error, err) } a.mx.Lock() if err := yaml.Unmarshal(bb, a); err != nil { return err } for k, v := range a.Alias { a.Alias[k] = client.NewGVR(v.String()) } defer a.mx.Unlock() return nil } func (a *Aliases) declare(gvr *client.GVR, aliases ...string) { a.Alias[gvr.String()] = gvr for _, alias := range aliases { a.Alias[alias] = gvr } } func (a *Aliases) loadDefaultAliases() { a.mx.Lock() defer a.mx.Unlock() a.declare(client.HlpGVR, "h", "?") a.declare(client.QGVR, "q", "q!", "qa", "Q") a.declare(client.AliGVR, "alias", "a") a.declare(client.HmGVR, "charts", "chart", "hm") a.declare(client.DirGVR, "dir", "d") a.declare(client.CtGVR, "context", "ctx") a.declare(client.UsrGVR, "user", "usr") a.declare(client.GrpGVR, "group", "grp") a.declare(client.PfGVR, "portforward", "pf") a.declare(client.BeGVR, "benchmark", "bench") a.declare(client.SdGVR, "screendump", "sd") a.declare(client.PuGVR, "pulse", "pu", "hz") a.declare(client.XGVR, "xray", "x") a.declare(client.WkGVR, "workload", "wk") } // Save alias to disk. func (a *Aliases) Save() error { slog.Debug("Saving Aliases...") a.mx.RLock() defer a.mx.RUnlock() return a.saveAliases(AppAliasesFile) } // SaveAliases saves aliases to a given file. func (a *Aliases) saveAliases(path string) error { if err := data.EnsureDirPath(path, data.DefaultDirMod); err != nil { return err } return data.SaveYAML(path, a) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/types.go
internal/config/types.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package config const ( defaultRefreshRate = 2 defaultMaxConnRetry = 5 // CPU tracks cpu usage. CPU = "cpu" // MEM tracks memory usage. MEM = "memory" ) // UI tracks ui specific configs. type UI struct { // EnableMouse toggles mouse support. EnableMouse bool `json:"enableMouse" yaml:"enableMouse"` // Headless toggles top header display. Headless bool `json:"headless" yaml:"headless"` // LogoLess toggles k9s logo. Logoless bool `json:"logoless" yaml:"logoless"` // Crumbsless toggles nav crumb display. Crumbsless bool `json:"crumbsless" yaml:"crumbsless"` // Splashless disables the splash screen on startup. Splashless bool `json:"splashless" yaml:"splashless"` // Reactive toggles reactive ui changes. Reactive bool `json:"reactive" yaml:"reactive"` // NoIcons toggles icons display. NoIcons bool `json:"noIcons" yaml:"noIcons"` // Skin reference the general k9s skin name. // Can be overridden per context. Skin string `json:"skin" yaml:"skin,omitempty"` // DefaultsToFullScreen toggles fullscreen on views like logs, yaml, details. DefaultsToFullScreen bool `json:"defaultsToFullScreen" yaml:"defaultsToFullScreen"` // UseFullGVRTitle toggles the display of full GVR (group/version/resource) vs R in views title. UseFullGVRTitle bool `json:"useFullGVRTitle" yaml:"useFullGVRTitle"` manualHeadless *bool manualLogoless *bool manualCrumbsless *bool manualSplashless *bool }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/threshold_test.go
internal/config/threshold_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package config_test import ( "testing" "github.com/derailed/k9s/internal/config" "github.com/stretchr/testify/assert" ) func TestSeverityValidate(t *testing.T) { uu := map[string]struct { d, e *config.Severity }{ "default": { d: config.NewSeverity(), e: config.NewSeverity(), }, "toast": { d: &config.Severity{Warn: 10}, e: &config.Severity{Warn: 10, Critical: 90}, }, "negative": { d: &config.Severity{Warn: -1}, e: config.NewSeverity(), }, "out-of-range": { d: &config.Severity{Warn: 150}, e: config.NewSeverity(), }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { u.d.Validate() assert.Equal(t, u.e, u.d) }) } } func TestLevelFor(t *testing.T) { uu := map[string]struct { k string v int e config.SeverityLevel }{ "normal": { k: config.CPU, v: 0, e: config.SeverityLow, }, "4": { k: config.CPU, v: 71, e: config.SeverityMedium, }, "3": { k: config.CPU, v: 75, e: config.SeverityMedium, }, "2": { k: config.CPU, v: 80, e: config.SeverityMedium, }, "1": { k: config.CPU, v: 100, e: config.SeverityHigh, }, "over": { k: config.CPU, v: 150, e: config.SeverityLow, }, "over-mem": { k: config.MEM, v: 150, e: config.SeverityLow, }, } o := config.NewThreshold() for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { assert.Equal(t, u.e, o.LevelFor(u.k, u.v)) }) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/config.go
internal/config/config.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package config import ( "errors" "fmt" "io/fs" "log/slog" "os" "time" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/config/data" "github.com/derailed/k9s/internal/config/json" "github.com/derailed/k9s/internal/slogs" "github.com/derailed/k9s/internal/view/cmd" "gopkg.in/yaml.v3" "k8s.io/cli-runtime/pkg/genericclioptions" ) // Config tracks K9s configuration options. type Config struct { K9s *K9s `yaml:"k9s" json:"k9s"` conn client.Connection settings data.KubeSettings } // NewConfig creates a new default config. func NewConfig(ks data.KubeSettings) *Config { return &Config{ settings: ks, K9s: NewK9s(nil, ks), } } // IsReadOnly returns true if K9s is running in read-only mode. func (c *Config) IsReadOnly() bool { return c.K9s.IsReadOnly() } // ActiveClusterName returns the corresponding cluster name. func (c *Config) ActiveClusterName(contextName string) (string, error) { ct, err := c.settings.GetContext(contextName) if err != nil { return "", err } return ct.Cluster, nil } // ContextHotkeysPath returns a context specific hotkeys file spec. func (c *Config) ContextHotkeysPath() string { ct, err := c.K9s.ActiveContext() if err != nil { return "" } return AppContextHotkeysFile(ct.ClusterName, c.K9s.activeContextName) } // ContextAliasesPath returns a context specific aliases file spec. func (c *Config) ContextAliasesPath() string { ct, err := c.K9s.ActiveContext() if err != nil { return "" } return AppContextAliasesFile(ct.GetClusterName(), c.K9s.activeContextName) } // ContextPluginsPath returns a context specific plugins file spec. func (c *Config) ContextPluginsPath() (string, error) { ct, err := c.K9s.ActiveContext() if err != nil { return "", err } return AppContextPluginsFile(ct.GetClusterName(), c.K9s.activeContextName), nil } func setK8sTimeout(flags *genericclioptions.ConfigFlags, d time.Duration) { v := d.String() flags.Timeout = &v } // Refine the configuration based on cli args. func (c *Config) Refine(flags *genericclioptions.ConfigFlags, k9sFlags *Flags, cfg *client.Config) error { if flags == nil { return nil } if !isStringSet(flags.Timeout) { if d, err := time.ParseDuration(c.K9s.APIServerTimeout); err == nil { setK8sTimeout(flags, d) } else { setK8sTimeout(flags, client.DefaultCallTimeoutDuration) } } if isStringSet(flags.Context) { if _, err := c.K9s.ActivateContext(*flags.Context); err != nil { return fmt.Errorf("k8sflags. unable to activate context %q: %w", *flags.Context, err) } } else { n, err := cfg.CurrentContextName() if err != nil { return fmt.Errorf("unable to retrieve kubeconfig current context %q: %w", n, err) } _, err = c.K9s.ActivateContext(n) if err != nil { return fmt.Errorf("unable to activate context %q: %w", n, err) } } slog.Debug("Using active context", slogs.Context, c.K9s.ActiveContextName()) var ns string switch { case k9sFlags != nil && IsBoolSet(k9sFlags.AllNamespaces): ns = client.NamespaceAll c.ResetActiveView() case isStringSet(flags.Namespace): ns = *flags.Namespace c.ResetActiveView() default: nss, err := c.K9s.ActiveContextNamespace() if err != nil { return err } ns = nss } if ns == "" { ns = client.DefaultNamespace } if err := c.SetActiveNamespace(ns); err != nil { return err } return data.EnsureDirPath(c.K9s.AppScreenDumpDir(), data.DefaultDirMod) } // Reset resets the context to the new current context/cluster. func (c *Config) Reset() { c.K9s.Reset() } func (c *Config) ActivateContext(n string) (*data.Context, error) { ct, err := c.K9s.ActivateContext(n) if err != nil { return nil, fmt.Errorf("set current context failed. %w", err) } return ct, nil } // CurrentContext fetch the configuration active context. func (c *Config) CurrentContext() (*data.Context, error) { return c.K9s.ActiveContext() } // ActiveNamespace returns the active namespace in the current context. // If none found return the empty ns. func (c *Config) ActiveNamespace() string { ns, err := c.K9s.ActiveContextNamespace() if err != nil { slog.Error("Unable to assert active namespace. Using default", slogs.Error, err) ns = client.DefaultNamespace } return ns } // FavNamespaces returns fav namespaces in the current context. func (c *Config) FavNamespaces() []string { ct, err := c.K9s.ActiveContext() if err != nil { return nil } ct.Validate(c.conn, c.K9s.getActiveContextName(), ct.ClusterName) return ct.Namespace.Favorites } // SetActiveNamespace set the active namespace in the current context. func (c *Config) SetActiveNamespace(ns string) error { if ns == client.NotNamespaced { slog.Debug("No namespace given. skipping!", slogs.Namespace, ns) return nil } ct, err := c.K9s.ActiveContext() if err != nil { return err } return ct.Namespace.SetActive(ns, c.settings) } // ActiveView returns the active view in the current context. func (c *Config) ActiveView() string { ct, err := c.K9s.ActiveContext() if err != nil { return data.DefaultView } v := ct.View.Active if c.K9s.manualCommand != nil && *c.K9s.manualCommand != "" { v = *c.K9s.manualCommand // We reset the manualCommand property because // the command-line switch should only be considered once, // on startup. *c.K9s.manualCommand = "" } return v } func (c *Config) ResetActiveView() { if isStringSet(c.K9s.manualCommand) { return } v := c.ActiveView() if v == "" { return } p := cmd.NewInterpreter(v) if p.HasNS() { c.SetActiveView(p.Cmd()) } } // SetActiveView sets current context active view. func (c *Config) SetActiveView(view string) { if ct, err := c.K9s.ActiveContext(); err == nil { ct.View.Active = view } } // GetConnection return an api server connection. func (c *Config) GetConnection() client.Connection { return c.conn } // SetConnection set an api server connection. func (c *Config) SetConnection(conn client.Connection) { c.conn = conn if conn != nil { c.K9s.resetConnection(conn) } } func (c *Config) ActiveContextName() string { return c.K9s.activeContextName } func (c *Config) Merge(c1 *Config) { c.K9s.Merge(c1.K9s) } // Load loads K9s configuration from file. func (c *Config) Load(path string, force bool) error { if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) { if err := c.Save(force); err != nil { return err } } bb, err := os.ReadFile(path) if err != nil { return err } var errs error if err := data.JSONValidator.Validate(json.K9sSchema, bb); err != nil { errs = errors.Join(errs, fmt.Errorf("k9s config file %q load failed:\n%w", path, err)) } var cfg Config if err := yaml.Unmarshal(bb, &cfg); err != nil { errs = errors.Join(errs, fmt.Errorf("main config.yaml load failed: %w", err)) } c.Merge(&cfg) return errs } // Save configuration to disk. func (c *Config) Save(force bool) error { contextName := c.K9s.ActiveContextName() clusterName, err := c.ActiveClusterName(contextName) if err != nil { return fmt.Errorf("unable to locate associated cluster for context %q: %w", contextName, err) } c.Validate(contextName, clusterName) if err := c.K9s.Save(contextName, clusterName, force); err != nil { return err } if _, err := os.Stat(AppConfigFile); errors.Is(err, fs.ErrNotExist) { return c.SaveFile(AppConfigFile) } return nil } // SaveFile K9s configuration to disk. func (c *Config) SaveFile(path string) error { if err := data.EnsureDirPath(path, data.DefaultDirMod); err != nil { return err } if err := data.SaveYAML(path, c); err != nil { slog.Error("Unable to save K9s config file", slogs.Error, err) return err } slog.Info("[CONFIG] Saving K9s config to disk", slogs.Path, path) return nil } // Validate the configuration. func (c *Config) Validate(contextName, clusterName string) { if c.K9s == nil { c.K9s = NewK9s(c.conn, c.settings) } c.K9s.Validate(c.conn, contextName, clusterName) } // Dump for debug... func (c *Config) Dump(msg string) { ct, err := c.K9s.ActiveContext() if err == nil { bb, _ := yaml.Marshal(ct) fmt.Printf("Dump: %q\n%s\n", msg, string(bb)) } else { fmt.Println("BOOM!", err) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/benchmark.go
internal/config/benchmark.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package config import ( "net/http" "os" "gopkg.in/yaml.v3" ) // K9sBench the name of the benchmarks config file. var K9sBench = "bench" type ( // Bench tracks K9s styling options. Bench struct { Benchmarks *Benchmarks `yaml:"benchmarks"` } // Benchmarks tracks K9s benchmarks configuration. Benchmarks struct { Defaults Benchmark `yaml:"defaults"` Services map[string]BenchConfig `yam':"services"` Containers map[string]BenchConfig `yam':"containers"` } // Auth basic auth creds. Auth struct { User string `yaml:"user"` Password string `yaml:"password"` } // Benchmark represents a generic benchmark. Benchmark struct { C int `yaml:"concurrency"` N int `yaml:"requests"` } // HTTP represents an http request. HTTP struct { Method string `yaml:"method"` Host string `yaml:"host"` Path string `yaml:"path"` HTTP2 bool `yaml:"http2"` Body string `yaml:"body"` Headers http.Header `yaml:"headers"` } // BenchConfig represents a service benchmark. BenchConfig struct { Name string C int `yaml:"concurrency"` N int `yaml:"requests"` Auth Auth `yaml:"auth"` HTTP HTTP `yaml:"http"` } ) const ( // DefaultC default concurrency. DefaultC = 1 // DefaultN default number of requests. DefaultN = 200 // DefaultMethod default http verb. DefaultMethod = "GET" ) // DefaultBenchSpec returns a default bench spec. func DefaultBenchSpec() BenchConfig { return BenchConfig{ C: DefaultC, N: DefaultN, HTTP: HTTP{ Method: DefaultMethod, Path: "/", }, } } func newBenchmark() Benchmark { return Benchmark{ C: DefaultC, N: DefaultN, } } // Empty checks if the benchmark is set. func (b Benchmark) Empty() bool { return b.C == 0 && b.N == 0 } func newBenchmarks() *Benchmarks { return &Benchmarks{ Defaults: newBenchmark(), } } // NewBench creates a new default config. func NewBench(path string) (*Bench, error) { s := &Bench{Benchmarks: newBenchmarks()} err := s.load(path) return s, err } // Reload update the configuration from disk. func (s *Bench) Reload(path string) error { return s.load(path) } // Load K9s benchmark configs from file. func (s *Bench) load(path string) error { f, err := os.ReadFile(path) if err != nil { return err } return yaml.Unmarshal(f, &s) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/color_test.go
internal/config/color_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package config_test import ( "testing" "github.com/derailed/k9s/internal/config" "github.com/derailed/tcell/v2" "github.com/stretchr/testify/assert" ) func TestColors(t *testing.T) { uu := map[string]struct { cc []string ee []tcell.Color }{ "empty": { ee: []tcell.Color{}, }, "default": { cc: []string{"default"}, ee: []tcell.Color{tcell.ColorDefault}, }, "multi": { cc: []string{ "default", "transparent", "blue", "green", }, ee: []tcell.Color{ tcell.ColorDefault, tcell.ColorDefault, tcell.ColorBlue.TrueColor(), tcell.ColorGreen.TrueColor(), }, }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { cc := make(config.Colors, 0, len(u.cc)) for _, c := range u.cc { cc = append(cc, config.NewColor(c)) } assert.Equal(t, u.ee, cc.Colors()) }) } } func TestColorString(t *testing.T) { uu := map[string]struct { c string e string }{ "empty": { e: "-", }, "default": { c: "default", e: "-", }, "transparent": { c: "-", e: "-", }, "blue": { c: "blue", e: "#0000ff", }, "lightgray": { c: "lightgray", e: "#d3d3d3", }, "hex": { c: "#00ff00", e: "#00ff00", }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { c := config.NewColor(u.c) assert.Equal(t, u.e, c.String()) }) } } func TestColorToColor(t *testing.T) { uu := map[string]struct { c string e tcell.Color }{ "default": { c: "default", e: tcell.ColorDefault, }, "transparent": { c: "-", e: tcell.ColorDefault, }, "aqua": { c: "aqua", e: tcell.ColorAqua.TrueColor(), }, } for k := range uu { u := uu[k] t.Run(k, func(t *testing.T) { c := config.NewColor(u.c) assert.Equal(t, u.e, c.Color()) }) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/k9s.go
internal/config/k9s.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package config import ( "errors" "fmt" "io/fs" "log/slog" "net/http" "net/url" "os" "path/filepath" "sync" "time" "github.com/derailed/k9s/internal/client" "github.com/derailed/k9s/internal/config/data" "github.com/derailed/k9s/internal/slogs" ) type gpuVendors map[string]string // KnownGPUVendors tracks a set of known GPU vendors. var KnownGPUVendors = defaultGPUVendors var defaultGPUVendors = gpuVendors{ "nvidia": "nvidia.com/gpu", "nvidia-shared": "nvidia.com/gpu.shared", "amd": "amd.com/gpu", "intel": "gpu.intel.com/i915", } // K9s tracks K9s configuration options. type K9s struct { LiveViewAutoRefresh bool `json:"liveViewAutoRefresh" yaml:"liveViewAutoRefresh"` GPUVendors gpuVendors `json:"gpuVendors" yaml:"gpuVendors"` ScreenDumpDir string `json:"screenDumpDir" yaml:"screenDumpDir,omitempty"` RefreshRate float32 `json:"refreshRate" yaml:"refreshRate"` APIServerTimeout string `json:"apiServerTimeout" yaml:"apiServerTimeout"` MaxConnRetry int32 `json:"maxConnRetry" yaml:"maxConnRetry"` ReadOnly bool `json:"readOnly" yaml:"readOnly"` NoExitOnCtrlC bool `json:"noExitOnCtrlC" yaml:"noExitOnCtrlC"` PortForwardAddress string `yaml:"portForwardAddress"` UI UI `json:"ui" yaml:"ui"` SkipLatestRevCheck bool `json:"skipLatestRevCheck" yaml:"skipLatestRevCheck"` DisablePodCounting bool `json:"disablePodCounting" yaml:"disablePodCounting"` ShellPod *ShellPod `json:"shellPod" yaml:"shellPod"` ImageScans ImageScans `json:"imageScans" yaml:"imageScans"` Logger Logger `json:"logger" yaml:"logger"` Thresholds Threshold `json:"thresholds" yaml:"thresholds"` DefaultView string `json:"defaultView" yaml:"defaultView"` manualRefreshRate float32 manualReadOnly *bool manualCommand *string manualScreenDumpDir *string refreshRateWarned bool dir *data.Dir activeContextName string activeConfig *data.Config conn client.Connection ks data.KubeSettings mx sync.RWMutex contextSwitch bool } // NewK9s create a new K9s configuration. func NewK9s(conn client.Connection, ks data.KubeSettings) *K9s { return &K9s{ RefreshRate: defaultRefreshRate, GPUVendors: make(gpuVendors), MaxConnRetry: defaultMaxConnRetry, APIServerTimeout: client.DefaultCallTimeoutDuration.String(), ScreenDumpDir: AppDumpsDir, Logger: NewLogger(), Thresholds: NewThreshold(), PortForwardAddress: defaultPFAddress(), ShellPod: NewShellPod(), ImageScans: NewImageScans(), dir: data.NewDir(AppContextsDir), conn: conn, ks: ks, } } func (k *K9s) ToggleContextSwitch(b bool) { k.mx.Lock() defer k.mx.Unlock() k.contextSwitch = b } func (k *K9s) getContextSwitch() bool { k.mx.Lock() defer k.mx.Unlock() return k.contextSwitch } func (k *K9s) resetConnection(conn client.Connection) { k.mx.Lock() defer k.mx.Unlock() k.conn = conn } // Save saves the k9s config to disk. func (k *K9s) Save(contextName, clusterName string, force bool) error { path := filepath.Join( AppContextsDir, data.SanitizeContextSubpath(clusterName, contextName), data.MainConfigFile, ) if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) || force { slog.Debug("[CONFIG] Saving context config to disk", slogs.Path, path, slogs.Cluster, k.getActiveConfig().Context.GetClusterName(), slogs.Context, k.getActiveContextName(), ) return k.dir.Save(path, k.getActiveConfig()) } return nil } // Merge merges k9s configs. func (k *K9s) Merge(k1 *K9s) { if k1 == nil { return } for k, v := range k1.GPUVendors { KnownGPUVendors[k] = v } k.LiveViewAutoRefresh = k1.LiveViewAutoRefresh k.DefaultView = k1.DefaultView k.ScreenDumpDir = k1.ScreenDumpDir k.RefreshRate = k1.RefreshRate k.APIServerTimeout = k1.APIServerTimeout k.MaxConnRetry = k1.MaxConnRetry k.ReadOnly = k1.ReadOnly k.NoExitOnCtrlC = k1.NoExitOnCtrlC k.PortForwardAddress = k1.PortForwardAddress k.UI = k1.UI k.SkipLatestRevCheck = k1.SkipLatestRevCheck k.DisablePodCounting = k1.DisablePodCounting k.ShellPod = k1.ShellPod k.Logger = k1.Logger k.ImageScans = k1.ImageScans if k1.Thresholds != nil { k.Thresholds = k1.Thresholds } } // AppScreenDumpDir fetch screen dumps dir. func (k *K9s) AppScreenDumpDir() string { d := k.ScreenDumpDir if isStringSet(k.manualScreenDumpDir) { d = *k.manualScreenDumpDir k.ScreenDumpDir = d } if d == "" { d = AppDumpsDir } return d } // ContextScreenDumpDir fetch context specific screen dumps dir. func (k *K9s) ContextScreenDumpDir() string { return filepath.Join(k.AppScreenDumpDir(), k.contextPath()) } func (k *K9s) contextPath() string { if k.getActiveConfig() == nil { return "na" } return data.SanitizeContextSubpath( k.getActiveConfig().Context.GetClusterName(), k.ActiveContextName(), ) } // Reset resets configuration and context. func (k *K9s) Reset() { k.setActiveConfig(nil) k.setActiveContextName("") } // ActiveContextNamespace fetch the context active ns. func (k *K9s) ActiveContextNamespace() (string, error) { act, err := k.ActiveContext() if err != nil { return "", err } return act.Namespace.Active, nil } // ActiveContextName returns the active context name. func (k *K9s) ActiveContextName() string { return k.getActiveContextName() } // ActiveContext returns the currently active context. func (k *K9s) ActiveContext() (*data.Context, error) { if cfg := k.getActiveConfig(); cfg != nil && cfg.Context != nil { return cfg.Context, nil } ct, err := k.ActivateContext(k.ActiveContextName()) return ct, err } func (k *K9s) setActiveConfig(c *data.Config) { k.mx.Lock() defer k.mx.Unlock() k.activeConfig = c } func (k *K9s) getActiveConfig() *data.Config { k.mx.RLock() defer k.mx.RUnlock() return k.activeConfig } func (k *K9s) setActiveContextName(n string) { k.mx.Lock() defer k.mx.Unlock() k.activeContextName = n } func (k *K9s) getActiveContextName() string { k.mx.RLock() defer k.mx.RUnlock() return k.activeContextName } // ActivateContext initializes the active context if not present. func (k *K9s) ActivateContext(contextName string) (*data.Context, error) { k.setActiveContextName(contextName) ct, err := k.ks.GetContext(contextName) if err != nil { return nil, err } cfg, err := k.dir.Load(contextName, ct) if err != nil { return nil, err } k.setActiveConfig(cfg) if cfg.Context.Proxy != nil { k.ks.SetProxy(func(*http.Request) (*url.URL, error) { slog.Debug("Using proxy address", slogs.Address, cfg.Context.Proxy.Address) return url.Parse(cfg.Context.Proxy.Address) }) if k.conn != nil && k.conn.Config() != nil { // We get on this branch when the user switches the context and k9s // already has an API connection object so we just set the proxy to // avoid recreation using client.InitConnection k.conn.Config().SetProxy(func(*http.Request) (*url.URL, error) { slog.Debug("Setting proxy address", slogs.Address, cfg.Context.Proxy.Address) return url.Parse(cfg.Context.Proxy.Address) }) if !k.conn.CheckConnectivity() { return nil, fmt.Errorf("unable to connect to context %q", contextName) } } } k.Validate(k.conn, contextName, ct.Cluster) // If the context specifies a namespace, use it! if ns := ct.Namespace; ns != client.BlankNamespace { k.getActiveConfig().Context.Namespace.Active = ns } else if k.getActiveConfig().Context.Namespace.Active == "" { k.getActiveConfig().Context.Namespace.Active = client.DefaultNamespace } if k.getActiveConfig().Context == nil { return nil, fmt.Errorf("context activation failed for: %s", contextName) } return k.getActiveConfig().Context, nil } // Reload reloads the context config from disk. func (k *K9s) Reload() error { // Switching context skipping reload... if k.getContextSwitch() { return nil } ct, err := k.ks.GetContext(k.getActiveContextName()) if err != nil { return err } cfg, err := k.dir.Load(k.getActiveContextName(), ct) if err != nil { return err } k.setActiveConfig(cfg) k.getActiveConfig().Validate(k.conn, k.getActiveContextName(), ct.Cluster) return nil } // Override overrides k9s config from cli args. func (k *K9s) Override(k9sFlags *Flags) { if k9sFlags.RefreshRate != nil && *k9sFlags.RefreshRate != DefaultRefreshRate { k.manualRefreshRate = float32(*k9sFlags.RefreshRate) } k.UI.manualHeadless = k9sFlags.Headless k.UI.manualLogoless = k9sFlags.Logoless k.UI.manualCrumbsless = k9sFlags.Crumbsless k.UI.manualSplashless = k9sFlags.Splashless if k9sFlags.ReadOnly != nil && *k9sFlags.ReadOnly { k.manualReadOnly = k9sFlags.ReadOnly } if k9sFlags.Write != nil && *k9sFlags.Write { var falseVal bool k.manualReadOnly = &falseVal } k.manualCommand = k9sFlags.Command k.manualScreenDumpDir = k9sFlags.ScreenDumpDir } // IsHeadless returns headless setting. func (k *K9s) IsHeadless() bool { if IsBoolSet(k.UI.manualHeadless) { return true } return k.UI.Headless } // IsLogoless returns logoless setting. func (k *K9s) IsLogoless() bool { if IsBoolSet(k.UI.manualLogoless) { return true } return k.UI.Logoless } // IsCrumbsless returns crumbsless setting. func (k *K9s) IsCrumbsless() bool { if IsBoolSet(k.UI.manualCrumbsless) { return true } return k.UI.Crumbsless } // IsSplashless returns splashless setting. func (k *K9s) IsSplashless() bool { if IsBoolSet(k.UI.manualSplashless) { return true } return k.UI.Splashless } // GetRefreshRate returns the current refresh rate. func (k *K9s) GetRefreshRate() float32 { k.mx.Lock() defer k.mx.Unlock() rate := k.RefreshRate if k.manualRefreshRate != 0 { rate = k.manualRefreshRate } if rate < DefaultRefreshRate { if !k.refreshRateWarned { slog.Warn("Refresh rate is below minimum, capping to minimum value", slogs.Requested, float64(rate), slogs.Minimum, float64(DefaultRefreshRate)) k.refreshRateWarned = true } return DefaultRefreshRate } return rate } // RefreshDuration returns the refresh rate as a time.Duration. func (k *K9s) RefreshDuration() time.Duration { return time.Duration(k.GetRefreshRate() * float32(time.Second)) } // IsReadOnly returns the readonly setting. func (k *K9s) IsReadOnly() bool { ro := k.ReadOnly if cfg := k.getActiveConfig(); cfg != nil && cfg.Context.ReadOnly != nil { ro = *cfg.Context.ReadOnly } if k.manualReadOnly != nil { ro = *k.manualReadOnly } return ro } // Validate the current configuration. func (k *K9s) Validate(c client.Connection, contextName, clusterName string) { if k.RefreshRate <= 0 { k.RefreshRate = defaultRefreshRate } if k.MaxConnRetry <= 0 { k.MaxConnRetry = defaultMaxConnRetry } if a := os.Getenv(envPFAddress); a != "" { k.PortForwardAddress = a } if k.PortForwardAddress == "" { k.PortForwardAddress = defaultPFAddress() } if k.getActiveConfig() == nil { _, _ = k.ActivateContext(contextName) } if k.ShellPod != nil { k.ShellPod.Validate() } k.Logger = k.Logger.Validate() k.Thresholds = k.Thresholds.Validate() if cfg := k.getActiveConfig(); cfg != nil { cfg.Validate(c, contextName, clusterName) } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/plugin_test.go
internal/config/plugin_test.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package config import ( "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestPluginLoad(t *testing.T) { uu := map[string]struct { path string err string ee Plugins }{ "snippet": { path: "testdata/plugins/dir/snippet.1.yaml", ee: Plugins{ Plugins: plugins{ "snippet.1": Plugin{ Scopes: []string{"po", "dp"}, Args: []string{"-n", "$NAMESPACE", "-boolean"}, ShortCut: "shift-s", Description: "blee", Command: "duh", Confirm: true, OverwriteOutput: true, }, }, }, }, "multi-snippets": { path: "testdata/plugins/dir/snippet.multi.yaml", ee: Plugins{ Plugins: plugins{ "crapola": Plugin{ ShortCut: "Shift-1", Command: "crapola", Description: "crapola", Scopes: []string{"pods"}, }, "bozo": Plugin{ ShortCut: "Shift-2", Description: "bozo", Command: "bozo", Scopes: []string{"pods", "svc"}, }, }, }, }, "full": { path: "testdata/plugins/plugins.yaml", ee: Plugins{ Plugins: plugins{ "blah": Plugin{ Scopes: []string{"po", "dp"}, Args: []string{"-n", "$NAMESPACE", "-boolean"}, ShortCut: "shift-s", Description: "blee", Command: "duh", Confirm: true, }, }, }, }, "toast-no-file": { path: "testdata/plugins/plugins-bozo.yaml", ee: NewPlugins(), }, "toast-invalid": { path: "testdata/plugins/plugins-toast.yaml", ee: NewPlugins(), err: "plugin validation failed for testdata/plugins/plugins-toast.yaml: scopes is required\nAdditional property plugins is not allowed\ncommand is required\ndescription is required\nscopes is required\nshortCut is required\ncommand is required\ndescription is required\nscopes is required\nshortCut is required", }, } for k, u := range uu { t.Run(k, func(t *testing.T) { p := NewPlugins() err := p.Load(u.path, false) if err != nil { assert.Equal(t, u.err, err.Error()) } assert.Equal(t, u.ee, p) }) } } func TestSinglePluginFileLoad(t *testing.T) { e := Plugin{ Scopes: []string{"po", "dp"}, Args: []string{"-n", "$NAMESPACE", "-boolean"}, ShortCut: "shift-s", Description: "blee", Command: "duh", Confirm: true, } p := NewPlugins() require.NoError(t, p.load("testdata/plugins/plugins.yaml")) require.NoError(t, p.loadDir("/random/dir/not/exist")) assert.Len(t, p.Plugins, 1) v, ok := p.Plugins["blah"] assert.True(t, ok) assert.ObjectsAreEqual(e, v) } func TestMultiplePluginFilesLoad(t *testing.T) { uu := map[string]struct { path string dir string ee Plugins }{ "empty": { path: "testdata/plugins/plugins.yaml", dir: "testdata/plugins/dir", ee: Plugins{ Plugins: plugins{ "blah": { Scopes: []string{"po", "dp"}, Args: []string{"-n", "$NAMESPACE", "-boolean"}, ShortCut: "shift-s", Description: "blee", Command: "duh", Confirm: true, }, "snippet.1": { ShortCut: "shift-s", Command: "duh", Scopes: []string{"po", "dp"}, Args: []string{"-n", "$NAMESPACE", "-boolean"}, Description: "blee", Confirm: true, OverwriteOutput: true, }, "snippet.2": { Scopes: []string{"svc", "ing"}, Args: []string{"-n", "$NAMESPACE", "-oyaml"}, ShortCut: "shift-r", Description: "bla", Command: "duha", Background: true, }, "crapola": { Scopes: []string{"pods"}, Command: "crapola", Description: "crapola", ShortCut: "Shift-1", }, "bozo": { Scopes: []string{"pods", "svc"}, Command: "bozo", Description: "bozo", ShortCut: "Shift-2", }, }, }, }, } for k, u := range uu { t.Run(k, func(t *testing.T) { p := NewPlugins() require.NoError(t, p.load(u.path)) require.NoError(t, p.loadDir(u.dir)) assert.Equal(t, u.ee, p) }) } } func TestPluginLoadSymlink(t *testing.T) { tmp := t.TempDir() linkFile := filepath.Join(tmp, "plugins-symlink.yaml") wd, err := os.Getwd() require.NoError(t, err) require.NoError(t, os.Symlink(filepath.Join(wd, "testdata", "plugins", "plugins.yaml"), linkFile)) linkDir := filepath.Join(tmp, "plugins-dir-symlink") require.NoError(t, os.Symlink(filepath.Join(wd, "testdata", "plugins", "dir"), linkDir)) // Add a symlink with an infinite loop loopDir := filepath.Join(tmp, "loop") require.NoError(t, os.Mkdir(loopDir, 0o755)) require.NoError(t, os.Symlink(loopDir, filepath.Join(loopDir, "self"))) p := NewPlugins() require.NoError(t, p.loadDir(tmp)) ee := Plugins{ Plugins: plugins{ "blah": Plugin{ Scopes: []string{"po", "dp"}, Args: []string{"-n", "$NAMESPACE", "-boolean"}, ShortCut: "shift-s", Description: "blee", Command: "duh", Confirm: true, }, "snippet.1": { ShortCut: "shift-s", Command: "duh", Scopes: []string{"po", "dp"}, Args: []string{"-n", "$NAMESPACE", "-boolean"}, Description: "blee", Confirm: true, OverwriteOutput: true, }, "snippet.2": { Scopes: []string{"svc", "ing"}, Args: []string{"-n", "$NAMESPACE", "-oyaml"}, ShortCut: "shift-r", Description: "bla", Command: "duha", Background: true, }, "crapola": { Scopes: []string{"pods"}, Command: "crapola", Description: "crapola", ShortCut: "Shift-1", }, "bozo": { Scopes: []string{"pods", "svc"}, Command: "bozo", Description: "bozo", ShortCut: "Shift-2", }, }, } assert.Equal(t, ee, p) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/styles.go
internal/config/styles.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package config import ( "fmt" "os" "github.com/derailed/k9s/internal/config/data" "github.com/derailed/k9s/internal/config/json" "github.com/derailed/tcell/v2" "github.com/derailed/tview" "gopkg.in/yaml.v3" ) // StyleListener represents a skin's listener. type StyleListener interface { // StylesChanged notifies listener the skin changed. StylesChanged(*Styles) } // TextStyle tracks text styles. type TextStyle string const ( // TextStyleNormal is the default text style. TextStyleNormal TextStyle = "normal" // TextStyleBold is the bold text style. TextStyleBold TextStyle = "bold" // TextStyleDim is the dim text style. TextStyleDim TextStyle = "dim" ) // ToShortString returns a short string representation of the text style. func (ts TextStyle) ToShortString() string { switch ts { case TextStyleNormal: return "-" case TextStyleBold: return "b" case TextStyleDim: return "d" default: return "d" } } type ( // Styles tracks K9s styling options. Styles struct { K9s Style `json:"k9s" yaml:"k9s"` listeners []StyleListener } // Style tracks K9s styles. Style struct { Body Body `json:"body" yaml:"body"` Prompt Prompt `json:"prompt" yaml:"prompt"` Help Help `json:"help" yaml:"help"` Frame Frame `json:"frame" yaml:"frame"` Info Info `json:"info" yaml:"info"` Views Views `json:"views" yaml:"views"` Dialog Dialog `json:"dialog" yaml:"dialog"` } // Prompt tracks command styles Prompt struct { FgColor Color `json:"fgColor" yaml:"fgColor"` BgColor Color `json:"bgColor" yaml:"bgColor"` SuggestColor Color `json:"" yaml:"suggestColor"` Border PromptBorder `json:"" yaml:"border"` } // PromptBorder tracks the color of the prompt depending on its kind (e.g., command or filter) PromptBorder struct { CommandColor Color `json:"command" yaml:"command"` DefaultColor Color `json:"default" yaml:"default"` } // Help tracks help styles. Help struct { FgColor Color `json:"fgColor" yaml:"fgColor"` BgColor Color `json:"bgColor" yaml:"bgColor"` SectionColor Color `json:"sectionColor" yaml:"sectionColor"` KeyColor Color `json:"keyColor" yaml:"keyColor"` NumKeyColor Color `json:"numKeyColor" yaml:"numKeyColor"` } // Body tracks body styles. Body struct { FgColor Color `json:"fgColor" yaml:"fgColor"` BgColor Color `json:"bgColor" yaml:"bgColor"` LogoColor Color `json:"logoColor" yaml:"logoColor"` LogoColorMsg Color `json:"logoColorMsg" yaml:"logoColorMsg"` LogoColorInfo Color `json:"logoColorInfo" yaml:"logoColorInfo"` LogoColorWarn Color `json:"logoColorWarn" yaml:"logoColorWarn"` LogoColorError Color `json:"logoColorError" yaml:"logoColorError"` } // Dialog tracks dialog styles. Dialog struct { FgColor Color `json:"fgColor" yaml:"fgColor"` BgColor Color `json:"bgColor" yaml:"bgColor"` ButtonFgColor Color `json:"buttonFgColor" yaml:"buttonFgColor"` ButtonBgColor Color `json:"buttonBgColor" yaml:"buttonBgColor"` ButtonFocusFgColor Color `json:"buttonFocusFgColor" yaml:"buttonFocusFgColor"` ButtonFocusBgColor Color `json:"buttonFocusBgColor" yaml:"buttonFocusBgColor"` LabelFgColor Color `json:"labelFgColor" yaml:"labelFgColor"` FieldFgColor Color `json:"fieldFgColor" yaml:"fieldFgColor"` } // Frame tracks frame styles. Frame struct { Title Title `json:"title" yaml:"title"` Border Border `json:"border" yaml:"border"` Menu Menu `json:"menu" yaml:"menu"` Crumb Crumb `json:"crumbs" yaml:"crumbs"` Status Status `json:"status" yaml:"status"` } // Views tracks individual view styles. Views struct { Table Table `json:"table" yaml:"table"` Xray Xray `json:"xray" yaml:"xray"` Charts Charts `json:"charts" yaml:"charts"` Yaml Yaml `json:"yaml" yaml:"yaml"` Picker Picker `json:"picker" yaml:"picker"` Log Log `json:"logs" yaml:"logs"` } // Status tracks resource status styles. Status struct { NewColor Color `json:"newColor" yaml:"newColor"` ModifyColor Color `json:"modifyColor" yaml:"modifyColor"` AddColor Color `json:"addColor" yaml:"addColor"` PendingColor Color `json:"pendingColor" yaml:"pendingColor"` ErrorColor Color `json:"errorColor" yaml:"errorColor"` HighlightColor Color `json:"highlightColor" yaml:"highlightColor"` KillColor Color `json:"killColor" yaml:"killColor"` CompletedColor Color `json:"completedColor" yaml:"completedColor"` } // Log tracks Log styles. Log struct { FgColor Color `json:"fgColor" yaml:"fgColor"` BgColor Color `json:"bgColor" yaml:"bgColor"` Indicator LogIndicator `json:"indicator" yaml:"indicator"` } // Picker tracks color when selecting containers Picker struct { MainColor Color `json:"mainColor" yaml:"mainColor"` FocusColor Color `json:"focusColor" yaml:"focusColor"` ShortcutColor Color `json:"shortcutColor" yaml:"shortcutColor"` } // LogIndicator tracks log view indicator. LogIndicator struct { FgColor Color `json:"fgColor" yaml:"fgColor"` BgColor Color `json:"bgColor" yaml:"bgColor"` ToggleOnColor Color `json:"toggleOnColor" yaml:"toggleOnColor"` ToggleOffColor Color `json:"toggleOffColor" yaml:"toggleOffColor"` } // Yaml tracks yaml styles. Yaml struct { KeyColor Color `json:"keyColor" yaml:"keyColor"` ValueColor Color `json:"valueColor" yaml:"valueColor"` ColonColor Color `json:"colonColor" yaml:"colonColor"` } // Title tracks title styles. Title struct { FgColor Color `json:"fgColor" yaml:"fgColor"` BgColor Color `json:"bgColor" yaml:"bgColor"` HighlightColor Color `json:"highlightColor" yaml:"highlightColor"` CounterColor Color `json:"counterColor" yaml:"counterColor"` FilterColor Color `json:"filterColor" yaml:"filterColor"` } // Info tracks info styles. Info struct { SectionColor Color `json:"sectionColor" yaml:"sectionColor"` FgColor Color `json:"fgColor" yaml:"fgColor"` CPUColor Color `json:"cpuColor" yaml:"cpuColor"` MEMColor Color `json:"memColor" yaml:"memColor"` K9sRevColor Color `json:"k9sRevColor" yaml:"k9sRevColor"` } // Border tracks border styles. Border struct { FgColor Color `json:"fgColor" yaml:"fgColor"` FocusColor Color `json:"focusColor" yaml:"focusColor"` } // Crumb tracks crumbs styles. Crumb struct { FgColor Color `json:"fgColor" yaml:"fgColor"` BgColor Color `json:"bgColor" yaml:"bgColor"` ActiveColor Color `json:"activeColor" yaml:"activeColor"` } // Table tracks table styles. Table struct { FgColor Color `json:"fgColor" yaml:"fgColor"` BgColor Color `json:"bgColor" yaml:"bgColor"` CursorFgColor Color `json:"cursorFgColor" yaml:"cursorFgColor"` CursorBgColor Color `json:"cursorBgColor" yaml:"cursorBgColor"` MarkColor Color `json:"markColor" yaml:"markColor"` Header TableHeader `json:"header" yaml:"header"` } // TableHeader tracks table header styles. TableHeader struct { FgColor Color `json:"fgColor" yaml:"fgColor"` BgColor Color `json:"bgColor" yaml:"bgColor"` SorterColor Color `json:"sorterColor" yaml:"sorterColor"` } // Xray tracks xray styles. Xray struct { FgColor Color `json:"fgColor" yaml:"fgColor"` BgColor Color `json:"bgColor" yaml:"bgColor"` CursorColor Color `json:"cursorColor" yaml:"cursorColor"` CursorTextColor Color `json:"cursorTextColor" yaml:"cursorTextColor"` GraphicColor Color `json:"graphicColor" yaml:"graphicColor"` } // Menu tracks menu styles. Menu struct { FgColor Color `json:"fgColor" yaml:"fgColor"` FgStyle TextStyle `json:"fgStyle" yaml:"fgStyle"` KeyColor Color `json:"keyColor" yaml:"keyColor"` NumKeyColor Color `json:"numKeyColor" yaml:"numKeyColor"` } // Charts tracks charts styles. Charts struct { BgColor Color `json:"bgColor" yaml:"bgColor"` DialBgColor Color `json:"dialBgColor" yaml:"dialBgColor"` ChartBgColor Color `json:"chartBgColor" yaml:"chartBgColor"` DefaultDialColors Colors `json:"defaultDialColors" yaml:"defaultDialColors"` DefaultChartColors Colors `json:"defaultChartColors" yaml:"defaultChartColors"` ResourceColors map[string]Colors `json:"resourceColors" yaml:"resourceColors"` FocusFgColor Color `yaml:"focusFgColor"` FocusBgColor Color `yaml:"focusBgColor"` } ) func newStyle() Style { return Style{ Body: newBody(), Prompt: newPrompt(), Help: newHelp(), Frame: newFrame(), Info: newInfo(), Views: newViews(), Dialog: newDialog(), } } func newDialog() Dialog { return Dialog{ FgColor: "cadetblue", BgColor: "black", ButtonBgColor: "darkslateblue", ButtonFgColor: "black", ButtonFocusBgColor: "dodgerblue", ButtonFocusFgColor: "black", LabelFgColor: "white", FieldFgColor: "white", } } func newPrompt() Prompt { return Prompt{ FgColor: "cadetblue", BgColor: "black", SuggestColor: "dodgerblue", Border: PromptBorder{ DefaultColor: "seagreen", CommandColor: "aqua", }, } } func newCharts() Charts { return Charts{ BgColor: "black", DialBgColor: "black", ChartBgColor: "black", DefaultDialColors: Colors{Color("palegreen"), Color("orangered")}, DefaultChartColors: Colors{Color("palegreen"), Color("orangered")}, ResourceColors: map[string]Colors{ CPU: {Color("dodgerblue"), Color("darkslateblue")}, MEM: {Color("yellow"), Color("goldenrod")}, }, FocusFgColor: "white", FocusBgColor: "orange", } } func newViews() Views { return Views{ Table: newTable(), Xray: newXray(), Charts: newCharts(), Yaml: newYaml(), Picker: newPicker(), Log: newLog(), } } func newFrame() Frame { return Frame{ Title: newTitle(), Border: newBorder(), Menu: newMenu(), Crumb: newCrumb(), Status: newStatus(), } } func newHelp() Help { return Help{ FgColor: "cadetblue", BgColor: "black", SectionColor: "green", KeyColor: "dodgerblue", NumKeyColor: "fuchsia", } } func newBody() Body { return Body{ FgColor: "cadetblue", BgColor: "black", LogoColor: "orange", LogoColorMsg: "white", LogoColorInfo: "green", LogoColorWarn: "mediumvioletred", LogoColorError: "red", } } func newStatus() Status { return Status{ NewColor: "lightskyblue", ModifyColor: "greenyellow", AddColor: "dodgerblue", PendingColor: "darkorange", ErrorColor: "orangered", HighlightColor: "aqua", KillColor: "mediumpurple", CompletedColor: "lightslategray", } } func newPicker() Picker { return Picker{ MainColor: "white", FocusColor: "aqua", ShortcutColor: "aqua", } } func newLog() Log { return Log{ FgColor: "lightskyblue", BgColor: "black", Indicator: newLogIndicator(), } } func newLogIndicator() LogIndicator { return LogIndicator{ FgColor: "dodgerblue", BgColor: "black", ToggleOnColor: "limegreen", ToggleOffColor: "gray", } } func newYaml() Yaml { return Yaml{ KeyColor: "steelblue", ColonColor: "white", ValueColor: "papayawhip", } } func newTitle() Title { return Title{ FgColor: "aqua", BgColor: "black", HighlightColor: "fuchsia", CounterColor: "papayawhip", FilterColor: "seagreen", } } func newInfo() Info { return Info{ SectionColor: "white", FgColor: "orange", CPUColor: "lawngreen", MEMColor: "darkturquoise", K9sRevColor: "aqua", } } func newXray() Xray { return Xray{ FgColor: "aqua", BgColor: "black", CursorColor: "dodgerblue", CursorTextColor: "black", GraphicColor: "cadetblue", } } func newTable() Table { return Table{ FgColor: "aqua", BgColor: "black", CursorFgColor: "black", CursorBgColor: "aqua", MarkColor: "palegreen", Header: newTableHeader(), } } func newTableHeader() TableHeader { return TableHeader{ FgColor: "white", BgColor: "black", SorterColor: "aqua", } } func newCrumb() Crumb { return Crumb{ FgColor: "black", BgColor: "aqua", ActiveColor: "orange", } } func newBorder() Border { return Border{ FgColor: "dodgerblue", FocusColor: "lightskyblue", } } func newMenu() Menu { return Menu{ FgColor: "white", KeyColor: "dodgerblue", NumKeyColor: "fuchsia", } } // NewStyles creates a new default config. func NewStyles() *Styles { var s Styles if err := yaml.Unmarshal(stockSkinTpl, &s); err == nil { return &s } return &Styles{ K9s: newStyle(), } } // Reset resets styles. func (s *Styles) Reset() { if err := yaml.Unmarshal(stockSkinTpl, s); err != nil { s.K9s = newStyle() } } // FgColor returns the foreground color. func (s *Styles) FgColor() tcell.Color { return s.Body().FgColor.Color() } // BgColor returns the background color. func (s *Styles) BgColor() tcell.Color { return s.Body().BgColor.Color() } // AddListener registers a new listener. func (s *Styles) AddListener(l StyleListener) { s.listeners = append(s.listeners, l) } // RemoveListener removes a listener. func (s *Styles) RemoveListener(l StyleListener) { victim := -1 for i, lis := range s.listeners { if lis == l { victim = i break } } if victim == -1 { return } s.listeners = append(s.listeners[:victim], s.listeners[victim+1:]...) } func (s *Styles) fireStylesChanged() { for _, list := range s.listeners { list.StylesChanged(s) } } // Body returns body styles. func (s *Styles) Body() Body { return s.K9s.Body } // Prompt returns prompt styles. func (s *Styles) Prompt() Prompt { return s.K9s.Prompt } // Frame returns frame styles. func (s *Styles) Frame() Frame { return s.K9s.Frame } // Crumb returns crumb styles. func (s *Styles) Crumb() Crumb { return s.Frame().Crumb } // Title returns title styles. func (s *Styles) Title() Title { return s.Frame().Title } // Charts returns charts styles. func (s *Styles) Charts() Charts { return s.K9s.Views.Charts } // Dialog returns dialog styles. func (s *Styles) Dialog() Dialog { return s.K9s.Dialog } // Table returns table styles. func (s *Styles) Table() Table { return s.K9s.Views.Table } // Xray returns xray styles. func (s *Styles) Xray() Xray { return s.K9s.Views.Xray } // Views returns views styles. func (s *Styles) Views() Views { return s.K9s.Views } // Load K9s configuration from file. func (s *Styles) Load(path string) error { bb, err := os.ReadFile(path) if err != nil { return err } if err := data.JSONValidator.Validate(json.SkinSchema, bb); err != nil { return err } if err := yaml.Unmarshal(bb, s); err != nil { return err } return nil } // Update apply terminal colors based on styles. func (s *Styles) Update() { tview.Styles.PrimitiveBackgroundColor = s.BgColor() tview.Styles.ContrastBackgroundColor = s.BgColor() tview.Styles.MoreContrastBackgroundColor = s.BgColor() tview.Styles.PrimaryTextColor = s.FgColor() tview.Styles.BorderColor = s.K9s.Frame.Border.FgColor.Color() tview.Styles.FocusColor = s.K9s.Frame.Border.FocusColor.Color() tview.Styles.TitleColor = s.FgColor() tview.Styles.GraphicsColor = s.FgColor() tview.Styles.SecondaryTextColor = s.FgColor() tview.Styles.TertiaryTextColor = s.FgColor() tview.Styles.InverseTextColor = s.FgColor() tview.Styles.ContrastSecondaryTextColor = s.FgColor() s.fireStylesChanged() } // Dump for debug. func (s *Styles) Dump() { bb, _ := yaml.Marshal(s) fmt.Println(string(bb)) }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false
derailed/k9s
https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/shell_pod.go
internal/config/shell_pod.go
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of K9s package config import ( v1 "k8s.io/api/core/v1" ) const defaultDockerShellImage = "busybox:1.37.0" // Limits represents resource limits. type Limits map[v1.ResourceName]string // ShellPod represents k9s shell configuration. type ShellPod struct { Image string `json:"image" yaml:"image"` Command []string `json:"command,omitempty" yaml:"command,omitempty"` Args []string `json:"args,omitempty" yaml:"args,omitempty"` Namespace string `json:"namespace" yaml:"namespace"` Limits Limits `json:"limits,omitempty" yaml:"limits,omitempty"` Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"` ImagePullSecrets []v1.LocalObjectReference `json:"imagePullSecrets,omitempty" yaml:"imagePullSecrets,omitempty"` ImagePullPolicy v1.PullPolicy `json:"imagePullPolicy,omitempty" yaml:"imagePullPolicy,omitempty"` TTY bool `json:"tty,omitempty" yaml:"tty,omitempty"` HostPathVolume []hostPathVolume `json:"hostPathVolume,omitempty" yaml:"hostPathVolume,omitempty"` } type hostPathVolume struct { Name string `json:"name" yaml:"name"` MountPath string `json:"mountPath" yaml:"mountPath"` HostPath string `json:"hostPath" yaml:"hostPath"` ReadOnly bool `json:"readOnly,omitempty" yaml:"readOnly,omitempty"` } // NewShellPod returns a new instance. func NewShellPod() *ShellPod { return &ShellPod{ Image: defaultDockerShellImage, Namespace: "default", Limits: defaultLimits(), } } // Validate validates the configuration. func (s *ShellPod) Validate() { if s.Image == "" { s.Image = defaultDockerShellImage } if len(s.Limits) == 0 { s.Limits = defaultLimits() } } func defaultLimits() Limits { return Limits{ v1.ResourceCPU: "100m", v1.ResourceMemory: "100Mi", } }
go
Apache-2.0
3784c12ae74593e8aca597c3c347e8714ad3d6b7
2026-01-07T08:36:21.587988Z
false