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/config/views.go | internal/config/views.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package config
import (
"cmp"
"errors"
"fmt"
"io/fs"
"log/slog"
"maps"
"os"
"regexp"
"slices"
"strings"
"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"
"gopkg.in/yaml.v3"
)
// ViewConfigListener represents a view config listener.
type ViewConfigListener interface {
// ViewSettingsChanged notifies listener the view configuration changed.
ViewSettingsChanged(*ViewSetting)
// GetNamespace return the view namespace
GetNamespace() string
}
// ViewSetting represents a view configuration.
type ViewSetting struct {
Columns []string `yaml:"columns"`
SortColumn string `yaml:"sortColumn"`
}
func (v *ViewSetting) HasCols() bool {
return len(v.Columns) > 0
}
func (v *ViewSetting) IsBlank() bool {
return v == nil || (len(v.Columns) == 0 && v.SortColumn == "")
}
func (v *ViewSetting) SortCol() (name string, asc bool, err error) {
if v == nil || v.SortColumn == "" {
return "", false, fmt.Errorf("no sort column specified")
}
tt := strings.Split(v.SortColumn, ":")
if len(tt) < 2 {
return "", false, fmt.Errorf("invalid sort column spec: %q. must be col-name:asc|desc", v.SortColumn)
}
return tt[0], tt[1] == "asc", nil
}
// Equals checks if two view settings are equal.
func (v *ViewSetting) Equals(vs *ViewSetting) bool {
if v == nil && vs == nil {
return true
}
if v == nil || vs == nil {
return false
}
if c := slices.Compare(v.Columns, vs.Columns); c != 0 {
return false
}
return cmp.Compare(v.SortColumn, vs.SortColumn) == 0
}
// CustomView represents a collection of view customization.
type CustomView struct {
Views map[string]ViewSetting `yaml:"views"`
listeners map[string]ViewConfigListener
}
// NewCustomView returns a views configuration.
func NewCustomView() *CustomView {
return &CustomView{
Views: make(map[string]ViewSetting),
listeners: make(map[string]ViewConfigListener),
}
}
// Reset clears out configurations.
func (v *CustomView) Reset() {
for k := range v.Views {
delete(v.Views, k)
}
}
// Load loads view configurations.
func (v *CustomView) Load(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.ViewsSchema, bb); err != nil {
slog.Warn("Validation failed. Please update your config and restart!",
slogs.Path, path,
slogs.Error, err,
)
}
var in CustomView
if err := yaml.Unmarshal(bb, &in); err != nil {
return err
}
v.Views = in.Views
v.fireConfigChanged()
return nil
}
// AddListeners registers a new listener for various commands.
func (v *CustomView) AddListeners(l ViewConfigListener, cmds ...string) {
for _, cmd := range cmds {
if cmd != "" {
v.listeners[cmd] = l
}
}
v.fireConfigChanged()
}
// AddListener registers a new listener.
func (v *CustomView) AddListener(cmd string, l ViewConfigListener) {
v.listeners[cmd] = l
v.fireConfigChanged()
}
// RemoveListener unregister a listener.
func (v *CustomView) RemoveListener(l ViewConfigListener) {
for k, list := range v.listeners {
if list == l {
delete(v.listeners, k)
}
}
}
func (v *CustomView) fireConfigChanged() {
cmds := slices.Collect(maps.Keys(v.listeners))
slices.SortFunc(cmds, func(a, b string) int {
switch {
case strings.Contains(a, "/") && !strings.Contains(b, "/"):
return 1
case !strings.Contains(a, "/") && strings.Contains(b, "/"):
return -1
default:
return strings.Compare(a, b)
}
})
type tuple struct {
cmd string
vs *ViewSetting
}
var victim tuple
for _, cmd := range cmds {
if vs := v.getVS(cmd, v.listeners[cmd].GetNamespace()); vs != nil {
slog.Debug("Reloading custom view settings", slogs.Command, cmd)
victim = tuple{cmd, vs}
break
}
victim = tuple{cmd, nil}
}
if victim.cmd != "" {
v.listeners[victim.cmd].ViewSettingsChanged(victim.vs)
}
}
func (v *CustomView) getVS(gvr, ns string) *ViewSetting {
if client.IsAllNamespaces(ns) {
ns = client.NamespaceAll
}
k := gvr
kk := slices.Collect(maps.Keys(v.Views))
slices.SortFunc(kk, strings.Compare)
slices.Reverse(kk)
for _, key := range kk {
if !strings.HasPrefix(key, gvr) && !strings.HasPrefix(gvr, key) {
continue
}
switch {
case strings.Contains(key, "@"):
tt := strings.Split(key, "@")
if len(tt) != 2 {
break
}
nsk := gvr
if ns != "" {
nsk += "@" + ns
}
if rx, err := regexp.Compile(tt[1]); err == nil && rx.MatchString(nsk) {
vs := v.Views[key]
return &vs
}
case strings.HasPrefix(k, key):
kk := strings.Fields(k)
if len(kk) == 2 {
if v, ok := v.Views[kk[0]+"@"+kk[1]]; ok {
return &v
}
if key == kk[0] {
vs := v.Views[key]
return &vs
}
}
fallthrough
case key == k:
vs := v.Views[key]
return &vs
}
}
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/logger_test.go | internal/config/logger_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 TestNewLogger(t *testing.T) {
l := config.NewLogger()
l = l.Validate()
assert.Equal(t, int64(100), l.TailCount)
assert.Equal(t, 5000, l.BufferSize)
}
func TestLoggerValidate(t *testing.T) {
var l config.Logger
l = l.Validate()
assert.Equal(t, int64(100), l.TailCount)
assert.Equal(t, 5000, l.BufferSize)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/scans_test.go | internal/config/scans_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 TestScansShouldExclude(t *testing.T) {
uu := map[string]struct {
sc config.ImageScans
ns string
ll map[string]string
e bool
}{
"empty": {
sc: config.NewImageScans(),
},
"exclude-ns": {
sc: config.ImageScans{
Enable: true,
Exclusions: config.ScanExcludes{
Namespaces: []string{"ns-1", "ns-2", "ns-3"},
Labels: config.Labels{
"app": []string{"fred", "blee"},
},
},
},
ns: "ns-1",
ll: map[string]string{
"app": "freddy",
},
e: true,
},
"include-ns": {
sc: config.ImageScans{
Enable: true,
Exclusions: config.ScanExcludes{
Namespaces: []string{"ns-1", "ns-2", "ns-3"},
Labels: config.Labels{
"app": []string{"fred", "blee"},
},
},
},
ns: "ns-4",
ll: map[string]string{
"app": "bozo",
},
},
"exclude-labels": {
sc: config.ImageScans{
Enable: true,
Exclusions: config.ScanExcludes{
Namespaces: []string{"ns-1", "ns-2", "ns-3"},
Labels: config.Labels{
"app": []string{"fred", "blee"},
},
},
},
ns: "ns-4",
ll: map[string]string{
"app": "fred",
},
e: true,
},
"include-labels": {
sc: config.ImageScans{
Enable: true,
Exclusions: config.ScanExcludes{
Namespaces: []string{"ns-1", "ns-2", "ns-3"},
Labels: config.Labels{
"app": []string{"fred", "blee"},
},
},
},
ns: "ns-4",
ll: map[string]string{
"app": "freddy",
},
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, u.sc.ShouldExclude(u.ns, u.ll))
})
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/files.go | internal/config/files.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package config
import (
_ "embed"
"errors"
"io/fs"
"log/slog"
"os"
"path/filepath"
"github.com/adrg/xdg"
"github.com/derailed/k9s/internal/config/data"
"github.com/derailed/k9s/internal/slogs"
)
const (
// K9sEnvConfigDir represents k9s configuration dir env var.
K9sEnvConfigDir = "K9S_CONFIG_DIR"
// K9sEnvLogsDir represents k9s logs dir env var.
K9sEnvLogsDir = "K9S_LOGS_DIR"
// AppName tracks k9s app name.
AppName = "k9s"
K9sLogsFile = "k9s.log"
)
var (
//go:embed templates/benchmarks.yaml
// benchmarkTpl tracks benchmark default config template
benchmarkTpl []byte
//go:embed templates/aliases.yaml
// aliasesTpl tracks aliases default config template
aliasesTpl []byte
//go:embed templates/hotkeys.yaml
// hotkeysTpl tracks hotkeys default config template
hotkeysTpl []byte
//go:embed templates/stock-skin.yaml
// stockSkinTpl tracks stock skin template
stockSkinTpl []byte
)
var (
// AppConfigDir tracks main k9s config home directory.
AppConfigDir string
// AppSkinsDir tracks skins data directory.
AppSkinsDir string
// AppBenchmarksDir tracks benchmarks results directory.
AppBenchmarksDir string
// AppDumpsDir tracks screen dumps data directory.
AppDumpsDir string
// AppContextsDir tracks contexts data directory.
AppContextsDir string
// AppConfigFile tracks k9s config file.
AppConfigFile string
// AppLogFile tracks k9s logs file.
AppLogFile string
// AppViewsFile tracks custom views config file.
AppViewsFile string
// AppAliasesFile tracks aliases config file.
AppAliasesFile string
// AppPluginsFile tracks plugins config file.
AppPluginsFile string
// AppHotKeysFile tracks hotkeys config file.
AppHotKeysFile string
)
// InitLogLoc initializes K9s logs location.
func InitLogLoc() error {
var appLogDir string
switch {
case isEnvSet(K9sEnvLogsDir):
appLogDir = os.Getenv(K9sEnvLogsDir)
case isEnvSet(K9sEnvConfigDir):
tmpDir, err := UserTmpDir()
if err != nil {
return err
}
appLogDir = tmpDir
default:
var err error
appLogDir, err = xdg.StateFile(AppName)
if err != nil {
return err
}
}
if err := data.EnsureFullPath(appLogDir, data.DefaultDirMod); err != nil {
return err
}
AppLogFile = filepath.Join(appLogDir, K9sLogsFile)
return nil
}
// InitLocs initializes k9s artifacts locations.
func InitLocs() error {
if isEnvSet(K9sEnvConfigDir) {
return initK9sEnvLocs()
}
return initXDGLocs()
}
func initK9sEnvLocs() error {
AppConfigDir = os.Getenv(K9sEnvConfigDir)
if err := data.EnsureFullPath(AppConfigDir, data.DefaultDirMod); err != nil {
return err
}
AppDumpsDir = filepath.Join(AppConfigDir, "screen-dumps")
if err := data.EnsureFullPath(AppDumpsDir, data.DefaultDirMod); err != nil {
slog.Warn("Unable to create screen-dumps dir", slogs.Dir, AppDumpsDir, slogs.Error, err)
}
AppBenchmarksDir = filepath.Join(AppConfigDir, "benchmarks")
if err := data.EnsureFullPath(AppBenchmarksDir, data.DefaultDirMod); err != nil {
slog.Warn("Unable to create benchmarks dir",
slogs.Dir, AppBenchmarksDir,
slogs.Error, err,
)
}
AppSkinsDir = filepath.Join(AppConfigDir, "skins")
if err := data.EnsureFullPath(AppSkinsDir, data.DefaultDirMod); err != nil {
slog.Warn("Unable to create skins dir",
slogs.Dir, AppSkinsDir,
slogs.Error, err,
)
}
AppContextsDir = filepath.Join(AppConfigDir, "clusters")
if err := data.EnsureFullPath(AppContextsDir, data.DefaultDirMod); err != nil {
slog.Warn("Unable to create clusters dir",
slogs.Dir, AppContextsDir,
slogs.Error, err,
)
}
AppConfigFile = filepath.Join(AppConfigDir, data.MainConfigFile)
AppHotKeysFile = filepath.Join(AppConfigDir, "hotkeys.yaml")
AppAliasesFile = filepath.Join(AppConfigDir, "aliases.yaml")
AppPluginsFile = filepath.Join(AppConfigDir, "plugins.yaml")
AppViewsFile = filepath.Join(AppConfigDir, "views.yaml")
return nil
}
func initXDGLocs() error {
var err error
AppConfigDir, err = xdg.ConfigFile(AppName)
if err != nil {
return err
}
AppConfigFile, err = xdg.ConfigFile(filepath.Join(AppName, data.MainConfigFile))
if err != nil {
return err
}
AppHotKeysFile = filepath.Join(AppConfigDir, "hotkeys.yaml")
AppAliasesFile = filepath.Join(AppConfigDir, "aliases.yaml")
AppPluginsFile = filepath.Join(AppConfigDir, "plugins.yaml")
AppViewsFile = filepath.Join(AppConfigDir, "views.yaml")
AppSkinsDir = filepath.Join(AppConfigDir, "skins")
if e := data.EnsureFullPath(AppSkinsDir, data.DefaultDirMod); e != nil {
slog.Warn("No skins dir detected", slogs.Error, e)
}
AppDumpsDir, err = xdg.StateFile(filepath.Join(AppName, "screen-dumps"))
if err != nil {
return err
}
AppBenchmarksDir, err = xdg.StateFile(filepath.Join(AppName, "benchmarks"))
if err != nil {
slog.Warn("No benchmarks dir detected",
slogs.Dir, AppBenchmarksDir,
slogs.Error, err,
)
}
dataDir, err := xdg.DataFile(AppName)
if err != nil {
return err
}
AppContextsDir = filepath.Join(dataDir, "clusters")
if err := data.EnsureFullPath(AppContextsDir, data.DefaultDirMod); err != nil {
slog.Warn("No context dir detected",
slogs.Dir, AppContextsDir,
slogs.Error, err,
)
}
return nil
}
// AppContextDir generates a valid context config dir.
func AppContextDir(cluster, context string) string {
return filepath.Join(AppContextsDir, data.SanitizeContextSubpath(cluster, context))
}
// AppContextAliasesFile generates a valid context specific aliases file path.
func AppContextAliasesFile(cluster, context string) string {
return filepath.Join(AppContextsDir, data.SanitizeContextSubpath(cluster, context), "aliases.yaml")
}
// AppContextPluginsFile generates a valid context specific plugins file path.
func AppContextPluginsFile(cluster, context string) string {
return filepath.Join(AppContextsDir, data.SanitizeContextSubpath(cluster, context), "plugins.yaml")
}
// AppContextHotkeysFile generates a valid context specific hotkeys file path.
func AppContextHotkeysFile(cluster, context string) string {
return filepath.Join(AppContextsDir, data.SanitizeContextSubpath(cluster, context), "hotkeys.yaml")
}
// AppContextConfig generates a valid context config file path.
func AppContextConfig(cluster, context string) string {
return filepath.Join(AppContextDir(cluster, context), data.MainConfigFile)
}
// DumpsDir generates a valid context dump directory.
func DumpsDir(cluster, context string) (string, error) {
dir := filepath.Join(AppDumpsDir, data.SanitizeContextSubpath(cluster, context))
return dir, data.EnsureDirPath(dir, data.DefaultDirMod)
}
// EnsureBenchmarksDir generates a valid benchmark results directory.
func EnsureBenchmarksDir(cluster, context string) (string, error) {
dir := filepath.Join(AppBenchmarksDir, data.SanitizeContextSubpath(cluster, context))
return dir, data.EnsureDirPath(dir, data.DefaultDirMod)
}
// EnsureBenchmarksCfgFile generates a valid benchmark file.
func EnsureBenchmarksCfgFile(cluster, context string) (string, error) {
f := filepath.Join(AppContextDir(cluster, context), "benchmarks.yaml")
if err := data.EnsureDirPath(f, data.DefaultDirMod); err != nil {
return "", err
}
if _, err := os.Stat(f); errors.Is(err, fs.ErrNotExist) {
return f, os.WriteFile(f, benchmarkTpl, data.DefaultFileMod)
}
return f, nil
}
// EnsureAliasesCfgFile generates a valid aliases file.
func EnsureAliasesCfgFile() (string, error) {
f := filepath.Join(AppConfigDir, "aliases.yaml")
if err := data.EnsureDirPath(f, data.DefaultDirMod); err != nil {
return "", err
}
if _, err := os.Stat(f); errors.Is(err, fs.ErrNotExist) {
return f, os.WriteFile(f, aliasesTpl, data.DefaultFileMod)
}
return f, nil
}
// EnsureHotkeysCfgFile generates a valid hotkeys file.
func EnsureHotkeysCfgFile() (string, error) {
f := filepath.Join(AppConfigDir, "hotkeys.yaml")
if err := data.EnsureDirPath(f, data.DefaultDirMod); err != nil {
return "", err
}
if _, err := os.Stat(f); errors.Is(err, fs.ErrNotExist) {
return f, os.WriteFile(f, hotkeysTpl, data.DefaultFileMod)
}
return f, nil
}
// SkinFileFromName generate skin file path from spec.
func SkinFileFromName(n string) string {
if n == "" {
n = "stock"
}
return filepath.Join(AppSkinsDir, n+".yaml")
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/files_int_test.go | internal/config/files_int_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package config
import (
"os"
"path/filepath"
"testing"
"github.com/adrg/xdg"
"github.com/derailed/k9s/internal/config/data"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_initXDGLocs(t *testing.T) {
tmp, err := UserTmpDir()
require.NoError(t, err)
require.NoError(t, os.Unsetenv("XDG_CONFIG_HOME"))
require.NoError(t, os.Unsetenv("XDG_CACHE_HOME"))
require.NoError(t, os.Unsetenv("XDG_STATE_HOME"))
require.NoError(t, os.Unsetenv("XDG_DATA_HOME"))
require.NoError(t, os.Setenv("XDG_CONFIG_HOME", filepath.Join(tmp, "k9s-xdg", "config")))
require.NoError(t, os.Setenv("XDG_CACHE_HOME", filepath.Join(tmp, "k9s-xdg", "cache")))
require.NoError(t, os.Setenv("XDG_STATE_HOME", filepath.Join(tmp, "k9s-xdg", "state")))
require.NoError(t, os.Setenv("XDG_DATA_HOME", filepath.Join(tmp, "k9s-xdg", "data")))
xdg.Reload()
uu := map[string]struct {
configDir string
configFile string
benchmarksDir string
contextsDir string
contextHotkeysFile string
contextConfig string
dumpsDir string
benchDir string
hkFile string
}{
"check-env": {
configDir: filepath.Join(tmp, "k9s-xdg", "config", "k9s"),
configFile: filepath.Join(tmp, "k9s-xdg", "config", "k9s", data.MainConfigFile),
benchmarksDir: filepath.Join(tmp, "k9s-xdg", "state", "k9s", "benchmarks"),
contextsDir: filepath.Join(tmp, "k9s-xdg", "data", "k9s", "clusters"),
contextHotkeysFile: filepath.Join(tmp, "k9s-xdg", "data", "k9s", "clusters", "cl-1", "ct-1-1", "hotkeys.yaml"),
contextConfig: filepath.Join(tmp, "k9s-xdg", "data", "k9s", "clusters", "cl-1", "ct-1-1", data.MainConfigFile),
dumpsDir: filepath.Join(tmp, "k9s-xdg", "state", "k9s", "screen-dumps", "cl-1", "ct-1-1"),
benchDir: filepath.Join(tmp, "k9s-xdg", "state", "k9s", "benchmarks", "cl-1", "ct-1-1"),
hkFile: filepath.Join(tmp, "k9s-xdg", "config", "k9s", "hotkeys.yaml"),
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
require.NoError(t, initXDGLocs())
assert.Equal(t, u.configDir, AppConfigDir)
assert.Equal(t, u.configFile, AppConfigFile)
assert.Equal(t, u.benchmarksDir, AppBenchmarksDir)
assert.Equal(t, u.contextsDir, AppContextsDir)
assert.Equal(t, u.contextHotkeysFile, AppContextHotkeysFile("cl-1", "ct-1-1"))
assert.Equal(t, u.contextConfig, AppContextConfig("cl-1", "ct-1-1"))
dir, err := DumpsDir("cl-1", "ct-1-1")
require.NoError(t, err)
assert.Equal(t, u.dumpsDir, dir)
bdir, err := EnsureBenchmarksDir("cl-1", "ct-1-1")
require.NoError(t, err)
assert.Equal(t, u.benchDir, bdir)
hk, err := EnsureHotkeysCfgFile()
require.NoError(t, err)
assert.Equal(t, u.hkFile, hk)
})
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/color.go | internal/config/color.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package config
import (
"fmt"
"github.com/derailed/tcell/v2"
)
const (
// DefaultColor represents a default color.
DefaultColor Color = "default"
// TransparentColor represents the terminal bg color.
TransparentColor Color = "-"
)
// Colors tracks multiple colors.
type Colors []Color
// Colors converts series string colors to colors.
func (c Colors) Colors() []tcell.Color {
cc := make([]tcell.Color, 0, len(c))
for _, color := range c {
cc = append(cc, color.Color())
}
return cc
}
// Color represents a color.
type Color string
// NewColor returns a new color.
func NewColor(c string) Color {
return Color(c)
}
// String returns color as string.
func (c Color) String() string {
if c.isHex() {
return string(c)
}
if c == DefaultColor {
return "-"
}
col := c.Color().TrueColor().Hex()
if col < 0 {
return "-"
}
return fmt.Sprintf("#%06x", col)
}
func (c Color) isHex() bool {
return len(c) == 7 && c[0] == '#'
}
// Color returns a view color.
func (c Color) Color() tcell.Color {
if c == DefaultColor {
return tcell.ColorDefault
}
return tcell.GetColor(string(c)).TrueColor()
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/scans.go | internal/config/scans.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package config
// Labels tracks a collection of labels.
type Labels map[string][]string
func (l Labels) exclude(k, val string) bool {
vv, ok := l[k]
if !ok {
return false
}
for _, v := range vv {
if v == val {
return true
}
}
return false
}
// ScanExcludes tracks vul scan exclusions.
type ScanExcludes struct {
Namespaces []string `json:"namespaces" yaml:"namespaces"`
Labels Labels `json:"labels" yaml:"labels"`
}
func newScanExcludes() ScanExcludes {
return ScanExcludes{
Labels: make(Labels),
}
}
func (b ScanExcludes) exclude(ns string, ll map[string]string) bool {
for _, nss := range b.Namespaces {
if nss == ns {
return true
}
}
for k, v := range ll {
if b.Labels.exclude(k, v) {
return true
}
}
return false
}
// ImageScans tracks vul scans options.
type ImageScans struct {
Enable bool `json:"enable" yaml:"enable"`
Exclusions ScanExcludes `json:"exclusions" yaml:"exclusions"`
}
// NewImageScans returns a new instance.
func NewImageScans() ImageScans {
return ImageScans{
Exclusions: newScanExcludes(),
}
}
// ShouldExclude checks if scan should be excluded given ns/labels
func (i ImageScans) ShouldExclude(ns string, ll map[string]string) bool {
if !i.Enable {
return false
}
return i.Exclusions.exclude(ns, ll)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/config_test.go | internal/config/config_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package config_test
import (
"errors"
"fmt"
"log/slog"
"os"
"path/filepath"
"testing"
"github.com/adrg/xdg"
"github.com/derailed/k9s/internal/client"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/config/data"
"github.com/derailed/k9s/internal/config/mock"
m "github.com/petergtz/pegomock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"k8s.io/cli-runtime/pkg/genericclioptions"
)
func init() {
slog.SetDefault(slog.New(slog.DiscardHandler))
}
func TestConfigSave(t *testing.T) {
config.AppConfigFile = "/tmp/k9s-test/k9s.yaml"
sd := "/tmp/k9s-test/screen-dumps"
cl, ct := "cl-1", "ct-1-1"
_ = os.RemoveAll(("/tmp/k9s-test"))
uu := map[string]struct {
ct string
flags *genericclioptions.ConfigFlags
k9sFlags *config.Flags
}{
"happy": {
ct: "ct-1-1",
flags: &genericclioptions.ConfigFlags{
ClusterName: &cl,
Context: &ct,
},
k9sFlags: &config.Flags{
ScreenDumpDir: &sd,
},
},
}
for k, u := range uu {
xdg.Reload()
t.Run(k, func(t *testing.T) {
c := mock.NewMockConfig(t)
_, err := c.K9s.ActivateContext(u.ct)
require.NoError(t, err)
if u.flags != nil {
c.K9s.Override(u.k9sFlags)
require.NoError(t, c.Refine(u.flags, u.k9sFlags, client.NewConfig(u.flags)))
}
require.NoError(t, c.Save(true))
bb, err := os.ReadFile(config.AppConfigFile)
require.NoError(t, err)
ee, err := os.ReadFile("testdata/configs/default.yaml")
require.NoError(t, err)
assert.Equal(t, string(ee), string(bb))
})
}
}
func TestSetActiveView(t *testing.T) {
var (
cfgFile = "testdata/kubes/test.yaml"
view = "dp"
)
uu := map[string]struct {
ct string
flags *genericclioptions.ConfigFlags
k9sFlags *config.Flags
view string
e string
}{
"empty": {
view: data.DefaultView,
e: data.DefaultView,
},
"not-exists": {
ct: "fred",
view: data.DefaultView,
e: data.DefaultView,
},
"happy": {
ct: "ct-1-1",
view: "xray",
e: "xray",
},
"cli-override": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &cfgFile,
},
k9sFlags: &config.Flags{
Command: &view,
},
ct: "ct-1-1",
view: "xray",
e: "dp",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
c := mock.NewMockConfig(t)
_, _ = c.K9s.ActivateContext(u.ct)
if u.flags != nil {
require.NoError(t, c.Refine(u.flags, nil, client.NewConfig(u.flags)))
c.K9s.Override(u.k9sFlags)
}
c.SetActiveView(u.view)
assert.Equal(t, u.e, c.ActiveView())
})
}
}
func TestActiveContextName(t *testing.T) {
var (
cfgFile = "testdata/kubes/test.yaml"
ct2 = "ct-1-2"
)
uu := map[string]struct {
flags *genericclioptions.ConfigFlags
k9sFlags *config.Flags
ct string
e string
}{
"empty": {},
"happy": {
ct: "ct-1-1",
e: "ct-1-1",
},
"cli-override": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &cfgFile,
Context: &ct2,
},
k9sFlags: &config.Flags{},
ct: "ct-1-1",
e: "ct-1-2",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
c := mock.NewMockConfig(t)
_, _ = c.K9s.ActivateContext(u.ct)
if u.flags != nil {
require.NoError(t, c.Refine(u.flags, nil, client.NewConfig(u.flags)))
c.K9s.Override(u.k9sFlags)
}
assert.Equal(t, u.e, c.ActiveContextName())
})
}
}
func TestActiveView(t *testing.T) {
var (
cfgFile = "testdata/kubes/test.yaml"
view = "dp"
)
uu := map[string]struct {
ct string
flags *genericclioptions.ConfigFlags
k9sFlags *config.Flags
e string
}{
"empty": {
e: data.DefaultView,
},
"not-exists": {
ct: "fred",
e: data.DefaultView,
},
"happy": {
ct: "ct-1-1",
e: data.DefaultView,
},
"happy1": {
ct: "ct-1-2",
e: data.DefaultView,
},
"cli-override": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &cfgFile,
},
k9sFlags: &config.Flags{
Command: &view,
},
e: "dp",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
c := mock.NewMockConfig(t)
_, _ = c.K9s.ActivateContext(u.ct)
if u.flags != nil {
require.NoError(t, c.Refine(u.flags, nil, client.NewConfig(u.flags)))
c.K9s.Override(u.k9sFlags)
}
assert.Equal(t, u.e, c.ActiveView())
})
}
}
func TestFavNamespaces(t *testing.T) {
uu := map[string]struct {
ct string
e []string
}{
"empty": {},
"not-exists": {
ct: "fred",
},
"happy": {
ct: "ct-1-1",
e: []string{client.DefaultNamespace},
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
c := mock.NewMockConfig(t)
_, _ = c.K9s.ActivateContext(u.ct)
assert.Equal(t, u.e, c.FavNamespaces())
})
}
}
func TestContextAliasesPath(t *testing.T) {
uu := map[string]struct {
ct string
e string
}{
"empty": {},
"not-exists": {
ct: "fred",
},
"happy": {
ct: "ct-1-1",
e: "/tmp/test/cl-1/ct-1-1/aliases.yaml",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
c := mock.NewMockConfig(t)
_, _ = c.K9s.ActivateContext(u.ct)
assert.Equal(t, u.e, c.ContextAliasesPath())
})
}
}
func TestContextPluginsPath(t *testing.T) {
uu := map[string]struct {
ct, e string
err error
}{
"empty": {
err: errors.New(`no context found for: ""`),
},
"happy": {
ct: "ct-1-1",
e: "/tmp/test/cl-1/ct-1-1/plugins.yaml",
},
"not-exists": {
ct: "fred",
err: errors.New(`no context found for: "fred"`),
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
c := mock.NewMockConfig(t)
_, _ = c.K9s.ActivateContext(u.ct)
s, err := c.ContextPluginsPath()
if err != nil {
assert.Equal(t, u.err, err)
}
assert.Equal(t, u.e, s)
})
}
}
func TestConfigLoader(t *testing.T) {
uu := map[string]struct {
f string
err string
}{
"happy": {
f: "testdata/configs/k9s.yaml",
},
"toast": {
f: "testdata/configs/k9s_toast.yaml",
err: `k9s config file "testdata/configs/k9s_toast.yaml" load failed:
Additional property disablePodCounts is not allowed
Additional property shellPods is not allowed
Invalid type. Expected: boolean, given: string`,
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
cfg := config.NewConfig(nil)
if err := cfg.Load(u.f, true); err != nil {
assert.Equal(t, u.err, err.Error())
}
})
}
}
func TestConfigActivateContext(t *testing.T) {
uu := map[string]struct {
cl, ct string
err string
}{
"happy": {
ct: "ct-1-2",
cl: "cl-1",
},
"toast": {
ct: "fred",
cl: "cl-1",
err: `set current context failed. no context found for: "fred"`,
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
cfg := mock.NewMockConfig(t)
ct, err := cfg.ActivateContext(u.ct)
if err != nil {
assert.Equal(t, u.err, err.Error())
return
}
require.NoError(t, err)
assert.Equal(t, u.cl, ct.ClusterName)
})
}
}
func TestConfigCurrentContext(t *testing.T) {
var (
cfgFile = "testdata/kubes/test.yaml"
ct2 = "ct-1-2"
)
uu := map[string]struct {
flags *genericclioptions.ConfigFlags
err error
context string
cluster string
namespace string
}{
"override-context": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &cfgFile,
Context: &ct2,
},
cluster: "cl-1",
context: "ct-1-2",
namespace: "ns-2",
},
"use-current-context": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &cfgFile,
},
cluster: "cl-1",
context: "ct-1-1",
namespace: client.DefaultNamespace,
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
cfg := mock.NewMockConfig(t)
err := cfg.Refine(u.flags, nil, client.NewConfig(u.flags))
require.NoError(t, err)
ct, err := cfg.CurrentContext()
require.NoError(t, err)
assert.Equal(t, u.cluster, ct.ClusterName)
assert.Equal(t, u.namespace, ct.Namespace.Active)
})
}
}
func TestConfigRefine(t *testing.T) {
var (
cfgFile = "testdata/kubes/test.yaml"
cl1 = "cl-1"
ct2 = "ct-1-2"
ns1, ns2, nsx = "ns-1", "ns-2", "ns-x"
trueVal = true
)
uu := map[string]struct {
flags *genericclioptions.ConfigFlags
k9sFlags *config.Flags
err string
context string
cluster string
namespace string
}{
"no-override": {
namespace: "default",
},
"override-cluster": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &cfgFile,
ClusterName: &cl1,
},
cluster: "cl-1",
context: "ct-1-1",
namespace: client.DefaultNamespace,
},
"override-cluster-context": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &cfgFile,
ClusterName: &cl1,
Context: &ct2,
},
cluster: "cl-1",
context: "ct-1-2",
namespace: "ns-2",
},
"override-bad-cluster": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &cfgFile,
ClusterName: &ns1,
},
cluster: "cl-1",
context: "ct-1-1",
namespace: client.DefaultNamespace,
},
"override-ns": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &cfgFile,
Namespace: &ns2,
},
cluster: "cl-1",
context: "ct-1-1",
namespace: "ns-2",
},
"all-ns": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &cfgFile,
Namespace: &ns2,
},
k9sFlags: &config.Flags{
AllNamespaces: &trueVal,
},
cluster: "cl-1",
context: "ct-1-1",
namespace: client.NamespaceAll,
},
"override-bad-ns": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &cfgFile,
Namespace: &nsx,
},
cluster: "cl-1",
context: "ct-1-1",
namespace: "ns-x",
},
"override-context": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &cfgFile,
Context: &ct2,
},
cluster: "cl-1",
context: "ct-1-2",
namespace: "ns-2",
},
"override-bad-context": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &cfgFile,
Context: &ns1,
},
err: `k8sflags. unable to activate context "ns-1": no context found for: "ns-1"`,
},
"use-current-context": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &cfgFile,
},
cluster: "cl-1",
context: "ct-1-1",
namespace: client.DefaultNamespace,
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
cfg := mock.NewMockConfig(t)
err := cfg.Refine(u.flags, u.k9sFlags, client.NewConfig(u.flags))
if err != nil {
assert.Equal(t, u.err, err.Error())
} else {
require.NoError(t, err)
assert.Equal(t, u.context, cfg.K9s.ActiveContextName())
assert.Equal(t, u.namespace, cfg.ActiveNamespace())
}
})
}
}
func TestConfigValidate(t *testing.T) {
cfg := mock.NewMockConfig(t)
cfg.SetConnection(mock.NewMockConnection())
require.NoError(t, cfg.Load("testdata/configs/k9s.yaml", true))
cfg.Validate("ct-1-1", "cl-1")
}
func TestConfigLoad(t *testing.T) {
cfg := mock.NewMockConfig(t)
require.NoError(t, cfg.Load("testdata/configs/k9s.yaml", true))
assert.InDelta(t, 2.0, cfg.K9s.RefreshRate, 0.001)
assert.Equal(t, int64(200), cfg.K9s.Logger.TailCount)
assert.Equal(t, 2000, cfg.K9s.Logger.BufferSize)
}
func TestConfigLoadCrap(t *testing.T) {
cfg := mock.NewMockConfig(t)
assert.Error(t, cfg.Load("testdata/configs/k9s_not_there.yaml", true))
}
func TestConfigSaveFile(t *testing.T) {
cfg := mock.NewMockConfig(t)
require.NoError(t, cfg.Load("testdata/configs/k9s.yaml", true))
cfg.K9s.RefreshRate = 100
cfg.K9s.GPUVendors = map[string]string{
"bozo": "bozo/gpu.com",
}
cfg.K9s.APIServerTimeout = "30s"
cfg.K9s.ReadOnly = true
cfg.K9s.Logger.TailCount = 500
cfg.K9s.Logger.BufferSize = 800
cfg.K9s.UI.UseFullGVRTitle = true
cfg.Validate("ct-1-1", "cl-1")
path := filepath.Join(os.TempDir(), "k9s.yaml")
require.NoError(t, cfg.SaveFile(path))
raw, err := os.ReadFile(path)
require.NoError(t, err)
ee, err := os.ReadFile("testdata/configs/expected.yaml")
require.NoError(t, err)
assert.Equal(t, string(ee), string(raw))
}
func TestConfigReset(t *testing.T) {
cfg := mock.NewMockConfig(t)
require.NoError(t, cfg.Load("testdata/configs/k9s.yaml", true))
cfg.Reset()
cfg.Validate("ct-1-1", "cl-1")
path := filepath.Join(os.TempDir(), "k9s.yaml")
require.NoError(t, cfg.SaveFile(path))
bb, err := os.ReadFile(path)
require.NoError(t, err)
ee, err := os.ReadFile("testdata/configs/k9s.yaml")
require.NoError(t, err)
assert.Equal(t, string(ee), string(bb))
}
// Helpers...
func TestSetup(t *testing.T) {
m.RegisterMockTestingT(t)
m.RegisterMockFailHandler(func(m string, i ...int) {
fmt.Println("Boom!", m, i)
})
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/alias_test.go | internal/config/alias_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package config_test
import (
"maps"
"os"
"path"
"slices"
"testing"
"github.com/derailed/k9s/internal/client"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/config/data"
"github.com/derailed/k9s/internal/view/cmd"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAliasClear(t *testing.T) {
a := testAliases()
a.Clear()
assert.Empty(t, slices.Collect(maps.Keys(a.Alias)))
}
func TestAliasKeys(t *testing.T) {
a := testAliases()
kk := maps.Keys(a.Alias)
assert.Equal(t, []string{"a1", "a11", "a2", "a3"}, slices.Sorted(kk))
}
func TestAliasShortNames(t *testing.T) {
a := testAliases()
ess := config.ShortNames{
gvr1: []string{"a1", "a11"},
gvr2: []string{"a2"},
gvr3: []string{"a3"},
}
ss := a.ShortNames()
assert.Len(t, ss, len(ess))
for k, v := range ss {
v1, ok := ess[k]
assert.True(t, ok, "missing: %q", k)
slices.Sort(v)
assert.Equal(t, v1, v)
}
}
func TestAliasDefine(t *testing.T) {
type aliasDef struct {
gvr *client.GVR
aliases []string
}
uu := map[string]struct {
aliases []aliasDef
registeredCommands map[string]*client.GVR
}{
"simple": {
aliases: []aliasDef{
{
gvr: client.NewGVR("one"),
aliases: []string{"blee", "duh"},
},
},
registeredCommands: map[string]*client.GVR{
"blee": client.NewGVR("one"),
"duh": client.NewGVR("one"),
},
},
"duplicates": {
aliases: []aliasDef{
{
gvr: client.NewGVR("one"),
aliases: []string{"blee", "duh"},
}, {
gvr: client.NewGVR("two"),
aliases: []string{"blee", "duh", "fred", "zorg"},
},
},
registeredCommands: map[string]*client.GVR{
"blee": client.NewGVR("one"),
"duh": client.NewGVR("one"),
"fred": client.NewGVR("two"),
"zorg": client.NewGVR("two"),
},
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
configAlias := config.NewAliases()
for _, aliases := range u.aliases {
for _, a := range aliases.aliases {
configAlias.Define(aliases.gvr, a)
}
}
for alias, cmd := range u.registeredCommands {
v, ok := configAlias.Get(alias)
assert.True(t, ok)
assert.Equal(t, cmd, v, "Wrong command for alias "+alias)
}
})
}
}
func TestAliasesLoad(t *testing.T) {
config.AppConfigDir = "testdata/aliases"
a := config.NewAliases()
require.NoError(t, a.Load(path.Join(config.AppConfigDir, "plain.yaml")))
assert.Len(t, a.Alias, 55)
}
func TestAliasesSave(t *testing.T) {
require.NoError(t, data.EnsureFullPath("/tmp/test-aliases", data.DefaultDirMod))
defer require.NoError(t, os.RemoveAll("/tmp/test-aliases"))
config.AppAliasesFile = "/tmp/test-aliases/aliases.yaml"
a := testAliases()
c := len(a.Alias)
assert.Len(t, a.Alias, c)
require.NoError(t, a.Save())
require.NoError(t, a.LoadFile(config.AppAliasesFile))
assert.Len(t, a.Alias, c)
}
func TestAliasResolve(t *testing.T) {
uu := map[string]struct {
exp string
ok bool
gvr *client.GVR
cmd *cmd.Interpreter
}{
"gvr": {
exp: "v1/pods",
ok: true,
gvr: client.PodGVR,
cmd: cmd.NewInterpreter("v1/pods"),
},
"kind": {
exp: "pod",
ok: true,
gvr: client.PodGVR,
cmd: cmd.NewInterpreter("v1/pods"),
},
"plural": {
exp: "pods",
ok: true,
gvr: client.PodGVR,
cmd: cmd.NewInterpreter("v1/pods"),
},
"short-name": {
exp: "po",
ok: true,
gvr: client.PodGVR,
cmd: cmd.NewInterpreter("v1/pods"),
},
"short-name-with-args": {
exp: "po 'a in (b,c)' @zorb bozo",
ok: true,
gvr: client.PodGVR,
cmd: cmd.NewInterpreter("v1/pods 'a in (b,c)' @zorb bozo"),
},
"alias": {
exp: "pipo",
ok: true,
gvr: client.PodGVR,
cmd: cmd.NewInterpreter("v1/pods"),
},
"toast-command": {
exp: "zorg",
},
"alias-no-args": {
exp: "wkl",
ok: true,
gvr: client.WkGVR,
cmd: cmd.NewInterpreter("workloads"),
},
"alias-ns-arg": {
exp: "pp",
ok: true,
gvr: client.PodGVR,
cmd: cmd.NewInterpreter("v1/pods default"),
},
"multi-alias-ns-inception": {
exp: "ppo",
ok: true,
gvr: client.PodGVR,
cmd: cmd.NewInterpreter("v1/pods 'a=b,b=c' default"),
},
"full-alias": {
exp: "ppc",
ok: true,
gvr: client.PodGVR,
cmd: cmd.NewInterpreter("v1/pods @fred 'app=fred' default"),
},
"plain-filter": {
exp: "po /fred @bozo ns-1",
ok: true,
gvr: client.PodGVR,
cmd: cmd.NewInterpreter("v1/pods /fred @bozo ns-1"),
},
"alias-filter": {
exp: "pipo /fred @bozo ns-1",
ok: true,
gvr: client.PodGVR,
cmd: cmd.NewInterpreter("v1/pods /fred @bozo ns-1"),
},
"complex-filter": {
exp: "ppc /fred @bozo ns-1",
ok: true,
gvr: client.PodGVR,
cmd: cmd.NewInterpreter("v1/pods @bozo /fred 'app=fred' ns-1"),
},
"filtered": {
exp: "pc",
ok: true,
gvr: client.PodGVR,
cmd: cmd.NewInterpreter("v1/pods /cilium kube-system"),
},
"labels-in": {
exp: "ppp",
ok: true,
gvr: client.PodGVR,
cmd: cmd.NewInterpreter("v1/pods 'app in (be,fe)'"),
},
}
a := config.NewAliases()
a.Define(client.PodGVR, "po", "pipo", "pod")
a.Define(client.PodGVR, client.PodGVR.String())
a.Define(client.PodGVR, client.PodGVR.AsResourceName())
a.Define(client.WkGVR, client.WkGVR.String(), "workload", "wkl")
a.Define(client.NewGVR("pod default"), "pp")
a.Define(client.NewGVR("pipo a=b,b=c default"), "ppo")
a.Define(client.NewGVR("pod default app=fred @fred"), "ppc")
a.Define(client.NewGVR("pod /cilium kube-system"), "pc")
a.Define(client.NewGVR("pod 'app in (be,fe)'"), "ppp")
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
p := cmd.NewInterpreter(u.exp)
gvr, ok := a.Resolve(p)
assert.Equal(t, u.ok, ok)
if ok {
assert.Equal(t, u.gvr, gvr)
assert.Equal(t, u.cmd.GetLine(), p.GetLine())
}
})
}
}
// Helpers...
var (
gvr1 = client.NewGVR("gvr1")
gvr2 = client.NewGVR("gvr2")
gvr3 = client.NewGVR("gvr3")
)
func testAliases() *config.Aliases {
a := config.NewAliases()
a.Alias["a1"] = gvr1
a.Alias["a11"] = gvr1
a.Alias["a2"] = gvr2
a.Alias["a3"] = gvr3
return a
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/hotkey_test.go | internal/config/hotkey_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"
"github.com/stretchr/testify/require"
)
func TestHotKeyLoad(t *testing.T) {
h := config.NewHotKeys()
require.NoError(t, h.LoadHotKeys("testdata/hotkeys/hotkeys.yaml"))
assert.Len(t, h.HotKey, 1)
k, ok := h.HotKey["pods"]
assert.True(t, ok)
assert.Equal(t, "shift-0", k.ShortCut)
assert.Equal(t, "Launch pod view", k.Description)
assert.Equal(t, "pods", k.Command)
assert.True(t, k.KeepHistory)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/benchmark_test.go | internal/config/benchmark_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package config
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestBenchEmpty(t *testing.T) {
uu := map[string]struct {
b Benchmark
e bool
}{
"empty": {Benchmark{}, true},
"notEmpty": {newBenchmark(), false},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, u.b.Empty())
})
}
}
func TestBenchLoad(t *testing.T) {
uu := map[string]struct {
file string
c, n int
svcCount int
coCount int
}{
"goodConfig": {
"testdata/benchmarks/b_good.yaml",
2,
1000,
2,
0,
},
"malformed": {
"testdata/benchmarks/b_toast.yaml",
1,
200,
0,
0,
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
b, err := NewBench(u.file)
require.NoError(t, err)
assert.Equal(t, u.c, b.Benchmarks.Defaults.C)
assert.Equal(t, u.n, b.Benchmarks.Defaults.N)
assert.Len(t, b.Benchmarks.Services, u.svcCount)
assert.Len(t, b.Benchmarks.Containers, u.coCount)
})
}
}
func TestBenchServiceLoad(t *testing.T) {
uu := map[string]struct {
key string
c, n int
method, host, path string
http2 bool
body string
auth Auth
headers http.Header
}{
"s1": {
"default/nginx",
2,
1000,
"GET",
"10.10.10.10",
"/",
true,
`{"fred": "blee"}`,
Auth{"fred", "blee"},
http.Header{"Accept": []string{"text/html"}, "Content-Type": []string{"application/json"}},
},
"s2": {
"blee/fred",
10,
1500,
"POST",
"20.20.20.20",
"/zorg",
false,
`{"fred": "blee"}`,
Auth{"fred", "blee"},
http.Header{"Accept": []string{"text/html"}, "Content-Type": []string{"application/json"}},
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
b, err := NewBench("testdata/benchmarks/b_good.yaml")
require.NoError(t, err)
assert.Len(t, b.Benchmarks.Services, 2)
svc := b.Benchmarks.Services[u.key]
assert.Equal(t, u.c, svc.C)
assert.Equal(t, u.n, svc.N)
assert.Equal(t, u.method, svc.HTTP.Method)
assert.Equal(t, u.host, svc.HTTP.Host)
assert.Equal(t, u.path, svc.HTTP.Path)
assert.Equal(t, u.http2, svc.HTTP.HTTP2)
assert.Equal(t, u.body, svc.HTTP.Body)
assert.Equal(t, u.auth, svc.Auth)
assert.Equal(t, u.headers, svc.HTTP.Headers)
})
}
}
func TestBenchReLoad(t *testing.T) {
b, err := NewBench("testdata/benchmarks/b_containers.yaml")
require.NoError(t, err)
assert.Equal(t, 2, b.Benchmarks.Defaults.C)
require.NoError(t, b.Reload("testdata/benchmarks/b_containers_1.yaml"))
assert.Equal(t, 20, b.Benchmarks.Defaults.C)
}
func TestBenchLoadToast(t *testing.T) {
_, err := NewBench("testdata/toast.yaml")
assert.Error(t, err)
}
func TestBenchContainerLoad(t *testing.T) {
uu := map[string]struct {
key string
c, n int
method, host, path string
http2 bool
body string
auth Auth
headers http.Header
}{
"c1": {
"c1",
2,
1000,
"GET",
"10.10.10.10",
"/duh",
true,
`{"fred": "blee"}`,
Auth{"fred", "blee"},
http.Header{"Accept": []string{"text/html"}, "Content-Type": []string{"application/json"}},
},
"c2": {
"c2",
10,
1500,
"POST",
"20.20.20.20",
"/fred",
false,
`{"fred": "blee"}`,
Auth{"fred", "blee"},
http.Header{"Accept": []string{"text/html"}, "Content-Type": []string{"application/json"}},
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
b, err := NewBench("testdata/benchmarks/b_containers.yaml")
require.NoError(t, err)
assert.Len(t, b.Benchmarks.Services, 2)
co := b.Benchmarks.Containers[u.key]
assert.Equal(t, u.c, co.C)
assert.Equal(t, u.n, co.N)
assert.Equal(t, u.method, co.HTTP.Method)
assert.Equal(t, u.host, co.HTTP.Host)
assert.Equal(t, u.path, co.HTTP.Path)
assert.Equal(t, u.http2, co.HTTP.HTTP2)
assert.Equal(t, u.body, co.HTTP.Body)
assert.Equal(t, u.auth, co.Auth)
assert.Equal(t, u.headers, co.HTTP.Headers)
})
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/views_test.go | internal/config/views_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package config_test
import (
"log/slog"
"testing"
"github.com/derailed/k9s/internal/client"
"github.com/derailed/k9s/internal/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func init() {
slog.SetDefault(slog.New(slog.DiscardHandler))
}
func TestCustomViewLoad(t *testing.T) {
uu := map[string]struct {
cv *config.CustomView
path string
key string
e []string
}{
"empty": {},
"gvr": {
path: "testdata/views/views.yaml",
key: client.PodGVR.String(),
e: []string{"NAMESPACE", "NAME", "AGE", "IP"},
},
"gvr+ns": {
path: "testdata/views/views.yaml",
key: "v1/pods@default",
e: []string{"NAME", "IP", "AGE"},
},
}
for k, u := range uu {
t.Run(k, func(t *testing.T) {
cfg := config.NewCustomView()
require.NoError(t, cfg.Load(u.path))
assert.Equal(t, u.e, cfg.Views[u.key].Columns)
})
}
}
func TestViewSettingEquals(t *testing.T) {
uu := map[string]struct {
v1, v2 *config.ViewSetting
e bool
}{
"v1-nil-v2-nil": {
e: true,
},
"v1-v2-empty": {
v1: new(config.ViewSetting),
v2: new(config.ViewSetting),
e: true,
},
"v1-nil": {
v1: new(config.ViewSetting),
},
"nil-v2": {
v2: new(config.ViewSetting),
},
"v1-v2-blank": {
v1: &config.ViewSetting{
Columns: []string{"A"},
},
v2: new(config.ViewSetting),
},
"v1-v2-nil": {
v1: &config.ViewSetting{
Columns: []string{"A"},
},
},
"same": {
v1: &config.ViewSetting{
Columns: []string{"A", "B", "C"},
},
v2: &config.ViewSetting{
Columns: []string{"A", "B", "C"},
},
e: true,
},
"order": {
v1: &config.ViewSetting{
Columns: []string{"C", "A", "B"},
},
v2: &config.ViewSetting{
Columns: []string{"A", "B", "C"},
},
},
"delta": {
v1: &config.ViewSetting{
Columns: []string{"A", "B", "C"},
},
v2: &config.ViewSetting{
Columns: []string{"B"},
},
},
}
for k, u := range uu {
t.Run(k, func(t *testing.T) {
assert.Equalf(t, u.e, u.v1.Equals(u.v2), "%#v and %#v", 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/config/styles_test.go | internal/config/styles_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/derailed/tview"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewStyle(t *testing.T) {
s := config.NewStyles()
assert.Equal(t, config.Color("black"), s.K9s.Body.BgColor)
assert.Equal(t, config.Color("cadetblue"), s.K9s.Body.FgColor)
assert.Equal(t, config.Color("lightskyblue"), s.K9s.Frame.Status.NewColor)
}
func TestColor(t *testing.T) {
uu := map[string]tcell.Color{
"blah": tcell.ColorDefault,
"blue": tcell.ColorBlue.TrueColor(),
"#ffffff": tcell.NewHexColor(16777215),
"#ff0000": tcell.NewHexColor(16711680),
}
for k := range uu {
c, u := k, uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u, config.NewColor(c).Color())
})
}
}
func TestSkinHappy(t *testing.T) {
s := config.NewStyles()
require.NoError(t, s.Load("../../skins/black-and-wtf.yaml"))
s.Update()
assert.Equal(t, "#ffffff", s.Body().FgColor.String())
assert.Equal(t, "#000000", s.Body().BgColor.String())
assert.Equal(t, "#000000", s.Table().BgColor.String())
assert.Equal(t, tcell.ColorWhite.TrueColor(), s.FgColor())
assert.Equal(t, tcell.ColorBlack.TrueColor(), s.BgColor())
assert.Equal(t, tcell.ColorBlack.TrueColor(), tview.Styles.PrimitiveBackgroundColor)
}
func TestSkinLoad(t *testing.T) {
uu := map[string]struct {
f string
err string
}{
"not-exist": {
f: "testdata/skins/blee.yaml",
err: "open testdata/skins/blee.yaml: no such file or directory",
},
"toast": {
f: "testdata/skins/boarked.yaml",
err: `Additional property bgColor is not allowed
Additional property fgColor is not allowed
Additional property logoColor is not allowed
Invalid type. Expected: object, given: array`,
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
s := config.NewStyles()
err := s.Load(u.f)
if err != nil {
assert.Equal(t, u.err, err.Error())
}
assert.Equal(t, "#5f9ea0", s.Body().FgColor.String())
assert.Equal(t, "#000000", s.Body().BgColor.String())
assert.Equal(t, "#000000", s.Table().BgColor.String())
assert.Equal(t, tcell.ColorCadetBlue.TrueColor(), s.FgColor())
assert.Equal(t, tcell.ColorBlack.TrueColor(), s.BgColor())
assert.Equal(t, tcell.ColorBlack.TrueColor(), tview.Styles.PrimitiveBackgroundColor)
})
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/threshold.go | internal/config/threshold.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package config
const (
// SeverityLow tracks low severity.
SeverityLow SeverityLevel = iota
// SeverityMedium tracks medium severity level.
SeverityMedium
// SeverityHigh tracks high severity level.
SeverityHigh
)
// SeverityLevel tracks severity levels.
type SeverityLevel int
// Severity tracks a resource severity levels.
type Severity struct {
Critical int `yaml:"critical"`
Warn int `yaml:"warn"`
}
// NewSeverity returns a new instance.
func NewSeverity() *Severity {
return &Severity{
Critical: 90,
Warn: 70,
}
}
// Validate checks all thresholds and make sure we're cool. If not use defaults.
func (s *Severity) Validate() {
norm := NewSeverity()
if !validateRange(s.Warn) {
s.Warn = norm.Warn
}
if !validateRange(s.Critical) {
s.Critical = norm.Critical
}
}
func validateRange(v int) bool {
if v <= 0 || v > 100 {
return false
}
return true
}
// Threshold tracks threshold to alert user when exceeded.
type Threshold map[string]*Severity
// NewThreshold returns a new threshold.
func NewThreshold() Threshold {
return Threshold{
CPU: NewSeverity(),
MEM: NewSeverity(),
}
}
// Validate a namespace is setup correctly.
func (t Threshold) Validate() Threshold {
for _, k := range []string{CPU, MEM} {
v, ok := t[k]
if !ok {
t[k] = NewSeverity()
} else {
v.Validate()
}
}
return t
}
// LevelFor returns a defcon level for the current state.
func (t Threshold) LevelFor(k string, v int) SeverityLevel {
s, ok := t[k]
if !ok || v < 0 || v > 100 {
return SeverityLow
}
if v >= s.Critical {
return SeverityHigh
}
if v >= s.Warn {
return SeverityMedium
}
return SeverityLow
}
// SeverityColor returns a defcon level associated level.
func (t *Threshold) SeverityColor(k string, v int) string {
//nolint:exhaustive
switch t.LevelFor(k, v) {
case SeverityHigh:
return "red"
case SeverityMedium:
return "orangered"
default:
return "green"
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/styles_int_test.go | internal/config/styles_int_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package config
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_newStyle(t *testing.T) {
s := newStyle()
assert.Equal(t, Color("black"), s.Body.BgColor)
assert.Equal(t, Color("cadetblue"), s.Body.FgColor)
assert.Equal(t, Color("lightskyblue"), s.Frame.Status.NewColor)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/logger.go | internal/config/logger.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package config
const (
// DefaultLoggerTailCount tracks default log tail size.
DefaultLoggerTailCount = 100
// MaxLogThreshold sets the max value for log size.
MaxLogThreshold = 5_000
// DefaultSinceSeconds tracks default log age.
DefaultSinceSeconds = -1 // tail logs by default
)
// Logger tracks logger options.
type Logger struct {
TailCount int64 `json:"tail" yaml:"tail"`
BufferSize int `json:"buffer" yaml:"buffer"`
SinceSeconds int64 `json:"sinceSeconds" yaml:"sinceSeconds"`
TextWrap bool `json:"textWrap" yaml:"textWrap"`
DisableAutoscroll bool `json:"disableAutoscroll" yaml:"disableAutoscroll"`
ColumnLock bool `json:"columnLock" yaml:"columnLock"`
ShowTime bool `json:"showTime" yaml:"showTime"`
}
// NewLogger returns a new instance.
func NewLogger() Logger {
return Logger{
TailCount: DefaultLoggerTailCount,
BufferSize: MaxLogThreshold,
SinceSeconds: DefaultSinceSeconds,
}
}
// Validate checks thresholds and make sure we're cool. If not use defaults.
func (l Logger) Validate() Logger {
if l.TailCount <= 0 {
l.TailCount = DefaultLoggerTailCount
}
if l.TailCount > MaxLogThreshold {
l.TailCount = MaxLogThreshold
}
if l.BufferSize <= 0 || l.BufferSize > MaxLogThreshold {
l.BufferSize = MaxLogThreshold
}
if l.SinceSeconds == 0 {
l.SinceSeconds = DefaultSinceSeconds
}
return l
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/k9s_test.go | internal/config/k9s_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package config_test
import (
"errors"
"testing"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/config/mock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"k8s.io/cli-runtime/pkg/genericclioptions"
)
func TestK9sReload(t *testing.T) {
config.AppConfigDir = "/tmp/k9s-test"
cl, ct := "cl-1", "ct-1-1"
uu := map[string]struct {
k *config.K9s
cl, ct string
err error
}{
"no-context": {
k: config.NewK9s(
mock.NewMockConnection(),
mock.NewMockKubeSettings(&genericclioptions.ConfigFlags{
ClusterName: &cl,
Context: &ct,
}),
),
err: errors.New(`no context found for: ""`),
},
"set-context": {
k: config.NewK9s(
mock.NewMockConnection(),
mock.NewMockKubeSettings(&genericclioptions.ConfigFlags{
ClusterName: &cl,
Context: &ct,
}),
),
ct: "ct-1-1",
cl: "cl-1",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
_, _ = u.k.ActivateContext(u.ct)
assert.Equal(t, u.err, u.k.Reload())
ct, err := u.k.ActiveContext()
assert.Equal(t, u.err, err)
if err == nil {
assert.Equal(t, u.cl, ct.ClusterName)
}
})
}
}
func TestK9sMerge(t *testing.T) {
cl, ct := "cl-1", "ct-1-1"
uu := map[string]struct {
k1, k2 *config.K9s
ek *config.K9s
}{
"no-opt": {
k1: config.NewK9s(
mock.NewMockConnection(),
mock.NewMockKubeSettings(&genericclioptions.ConfigFlags{
ClusterName: &cl,
Context: &ct,
}),
),
ek: config.NewK9s(
mock.NewMockConnection(),
mock.NewMockKubeSettings(&genericclioptions.ConfigFlags{
ClusterName: &cl,
Context: &ct,
}),
),
},
"override": {
k1: &config.K9s{
LiveViewAutoRefresh: false,
ScreenDumpDir: "",
RefreshRate: 0,
MaxConnRetry: 0,
ReadOnly: false,
NoExitOnCtrlC: false,
UI: config.UI{},
SkipLatestRevCheck: false,
DisablePodCounting: false,
ShellPod: new(config.ShellPod),
ImageScans: config.ImageScans{},
Logger: config.Logger{},
Thresholds: nil,
},
k2: &config.K9s{
LiveViewAutoRefresh: true,
MaxConnRetry: 100,
ShellPod: config.NewShellPod(),
},
ek: &config.K9s{
LiveViewAutoRefresh: true,
ScreenDumpDir: "",
RefreshRate: 0,
MaxConnRetry: 100,
ReadOnly: false,
NoExitOnCtrlC: false,
UI: config.UI{},
SkipLatestRevCheck: false,
DisablePodCounting: false,
ShellPod: config.NewShellPod(),
ImageScans: config.ImageScans{},
Logger: config.Logger{},
Thresholds: nil,
},
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
u.k1.Merge(u.k2)
assert.Equal(t, u.ek, u.k1)
})
}
}
func TestContextScreenDumpDir(t *testing.T) {
cfg := mock.NewMockConfig(t)
_, err := cfg.K9s.ActivateContext("ct-1-1")
require.NoError(t, err)
require.NoError(t, cfg.Load("testdata/configs/k9s.yaml", true))
assert.Equal(t, "/tmp/k9s-test/screen-dumps/cl-1/ct-1-1", cfg.K9s.ContextScreenDumpDir())
}
func TestAppScreenDumpDir(t *testing.T) {
cfg := mock.NewMockConfig(t)
require.NoError(t, cfg.Load("testdata/configs/k9s.yaml", true))
assert.Equal(t, "/tmp/k9s-test/screen-dumps", 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/plugin.go | internal/config/plugin.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package config
import (
"bytes"
"errors"
"fmt"
"io/fs"
"log/slog"
"os"
"path/filepath"
"strings"
"github.com/adrg/xdg"
"github.com/derailed/k9s/internal/config/data"
"github.com/derailed/k9s/internal/config/json"
"github.com/derailed/k9s/internal/slogs"
"github.com/karrick/godirwalk"
"gopkg.in/yaml.v3"
)
type plugins map[string]Plugin
// Plugins represents a collection of plugins.
type Plugins struct {
Plugins plugins `yaml:"plugins"`
}
// Plugin describes a K9s plugin.
type Plugin struct {
Scopes []string `yaml:"scopes"`
Args []string `yaml:"args"`
ShortCut string `yaml:"shortCut"`
Override bool `yaml:"override"`
Pipes []string `yaml:"pipes"`
Description string `yaml:"description"`
Command string `yaml:"command"`
Confirm bool `yaml:"confirm"`
Background bool `yaml:"background"`
Dangerous bool `yaml:"dangerous"`
OverwriteOutput bool `yaml:"overwriteOutput"`
}
func (p Plugin) String() string {
return fmt.Sprintf("[%s] %s(%s)", p.ShortCut, p.Command, strings.Join(p.Args, " "))
}
// NewPlugins returns a new plugin.
func NewPlugins() Plugins {
return Plugins{
Plugins: make(map[string]Plugin),
}
}
// Load K9s plugins.
func (p Plugins) Load(path string, loadExtra bool) error {
var errs error
// Load from global config file
if err := p.load(AppPluginsFile); err != nil {
errs = errors.Join(errs, err)
}
// Load from cluster/context config
if err := p.load(path); err != nil {
errs = errors.Join(errs, err)
}
if !loadExtra {
return errs
}
// Load from XDG dirs
const k9sPluginsDir = "k9s/plugins"
for _, dir := range append(xdg.DataDirs, xdg.DataHome, xdg.ConfigHome) {
path := filepath.Join(dir, k9sPluginsDir)
if err := p.loadDir(path); err != nil {
errs = errors.Join(errs, err)
}
}
return errs
}
func (p *Plugins) load(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
}
scheme, err := data.JSONValidator.ValidatePlugins(bb)
if err != nil {
slog.Warn("Plugin schema validation failed",
slogs.Path, path,
slogs.Error, err,
)
return fmt.Errorf("plugin validation failed for %s: %w", path, err)
}
d := yaml.NewDecoder(bytes.NewReader(bb))
d.KnownFields(true)
switch scheme {
case json.PluginSchema:
var o Plugin
if err := yaml.Unmarshal(bb, &o); err != nil {
return fmt.Errorf("plugin unmarshal failed for %s: %w", path, err)
}
p.Plugins[strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))] = o
case json.PluginsSchema:
var oo Plugins
if err := yaml.Unmarshal(bb, &oo); err != nil {
return fmt.Errorf("plugin unmarshal failed for %s: %w", path, err)
}
for k := range oo.Plugins {
p.Plugins[k] = oo.Plugins[k]
}
case json.PluginMultiSchema:
var oo plugins
if err := yaml.Unmarshal(bb, &oo); err != nil {
return fmt.Errorf("plugin unmarshal failed for %s: %w", path, err)
}
for k := range oo {
p.Plugins[k] = oo[k]
}
}
return nil
}
func (p Plugins) loadDir(dir string) error {
if _, err := os.Stat(dir); errors.Is(err, fs.ErrNotExist) {
return nil
}
var errs error
errs = errors.Join(errs, godirwalk.Walk(dir, &godirwalk.Options{
FollowSymbolicLinks: true,
Callback: func(path string, de *godirwalk.Dirent) error {
if de.IsDir() || !isYamlFile(de.Name()) {
return nil
}
errs = errors.Join(errs, p.load(path))
return nil
},
ErrorCallback: func(osPathname string, err error) godirwalk.ErrorAction {
slog.Warn("Error at %s: %v - skipping node", slogs.Path, osPathname, slogs.Error, err)
return godirwalk.SkipNode
},
}))
return errs
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/flags_test.go | internal/config/flags_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 TestNewFlags(t *testing.T) {
config.AppDumpsDir = "/tmp/k9s-test/screen-dumps"
config.AppLogFile = "/tmp/k9s-test/k9s.log"
f := config.NewFlags()
assert.InDelta(t, 2.0, *f.RefreshRate, 0.001)
assert.Equal(t, "info", *f.LogLevel)
assert.Equal(t, "/tmp/k9s-test/k9s.log", *f.LogFile)
assert.Equal(t, config.AppDumpsDir, *f.ScreenDumpDir)
assert.Empty(t, *f.Command)
assert.False(t, *f.Headless)
assert.False(t, *f.Logoless)
assert.False(t, *f.AllNamespaces)
assert.False(t, *f.ReadOnly)
assert.False(t, *f.Write)
assert.False(t, *f.Crumbsless)
assert.False(t, *f.Splashless)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/helpers.go | internal/config/helpers.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package config
import (
"log/slog"
"os"
"os/user"
"path/filepath"
"github.com/derailed/k9s/internal/slogs"
)
const (
envPFAddress = "K9S_DEFAULT_PF_ADDRESS"
defaultPortFwdAddress = "localhost"
)
// IsBoolSet checks if a bool ptr is set.
func IsBoolSet(b *bool) bool {
return b != nil && *b
}
func isStringSet(s *string) bool {
return s != nil && *s != ""
}
func isYamlFile(file string) bool {
ext := filepath.Ext(file)
return ext == ".yml" || ext == ".yaml"
}
// isEnvSet checks if env var is set.
func isEnvSet(env string) bool {
return os.Getenv(env) != ""
}
// UserTmpDir returns the temp dir with the current user name.
func UserTmpDir() (string, error) {
u, err := user.Current()
if err != nil {
return "", err
}
dir := filepath.Join(os.TempDir(), u.Username, AppName)
return dir, nil
}
// MustK9sUser establishes current user identity or fail.
func MustK9sUser() string {
usr, err := user.Current()
if err != nil {
envUsr := os.Getenv("USER")
if envUsr != "" {
return envUsr
}
envUsr = os.Getenv("LOGNAME")
if envUsr != "" {
return envUsr
}
slog.Error("Die on retrieving user info", slogs.Error, err)
os.Exit(1)
}
return usr.Username
}
func defaultPFAddress() string {
if a := os.Getenv(envPFAddress); a != "" {
return a
}
return defaultPortFwdAddress
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/mock/test_helpers.go | internal/config/mock/test_helpers.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package mock
import (
"errors"
"fmt"
"io/fs"
"net/http"
"net/url"
"os"
"strings"
"testing"
"github.com/derailed/k9s/internal/client"
"github.com/derailed/k9s/internal/config"
"github.com/stretchr/testify/require"
version "k8s.io/apimachinery/pkg/version"
"k8s.io/cli-runtime/pkg/genericclioptions"
disk "k8s.io/client-go/discovery/cached/disk"
dynamic "k8s.io/client-go/dynamic"
kubernetes "k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd/api"
versioned "k8s.io/metrics/pkg/client/clientset/versioned"
)
func EnsureDir(d string) error {
if _, err := os.Stat(d); errors.Is(err, fs.ErrNotExist) {
return os.MkdirAll(d, 0700)
}
if err := os.RemoveAll(d); err != nil {
return err
}
return os.MkdirAll(d, 0700)
}
func NewMockConfig(t testing.TB) *config.Config {
if _, err := os.Stat("/tmp/test"); err == nil {
if e := os.RemoveAll("/tmp/test"); e != nil {
require.NoError(t, e)
}
}
config.AppContextsDir = "/tmp/test"
cl, ct := "cl-1", "ct-1-1"
flags := genericclioptions.ConfigFlags{
ClusterName: &cl,
Context: &ct,
}
cfg := config.NewConfig(
NewMockKubeSettings(&flags),
)
return cfg
}
type mockKubeSettings struct {
flags *genericclioptions.ConfigFlags
cts map[string]*api.Context
}
func NewMockKubeSettings(f *genericclioptions.ConfigFlags) mockKubeSettings {
_, idx, _ := strings.Cut(*f.ClusterName, "-")
ctId := "ct-" + idx
return mockKubeSettings{
flags: f,
cts: map[string]*api.Context{
ctId + "-1": {
Cluster: *f.ClusterName,
Namespace: "",
},
ctId + "-2": {
Cluster: *f.ClusterName,
Namespace: "ns-2",
},
ctId + "-3": {
Cluster: *f.ClusterName,
Namespace: client.DefaultNamespace,
},
"fred-blee": {
Cluster: "arn:aws:eks:eu-central-1:xxx:cluster/fred-blee",
Namespace: client.DefaultNamespace,
},
},
}
}
func (m mockKubeSettings) CurrentContextName() (string, error) {
return *m.flags.Context, nil
}
func (m mockKubeSettings) CurrentClusterName() (string, error) {
return *m.flags.ClusterName, nil
}
func (mockKubeSettings) CurrentNamespaceName() (string, error) {
return "default", nil
}
func (m mockKubeSettings) GetContext(s string) (*api.Context, error) {
ct, ok := m.cts[s]
if !ok {
return nil, fmt.Errorf("no context found for: %q", s)
}
return ct, nil
}
func (m mockKubeSettings) CurrentContext() (*api.Context, error) {
return m.GetContext(*m.flags.Context)
}
func (m mockKubeSettings) ContextNames() (map[string]struct{}, error) {
mm := make(map[string]struct{}, len(m.cts))
for k := range m.cts {
mm[k] = struct{}{}
}
return mm, nil
}
func (mockKubeSettings) SetProxy(func(*http.Request) (*url.URL, error)) {}
type mockConnection struct {
ct string
}
func NewMockConnection() mockConnection {
return mockConnection{}
}
func NewMockConnectionWithContext(ct string) mockConnection {
return mockConnection{ct: ct}
}
func (mockConnection) CanI(string, *client.GVR, string, []string) (bool, error) {
return true, nil
}
func (mockConnection) Config() *client.Config {
return nil
}
func (mockConnection) ConnectionOK() bool {
return false
}
func (mockConnection) Dial() (kubernetes.Interface, error) {
return nil, nil
}
func (mockConnection) DialLogs() (kubernetes.Interface, error) {
return nil, nil
}
func (mockConnection) SwitchContext(string) error {
return nil
}
func (mockConnection) CachedDiscovery() (*disk.CachedDiscoveryClient, error) {
return nil, nil
}
func (mockConnection) RestConfig() (*restclient.Config, error) {
return nil, nil
}
func (mockConnection) MXDial() (*versioned.Clientset, error) {
return nil, nil
}
func (mockConnection) DynDial() (dynamic.Interface, error) {
return nil, nil
}
func (mockConnection) HasMetrics() bool {
return false
}
func (mockConnection) ValidNamespaceNames() (client.NamespaceNames, error) {
return nil, nil
}
func (mockConnection) IsValidNamespace(string) bool {
return true
}
func (mockConnection) ServerVersion() (*version.Info, error) {
return nil, nil
}
func (mockConnection) CheckConnectivity() bool {
return false
}
func (m mockConnection) ActiveContext() string {
return m.ct
}
func (mockConnection) ActiveNamespace() string {
return ""
}
func (mockConnection) IsActiveNamespace(string) bool {
return false
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/json/validator_test.go | internal/config/json/validator_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package json_test
import (
"os"
"path/filepath"
"testing"
"github.com/derailed/k9s/internal/config/json"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestValidatePluginSnippet(t *testing.T) {
plugPath := "testdata/plugins/snippet.yaml"
bb, err := os.ReadFile(plugPath)
require.NoError(t, err)
p := json.NewValidator()
require.NoError(t, p.Validate(json.PluginSchema, bb), plugPath)
}
func TestValidatePlugins(t *testing.T) {
uu := map[string]struct {
path, schema string
err string
}{
"cool": {
path: "testdata/plugins/cool.yaml",
schema: json.PluginsSchema,
},
"toast": {
path: "testdata/plugins/toast.yaml",
schema: json.PluginsSchema,
err: "scopes is required\nshortCut is required",
},
"cool-snippet": {
path: "testdata/plugins/snippet.yaml",
schema: json.PluginSchema,
},
"cool-snippets": {
path: "testdata/plugins/snippets.yaml",
schema: json.PluginMultiSchema,
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
bb, err := os.ReadFile(u.path)
require.NoError(t, err)
v := json.NewValidator()
if err := v.Validate(u.schema, bb); err != nil {
assert.Equal(t, u.err, err.Error())
}
})
}
}
func TestValidatePluginDir(t *testing.T) {
plugDir := "../../../plugins"
ee, err := os.ReadDir(plugDir)
require.NoError(t, err)
for _, e := range ee {
if e.IsDir() {
continue
}
ext := filepath.Ext(e.Name())
if ext == ".md" {
continue
}
assert.Equal(t, ".yaml", ext, "expected yaml file: %q", e.Name())
assert.NotContains(t, "_", e.Name(), "underscore in: %q", e.Name())
bb, err := os.ReadFile(filepath.Join(plugDir, e.Name()))
require.NoError(t, err)
p := json.NewValidator()
require.NoError(t, p.Validate(json.PluginsSchema, bb), e.Name())
}
}
func TestValidateSkinDir(t *testing.T) {
skinDir := "../../../skins"
ee, err := os.ReadDir(skinDir)
require.NoError(t, err)
p := json.NewValidator()
for _, e := range ee {
if e.IsDir() {
continue
}
ext := filepath.Ext(e.Name())
assert.Equal(t, ".yaml", ext, "expected yaml file: %q", e.Name())
assert.NotContains(t, "_", e.Name(), "underscore in: %q", e.Name())
bb, err := os.ReadFile(filepath.Join(skinDir, e.Name()))
require.NoError(t, err)
require.NoError(t, p.Validate(json.SkinSchema, bb), e.Name())
}
}
func TestValidateSkin(t *testing.T) {
uu := map[string]struct {
f string
err string
}{
"happy": {
f: "testdata/skins/cool.yaml",
},
"toast": {
f: "testdata/skins/toast.yaml",
err: `Additional property bodys is not allowed`,
},
}
v := json.NewValidator()
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
bb, err := os.ReadFile(u.f)
require.NoError(t, err)
if err := v.Validate(json.SkinSchema, bb); err != nil {
assert.Equal(t, u.err, err.Error())
}
})
}
}
func TestValidateK9s(t *testing.T) {
uu := map[string]struct {
f string
err string
}{
"happy": {
f: "testdata/k9s/cool.yaml",
},
"toast": {
f: "testdata/k9s/toast.yaml",
err: `Additional property shellPods is not allowed`,
},
}
v := json.NewValidator()
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
bb, err := os.ReadFile(u.f)
require.NoError(t, err)
if err := v.Validate(json.K9sSchema, bb); err != nil {
assert.Equal(t, u.err, err.Error())
}
})
}
}
func TestValidateContext(t *testing.T) {
uu := map[string]struct {
f string
err string
}{
"happy": {
f: "testdata/context/cool.yaml",
},
"toast": {
f: "testdata/context/toast.yaml",
err: `Additional property fred is not allowed
Additional property namespaces is not allowed`,
},
}
v := json.NewValidator()
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
bb, err := os.ReadFile(u.f)
require.NoError(t, err)
if err := v.Validate(json.ContextSchema, bb); err != nil {
assert.Equal(t, u.err, err.Error())
}
})
}
}
func TestValidateAliases(t *testing.T) {
uu := map[string]struct {
f string
err string
}{
"happy": {
f: "testdata/aliases/cool.yaml",
},
"toast": {
f: "testdata/aliases/toast.yaml",
err: `Additional property alias is not allowed
aliases is required`,
},
}
v := json.NewValidator()
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
bb, err := os.ReadFile(u.f)
require.NoError(t, err)
if err := v.Validate(json.AliasesSchema, bb); err != nil {
assert.Equal(t, u.err, err.Error())
}
})
}
}
func TestValidateViews(t *testing.T) {
uu := map[string]struct {
f string
err string
}{
"happy": {
f: "testdata/views/cool.yaml",
},
"toast": {
f: "testdata/views/toast.yaml",
err: `Additional property cols is not allowed
Additional property sortCol is not allowed
Invalid type. Expected: object, given: null
columns is required`,
},
}
v := json.NewValidator()
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
bb, err := os.ReadFile(u.f)
require.NoError(t, err)
if err := v.Validate(json.ViewsSchema, bb); err != nil {
assert.Equal(t, u.err, err.Error())
}
})
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/json/validator.go | internal/config/json/validator.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package json
import (
"cmp"
_ "embed"
"errors"
"fmt"
"log/slog"
"slices"
"github.com/derailed/k9s/internal/slogs"
"github.com/xeipuuv/gojsonschema"
"gopkg.in/yaml.v3"
)
const (
// PluginsSchema describes plugins schema.
PluginsSchema = "plugins.json"
// PluginSchema describes a plugin snippet schema.
PluginSchema = "plugin.json"
// PluginMultiSchema describes plugin snippets schema.
PluginMultiSchema = "plugin-multi.json"
// AliasesSchema describes aliases schema.
AliasesSchema = "aliases.json"
// ViewsSchema describes views schema.
ViewsSchema = "views.json"
// HotkeysSchema describes hotkeys schema.
HotkeysSchema = "hotkeys.json"
// K9sSchema describes k9s config schema.
K9sSchema = "k9s.json"
// ContextSchema describes context config schema.
ContextSchema = "context.json"
// SkinSchema describes skin config schema.
SkinSchema = "skin.json"
)
var (
//go:embed schemas/plugins.json
pluginsSchema string
//go:embed schemas/plugin.json
pluginSchema string
//go:embed schemas/plugin-multi.json
pluginMultiSchema string
//go:embed schemas/aliases.json
aliasSchema string
//go:embed schemas/views.json
viewsSchema string
//go:embed schemas/k9s.json
k9sSchema string
//go:embed schemas/context.json
contextSchema string
//go:embed schemas/hotkeys.json
hotkeysSchema string
//go:embed schemas/skin.json
skinSchema string
)
// Validator tracks schemas validation.
type Validator struct {
schemas map[string]gojsonschema.JSONLoader
loader *gojsonschema.SchemaLoader
}
// NewValidator returns a new instance.
func NewValidator() *Validator {
v := Validator{
schemas: map[string]gojsonschema.JSONLoader{
K9sSchema: gojsonschema.NewStringLoader(k9sSchema),
ContextSchema: gojsonschema.NewStringLoader(contextSchema),
AliasesSchema: gojsonschema.NewStringLoader(aliasSchema),
ViewsSchema: gojsonschema.NewStringLoader(viewsSchema),
PluginsSchema: gojsonschema.NewStringLoader(pluginsSchema),
PluginSchema: gojsonschema.NewStringLoader(pluginSchema),
PluginMultiSchema: gojsonschema.NewStringLoader(pluginMultiSchema),
HotkeysSchema: gojsonschema.NewStringLoader(hotkeysSchema),
SkinSchema: gojsonschema.NewStringLoader(skinSchema),
},
}
v.register()
return &v
}
// Init initializes the schemas.
func (v *Validator) register() {
v.loader = gojsonschema.NewSchemaLoader()
v.loader.Validate = true
clog := slog.With(slogs.Subsys, "schema")
for k, s := range v.schemas {
if err := v.loader.AddSchema(k, s); err != nil {
clog.Error("Schema initialization failed",
slogs.SchemaFile, k,
slogs.Error, err,
)
}
}
}
// ValidatePlugins validates plugins schema.
// Checks for full, snippet and multi snippets schemas.
func (v *Validator) ValidatePlugins(bb []byte) (string, error) {
var errs error
for _, k := range []string{PluginsSchema, PluginSchema, PluginMultiSchema} {
if err := v.Validate(k, bb); err != nil {
errs = errors.Join(errs, err)
continue
}
return k, nil
}
return "", errs
}
// Validate runs document thru given schema validation.
func (v *Validator) Validate(k string, bb []byte) error {
var m any
err := yaml.Unmarshal(bb, &m)
if err != nil {
return err
}
s, ok := v.schemas[k]
if !ok {
return fmt.Errorf("no schema found for: %q", k)
}
result, err := gojsonschema.Validate(s, gojsonschema.NewGoLoader(m))
if err != nil {
return err
}
if result.Valid() {
return nil
}
slices.SortFunc(result.Errors(), func(a, b gojsonschema.ResultError) int {
return cmp.Compare(a.Description(), b.Description())
})
var errs error
for _, re := range result.Errors() {
errs = errors.Join(errs, errors.New(re.Description()))
}
return errs
}
func (v *Validator) ValidateObj(k string, o any) error {
s, ok := v.schemas[k]
if !ok {
return fmt.Errorf("no schema found for: %q", k)
}
result, err := gojsonschema.Validate(s, gojsonschema.NewGoLoader(o))
if err != nil {
return err
}
if result.Valid() {
return nil
}
slices.SortFunc(result.Errors(), func(a, b gojsonschema.ResultError) int {
return cmp.Compare(a.Description(), b.Description())
})
var errs error
for _, re := range result.Errors() {
errs = errors.Join(errs, errors.New(re.Description()))
}
return errs
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/data/view.go | internal/config/data/view.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package data
const DefaultView = "po"
// View tracks view configuration options.
type View struct {
Active string `yaml:"active"`
}
// NewView creates a new view configuration.
func NewView() *View {
return &View{Active: DefaultView}
}
// Validate a view configuration.
func (v *View) Validate() {
if v.Active == "" {
v.Active = DefaultView
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/data/proxy.go | internal/config/data/proxy.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package data
// Proxy tracks a context's proxy configuration.
type Proxy struct {
Address string `yaml:"address"`
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/data/feature_gate.go | internal/config/data/feature_gate.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package data
// FeatureGates represents K9s opt-in features.
type FeatureGates struct {
NodeShell bool `yaml:"nodeShell"`
}
// NewFeatureGates returns a new feature gate.
func NewFeatureGates() FeatureGates {
return FeatureGates{}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/data/dir_test.go | internal/config/data/dir_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package data_test
import (
"log/slog"
"os"
"strings"
"testing"
"github.com/derailed/k9s/internal/config/data"
"github.com/derailed/k9s/internal/config/mock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
"k8s.io/cli-runtime/pkg/genericclioptions"
)
func init() {
slog.SetDefault(slog.New(slog.DiscardHandler))
}
func TestDirLoad(t *testing.T) {
uu := map[string]struct {
dir string
flags *genericclioptions.ConfigFlags
err error
cfg *data.Config
}{
"happy-cl-1-ct-1": {
dir: "testdata/data/k9s",
flags: makeFlags("cl-1", "ct-1-1"),
cfg: mustLoadConfig("testdata/configs/ct-1-1.yaml"),
},
"happy-cl-1-ct2": {
dir: "testdata/data/k9s",
flags: makeFlags("cl-1", "ct-1-2"),
cfg: mustLoadConfig("testdata/configs/ct-1-2.yaml"),
},
"happy-cl-2": {
dir: "testdata/data/k9s",
flags: makeFlags("cl-2", "ct-2-1"),
cfg: mustLoadConfig("testdata/configs/ct-2-1.yaml"),
},
"toast": {
dir: "/tmp/data/k9s",
flags: makeFlags("cl-test", "ct-test-1"),
cfg: mustLoadConfig("testdata/configs/def_ct.yaml"),
},
"non-sanitized-path": {
dir: "/tmp/data/k9s",
flags: makeFlags("arn:aws:eks:eu-central-1:xxx:cluster/fred-blee", "fred-blee"),
cfg: mustLoadConfig("testdata/configs/aws_ct.yaml"),
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.NotNil(t, u.cfg, "test config must not be nil")
if u.cfg == nil {
return
}
ks := mock.NewMockKubeSettings(u.flags)
if strings.Index(u.dir, "/tmp") == 0 {
require.NoError(t, mock.EnsureDir(u.dir))
}
d := data.NewDir(u.dir)
ct, err := ks.CurrentContext()
require.NoError(t, err)
if err != nil {
return
}
cfg, err := d.Load(*u.flags.Context, ct)
assert.Equal(t, u.err, err)
if u.err == nil {
assert.Equal(t, u.cfg, cfg)
}
})
}
}
// Helpers...
func makeFlags(cl, ct string) *genericclioptions.ConfigFlags {
return &genericclioptions.ConfigFlags{
ClusterName: &cl,
Context: &ct,
}
}
func mustLoadConfig(cfg string) *data.Config {
bb, err := os.ReadFile(cfg)
if err != nil {
return nil
}
var ct data.Config
if err = yaml.Unmarshal(bb, &ct); err != nil {
return nil
}
return &ct
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/data/types.go | internal/config/data/types.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package data
import (
"net/http"
"net/url"
"os"
"github.com/derailed/k9s/internal/config/json"
"k8s.io/client-go/tools/clientcmd/api"
)
// JSONValidator validate yaml configurations.
var JSONValidator = json.NewValidator()
const (
// DefaultDirMod default unix perms for k9s directory.
DefaultDirMod os.FileMode = 0744
// DefaultFileMod default unix perms for k9s files.
DefaultFileMod os.FileMode = 0600
// MainConfigFile track main configuration file.
MainConfigFile = "config.yaml"
)
// KubeSettings exposes kubeconfig context information.
type KubeSettings interface {
// CurrentContextName returns the name of the current context.
CurrentContextName() (string, error)
// CurrentClusterName returns the name of the current cluster.
CurrentClusterName() (string, error)
// CurrentNamespaceName returns the name of the current namespace.
CurrentNamespaceName() (string, error)
// ContextNames returns all available context names.
ContextNames() (map[string]struct{}, error)
// CurrentContext returns the current context configuration.
CurrentContext() (*api.Context, error)
// GetContext returns a given context configuration or err if not found.
GetContext(string) (*api.Context, error)
// SetProxy sets the proxy for the active context, if present
SetProxy(proxy func(*http.Request) (*url.URL, error))
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/data/context_test.go | internal/config/data/context_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package data_test
import (
"testing"
"github.com/derailed/k9s/internal/config/data"
"github.com/derailed/k9s/internal/config/mock"
"github.com/stretchr/testify/assert"
)
func TestClusterValidate(t *testing.T) {
c := data.NewContext()
c.Validate(mock.NewMockConnection(), "ct-1", "cl-1")
assert.Equal(t, data.DefaultView, c.View.Active)
assert.Equal(t, "default", c.Namespace.Active)
assert.Len(t, c.Namespace.Favorites, 1)
assert.Equal(t, []string{"default"}, c.Namespace.Favorites)
}
func TestClusterValidateEmpty(t *testing.T) {
c := data.NewContext()
c.Validate(mock.NewMockConnection(), "ct-1", "cl-1")
assert.Equal(t, data.DefaultView, c.View.Active)
assert.Equal(t, "default", c.Namespace.Active)
assert.Len(t, c.Namespace.Favorites, 1)
assert.Equal(t, []string{"default"}, c.Namespace.Favorites)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/data/config.go | internal/config/data/config.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package data
import (
"fmt"
"io"
"sync"
"github.com/derailed/k9s/internal/client"
"gopkg.in/yaml.v3"
"k8s.io/client-go/tools/clientcmd/api"
)
// Config tracks a context configuration.
type Config struct {
Context *Context `yaml:"k9s"`
mx sync.RWMutex
}
// NewConfig returns a new config.
func NewConfig(ct *api.Context) *Config {
return &Config{
Context: NewContextFromConfig(ct),
}
}
// Merge merges configs and updates receiver.
func (c *Config) Merge(c1 *Config) {
if c1 == nil {
return
}
if c.Context != nil && c1.Context != nil {
c.Context.merge(c1.Context)
}
}
// Validate ensures config is in norms.
func (c *Config) Validate(conn client.Connection, contextName, clusterName string) {
c.mx.Lock()
defer c.mx.Unlock()
if c.Context == nil {
c.Context = NewContext()
}
c.Context.Validate(conn, contextName, clusterName)
}
// Dump used for debugging.
func (c *Config) Dump(w io.Writer) {
bb, _ := yaml.Marshal(&c)
_, _ = fmt.Fprintf(w, "%s\n", 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/data/ns_test.go | internal/config/data/ns_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package data_test
import (
"testing"
"github.com/derailed/k9s/internal/config/data"
"github.com/derailed/k9s/internal/config/mock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNSValidate(t *testing.T) {
ns := data.NewNamespace()
ns.Validate(mock.NewMockConnection())
assert.Equal(t, "default", ns.Active)
assert.Equal(t, []string{"default"}, ns.Favorites)
}
func TestNSValidateMissing(t *testing.T) {
ns := data.NewNamespace()
ns.Validate(mock.NewMockConnection())
assert.Equal(t, "default", ns.Active)
assert.Equal(t, []string{"default"}, ns.Favorites)
}
func TestNSValidateNoNS(t *testing.T) {
ns := data.NewNamespace()
ns.Validate(mock.NewMockConnection())
assert.Equal(t, "default", ns.Active)
assert.Equal(t, []string{"default"}, ns.Favorites)
}
func TestNsValidateMaxNS(t *testing.T) {
allNS := []string{"ns9", "ns8", "ns7", "ns6", "ns5", "ns4", "ns3", "ns2", "ns1", "all", "default"}
ns := data.NewNamespace()
ns.Favorites = allNS
ns.Validate(mock.NewMockConnection())
assert.Len(t, ns.Favorites, data.MaxFavoritesNS)
}
func TestNSSetActive(t *testing.T) {
allNS := []string{"ns4", "ns3", "ns2", "ns1", "all", "default"}
uu := []struct {
ns string
fav []string
}{
{"all", []string{"all", "default"}},
{"ns1", []string{"ns1", "all", "default"}},
{"ns2", []string{"ns2", "ns1", "all", "default"}},
{"ns3", []string{"ns3", "ns2", "ns1", "all", "default"}},
{"ns4", allNS},
}
mk := mock.NewMockKubeSettings(makeFlags("cl-1", "ct-1"))
ns := data.NewNamespace()
for _, u := range uu {
err := ns.SetActive(u.ns, mk)
require.NoError(t, err)
assert.Equal(t, u.ns, ns.Active)
assert.Equal(t, u.fav, ns.Favorites)
}
}
func TestNSValidateRmFavs(t *testing.T) {
ns := data.NewNamespace()
ns.Favorites = []string{"default", "fred"}
ns.Validate(mock.NewMockConnection())
assert.Equal(t, []string{"default", "fred"}, ns.Favorites)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/data/helpers_test.go | internal/config/data/helpers_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package data_test
import (
"os"
"path/filepath"
"slices"
"testing"
"github.com/derailed/k9s/internal/config/data"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSanitizeFileName(t *testing.T) {
uu := map[string]struct {
file, e string
}{
"empty": {},
"plain": {
file: "bumble-bee-tuna",
e: "bumble-bee-tuna",
},
"slash": {
file: "bumble/bee/tuna",
e: "bumble-bee-tuna",
},
"column": {
file: "bumble::bee:tuna",
e: "bumble-bee-tuna",
},
"eks": {
file: "arn:aws:eks:us-east-1:123456789:cluster/us-east-1-app-dev-common-eks",
e: "arn-aws-eks-us-east-1-123456789-cluster-us-east-1-app-dev-common-eks",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, data.SanitizeFileName(u.file))
})
}
}
func TestHelperInList(t *testing.T) {
uu := []struct {
item string
list []string
expected bool
}{
{"a", []string{}, false},
{"", []string{}, false},
{"", []string{""}, true},
{"a", []string{"a", "b", "c", "d"}, true},
{"z", []string{"a", "b", "c", "d"}, false},
}
for _, u := range uu {
assert.Equal(t, u.expected, slices.Contains(u.list, u.item))
}
}
func TestEnsureDirPathNone(t *testing.T) {
const mod = 0744
dir := filepath.Join(os.TempDir(), "k9s-test")
_ = os.Remove(dir)
path := filepath.Join(dir, "duh.yaml")
require.NoError(t, data.EnsureDirPath(path, mod))
p, err := os.Stat(dir)
require.NoError(t, err)
assert.Equal(t, "drwxr--r--", p.Mode().String())
}
func TestEnsureDirPathNoOpt(t *testing.T) {
var mod os.FileMode = 0744
dir := filepath.Join(os.TempDir(), "k9s-test")
require.NoError(t, os.RemoveAll(dir))
require.NoError(t, os.Mkdir(dir, mod))
path := filepath.Join(dir, "duh.yaml")
require.NoError(t, data.EnsureDirPath(path, mod))
p, err := os.Stat(dir)
require.NoError(t, err)
assert.Equal(t, "drwxr--r--", p.Mode().String())
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/data/ns.go | internal/config/data/ns.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package data
import (
"log/slog"
"slices"
"sync"
"github.com/derailed/k9s/internal/client"
"github.com/derailed/k9s/internal/slogs"
)
const (
// MaxFavoritesNS number # favorite namespaces to keep in the configuration.
MaxFavoritesNS = 9
)
// Namespace tracks active and favorites namespaces.
type Namespace struct {
Active string `yaml:"active"`
LockFavorites bool `yaml:"lockFavorites"`
Favorites []string `yaml:"favorites"`
mx sync.RWMutex
}
// NewNamespace create a new namespace configuration.
func NewNamespace() *Namespace {
return NewActiveNamespace(client.DefaultNamespace)
}
func NewActiveNamespace(n string) *Namespace {
if n == client.BlankNamespace {
n = client.DefaultNamespace
}
return &Namespace{
Active: n,
Favorites: []string{client.DefaultNamespace},
}
}
func (n *Namespace) merge(old *Namespace) {
n.mx.Lock()
defer n.mx.Unlock()
if n.LockFavorites {
return
}
for _, fav := range old.Favorites {
if slices.Contains(n.Favorites, fav) {
continue
}
n.Favorites = append(n.Favorites, fav)
}
n.trimFavNs()
}
// Validate validates a namespace is setup correctly.
func (n *Namespace) Validate(conn client.Connection) {
n.mx.RLock()
defer n.mx.RUnlock()
if conn == nil || !conn.IsValidNamespace(n.Active) {
return
}
for _, ns := range n.Favorites {
if !conn.IsValidNamespace(ns) {
slog.Debug("Invalid favorite found",
slogs.Namespace, ns,
slogs.AllNS, n.isAllNamespaces(),
)
n.rmFavNS(ns)
}
}
n.trimFavNs()
}
// SetActive set the active namespace.
func (n *Namespace) SetActive(ns string, _ KubeSettings) error {
if n == nil {
n = NewActiveNamespace(ns)
}
n.mx.Lock()
defer n.mx.Unlock()
if ns == client.BlankNamespace {
ns = client.NamespaceAll
}
n.Active = ns
if ns != "" && !n.LockFavorites {
n.addFavNS(ns)
}
return nil
}
func (n *Namespace) isAllNamespaces() bool {
return n.Active == client.NamespaceAll || n.Active == ""
}
func (n *Namespace) addFavNS(ns string) {
if slices.Contains(n.Favorites, ns) {
return
}
nfv := make([]string, 0, MaxFavoritesNS)
nfv = append(nfv, ns)
for i := range n.Favorites {
if i+1 < MaxFavoritesNS {
nfv = append(nfv, n.Favorites[i])
}
}
n.Favorites = nfv
}
func (n *Namespace) rmFavNS(ns string) {
if n.LockFavorites {
return
}
victim := -1
for i, f := range n.Favorites {
if f == ns {
victim = i
break
}
}
if victim < 0 {
return
}
n.Favorites = append(n.Favorites[:victim], n.Favorites[victim+1:]...)
}
func (n *Namespace) trimFavNs() {
if len(n.Favorites) > MaxFavoritesNS {
slog.Debug("Number of favorite exceeds hard limit. Trimming.", slogs.Max, MaxFavoritesNS)
n.Favorites = n.Favorites[:MaxFavoritesNS]
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/data/context.go | internal/config/data/context.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package data
import (
"os"
"sync"
"github.com/derailed/k9s/internal/client"
"k8s.io/client-go/tools/clientcmd/api"
)
// Context tracks K9s context configuration.
type Context struct {
ClusterName string `yaml:"cluster,omitempty"`
ReadOnly *bool `yaml:"readOnly,omitempty"`
Skin string `yaml:"skin,omitempty"`
Namespace *Namespace `yaml:"namespace"`
View *View `yaml:"view"`
FeatureGates FeatureGates `yaml:"featureGates"`
Proxy *Proxy `yaml:"proxy"`
mx sync.RWMutex
}
// NewContext creates a new cluster configuration.
func NewContext() *Context {
return &Context{
Namespace: NewNamespace(),
View: NewView(),
FeatureGates: NewFeatureGates(),
}
}
// NewContextFromConfig returns a config based on a kubecontext.
func NewContextFromConfig(cfg *api.Context) *Context {
ct := NewContext()
ct.Namespace, ct.ClusterName = NewActiveNamespace(cfg.Namespace), cfg.Cluster
return ct
}
// NewContextFromKubeConfig returns a new instance based on kubesettings or an error.
func NewContextFromKubeConfig(ks KubeSettings) (*Context, error) {
ct, err := ks.CurrentContext()
if err != nil {
return nil, err
}
return NewContextFromConfig(ct), nil
}
func (c *Context) merge(old *Context) {
if old == nil || old.Namespace == nil {
return
}
if c.Namespace == nil {
c.Namespace = NewNamespace()
}
c.Namespace.merge(old.Namespace)
}
func (c *Context) GetClusterName() string {
c.mx.RLock()
defer c.mx.RUnlock()
return c.ClusterName
}
// Validate ensures a context config is tip top.
func (c *Context) Validate(conn client.Connection, _, clusterName string) {
c.mx.Lock()
defer c.mx.Unlock()
c.ClusterName = clusterName
if b := os.Getenv(envFGNodeShell); b != "" {
c.FeatureGates.NodeShell = defaultFGNodeShell()
}
if c.Namespace == nil {
c.Namespace = NewNamespace()
}
c.Namespace.Validate(conn)
if c.View == nil {
c.View = NewView()
}
c.View.Validate()
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/data/view_test.go | internal/config/data/view_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package data_test
import (
"testing"
"github.com/derailed/k9s/internal/config/data"
"github.com/stretchr/testify/assert"
)
func TestViewValidate(t *testing.T) {
v := data.NewView()
v.Validate()
assert.Equal(t, "po", v.Active)
v.Active = "fred"
v.Validate()
assert.Equal(t, "fred", v.Active)
}
func TestViewValidateBlank(t *testing.T) {
var v data.View
v.Validate()
assert.Equal(t, "po", v.Active)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/data/context_int_test.go | internal/config/data/context_int_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package data
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_contextMerge(t *testing.T) {
uu := map[string]struct {
c1, c2, e *Context
}{
"empty": {},
"nil": {
c1: &Context{
Namespace: &Namespace{
Active: "ns1",
Favorites: []string{"ns1", "ns2", "ns3"},
},
},
e: &Context{
Namespace: &Namespace{
Active: "ns1",
Favorites: []string{"ns1", "ns2", "ns3"},
},
},
},
"deltas": {
c1: &Context{
Namespace: &Namespace{
Active: "ns1",
Favorites: []string{"ns1", "ns2", "ns3"},
},
},
c2: &Context{
Namespace: &Namespace{
Active: "ns10",
Favorites: []string{"ns10", "ns11", "ns12"},
},
},
e: &Context{
Namespace: &Namespace{
Active: "ns1",
Favorites: []string{"ns1", "ns2", "ns3", "ns10", "ns11", "ns12"},
},
},
},
"deltas-locked": {
c1: &Context{
Namespace: &Namespace{
Active: "ns1",
LockFavorites: true,
Favorites: []string{"ns1", "ns2", "ns3"},
},
},
c2: &Context{
Namespace: &Namespace{
Active: "ns10",
Favorites: []string{"ns10", "ns11", "ns12"},
},
},
e: &Context{
Namespace: &Namespace{
Active: "ns1",
LockFavorites: true,
Favorites: []string{"ns1", "ns2", "ns3"},
},
},
},
"no-namespace": {
c1: NewContext(),
c2: &Context{},
e: NewContext(),
},
"too-many-favs": {
c1: &Context{
Namespace: &Namespace{
Active: "ns1",
Favorites: []string{"ns1", "ns2", "ns3", "ns4", "ns5", "ns6", "ns7", "ns8", "ns9"},
},
},
c2: &Context{
Namespace: &Namespace{
Active: "ns10",
Favorites: []string{"ns10", "ns11", "ns12"},
},
},
e: &Context{
Namespace: &Namespace{
Active: "ns1",
Favorites: []string{"ns1", "ns2", "ns3", "ns4", "ns5", "ns6", "ns7", "ns8", "ns9"},
},
},
},
}
for k, u := range uu {
t.Run(k, func(t *testing.T) {
u.c1.merge(u.c2)
assert.Equal(t, u.e, u.c1)
})
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/data/helpers.go | internal/config/data/helpers.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package data
import (
"bytes"
"errors"
"io/fs"
"os"
"path/filepath"
"regexp"
"gopkg.in/yaml.v3"
)
const envFGNodeShell = "K9S_FEATURE_GATE_NODE_SHELL"
var invalidPathCharsRX = regexp.MustCompile(`[:/]+`)
// SanitizeContextSubpath ensure cluster/context produces a valid path.
func SanitizeContextSubpath(cluster, context string) string {
return filepath.Join(SanitizeFileName(cluster), SanitizeFileName(context))
}
// SanitizeFileName ensure file spec is valid.
func SanitizeFileName(name string) string {
return invalidPathCharsRX.ReplaceAllString(name, "-")
}
func defaultFGNodeShell() bool {
if a := os.Getenv(envFGNodeShell); a != "" {
return a == "true"
}
return false
}
// EnsureDirPath ensures a directory exist from the given path.
func EnsureDirPath(path string, mod os.FileMode) error {
return EnsureFullPath(filepath.Dir(path), mod)
}
// EnsureFullPath ensures a directory exist from the given path.
func EnsureFullPath(path string, mod os.FileMode) error {
if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) {
if e := os.MkdirAll(path, mod); e != nil {
return e
}
}
return nil
}
// WriteYAML writes a yaml file to bytes.
func WriteYAML(content any) ([]byte, error) {
buff := bytes.NewBuffer(nil)
ec := yaml.NewEncoder(buff)
ec.SetIndent(2)
if err := ec.Encode(content); err != nil {
return nil, err
}
return buff.Bytes(), nil
}
// SaveYAML writes a yaml file to disk.
func SaveYAML(path string, content any) error {
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|os.O_TRUNC, DefaultFileMod)
if err != nil {
return err
}
ec := yaml.NewEncoder(f)
ec.SetIndent(2)
return ec.Encode(content)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/config/data/dir.go | internal/config/data/dir.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package data
import (
"errors"
"fmt"
"io/fs"
"log/slog"
"os"
"path/filepath"
"sync"
"github.com/derailed/k9s/internal/config/json"
"github.com/derailed/k9s/internal/slogs"
"gopkg.in/yaml.v3"
"k8s.io/client-go/tools/clientcmd/api"
)
// Dir tracks context configurations.
type Dir struct {
root string
mx sync.Mutex
}
// NewDir returns a new instance.
func NewDir(root string) *Dir {
return &Dir{
root: root,
}
}
// Load loads context configuration.
func (d *Dir) Load(contextName string, ct *api.Context) (*Config, error) {
if ct == nil {
return nil, errors.New("api.Context must not be nil")
}
path := filepath.Join(d.root, SanitizeContextSubpath(ct.Cluster, contextName), MainConfigFile)
slog.Debug("[CONFIG] Loading context config from disk", slogs.Path, path, slogs.Cluster, ct.Cluster, slogs.Context, contextName)
f, err := os.Stat(path)
if errors.Is(err, fs.ErrPermission) {
return nil, err
}
if errors.Is(err, fs.ErrNotExist) || (f != nil && f.Size() == 0) {
slog.Debug("Context config not found! Generating..", slogs.Path, path)
return d.genConfig(path, ct)
}
if err != nil {
return nil, err
}
return d.loadConfig(path)
}
func (d *Dir) genConfig(path string, ct *api.Context) (*Config, error) {
cfg := NewConfig(ct)
if err := d.Save(path, cfg); err != nil {
return nil, err
}
return cfg, nil
}
func (d *Dir) Save(path string, c *Config) error {
if cfg, err := d.loadConfig(path); err == nil {
c.Merge(cfg)
}
d.mx.Lock()
defer d.mx.Unlock()
if err := EnsureDirPath(path, DefaultDirMod); err != nil {
return err
}
return SaveYAML(path, c)
}
func (d *Dir) loadConfig(path string) (*Config, error) {
d.mx.Lock()
defer d.mx.Unlock()
bb, err := os.ReadFile(path)
if err != nil {
return nil, err
}
if err := JSONValidator.Validate(json.ContextSchema, bb); err != nil {
slog.Warn("Validation failed. Please update your config and restart!",
slogs.Path, path,
slogs.Error, err,
)
}
var cfg Config
if err := yaml.Unmarshal(bb, &cfg); err != nil {
return nil, fmt.Errorf("context-config yaml load failed: %w\n%s", err, string(bb))
}
return &cfg, nil
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/client/metrics.go | internal/client/metrics.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package client
import (
"context"
"errors"
"fmt"
"math"
"strconv"
"time"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/cache"
mv1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1"
)
const (
mxCacheSize = 100
mxCacheExpiry = 1 * time.Minute
)
// MetricsDial tracks global metric server handle.
var MetricsDial *MetricsServer
// DialMetrics dials the metrics server.
func DialMetrics(c Connection) *MetricsServer {
if MetricsDial == nil {
MetricsDial = NewMetricsServer(c)
}
return MetricsDial
}
// ResetMetrics resets the metric server handle.
func ResetMetrics() {
MetricsDial = nil
}
// MetricsServer serves cluster metrics for nodes and pods.
type MetricsServer struct {
Connection
cache *cache.LRUExpireCache
}
// NewMetricsServer return a metric server instance.
func NewMetricsServer(c Connection) *MetricsServer {
return &MetricsServer{
Connection: c,
cache: cache.NewLRUExpireCache(mxCacheSize),
}
}
// ClusterLoad retrieves all cluster nodes metrics.
func (*MetricsServer) ClusterLoad(nos *v1.NodeList, nmx *mv1beta1.NodeMetricsList, mx *ClusterMetrics) error {
if nos == nil || nmx == nil {
return fmt.Errorf("invalid node or node metrics lists")
}
nodeMetrics := make(NodesMetrics, len(nos.Items))
for i := range nos.Items {
nodeMetrics[nos.Items[i].Name] = NodeMetrics{
AllocatableCPU: nos.Items[i].Status.Allocatable.Cpu().MilliValue(),
AllocatableMEM: nos.Items[i].Status.Allocatable.Memory().Value(),
}
}
for i := range nmx.Items {
if node, ok := nodeMetrics[nmx.Items[i].Name]; ok {
node.CurrentCPU = nmx.Items[i].Usage.Cpu().MilliValue()
node.CurrentMEM = nmx.Items[i].Usage.Memory().Value()
nodeMetrics[nmx.Items[i].Name] = node
}
}
var ccpu, cmem, tcpu, tmem int64
for _, mx := range nodeMetrics {
ccpu += mx.CurrentCPU
cmem += mx.CurrentMEM
tcpu += mx.AllocatableCPU
tmem += mx.AllocatableMEM
}
mx.PercCPU, mx.PercMEM = ToPercentage(ccpu, tcpu), ToPercentage(cmem, tmem)
return nil
}
func (m *MetricsServer) checkAccess(ns string, gvr *GVR, msg string) error {
if !m.HasMetrics() {
return errors.New("no metrics-server detected on cluster")
}
auth, err := m.CanI(ns, gvr, "", ListAccess)
if err != nil {
return err
}
if !auth {
return errors.New(msg)
}
return nil
}
// NodesMetrics retrieves metrics for a given set of nodes.
func (*MetricsServer) NodesMetrics(nodes *v1.NodeList, metrics *mv1beta1.NodeMetricsList, mmx NodesMetrics) {
if nodes == nil || metrics == nil {
return
}
for i := range nodes.Items {
mmx[nodes.Items[i].Name] = NodeMetrics{
AllocatableCPU: nodes.Items[i].Status.Allocatable.Cpu().MilliValue(),
AllocatableMEM: ToMB(nodes.Items[i].Status.Allocatable.Memory().Value()),
AllocatableEphemeral: ToMB(nodes.Items[i].Status.Allocatable.StorageEphemeral().Value()),
TotalCPU: nodes.Items[i].Status.Capacity.Cpu().MilliValue(),
TotalMEM: ToMB(nodes.Items[i].Status.Capacity.Memory().Value()),
TotalEphemeral: ToMB(nodes.Items[i].Status.Capacity.StorageEphemeral().Value()),
}
}
for i := range metrics.Items {
mx, ok := mmx[metrics.Items[i].Name]
if !ok {
continue
}
mx.CurrentCPU = metrics.Items[i].Usage.Cpu().MilliValue()
mx.CurrentMEM = ToMB(metrics.Items[i].Usage.Memory().Value())
mx.AvailableCPU = mx.AllocatableCPU - mx.CurrentCPU
mx.AvailableMEM = mx.AllocatableMEM - mx.CurrentMEM
mmx[metrics.Items[i].Name] = mx
}
}
// FetchNodesMetricsMap fetch node metrics as a map.
func (m *MetricsServer) FetchNodesMetricsMap(ctx context.Context) (NodesMetricsMap, error) {
mm, err := m.FetchNodesMetrics(ctx)
if err != nil {
return nil, err
}
hh := make(NodesMetricsMap, len(mm.Items))
for i := range mm.Items {
mx := mm.Items[i]
hh[mx.Name] = &mx
}
return hh, nil
}
// FetchNodesMetrics return all metrics for nodes.
func (m *MetricsServer) FetchNodesMetrics(ctx context.Context) (*mv1beta1.NodeMetricsList, error) {
const msg = "user is not authorized to list node metrics"
mx := new(mv1beta1.NodeMetricsList)
if err := m.checkAccess(ClusterScope, NmxGVR, msg); err != nil {
return mx, err
}
const key = "nodes"
if entry, ok := m.cache.Get(key); ok && entry != nil {
mxList, ok := entry.(*mv1beta1.NodeMetricsList)
if !ok {
return nil, fmt.Errorf("expected nodemetricslist but got %T", entry)
}
return mxList, nil
}
client, err := m.MXDial()
if err != nil {
return mx, err
}
mxList, err := client.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{})
if err != nil {
return mx, err
}
m.cache.Add(key, mxList, mxCacheExpiry)
return mxList, nil
}
// FetchNodeMetrics return all metrics for nodes.
func (m *MetricsServer) FetchNodeMetrics(ctx context.Context, n string) (*mv1beta1.NodeMetrics, error) {
const msg = "user is not authorized to list node metrics"
mx := new(mv1beta1.NodeMetrics)
if err := m.checkAccess(ClusterScope, NmxGVR, msg); err != nil {
return mx, err
}
mmx, err := m.FetchNodesMetricsMap(ctx)
if err != nil {
return nil, err
}
mx, ok := mmx[n]
if !ok {
return nil, fmt.Errorf("unable to retrieve node metrics for %q", n)
}
return mx, nil
}
// FetchPodsMetricsMap fetch pods metrics as a map.
func (m *MetricsServer) FetchPodsMetricsMap(ctx context.Context, ns string) (PodsMetricsMap, error) {
mm, err := m.FetchPodsMetrics(ctx, ns)
if err != nil {
return nil, err
}
hh := make(PodsMetricsMap, len(mm.Items))
for i := range mm.Items {
mx := mm.Items[i]
hh[FQN(mx.Namespace, mx.Name)] = &mx
}
return hh, nil
}
// FetchPodsMetrics return all metrics for pods in a given namespace.
func (m *MetricsServer) FetchPodsMetrics(ctx context.Context, ns string) (*mv1beta1.PodMetricsList, error) {
mx := new(mv1beta1.PodMetricsList)
const msg = "user is not authorized to list pods metrics"
if ns == NamespaceAll {
ns = BlankNamespace
}
if err := m.checkAccess(ns, PmxGVR, msg); err != nil {
return mx, err
}
key := FQN(ns, "pods")
if entry, ok := m.cache.Get(key); ok {
mxList, ok := entry.(*mv1beta1.PodMetricsList)
if !ok {
return mx, fmt.Errorf("expected PodMetricsList but got %T", entry)
}
return mxList, nil
}
client, err := m.MXDial()
if err != nil {
return mx, err
}
mxList, err := client.MetricsV1beta1().PodMetricses(ns).List(ctx, metav1.ListOptions{})
if err != nil {
return mx, err
}
m.cache.Add(key, mxList, mxCacheExpiry)
return mxList, err
}
// FetchContainersMetrics returns a pod's containers metrics.
func (m *MetricsServer) FetchContainersMetrics(ctx context.Context, fqn string) (ContainersMetrics, error) {
mm, err := m.FetchPodMetrics(ctx, fqn)
if err != nil {
return nil, err
}
cmx := make(ContainersMetrics, len(mm.Containers))
for i := range mm.Containers {
c := mm.Containers[i]
cmx[c.Name] = &c
}
return cmx, nil
}
// FetchPodMetrics return all metrics for pods in a given namespace.
func (m *MetricsServer) FetchPodMetrics(ctx context.Context, fqn string) (*mv1beta1.PodMetrics, error) {
var mx *mv1beta1.PodMetrics
const msg = "user is not authorized to list pod metrics"
ns, _ := Namespaced(fqn)
if ns == NamespaceAll {
ns = BlankNamespace
}
if err := m.checkAccess(ns, PmxGVR, msg); err != nil {
return mx, err
}
mmx, err := m.FetchPodsMetricsMap(ctx, ns)
if err != nil {
return nil, err
}
pmx, ok := mmx[fqn]
if !ok {
return nil, fmt.Errorf("unable to locate pod metrics for pod %q", fqn)
}
return pmx, nil
}
// PodsMetrics retrieves metrics for all pods in a given namespace.
func (*MetricsServer) PodsMetrics(pods *mv1beta1.PodMetricsList, mmx PodsMetrics) {
if pods == nil {
return
}
// Compute all pod's containers metrics.
for i := range pods.Items {
var mx PodMetrics
for _, c := range pods.Items[i].Containers {
mx.CurrentCPU += c.Usage.Cpu().MilliValue()
mx.CurrentMEM += ToMB(c.Usage.Memory().Value())
}
mmx[pods.Items[i].Namespace+"/"+pods.Items[i].Name] = mx
}
}
// ----------------------------------------------------------------------------
// Helpers...
// MegaByte represents a megabyte.
const MegaByte = 1024 * 1024
// ToMB converts bytes to megabytes.
func ToMB(v int64) int64 {
return v / MegaByte
}
// ToPercentage computes percentage as string otherwise n/aa.
func ToPercentage(v, dv int64) int {
if dv == 0 {
return 0
}
return int(math.Floor((float64(v) / float64(dv)) * 100))
}
// ToPercentageStr computes percentage, but if v2 is 0, it will return NAValue instead of 0.
func ToPercentageStr(v, dv int64) string {
if dv == 0 {
return NA
}
return strconv.Itoa(ToPercentage(v, dv))
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/client/gvr_test.go | internal/client/gvr_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package client_test
import (
"path"
"sort"
"testing"
"github.com/derailed/k9s/internal/client"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/runtime/schema"
)
func TestGVRSort(t *testing.T) {
gg := client.GVRs{
client.PodGVR,
client.SvcGVR,
client.DpGVR,
}
sort.Sort(gg)
assert.Equal(t, client.GVRs{
client.PodGVR,
client.SvcGVR,
client.DpGVR,
}, gg)
}
func TestGVRCan(t *testing.T) {
uu := map[string]struct {
vv []string
v string
e bool
}{
"describe": {[]string{"get"}, "describe", true},
"view": {[]string{"get", "list", "watch"}, "view", true},
"delete": {[]string{"delete", "list", "watch"}, "delete", true},
"no_delete": {[]string{"get", "list", "watch"}, "delete", false},
"edit": {[]string{"path", "update", "watch"}, "edit", true},
"no_edit": {[]string{"get", "list", "watch"}, "edit", false},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, client.Can(u.vv, u.v))
})
}
}
func TestGVR(t *testing.T) {
uu := map[string]struct {
gvr string
e schema.GroupVersionResource
}{
"full": {client.DpGVR.String(), schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"}},
"core": {client.PodGVR.String(), schema.GroupVersionResource{Version: "v1", Resource: "pods"}},
"bork": {client.UsrGVR.String(), schema.GroupVersionResource{Resource: "users"}},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, client.NewGVR(u.gvr).GVR())
})
}
}
func TestAsGV(t *testing.T) {
uu := map[string]struct {
gvr string
e schema.GroupVersion
}{
"full": {client.DpGVR.String(), schema.GroupVersion{Group: "apps", Version: "v1"}},
"core": {client.PodGVR.String(), schema.GroupVersion{Version: "v1"}},
"bork": {client.UsrGVR.String(), schema.GroupVersion{}},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, client.NewGVR(u.gvr).GV())
})
}
}
func TestNewGVR(t *testing.T) {
uu := map[string]struct {
g, v, r string
e string
}{
"full": {"apps", "v1", "deployments", client.DpGVR.String()},
"core": {"", "v1", "pods", client.PodGVR.String()},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, client.NewGVR(path.Join(u.g, u.v, u.r)).String())
})
}
}
func TestGVRAsResourceName(t *testing.T) {
uu := map[string]struct {
gvr string
e string
}{
"full": {client.DpGVR.String(), "deployments.v1.apps"},
"core": {client.PodGVR.String(), "pods"},
"k9s": {client.UsrGVR.String(), "users"},
"empty": {"", ""},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, client.NewGVR(u.gvr).AsResourceName())
})
}
}
func TestToR(t *testing.T) {
uu := map[string]struct {
gvr string
e string
}{
"full": {client.DpGVR.String(), "deployments"},
"core": {client.PodGVR.String(), "pods"},
"k9s": {client.UsrGVR.String(), "users"},
"empty": {"", ""},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, client.NewGVR(u.gvr).R())
})
}
}
func TestToG(t *testing.T) {
uu := map[string]struct {
gvr string
e string
}{
"full": {client.DpGVR.String(), "apps"},
"core": {client.PodGVR.String(), ""},
"k9s": {client.UsrGVR.String(), ""},
"empty": {"", ""},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, client.NewGVR(u.gvr).G())
})
}
}
func TestToV(t *testing.T) {
uu := map[string]struct {
gvr string
e string
}{
"full": {client.DpGVR.String(), "v1"},
"core": {"v1beta1/pods", "v1beta1"},
"k9s": {client.UsrGVR.String(), ""},
"empty": {"", ""},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, client.NewGVR(u.gvr).V())
})
}
}
func TestToString(t *testing.T) {
uu := map[string]struct {
gvr string
}{
"full": {client.DpGVR.String()},
"core": {"v1beta1/pods"},
"k9s": {client.UsrGVR.String()},
"empty": {""},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.gvr, client.NewGVR(u.gvr).String())
})
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/client/client.go | internal/client/client.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package client
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/derailed/k9s/internal/slogs"
authorizationv1 "k8s.io/api/authorization/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/cache"
"k8s.io/apimachinery/pkg/version"
"k8s.io/client-go/discovery/cached/disk"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
metricsapi "k8s.io/metrics/pkg/apis/metrics"
"k8s.io/metrics/pkg/client/clientset/versioned"
)
const (
cacheSize = 100
cacheExpiry = 5 * time.Minute
cacheMXAPIKey = "metricsAPI"
serverVersion = "serverVersion"
cacheNSKey = "validNamespaces"
)
var supportedMetricsAPIVersions = []string{"v1beta1"}
// NamespaceNames tracks a collection of namespace names.
type NamespaceNames map[string]struct{}
// APIClient represents a Kubernetes api client.
type APIClient struct {
client, logClient kubernetes.Interface
dClient dynamic.Interface
nsClient dynamic.NamespaceableResourceInterface
mxsClient *versioned.Clientset
cachedClient *disk.CachedDiscoveryClient
config *Config
mx sync.RWMutex
cache *cache.LRUExpireCache
connOK bool
log *slog.Logger
}
// NewTestAPIClient for testing ONLY!!
func NewTestAPIClient() *APIClient {
return &APIClient{
config: NewConfig(nil),
cache: cache.NewLRUExpireCache(cacheSize),
}
}
// InitConnection initialize connection from command line args.
// Checks for connectivity with the api server.
func InitConnection(config *Config, log *slog.Logger) (*APIClient, error) {
a := APIClient{
config: config,
cache: cache.NewLRUExpireCache(cacheSize),
connOK: true,
log: log.With(slogs.Subsys, "client"),
}
err := a.supportsMetricsResources()
if err != nil {
slog.Warn("Fail to locate metrics-server", slogs.Error, err)
}
if err == nil || errors.Is(err, noMetricServerErr) || errors.Is(err, metricsUnsupportedErr) {
return &a, nil
}
a.connOK = false
return &a, err
}
// ConnectionOK returns connection status.
func (a *APIClient) ConnectionOK() bool {
return a.connOK
}
func makeSAR(ns string, gvr *GVR, name string) *authorizationv1.SelfSubjectAccessReview {
if ns == ClusterScope {
ns = BlankNamespace
}
res := gvr.GVR()
return &authorizationv1.SelfSubjectAccessReview{
Spec: authorizationv1.SelfSubjectAccessReviewSpec{
ResourceAttributes: &authorizationv1.ResourceAttributes{
Namespace: ns,
Group: res.Group,
Version: res.Version,
Resource: res.Resource,
Subresource: gvr.SubResource(),
Name: name,
},
},
}
}
func makeCacheKey(ns string, gvr *GVR, n string, vv []string) string {
return ns + ":" + gvr.String() + ":" + n + "::" + strings.Join(vv, ",")
}
// ActiveContext returns the current context name.
func (a *APIClient) ActiveContext() string {
c, err := a.config.CurrentContextName()
if err != nil {
slog.Error("unable to located active cluster", slogs.Error, err)
return ""
}
return c
}
// IsActiveNamespace returns true if namespaces matches.
func (a *APIClient) IsActiveNamespace(ns string) bool {
if a.ActiveNamespace() == BlankNamespace {
return true
}
return a.ActiveNamespace() == ns
}
// ActiveNamespace returns the current namespace.
func (a *APIClient) ActiveNamespace() string {
if ns, err := a.CurrentNamespaceName(); err == nil {
return ns
}
return BlankNamespace
}
func (a *APIClient) clearCache() {
for _, k := range a.cache.Keys() {
a.cache.Remove(k)
}
}
// CanI checks if user has access to a certain resource.
func (a *APIClient) CanI(ns string, gvr *GVR, name string, verbs []string) (auth bool, err error) {
if !a.getConnOK() {
return false, errors.New("ACCESS -- No API server connection")
}
if gvr == NsGVR {
// The name of the namespace is required to check permissions in some cases
ns = name
}
if IsClusterWide(ns) {
ns = BlankNamespace
}
if gvr == HmGVR {
// helm stores release data in secrets
gvr = SecGVR
}
key := makeCacheKey(ns, gvr, name, verbs)
if v, ok := a.cache.Get(key); ok {
if auth, ok = v.(bool); ok {
return auth, nil
}
}
clog := a.log.With(slogs.Subsys, "can")
dial, err := a.Dial()
if err != nil {
return false, err
}
client, sar := dial.AuthorizationV1().SelfSubjectAccessReviews(), makeSAR(ns, gvr, name)
ctx, cancel := context.WithTimeout(context.Background(), a.config.CallTimeout())
defer cancel()
for _, v := range verbs {
sar.Spec.ResourceAttributes.Verb = v
resp, err := client.Create(ctx, sar, metav1.CreateOptions{})
clog.Debug("[CAN] access",
slogs.GVR, gvr,
slogs.Namespace, ns,
slogs.ResName, name,
slogs.Verb, verbs,
)
if resp != nil {
clog.Debug("[CAN] response",
slogs.AuthStatus, resp.Status.Allowed,
slogs.AuthReason, resp.Status.Reason,
)
}
if err != nil {
clog.Warn("Auth request failed", slogs.Error, err)
a.cache.Add(key, false, cacheExpiry)
return auth, err
}
if !resp.Status.Allowed {
a.cache.Add(key, false, cacheExpiry)
return auth, fmt.Errorf("(%s) access denied for user on resource %q:%s in namespace %q", v, name, gvr, ns)
}
}
auth = true
a.cache.Add(key, true, cacheExpiry)
return
}
// CurrentNamespaceName return namespace name set via either cli arg or cluster config.
func (a *APIClient) CurrentNamespaceName() (string, error) {
return a.config.CurrentNamespaceName()
}
// ServerVersion returns the current server version info.
func (a *APIClient) ServerVersion() (*version.Info, error) {
if v, ok := a.cache.Get(serverVersion); ok {
if vi, ok := v.(*version.Info); ok {
return vi, nil
}
}
dial, err := a.CachedDiscovery()
if err != nil {
return nil, err
}
info, err := dial.ServerVersion()
if err != nil {
return nil, err
}
a.cache.Add(serverVersion, info, cacheExpiry)
return info, nil
}
func (a *APIClient) IsValidNamespace(ns string) bool {
ok, err := a.isValidNamespace(ns)
if err != nil {
slog.Warn("Namespace validation failed",
slogs.Namespace, ns,
slogs.Error, err,
)
}
return ok
}
func (a *APIClient) isValidNamespace(n string) (bool, error) {
if IsClusterWide(n) || n == NotNamespaced {
return true, nil
}
nn, err := a.ValidNamespaceNames()
if err != nil {
return false, err
}
_, ok := nn[n]
return ok, nil
}
// ValidNamespaceNames returns all available namespaces.
func (a *APIClient) ValidNamespaceNames() (NamespaceNames, error) {
if a == nil {
return nil, fmt.Errorf("validNamespaces: no available client found")
}
if nn, ok := a.cache.Get(cacheNSKey); ok {
if nss, ok := nn.(NamespaceNames); ok {
return nss, nil
}
}
ok, err := a.CanI(ClusterScope, NsGVR, "", ListAccess)
if !ok || err != nil {
a.cache.Add(cacheNSKey, NamespaceNames{}, cacheExpiry)
return nil, fmt.Errorf("user not authorized to list all namespaces")
}
dial, err := a.Dial()
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), a.config.CallTimeout())
defer cancel()
nn, err := dial.CoreV1().Namespaces().List(ctx, metav1.ListOptions{})
if err != nil {
return nil, err
}
nns := make(NamespaceNames, len(nn.Items))
for i := range nn.Items {
nns[nn.Items[i].Name] = struct{}{}
}
a.cache.Add(cacheNSKey, nns, cacheExpiry)
return nns, nil
}
// CheckConnectivity return true if api server is cool or false otherwise.
func (a *APIClient) CheckConnectivity() bool {
defer func() {
if err := recover(); err != nil {
a.setConnOK(false)
}
if !a.getConnOK() {
a.clearCache()
}
}()
cfg, err := a.config.RESTConfig()
if err != nil {
slog.Error("RestConfig load failed", slogs.Error, err)
a.connOK = false
return a.connOK
}
cfg.Timeout = a.config.CallTimeout()
client, err := kubernetes.NewForConfig(cfg)
if err != nil {
slog.Error("Unable to connect to api server", slogs.Error, err)
a.setConnOK(false)
return a.getConnOK()
}
// Check connection
if _, err := client.ServerVersion(); err == nil {
if !a.getConnOK() {
a.reset()
}
} else {
slog.Error("Unable to fetch server version", slogs.Error, err)
a.setConnOK(false)
}
return a.getConnOK()
}
// Config return a kubernetes configuration.
func (a *APIClient) Config() *Config {
return a.config
}
// HasMetrics checks if the cluster supports metrics.
func (a *APIClient) HasMetrics() bool {
return a.supportsMetricsResources() == nil
}
func (a *APIClient) getMxsClient() *versioned.Clientset {
a.mx.RLock()
defer a.mx.RUnlock()
return a.mxsClient
}
func (a *APIClient) setMxsClient(c *versioned.Clientset) {
a.mx.Lock()
defer a.mx.Unlock()
a.mxsClient = c
}
func (a *APIClient) getCachedClient() *disk.CachedDiscoveryClient {
a.mx.RLock()
defer a.mx.RUnlock()
return a.cachedClient
}
func (a *APIClient) setCachedClient(c *disk.CachedDiscoveryClient) {
a.mx.Lock()
defer a.mx.Unlock()
a.cachedClient = c
}
func (a *APIClient) getDClient() dynamic.Interface {
a.mx.RLock()
defer a.mx.RUnlock()
return a.dClient
}
func (a *APIClient) setDClient(c dynamic.Interface) {
a.mx.Lock()
defer a.mx.Unlock()
a.dClient = c
}
func (a *APIClient) getConnOK() bool {
a.mx.RLock()
defer a.mx.RUnlock()
return a.connOK
}
func (a *APIClient) setConnOK(b bool) {
a.mx.Lock()
defer a.mx.Unlock()
a.connOK = b
}
func (a *APIClient) setLogClient(k kubernetes.Interface) {
a.mx.Lock()
defer a.mx.Unlock()
a.logClient = k
}
func (a *APIClient) getLogClient() kubernetes.Interface {
a.mx.RLock()
defer a.mx.RUnlock()
return a.logClient
}
func (a *APIClient) setClient(k kubernetes.Interface) {
a.mx.Lock()
defer a.mx.Unlock()
a.client = k
}
func (a *APIClient) getClient() kubernetes.Interface {
a.mx.RLock()
defer a.mx.RUnlock()
return a.client
}
// DialLogs returns a handle to api server for logs.
func (a *APIClient) DialLogs() (kubernetes.Interface, error) {
if !a.getConnOK() {
return nil, errors.New("dialLogs - no connection to dial")
}
if clt := a.getLogClient(); clt != nil {
return clt, nil
}
cfg, err := a.RestConfig()
if err != nil {
return nil, err
}
cfg.Timeout = 0
c, err := kubernetes.NewForConfig(cfg)
if err != nil {
return nil, err
}
a.setLogClient(c)
return a.getLogClient(), nil
}
// Dial returns a handle to api server or die.
func (a *APIClient) Dial() (kubernetes.Interface, error) {
if !a.getConnOK() {
return nil, errors.New("no connection to dial")
}
if c := a.getClient(); c != nil {
return c, nil
}
cfg, err := a.RestConfig()
if err != nil {
return nil, err
}
c, err := kubernetes.NewForConfig(cfg)
if err != nil {
return nil, err
}
a.setClient(c)
return a.getClient(), nil
}
// RestConfig returns a rest api client.
func (a *APIClient) RestConfig() (*restclient.Config, error) {
return a.config.RESTConfig()
}
// CachedDiscovery returns a cached discovery client.
func (a *APIClient) CachedDiscovery() (*disk.CachedDiscoveryClient, error) {
if !a.getConnOK() {
return nil, errors.New("no connection to cached dial")
}
if c := a.getCachedClient(); c != nil {
return c, nil
}
cfg, err := a.RestConfig()
if err != nil {
return nil, err
}
baseCacheDir := os.Getenv("KUBECACHEDIR")
if baseCacheDir == "" {
baseCacheDir = filepath.Join(mustHomeDir(), ".kube", "cache")
}
httpCacheDir := filepath.Join(baseCacheDir, "http")
discCacheDir := filepath.Join(baseCacheDir, "discovery", toHostDir(cfg.Host))
c, err := disk.NewCachedDiscoveryClientForConfig(cfg, discCacheDir, httpCacheDir, cacheExpiry)
if err != nil {
return nil, err
}
a.setCachedClient(c)
return a.getCachedClient(), nil
}
// DynDial returns a handle to a dynamic interface.
func (a *APIClient) DynDial() (dynamic.Interface, error) {
if c := a.getDClient(); c != nil {
return c, nil
}
cfg, err := a.RestConfig()
if err != nil {
return nil, err
}
c, err := dynamic.NewForConfig(cfg)
if err != nil {
return nil, err
}
a.setDClient(c)
return a.getDClient(), nil
}
// MXDial returns a handle to the metrics server.
func (a *APIClient) MXDial() (*versioned.Clientset, error) {
if c := a.getMxsClient(); c != nil {
return c, nil
}
cfg, err := a.RestConfig()
if err != nil {
return nil, err
}
c, err := versioned.NewForConfig(cfg)
if err != nil {
return nil, err
}
a.setMxsClient(c)
return a.getMxsClient(), err
}
func (a *APIClient) invalidateCache() error {
dial, err := a.CachedDiscovery()
if err != nil {
return err
}
dial.Invalidate()
return nil
}
// SwitchContext handles kubeconfig context switches.
func (a *APIClient) SwitchContext(name string) error {
slog.Debug("Switching context", slogs.Context, name)
if err := a.config.SwitchContext(name); err != nil {
return err
}
if !a.CheckConnectivity() {
slog.Debug("No connectivity, skipping cache invalidation")
} else if err := a.invalidateCache(); err != nil {
return err
}
a.reset()
ResetMetrics()
// Need reload to pick up any kubeconfig changes.
a.config = NewConfig(a.config.flags)
return a.invalidateCache()
}
func (a *APIClient) reset() {
a.config.reset()
a.cache = cache.NewLRUExpireCache(cacheSize)
a.nsClient = nil
a.setDClient(nil)
a.setMxsClient(nil)
a.setCachedClient(nil)
a.setClient(nil)
a.setLogClient(nil)
a.setConnOK(true)
}
func (a *APIClient) checkCacheBool(key string) (state, ok bool) {
v, found := a.cache.Get(key)
if !found {
return
}
state, ok = v.(bool)
return
}
func (a *APIClient) supportsMetricsResources() error {
supported, ok := a.checkCacheBool(cacheMXAPIKey)
if ok {
if supported {
return nil
}
return noMetricServerErr
}
defer func() {
a.cache.Add(cacheMXAPIKey, supported, cacheExpiry)
}()
dial, err := a.Dial()
if err != nil {
slog.Warn("Unable to dial API client for metrics", slogs.Error, err)
return err
}
apiGroups, err := dial.Discovery().ServerGroups()
if err != nil {
return err
}
for i := range apiGroups.Groups {
if apiGroups.Groups[i].Name != metricsapi.GroupName {
continue
}
if checkMetricsVersion(&(apiGroups.Groups[i])) {
supported = true
return nil
}
}
return metricsUnsupportedErr
}
func checkMetricsVersion(grp *metav1.APIGroup) bool {
for _, v := range grp.Versions {
for _, supportedVersion := range supportedMetricsAPIVersions {
if v.Version == supportedVersion {
return true
}
}
}
return false
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/client/types.go | internal/client/types.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package client
import (
"k8s.io/apimachinery/pkg/version"
"k8s.io/client-go/discovery/cached/disk"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
mv1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1"
versioned "k8s.io/metrics/pkg/client/clientset/versioned"
)
const (
// NA Not available.
NA = "n/a"
// NamespaceAll designates the fictional all namespace.
NamespaceAll = "all"
// BlankNamespace designates no namespace.
BlankNamespace = ""
// DefaultNamespace designates the default namespace.
DefaultNamespace = "default"
// ClusterScope designates a resource is not namespaced.
ClusterScope = "-"
// NotNamespaced designates a non resource namespace.
NotNamespaced = "*"
// CreateVerb represents create access on a resource.
CreateVerb = "create"
// UpdateVerb represents an update access on a resource.
UpdateVerb = "update"
// PatchVerb represents a patch access on a resource.
PatchVerb = "patch"
// DeleteVerb represents a delete access on a resource.
DeleteVerb = "delete"
// GetVerb represents a get access on a resource.
GetVerb = "get"
// ListVerb represents a list access on a resource.
ListVerb = "list"
// WatchVerb represents a watch access on a resource.
WatchVerb = "watch"
)
var (
// PatchAccess patch a resource.
PatchAccess = []string{PatchVerb}
// GetAccess reads a resource.
GetAccess = []string{GetVerb}
// ListAccess list resources.
ListAccess = []string{ListVerb}
// MonitorAccess monitors a collection of resources.
MonitorAccess = []string{ListVerb, WatchVerb}
// ReadAllAccess represents an all read access to a resource.
ReadAllAccess = []string{GetVerb, ListVerb, WatchVerb}
)
// ContainersMetrics tracks containers metrics.
type ContainersMetrics map[string]*mv1beta1.ContainerMetrics
// NodesMetricsMap tracks node metrics.
type NodesMetricsMap map[string]*mv1beta1.NodeMetrics
// PodsMetricsMap tracks pod metrics.
type PodsMetricsMap map[string]*mv1beta1.PodMetrics
// Authorizer checks what a user can or cannot do to a resource.
type Authorizer interface {
// CanI returns true if the user can use these actions for a given resource.
CanI(ns string, gvr *GVR, n string, verbs []string) (bool, error)
}
// Connection represents a Kubernetes apiserver connection.
type Connection interface {
Authorizer
// Config returns current config.
Config() *Config
// ConnectionOK checks api server connection status.
ConnectionOK() bool
// Dial connects to api server.
Dial() (kubernetes.Interface, error)
// DialLogs connects to api server for logs.
DialLogs() (kubernetes.Interface, error)
// SwitchContext switches cluster based on context.
SwitchContext(ctx string) error
// CachedDiscovery connects to discovery client.
CachedDiscovery() (*disk.CachedDiscoveryClient, error)
// RestConfig connects to rest client.
RestConfig() (*restclient.Config, error)
// MXDial connects to metrics server.
MXDial() (*versioned.Clientset, error)
// DynDial connects to dynamic client.
DynDial() (dynamic.Interface, error)
// HasMetrics checks if metrics server is available.
HasMetrics() bool
// ValidNamespaceNames returns all available namespace names.
ValidNamespaceNames() (NamespaceNames, error)
// IsValidNamespace checks if given namespace is known.
IsValidNamespace(string) bool
// ServerVersion returns current server version.
ServerVersion() (*version.Info, error)
// CheckConnectivity checks if api server connection is happy or not.
CheckConnectivity() bool
// ActiveContext returns the current context name.
ActiveContext() string
// ActiveNamespace returns the current namespace.
ActiveNamespace() string
// IsActiveNamespace checks if given ns is active.
IsActiveNamespace(string) bool
}
// CurrentMetrics tracks current cpu/mem.
type CurrentMetrics struct {
CurrentCPU, CurrentMEM, CurrentEphemeral int64
}
// PodMetrics represent an aggregation of all pod containers metrics.
type PodMetrics CurrentMetrics
// NodeMetrics describes raw node metrics.
type NodeMetrics struct {
CurrentMetrics
AllocatableCPU, AllocatableMEM, AllocatableEphemeral int64
AvailableCPU, AvailableMEM, AvailableEphemeral int64
TotalCPU, TotalMEM, TotalEphemeral int64
}
// ClusterMetrics summarizes total node metrics as percentages.
type ClusterMetrics struct {
PercCPU, PercMEM, PercEphemeral int
}
// NodesMetrics tracks usage metrics per nodes.
type NodesMetrics map[string]NodeMetrics
// PodsMetrics tracks usage metrics per pods.
type PodsMetrics map[string]PodMetrics
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/client/errors.go | internal/client/errors.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package client
import metricsapi "k8s.io/metrics/pkg/apis/metrics"
// Error represents an error.
type Error string
// Error returns the error text.
func (e Error) Error() string {
return string(e)
}
const (
noMetricServerErr = Error("No metrics-server detected")
metricsUnsupportedErr = Error("No metrics api group " + metricsapi.GroupName + " found on cluster")
)
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/client/helper_test.go | internal/client/helper_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package client_test
import (
"testing"
"github.com/derailed/k9s/internal/client"
"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func TestMetaFQN(t *testing.T) {
uu := map[string]struct {
meta metav1.ObjectMeta
e string
}{
"empty": {
e: "-/",
},
"full": {
meta: metav1.ObjectMeta{Name: "blee", Namespace: "ns1"},
e: "ns1/blee",
},
"no-ns": {
meta: metav1.ObjectMeta{Name: "blee"},
e: "-/blee",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, client.MetaFQN(&u.meta))
})
}
}
func TestCoFQN(t *testing.T) {
uu := map[string]struct {
meta metav1.ObjectMeta
co string
e string
}{
"empty": {
e: "-/:",
},
"full": {
meta: metav1.ObjectMeta{Name: "blee", Namespace: "ns1"},
co: "fred",
e: "ns1/blee:fred",
},
"no-co": {
meta: metav1.ObjectMeta{Name: "blee", Namespace: "ns1"},
e: "ns1/blee:",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, client.CoFQN(&u.meta, u.co))
})
}
}
func TestIsClusterScoped(t *testing.T) {
uu := map[string]struct {
ns string
e bool
}{
"empty": {},
"all": {
ns: client.NamespaceAll,
},
"none": {
ns: client.BlankNamespace,
},
"custom": {
ns: "fred",
},
"scoped": {
ns: "-",
e: true,
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, client.IsClusterScoped(u.ns))
})
}
}
func TestIsNamespaced(t *testing.T) {
uu := map[string]struct {
ns string
e bool
}{
"empty": {},
"all": {
ns: client.NamespaceAll,
},
"cluster": {
ns: client.ClusterScope,
},
"none": {
ns: client.BlankNamespace,
},
"custom": {
ns: "fred",
e: true,
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, client.IsNamespaced(u.ns))
})
}
}
func TestIsAllNamespaces(t *testing.T) {
uu := map[string]struct {
ns string
e bool
}{
"empty": {
e: true,
},
"all": {
ns: client.NamespaceAll,
e: true,
},
"none": {
ns: client.BlankNamespace,
e: true,
},
"custom": {
ns: "fred",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, client.IsAllNamespaces(u.ns))
})
}
}
func TestIsAllNamespace(t *testing.T) {
uu := map[string]struct {
ns string
e bool
}{
"empty": {},
"all": {
ns: client.NamespaceAll,
e: true,
},
"custom": {
ns: "fred",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, client.IsAllNamespace(u.ns))
})
}
}
func TestCleanseNamespace(t *testing.T) {
uu := map[string]struct {
ns, e string
}{
"empty": {},
"all": {
ns: client.NamespaceAll,
e: client.BlankNamespace,
},
"custom": {
ns: "fred",
e: "fred",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, client.CleanseNamespace(u.ns))
})
}
}
func TestNamespaced(t *testing.T) {
uu := []struct {
p, ns, n string
}{
{"fred/blee", "fred", "blee"},
{"blee", "", "blee"},
}
for _, u := range uu {
ns, n := client.Namespaced(u.p)
assert.Equal(t, u.ns, ns)
assert.Equal(t, u.n, n)
}
}
func TestFQN(t *testing.T) {
uu := []struct {
ns, n string
e string
}{
{"fred", "blee", "fred/blee"},
{"", "blee", "blee"},
}
for _, u := range uu {
assert.Equal(t, u.e, client.FQN(u.ns, u.n))
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/client/config.go | internal/client/config.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package client
import (
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"time"
"k8s.io/cli-runtime/pkg/genericclioptions"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/clientcmd/api"
)
const (
// DefaultCallTimeoutDuration is the default api server call timeout duration.
DefaultCallTimeoutDuration time.Duration = 120 * time.Second
// UsePersistentConfig caches client config to avoid reloads.
UsePersistentConfig = true
)
// Config tracks a kubernetes configuration.
type Config struct {
flags *genericclioptions.ConfigFlags
mx sync.RWMutex
proxy func(*http.Request) (*url.URL, error)
}
// NewConfig returns a new k8s config or an error if the flags are invalid.
func NewConfig(f *genericclioptions.ConfigFlags) *Config {
return &Config{
flags: f,
}
}
// CallTimeout returns the call timeout if set or the default if not set.
func (c *Config) CallTimeout() time.Duration {
if !isSet(c.flags.Timeout) {
return DefaultCallTimeoutDuration
}
dur, err := time.ParseDuration(*c.flags.Timeout)
if err != nil {
return DefaultCallTimeoutDuration
}
return dur
}
func (c *Config) RESTConfig() (*restclient.Config, error) {
cfg, err := c.clientConfig().ClientConfig()
if err != nil {
return nil, err
}
if c.proxy != nil {
cfg.Proxy = c.proxy
}
return cfg, nil
}
// Flags returns configuration flags.
func (c *Config) Flags() *genericclioptions.ConfigFlags {
return c.flags
}
func (c *Config) RawConfig() (api.Config, error) {
return c.clientConfig().RawConfig()
}
func (c *Config) clientConfig() clientcmd.ClientConfig {
return c.flags.ToRawKubeConfigLoader()
}
func (*Config) reset() {}
// SwitchContext changes the kubeconfig context to a new cluster.
func (c *Config) SwitchContext(name string) error {
ct, err := c.GetContext(name)
if err != nil {
return fmt.Errorf("context %q does not exist", name)
}
// !!BOZO!! Do you need to reset the flags?
flags := genericclioptions.NewConfigFlags(UsePersistentConfig)
flags.Context, flags.ClusterName = &name, &ct.Cluster
flags.Namespace = c.flags.Namespace
flags.Timeout = c.flags.Timeout
flags.KubeConfig = c.flags.KubeConfig
flags.Impersonate = c.flags.Impersonate
flags.ImpersonateGroup = c.flags.ImpersonateGroup
flags.ImpersonateUID = c.flags.ImpersonateUID
flags.Insecure = c.flags.Insecure
flags.BearerToken = c.flags.BearerToken
c.flags = flags
return nil
}
func (c *Config) Clone(ns string) (*genericclioptions.ConfigFlags, error) {
flags := genericclioptions.NewConfigFlags(false)
ct, err := c.CurrentContextName()
if err != nil {
return nil, err
}
cl, err := c.CurrentClusterName()
if err != nil {
return nil, err
}
flags.Context, flags.ClusterName = &ct, &cl
flags.Namespace = &ns
flags.Timeout = c.Flags().Timeout
flags.KubeConfig = c.Flags().KubeConfig
return flags, nil
}
// CurrentClusterName returns the currently active cluster name.
func (c *Config) CurrentClusterName() (string, error) {
if isSet(c.flags.ClusterName) {
return *c.flags.ClusterName, nil
}
cfg, err := c.RawConfig()
if err != nil {
return "", err
}
ct, ok := cfg.Contexts[cfg.CurrentContext]
if !ok {
return "", fmt.Errorf("invalid current context specified: %q", cfg.CurrentContext)
}
if isSet(c.flags.Context) {
ct, ok = cfg.Contexts[*c.flags.Context]
if !ok {
return "", fmt.Errorf("current-cluster - invalid context specified: %q", *c.flags.Context)
}
}
return ct.Cluster, nil
}
// CurrentContextName returns the currently active config context.
func (c *Config) CurrentContextName() (string, error) {
if isSet(c.flags.Context) {
return *c.flags.Context, nil
}
cfg, err := c.RawConfig()
if err != nil {
return "", fmt.Errorf("fail to load rawConfig: %w", err)
}
return cfg.CurrentContext, nil
}
func (c *Config) CurrentContextNamespace() (string, error) {
name, err := c.CurrentContextName()
if err != nil {
return "", err
}
context, err := c.GetContext(name)
if err != nil {
return "", err
}
return context.Namespace, nil
}
// CurrentContext returns the current context configuration.
func (c *Config) CurrentContext() (*api.Context, error) {
n, err := c.CurrentContextName()
if err != nil {
return nil, err
}
return c.GetContext(n)
}
// GetContext fetch a given context or error if it does not exist.
func (c *Config) GetContext(n string) (*api.Context, error) {
cfg, err := c.RawConfig()
if err != nil {
return nil, err
}
if c, ok := cfg.Contexts[n]; ok {
return c, nil
}
return nil, fmt.Errorf("getcontext - invalid context specified: %q", n)
}
// SetProxy sets the proxy function.
func (c *Config) SetProxy(proxy func(*http.Request) (*url.URL, error)) {
c.proxy = proxy
}
// Contexts fetch all available contexts.
func (c *Config) Contexts() (map[string]*api.Context, error) {
cfg, err := c.RawConfig()
if err != nil {
return nil, err
}
return cfg.Contexts, nil
}
// DelContext remove a given context from the configuration.
func (c *Config) DelContext(n string) error {
cfg, err := c.RawConfig()
if err != nil {
return err
}
delete(cfg.Contexts, n)
acc, err := c.ConfigAccess()
if err != nil {
return err
}
return clientcmd.ModifyConfig(acc, cfg, true)
}
// RenameContext renames a context.
func (c *Config) RenameContext(oldCtx, newCtx string) error {
cfg, err := c.RawConfig()
if err != nil {
return err
}
if _, ok := cfg.Contexts[newCtx]; ok {
return fmt.Errorf("context with name %s already exists", newCtx)
}
cfg.Contexts[newCtx] = cfg.Contexts[oldCtx]
delete(cfg.Contexts, oldCtx)
acc, err := c.ConfigAccess()
if err != nil {
return err
}
if e := clientcmd.ModifyConfig(acc, cfg, true); e != nil {
return e
}
current, err := c.CurrentContextName()
if err != nil {
return err
}
if current == oldCtx {
return c.SwitchContext(newCtx)
}
return nil
}
// ContextNames fetch all available contexts.
func (c *Config) ContextNames() (map[string]struct{}, error) {
cfg, err := c.RawConfig()
if err != nil {
return nil, err
}
cc := make(map[string]struct{}, len(cfg.Contexts))
for n := range cfg.Contexts {
cc[n] = struct{}{}
}
return cc, nil
}
// CurrentGroupNames retrieves the active group names.
func (c *Config) CurrentGroupNames() ([]string, error) {
if areSet(c.flags.ImpersonateGroup) {
return *c.flags.ImpersonateGroup, nil
}
return []string{}, errors.New("unable to locate current group")
}
// ImpersonateGroups retrieves the active groups if set on the CLI.
func (c *Config) ImpersonateGroups() (string, error) {
if areSet(c.flags.ImpersonateGroup) {
return strings.Join(*c.flags.ImpersonateGroup, ","), nil
}
return "", errors.New("no groups set")
}
// ImpersonateUser retrieves the active user name if set on the CLI.
func (c *Config) ImpersonateUser() (string, error) {
if isSet(c.flags.Impersonate) {
return *c.flags.Impersonate, nil
}
return "", errors.New("no user set")
}
// CurrentUserName retrieves the active user name.
func (c *Config) CurrentUserName() (string, error) {
if isSet(c.flags.Impersonate) {
return *c.flags.Impersonate, nil
}
if isSet(c.flags.AuthInfoName) {
return *c.flags.AuthInfoName, nil
}
cfg, err := c.RawConfig()
if err != nil {
return "", err
}
current := cfg.CurrentContext
if isSet(c.flags.Context) {
current = *c.flags.Context
}
if ctx, ok := cfg.Contexts[current]; ok {
return ctx.AuthInfo, nil
}
return "", errors.New("unable to locate current user")
}
// CurrentNamespaceName retrieves the active namespace.
func (c *Config) CurrentNamespaceName() (string, error) {
ns, overridden, err := c.clientConfig().Namespace()
if err != nil {
return BlankNamespace, err
}
// Checks if ns is passed is in args.
if overridden {
return ns, nil
}
// Return ns set in context if any??
return c.CurrentContextNamespace()
}
// ConfigAccess return the current kubeconfig api server access configuration.
func (c *Config) ConfigAccess() (clientcmd.ConfigAccess, error) {
c.mx.RLock()
defer c.mx.RUnlock()
return c.clientConfig().ConfigAccess(), nil
}
// ----------------------------------------------------------------------------
// Helpers...
func isSet(s *string) bool {
return s != nil && *s != ""
}
func areSet(ss *[]string) bool {
return ss != nil && len(*ss) != 0
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/client/client_test.go | internal/client/client_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package client
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
authorizationv1 "k8s.io/api/authorization/v1"
)
func TestMakeSAR(t *testing.T) {
uu := map[string]struct {
ns string
gvr *GVR
sar *authorizationv1.SelfSubjectAccessReview
}{
"all-pods": {
ns: NamespaceAll,
gvr: PodGVR,
sar: &authorizationv1.SelfSubjectAccessReview{
Spec: authorizationv1.SelfSubjectAccessReviewSpec{
ResourceAttributes: &authorizationv1.ResourceAttributes{
Namespace: NamespaceAll,
Version: "v1",
Resource: "pods",
},
},
},
},
"ns-pods": {
ns: "fred",
gvr: PodGVR,
sar: &authorizationv1.SelfSubjectAccessReview{
Spec: authorizationv1.SelfSubjectAccessReviewSpec{
ResourceAttributes: &authorizationv1.ResourceAttributes{
Namespace: "fred",
Version: "v1",
Resource: "pods",
},
},
},
},
"clusterscope-ns": {
ns: ClusterScope,
gvr: NsGVR,
sar: &authorizationv1.SelfSubjectAccessReview{
Spec: authorizationv1.SelfSubjectAccessReviewSpec{
ResourceAttributes: &authorizationv1.ResourceAttributes{
Version: "v1",
Resource: "namespaces",
},
},
},
},
"subres-pods": {
ns: "fred",
gvr: NewGVR("v1/pods:logs"),
sar: &authorizationv1.SelfSubjectAccessReview{
Spec: authorizationv1.SelfSubjectAccessReviewSpec{
ResourceAttributes: &authorizationv1.ResourceAttributes{
Namespace: "fred",
Version: "v1",
Resource: "pods",
Subresource: "logs",
},
},
},
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.sar, makeSAR(u.ns, u.gvr, ""))
})
}
}
func TestIsValidNamespace(t *testing.T) {
c := NewTestAPIClient()
uu := map[string]struct {
ns string
cache NamespaceNames
ok bool
}{
"all-ns": {
ns: NamespaceAll,
cache: NamespaceNames{
DefaultNamespace: {},
},
ok: true,
},
"blank-ns": {
ns: BlankNamespace,
cache: NamespaceNames{
DefaultNamespace: {},
},
ok: true,
},
"cluster-ns": {
ns: ClusterScope,
cache: NamespaceNames{
DefaultNamespace: {},
},
ok: true,
},
"no-ns": {
ns: NotNamespaced,
cache: NamespaceNames{
DefaultNamespace: {},
},
ok: true,
},
"default-ns": {
ns: DefaultNamespace,
cache: NamespaceNames{
DefaultNamespace: {},
},
ok: true,
},
"valid-ns": {
ns: "fred",
cache: NamespaceNames{
"fred": {},
},
ok: true,
},
"invalid-ns": {
ns: "fred",
cache: NamespaceNames{
DefaultNamespace: {},
},
},
}
expiry := 1 * time.Millisecond
for k := range uu {
u := uu[k]
c.cache.Add("validNamespaces", u.cache, expiry)
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.ok, c.IsValidNamespace(u.ns))
})
}
}
func TestCheckCacheBool(t *testing.T) {
c := NewTestAPIClient()
const key = "fred"
uu := map[string]struct {
key string
val any
found, actual, sleep bool
}{
"setTrue": {
key: key,
val: true,
found: true,
actual: true,
},
"setFalse": {
key: key,
val: false,
found: true,
},
"missing": {
key: "blah",
val: false,
},
"expired": {
key: key,
val: true,
sleep: true,
},
}
expiry := 1 * time.Millisecond
for k := range uu {
u := uu[k]
c.cache.Add(key, u.val, expiry)
if u.sleep {
time.Sleep(expiry)
}
t.Run(k, func(t *testing.T) {
val, ok := c.checkCacheBool(u.key)
assert.Equal(t, u.found, ok)
assert.Equal(t, u.actual, val)
})
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/client/config_test.go | internal/client/config_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package client_test
import (
"errors"
"log/slog"
"os"
"testing"
"time"
"github.com/derailed/k9s/internal/client"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"k8s.io/cli-runtime/pkg/genericclioptions"
)
var kubeConfig = "./testdata/config"
func init() {
slog.SetDefault(slog.New(slog.DiscardHandler))
}
func TestCallTimeout(t *testing.T) {
uu := map[string]struct {
t string
e time.Duration
}{
"custom": {
t: "1m",
e: 1 * time.Minute,
},
"default": {
e: client.DefaultCallTimeoutDuration,
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
flags := genericclioptions.NewConfigFlags(false)
flags.Timeout = &u.t
cfg := client.NewConfig(flags)
assert.Equal(t, u.e, cfg.CallTimeout())
})
}
}
func TestConfigCurrentContext(t *testing.T) {
uu := map[string]struct {
context string
e string
}{
"default": {
e: "fred",
},
"custom": {
context: "blee",
e: "blee",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
flags := genericclioptions.NewConfigFlags(false)
flags.KubeConfig = &kubeConfig
if u.context != "" {
flags.Context = &u.context
}
cfg := client.NewConfig(flags)
ctx, err := cfg.CurrentContextName()
require.NoError(t, err)
assert.Equal(t, u.e, ctx)
})
}
}
func TestConfigCurrentCluster(t *testing.T) {
name := "blee"
uu := map[string]struct {
flags *genericclioptions.ConfigFlags
cluster string
}{
"default": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &kubeConfig,
},
cluster: "zorg",
},
"custom": {
flags: &genericclioptions.ConfigFlags{
KubeConfig: &kubeConfig,
Context: &name,
},
cluster: "blee",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
cfg := client.NewConfig(u.flags)
ct, err := cfg.CurrentClusterName()
require.NoError(t, err)
assert.Equal(t, u.cluster, ct)
})
}
}
func TestConfigCurrentUser(t *testing.T) {
name := "blee"
uu := map[string]struct {
flags *genericclioptions.ConfigFlags
user string
}{
"default": {
flags: &genericclioptions.ConfigFlags{KubeConfig: &kubeConfig},
user: "fred",
},
"custom": {
flags: &genericclioptions.ConfigFlags{KubeConfig: &kubeConfig, AuthInfoName: &name},
user: "blee",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
cfg := client.NewConfig(u.flags)
ctx, err := cfg.CurrentUserName()
require.NoError(t, err)
assert.Equal(t, u.user, ctx)
})
}
}
func TestConfigCurrentNamespace(t *testing.T) {
bleeNS, bleeCTX := "blee", "blee"
uu := map[string]struct {
flags *genericclioptions.ConfigFlags
namespace string
}{
"default": {
flags: &genericclioptions.ConfigFlags{KubeConfig: &kubeConfig},
namespace: "",
},
"withContext": {
flags: &genericclioptions.ConfigFlags{KubeConfig: &kubeConfig, Context: &bleeCTX},
namespace: "zorg",
},
"withNS": {
flags: &genericclioptions.ConfigFlags{KubeConfig: &kubeConfig, Namespace: &bleeNS},
namespace: "blee",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
cfg := client.NewConfig(u.flags)
ns, err := cfg.CurrentNamespaceName()
if ns != "" {
require.NoError(t, err)
}
assert.Equal(t, u.namespace, ns)
})
}
}
func TestConfigGetContext(t *testing.T) {
uu := map[string]struct {
cluster string
err error
}{
"default": {
cluster: "blee",
},
"custom": {
cluster: "bozo",
err: errors.New(`getcontext - invalid context specified: "bozo"`),
},
}
flags := &genericclioptions.ConfigFlags{KubeConfig: &kubeConfig}
cfg := client.NewConfig(flags)
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
ctx, err := cfg.GetContext(u.cluster)
if err != nil {
assert.Equal(t, u.err, err)
} else {
assert.NotNil(t, ctx)
assert.Equal(t, u.cluster, ctx.Cluster)
}
})
}
}
func TestConfigSwitchContext(t *testing.T) {
cluster := "duh"
flags := genericclioptions.ConfigFlags{
KubeConfig: &kubeConfig,
Context: &cluster,
}
cfg := client.NewConfig(&flags)
err := cfg.SwitchContext("blee")
require.NoError(t, err)
ctx, err := cfg.CurrentContextName()
require.NoError(t, err)
assert.Equal(t, "blee", ctx)
}
func TestConfigAccess(t *testing.T) {
context := "duh"
flags := genericclioptions.ConfigFlags{
KubeConfig: &kubeConfig,
Context: &context,
}
cfg := client.NewConfig(&flags)
acc, err := cfg.ConfigAccess()
require.NoError(t, err)
assert.NotEmpty(t, acc.GetDefaultFilename())
}
func TestConfigContextNames(t *testing.T) {
cluster := "duh"
flags := genericclioptions.ConfigFlags{
KubeConfig: &kubeConfig,
Context: &cluster,
}
cfg := client.NewConfig(&flags)
cc, err := cfg.ContextNames()
require.NoError(t, err)
assert.Len(t, cc, 3)
}
func TestConfigContexts(t *testing.T) {
context := "duh"
flags := genericclioptions.ConfigFlags{
KubeConfig: &kubeConfig,
Context: &context,
}
cfg := client.NewConfig(&flags)
cc, err := cfg.Contexts()
require.NoError(t, err)
assert.Len(t, cc, 3)
}
func TestConfigDelContext(t *testing.T) {
require.NoError(t, cp("./testdata/config.2", "./testdata/config.1"))
context, kubeCfg := "duh", "./testdata/config.1"
flags := genericclioptions.ConfigFlags{
KubeConfig: &kubeCfg,
Context: &context,
}
cfg := client.NewConfig(&flags)
err := cfg.DelContext("fred")
require.NoError(t, err)
cc, err := cfg.ContextNames()
require.NoError(t, err)
assert.Len(t, cc, 1)
_, ok := cc["blee"]
assert.True(t, ok)
}
func TestConfigRestConfig(t *testing.T) {
flags := genericclioptions.ConfigFlags{
KubeConfig: &kubeConfig,
}
cfg := client.NewConfig(&flags)
rc, err := cfg.RESTConfig()
require.NoError(t, err)
assert.Equal(t, "https://localhost:3002", rc.Host)
}
func TestConfigBadConfig(t *testing.T) {
kubeConfig := "./testdata/bork_config"
flags := genericclioptions.ConfigFlags{
KubeConfig: &kubeConfig,
}
cfg := client.NewConfig(&flags)
_, err := cfg.RESTConfig()
assert.Error(t, err)
}
// Helpers...
func cp(src, dst string) error {
data, err := os.ReadFile(src)
if err != nil {
return err
}
return os.WriteFile(dst, data, 0600)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/client/metrics_test.go | internal/client/metrics_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package client_test
import (
"testing"
"github.com/derailed/k9s/internal/client"
"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"
v1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1"
)
func TestToPercentage(t *testing.T) {
uu := []struct {
v1, v2 int64
e int
}{
{0, 0, 0},
{100, 200, 50},
{200, 100, 200},
{224, 4000, 5},
}
for _, u := range uu {
assert.Equal(t, u.e, client.ToPercentage(u.v1, u.v2))
}
}
func TestToMB(t *testing.T) {
uu := []struct {
v int64
e int64
}{
{0, 0},
{2 * client.MegaByte, 2},
{10 * client.MegaByte, 10},
}
for _, u := range uu {
assert.Equal(t, u.e, client.ToMB(u.v))
}
}
func TestPodsMetrics(t *testing.T) {
uu := map[string]struct {
metrics *v1beta1.PodMetricsList
eSize int
e client.PodsMetrics
}{
"dud": {
eSize: 0,
},
"ok": {
metrics: &v1beta1.PodMetricsList{
Items: []v1beta1.PodMetrics{
*makeMxPod("p1", "1", "4Gi"),
*makeMxPod("p2", "50m", "1Mi"),
},
},
eSize: 2,
e: client.PodsMetrics{
"default/p1": client.PodMetrics{
CurrentCPU: 3000,
CurrentMEM: 12288,
},
},
},
}
m := client.NewMetricsServer(nil)
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
mmx := make(client.PodsMetrics)
m.PodsMetrics(u.metrics, mmx)
assert.Len(t, mmx, u.eSize)
if u.eSize == 0 {
return
}
mx, ok := mmx["default/p1"]
assert.True(t, ok)
assert.Equal(t, u.e["default/p1"], mx)
})
}
}
func BenchmarkPodsMetrics(b *testing.B) {
m := client.NewMetricsServer(nil)
metrics := v1beta1.PodMetricsList{
Items: []v1beta1.PodMetrics{
*makeMxPod("p1", "1", "4Gi"),
*makeMxPod("p2", "50m", "1Mi"),
*makeMxPod("p3", "50m", "1Mi"),
},
}
mmx := make(client.PodsMetrics, 3)
b.ResetTimer()
b.ReportAllocs()
for range b.N {
m.PodsMetrics(&metrics, mmx)
}
}
func TestNodesMetrics(t *testing.T) {
uu := map[string]struct {
nodes *v1.NodeList
metrics *v1beta1.NodeMetricsList
eSize int
e client.NodesMetrics
}{
"duds": {
eSize: 0,
},
"no_nodes": {
metrics: &v1beta1.NodeMetricsList{
Items: []v1beta1.NodeMetrics{
*makeMxNode("n1", "10", "8Gi"),
*makeMxNode("n2", "50m", "1Mi"),
},
},
eSize: 0,
},
"no_metrics": {
nodes: &v1.NodeList{
Items: []v1.Node{
makeNode("n1", "32", "128Gi", "50m", "2Mi"),
makeNode("n2", "8", "4Gi", "50m", "10Mi"),
},
},
eSize: 0,
},
"ok": {
nodes: &v1.NodeList{
Items: []v1.Node{
makeNode("n1", "32", "128Gi", "32", "128Gi"),
makeNode("n2", "8", "4Gi", "8", "4Gi"),
},
},
metrics: &v1beta1.NodeMetricsList{
Items: []v1beta1.NodeMetrics{
*makeMxNode("n1", "10", "8Gi"),
*makeMxNode("n2", "50m", "1Mi"),
},
},
eSize: 2,
e: client.NodesMetrics{
"n1": client.NodeMetrics{
TotalCPU: 32000,
TotalMEM: 131072,
AllocatableCPU: 32000,
AllocatableMEM: 131072,
AvailableCPU: 22000,
AvailableMEM: 122880,
CurrentMetrics: client.CurrentMetrics{
CurrentCPU: 10000,
CurrentMEM: 8192,
},
},
},
},
}
m := client.NewMetricsServer(nil)
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
mmx := make(client.NodesMetrics)
m.NodesMetrics(u.nodes, u.metrics, mmx)
assert.Len(t, mmx, u.eSize)
if u.eSize == 0 {
return
}
mx, ok := mmx["n1"]
assert.True(t, ok)
assert.Equal(t, u.e["n1"], mx)
})
}
}
func BenchmarkNodesMetrics(b *testing.B) {
nodes := v1.NodeList{
Items: []v1.Node{
makeNode("n1", "100m", "4Mi", "100m", "2Mi"),
makeNode("n2", "100m", "4Mi", "100m", "2Mi"),
},
}
metrics := v1beta1.NodeMetricsList{
Items: []v1beta1.NodeMetrics{
*makeMxNode("n1", "50m", "1Mi"),
*makeMxNode("n2", "50m", "1Mi"),
},
}
m := client.NewMetricsServer(nil)
mmx := make(client.NodesMetrics)
b.ResetTimer()
b.ReportAllocs()
for range b.N {
m.NodesMetrics(&nodes, &metrics, mmx)
}
}
func TestClusterLoad(t *testing.T) {
uu := map[string]struct {
nodes *v1.NodeList
metrics *v1beta1.NodeMetricsList
eSize int
e client.ClusterMetrics
}{
"duds": {
eSize: 0,
},
"no_nodes": {
metrics: &v1beta1.NodeMetricsList{
Items: []v1beta1.NodeMetrics{
*makeMxNode("n1", "10", "8Gi"),
*makeMxNode("n2", "50m", "1Mi"),
},
},
eSize: 0,
},
"no_metrics": {
nodes: &v1.NodeList{
Items: []v1.Node{
makeNode("n1", "32", "128Gi", "50m", "2Mi"),
makeNode("n2", "8", "4Gi", "50m", "10Mi"),
},
},
eSize: 0,
},
"ok": {
nodes: &v1.NodeList{
Items: []v1.Node{
makeNode("n1", "100m", "4Mi", "50m", "2Mi"),
makeNode("n2", "100m", "4Mi", "50m", "2Mi"),
},
},
metrics: &v1beta1.NodeMetricsList{
Items: []v1beta1.NodeMetrics{
*makeMxNode("n1", "50m", "1Mi"),
*makeMxNode("n2", "50m", "1Mi"),
},
},
eSize: 2,
e: client.ClusterMetrics{
PercCPU: 100.0,
PercMEM: 50.0,
},
},
}
m := client.NewMetricsServer(nil)
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
var cmx client.ClusterMetrics
_ = m.ClusterLoad(u.nodes, u.metrics, &cmx)
assert.Equal(t, u.e, cmx)
})
}
}
func BenchmarkClusterLoad(b *testing.B) {
nodes := v1.NodeList{
Items: []v1.Node{
makeNode("n1", "100m", "4Mi", "50m", "2Mi"),
makeNode("n2", "100m", "4Mi", "50m", "2Mi"),
},
}
metrics := v1beta1.NodeMetricsList{
Items: []v1beta1.NodeMetrics{
*makeMxNode("n1", "50m", "1Mi"),
*makeMxNode("n2", "50m", "1Mi"),
},
}
m := client.NewMetricsServer(nil)
var mx client.ClusterMetrics
b.ResetTimer()
b.ReportAllocs()
for range b.N {
_ = m.ClusterLoad(&nodes, &metrics, &mx)
}
}
// ----------------------------------------------------------------------------
// Helpers...
func makeMxPod(name, cpu, mem string) *v1beta1.PodMetrics {
return &v1beta1.PodMetrics{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: "default",
},
Containers: []v1beta1.ContainerMetrics{
{Usage: makeRes(cpu, mem)},
{Usage: makeRes(cpu, mem)},
{Usage: makeRes(cpu, mem)},
},
}
}
func makeNode(name, tcpu, tmem, acpu, amem string) v1.Node {
return v1.Node{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Status: v1.NodeStatus{
Capacity: makeRes(tcpu, tmem),
Allocatable: makeRes(acpu, amem),
},
}
}
func makeMxNode(name, cpu, mem string) *v1beta1.NodeMetrics {
return &v1beta1.NodeMetrics{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Usage: makeRes(cpu, mem),
}
}
func makeRes(c, m string) v1.ResourceList {
cpu, _ := resource.ParseQuantity(c)
mem, _ := resource.ParseQuantity(m)
return v1.ResourceList{
v1.ResourceCPU: cpu,
v1.ResourceMemory: mem,
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/client/gvrs.go | internal/client/gvrs.go | package client
import "k8s.io/apimachinery/pkg/util/sets"
var (
// Apps...
DpGVR = NewGVR("apps/v1/deployments")
StsGVR = NewGVR("apps/v1/statefulsets")
DsGVR = NewGVR("apps/v1/daemonsets")
RsGVR = NewGVR("apps/v1/replicasets")
// Core...
SaGVR = NewGVR("v1/serviceaccounts")
PvcGVR = NewGVR("v1/persistentvolumeclaims")
PvGVR = NewGVR("v1/persistentvolumes")
CmGVR = NewGVR("v1/configmaps")
SecGVR = NewGVR("v1/secrets")
EvGVR = NewGVR("events.k8s.io/v1/events")
EpGVR = NewGVR("v1/endpoints")
PodGVR = NewGVR("v1/pods")
NsGVR = NewGVR("v1/namespaces")
NodeGVR = NewGVR("v1/nodes")
SvcGVR = NewGVR("v1/services")
// Discovery...
EpsGVR = NewGVR("discovery.k8s.io/v1/endpointslices")
// Autoscaling...
HpaGVR = NewGVR("autoscaling/v1/horizontalpodautoscalers")
// Batch...
CjGVR = NewGVR("batch/v1/cronjobs")
JobGVR = NewGVR("batch/v1/jobs")
// Misc...
CrdGVR = NewGVR("apiextensions.k8s.io/v1/customresourcedefinitions")
PcGVR = NewGVR("scheduling.k8s.io/v1/priorityclasses")
NpGVR = NewGVR("networking.k8s.io/v1/networkpolicies")
ScGVR = NewGVR("storage.k8s.io/v1/storageclasses")
// Policy...
PdbGVR = NewGVR("policy/v1/poddisruptionbudgets")
PspGVR = NewGVR("policy/v1beta1/podsecuritypolicies")
IngGVR = NewGVR("networking.k8s.io/v1/ingresses")
// Metrics...
NmxGVR = NewGVR("metrics.k8s.io/v1beta1/nodes")
PmxGVR = NewGVR("metrics.k8s.io/v1beta1/pods")
// K9s...
CpuGVR = NewGVR("cpu")
MemGVR = NewGVR("memory")
WkGVR = NewGVR("workloads")
CoGVR = NewGVR("containers")
CtGVR = NewGVR("contexts")
RefGVR = NewGVR("references")
PuGVR = NewGVR("pulses")
ScnGVR = NewGVR("scans")
DirGVR = NewGVR("dirs")
PfGVR = NewGVR("portforwards")
SdGVR = NewGVR("screendumps")
BeGVR = NewGVR("benchmarks")
AliGVR = NewGVR("aliases")
XGVR = NewGVR("xrays")
HlpGVR = NewGVR("help")
QGVR = NewGVR("quit")
// Helm...
HmGVR = NewGVR("helm")
HmhGVR = NewGVR("helm-history")
// RBAC...
RbacGVR = NewGVR("rbac")
PolGVR = NewGVR("policy")
UsrGVR = NewGVR("users")
GrpGVR = NewGVR("groups")
CrGVR = NewGVR("rbac.authorization.k8s.io/v1/clusterroles")
CrbGVR = NewGVR("rbac.authorization.k8s.io/v1/clusterrolebindings")
RoGVR = NewGVR("rbac.authorization.k8s.io/v1/roles")
RobGVR = NewGVR("rbac.authorization.k8s.io/v1/rolebindings")
)
var reservedGVRs = sets.New(
CpuGVR,
MemGVR,
WkGVR,
CoGVR,
CtGVR,
RefGVR,
PuGVR,
ScnGVR,
DirGVR,
PfGVR,
SdGVR,
BeGVR,
AliGVR,
XGVR,
HlpGVR,
QGVR,
HmGVR,
HmhGVR,
RbacGVR,
PolGVR,
UsrGVR,
GrpGVR,
)
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/client/helpers.go | internal/client/helpers.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package client
import (
"log/slog"
"os"
"os/user"
"path"
"regexp"
"strings"
"github.com/derailed/k9s/internal/slogs"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
var toFileName = regexp.MustCompile(`[^(\w/.)]`)
// IsClusterWide returns true if ns designates cluster scope, false otherwise.
func IsClusterWide(ns string) bool {
return ns == NamespaceAll || ns == BlankNamespace || ns == ClusterScope
}
func PrintNamespace(ns string) string {
if IsAllNamespaces(ns) {
return "all"
}
return ns
}
// CleanseNamespace ensures all ns maps to blank.
func CleanseNamespace(ns string) string {
if IsAllNamespace(ns) {
return BlankNamespace
}
return ns
}
// IsAllNamespace returns true if ns == all.
func IsAllNamespace(ns string) bool {
return ns == NamespaceAll
}
// IsAllNamespaces returns true if all namespaces, false otherwise.
func IsAllNamespaces(ns string) bool {
return ns == NamespaceAll || ns == BlankNamespace
}
// IsNamespaced returns true if a specific ns is given.
func IsNamespaced(ns string) bool {
return !IsAllNamespaces(ns) && !IsClusterScoped(ns)
}
// IsClusterScoped returns true if resource is not namespaced.
func IsClusterScoped(ns string) bool {
return ns == ClusterScope
}
// Namespaced converts a resource path to namespace and resource name.
func Namespaced(p string) (ns, name string) {
ns, name = path.Split(p)
return strings.Trim(ns, "/"), name
}
// CoFQN returns a fully qualified container name.
func CoFQN(m *metav1.ObjectMeta, co string) string {
return MetaFQN(m) + ":" + co
}
// FQN returns a fully qualified resource name.
func FQN(ns, n string) string {
if ns == "" {
return n
}
return ns + "/" + n
}
// MetaFQN returns a fully qualified resource name.
func MetaFQN(m *metav1.ObjectMeta) string {
if m.Namespace == "" {
return FQN(ClusterScope, m.Name)
}
return FQN(m.Namespace, m.Name)
}
func mustHomeDir() string {
usr, err := user.Current()
if err != nil {
slog.Error("Die getting user home directory", slogs.Error, err)
os.Exit(1)
}
return usr.HomeDir
}
func toHostDir(host string) string {
h := strings.Replace(
strings.Replace(host, "https://", "", 1),
"http://", "", 1,
)
return toFileName.ReplaceAllString(h, "_")
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/client/gvr.go | internal/client/gvr.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package client
import (
"fmt"
"log/slog"
"path"
"strings"
"sync"
"github.com/derailed/k9s/internal/slogs"
"github.com/fvbommel/sortorder"
"gopkg.in/yaml.v3"
apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
)
var NoGVR = new(GVR)
// GVR represents a kubernetes resource schema as a string.
// Format is group/version/resources:subresource.
type GVR struct {
raw, g, v, r, sr string
}
type gvrCache struct {
data map[string]*GVR
sync.RWMutex
}
func (c *gvrCache) add(gvr *GVR) {
if c.get(gvr.String()) == nil {
c.Lock()
c.data[gvr.String()] = gvr
c.Unlock()
}
}
func (c *gvrCache) get(gvrs string) *GVR {
c.RLock()
defer c.RUnlock()
if gvr, ok := c.data[gvrs]; ok {
return gvr
}
return nil
}
var gvrsCache = gvrCache{
data: make(map[string]*GVR),
}
// NewGVR builds a new gvr from a group, version, resource.
func NewGVR(s string) *GVR {
raw := s
tokens := strings.Split(s, ":")
var g, v, r, sr string
if len(tokens) == 2 {
raw, sr = tokens[0], tokens[1]
}
tokens = strings.Split(raw, "/")
switch len(tokens) {
case 3:
g, v, r = tokens[0], tokens[1], tokens[2]
case 2:
v, r = tokens[0], tokens[1]
case 1:
r = tokens[0]
default:
slog.Error("GVR init failed!", slogs.Error, fmt.Errorf("can't parse GVR %q", s))
}
gvr := GVR{raw: s, g: g, v: v, r: r, sr: sr}
if cgvr := gvrsCache.get(gvr.String()); cgvr != nil {
return cgvr
}
gvrsCache.add(&gvr)
return &gvr
}
func (g *GVR) IsAlias() bool {
return !g.IsK8sRes()
}
func (g *GVR) IsK8sRes() bool {
return g != nil && ((!strings.Contains(g.raw, " ") && strings.Contains(g.raw, "/") && !strings.Contains(g.raw, " /")) || reservedGVRs.Has(g))
}
// WithSubResource builds a new gvr with a sub resource.
func (g *GVR) WithSubResource(sub string) *GVR {
return NewGVR(g.String() + ":" + sub)
}
// NewGVRFromMeta builds a gvr from resource metadata.
func NewGVRFromMeta(a *metav1.APIResource) *GVR {
return NewGVR(path.Join(a.Group, a.Version, a.Name))
}
// NewGVRFromCRD builds a gvr from a custom resource definition.
func NewGVRFromCRD(crd *apiext.CustomResourceDefinition) map[*GVR]*apiext.CustomResourceDefinitionVersion {
mm := make(map[*GVR]*apiext.CustomResourceDefinitionVersion, len(crd.Spec.Versions))
for _, v := range crd.Spec.Versions {
if v.Served && !v.Deprecated {
gvr := NewGVRFromMeta(&metav1.APIResource{
Kind: crd.Spec.Names.Kind,
Group: crd.Spec.Group,
Name: crd.Spec.Names.Plural,
Version: v.Name,
})
mm[gvr] = &v
}
}
return mm
}
// FromGVAndR builds a gvr from a group/version and resource.
func FromGVAndR(gv, r string) *GVR {
return NewGVR(path.Join(gv, r))
}
// FQN returns a fully qualified resource name.
func (g *GVR) FQN(n string) string {
return path.Join(g.AsResourceName(), n)
}
// AsResourceName returns a resource . separated descriptor in the shape of kind.version.group.
func (g *GVR) AsResourceName() string {
if g.g == "" {
return g.r
}
return g.r + "." + g.v + "." + g.g
}
// SubResource returns a sub resource if available.
func (g *GVR) SubResource() string {
return g.sr
}
// String returns gvr as string.
func (g *GVR) String() string {
return g.raw
}
// GV returns the group version scheme representation.
func (g *GVR) GV() schema.GroupVersion {
return schema.GroupVersion{
Group: g.g,
Version: g.v,
}
}
// GVK returns a full schema representation.
func (g *GVR) GVK() schema.GroupVersionKind {
return schema.GroupVersionKind{
Group: g.G(),
Version: g.V(),
Kind: g.R(),
}
}
// GVR returns a full schema representation.
func (g *GVR) GVR() schema.GroupVersionResource {
return schema.GroupVersionResource{
Group: g.G(),
Version: g.V(),
Resource: g.R(),
}
}
// GVSub returns group vervion sub path.
func (g *GVR) GVSub() string {
if g.G() == "" {
return g.V()
}
return g.G() + "/" + g.V()
}
// GR returns a full schema representation.
func (g *GVR) GR() *schema.GroupResource {
return &schema.GroupResource{
Group: g.G(),
Resource: g.R(),
}
}
// V returns the resource version.
func (g *GVR) V() string {
return g.v
}
// RG returns the resource and group.
func (g *GVR) RG() (resource, group string) {
return g.r, g.g
}
// R returns the resource name.
func (g *GVR) R() string {
return g.r
}
// G returns the resource group name.
func (g *GVR) G() string {
return g.g
}
// IsDecodable checks if the k8s resource has a decodable view
func (g *GVR) IsDecodable() bool {
return g == SecGVR
}
var _ = yaml.Marshaler((*GVR)(nil))
var _ = yaml.Unmarshaler((*GVR)(nil))
func (g *GVR) MarshalYAML() (any, error) {
return g.String(), nil
}
func (g *GVR) UnmarshalYAML(n *yaml.Node) error {
*g = *NewGVR(n.Value)
return nil
}
// GVRs represents a collection of gvr.
type GVRs []*GVR
// Len returns the list size.
func (g GVRs) Len() int {
return len(g)
}
// Swap swaps list values.
func (g GVRs) Swap(i, j int) {
g[i], g[j] = g[j], g[i]
}
// Less returns true if i < j.
func (g GVRs) Less(i, j int) bool {
g1, g2 := g[i].G(), g[j].G()
return sortorder.NaturalLess(g1, g2)
}
// Helper...
// Can determines the available actions for a given resource.
func Can(verbs []string, v string) bool {
if verbs == nil {
return true
}
if len(verbs) == 0 {
return false
}
for _, verb := range verbs {
candidates, err := mapVerb(v)
if err != nil {
slog.Error("Access verb mapping failed", slogs.Error, err)
return false
}
for _, c := range candidates {
if verb == c {
return true
}
}
}
return false
}
func mapVerb(v string) ([]string, error) {
switch v {
case "describe":
return []string{"get"}, nil
case "view":
return []string{"get", "list"}, nil
case "delete":
return []string{"delete"}, nil
case "edit":
return []string{"patch", "update"}, nil
default:
return []string{}, fmt.Errorf("no standard verb for %q", v)
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/watch/helper.go | internal/watch/helper.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package watch
import (
"fmt"
"log/slog"
"path"
"strings"
"k8s.io/apimachinery/pkg/runtime/schema"
)
func toGVR(gvr string) schema.GroupVersionResource {
tokens := strings.Split(gvr, "/")
if len(tokens) < 3 {
tokens = append([]string{""}, tokens...)
}
return schema.GroupVersionResource{
Group: tokens[0],
Version: tokens[1],
Resource: tokens[2],
}
}
func namespaced(n string) (ns, res string) {
ns, res = path.Split(n)
return strings.Trim(ns, "/"), res
}
// DumpFactory for debug.
func DumpFactory(f *Factory) {
slog.Debug("----------- FACTORIES -------------")
for ns := range f.factories {
slog.Debug(fmt.Sprintf(" Factory for NS %q", ns))
}
slog.Debug("-----------------------------------")
}
// DebugFactory for debug.
func DebugFactory(f *Factory, ns, gvr string) {
slog.Debug(fmt.Sprintf("----------- DEBUG FACTORY (%s) -------------", gvr))
fac, ok := f.factories[ns]
if !ok {
return
}
inf := fac.ForResource(toGVR(gvr))
for i, k := range inf.Informer().GetStore().ListKeys() {
slog.Debug(fmt.Sprintf("%d -- %s", i, k))
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/watch/forwarders_test.go | internal/watch/forwarders_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package watch_test
import (
"log/slog"
"testing"
"time"
"github.com/derailed/k9s/internal/port"
"github.com/derailed/k9s/internal/watch"
"github.com/stretchr/testify/assert"
"k8s.io/client-go/tools/portforward"
)
func init() {
slog.SetDefault(slog.New(slog.DiscardHandler))
}
func TestIsPodForwarded(t *testing.T) {
uu := map[string]struct {
ff watch.Forwarders
fqn string
e bool
}{
"happy": {
ff: watch.Forwarders{
"ns1/p1||8080:8080": newNoOpForwarder(),
},
fqn: "ns1/p1",
e: true,
},
"dud": {
ff: watch.Forwarders{
"ns1/p1||8080:8080": newNoOpForwarder(),
},
fqn: "ns1/p2",
},
"sub": {
ff: watch.Forwarders{
"ns1/freddy||8080:8080": newNoOpForwarder(),
},
fqn: "ns1/fred",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, u.ff.IsPodForwarded(u.fqn))
})
}
}
func TestIsContainerForwarded(t *testing.T) {
uu := map[string]struct {
ff watch.Forwarders
fqn, co string
e bool
}{
"happy": {
ff: watch.Forwarders{
"ns1/p1|c1|8080:8080": newNoOpForwarder(),
},
fqn: "ns1/p1",
co: "c1",
e: true,
},
"dud": {
ff: watch.Forwarders{
"ns1/p1|c1|8080:8080": newNoOpForwarder(),
},
fqn: "ns1/p1",
co: "c2",
},
"sub": {
ff: watch.Forwarders{
"ns1/freddy|c1|8080:8080": newNoOpForwarder(),
},
fqn: "ns1/fred",
co: "c1",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, u.ff.IsContainerForwarded(u.fqn, u.co))
})
}
}
func TestKill(t *testing.T) {
uu := map[string]struct {
ff watch.Forwarders
path string
kills int
}{
"partial_match": {
ff: watch.Forwarders{
"ns1/p1|c1|8080:8080": newNoOpForwarder(),
"ns1/p1_1|c1|8080:8080": newNoOpForwarder(),
"ns1/p2|c1|8080:8080": newNoOpForwarder(),
},
path: "ns1/p1",
kills: 1,
},
"partial_no_match": {
ff: watch.Forwarders{
"ns1/p1|c1|8080:8080": newNoOpForwarder(),
"ns1/p1_1|c1|8080:8080": newNoOpForwarder(),
"ns1/p2|c1|8080:8080": newNoOpForwarder(),
},
path: "ns1/p",
},
"path_sub": {
ff: watch.Forwarders{
"ns1/p1|c1|8080:8080": newNoOpForwarder(),
"ns1/p1_1|c1|8080:8080": newNoOpForwarder(),
"ns1/p2|c1|8080:8080": newNoOpForwarder(),
},
path: "ns1/p1",
kills: 1,
},
"partial_multi": {
ff: watch.Forwarders{
"ns1/p1|c1|8080:8080": newNoOpForwarder(),
"ns1/p1|c2|8081:8081": newNoOpForwarder(),
"ns1/p2|c1|8080:8080": newNoOpForwarder(),
},
path: "ns1/p1",
kills: 2,
},
"full_match": {
ff: watch.Forwarders{
"ns1/p1|c1|8080:8080": newNoOpForwarder(),
"ns1/p1_1|c1|8080:8080": newNoOpForwarder(),
"ns1/p2|c1|8080:8080": newNoOpForwarder(),
},
path: "ns1/p1|c1|8080:8080",
kills: 1,
},
"full_no_match_co": {
ff: watch.Forwarders{
"ns1/p1|c1|8080:8080": newNoOpForwarder(),
"ns1/p1_1|c1|8080:8080": newNoOpForwarder(),
"ns1/p2|c1|8080:8080": newNoOpForwarder(),
},
path: "ns1/p1|c2|8080:8080",
},
"full_no_match_ports": {
ff: watch.Forwarders{
"ns1/p1|c1|8080:8080": newNoOpForwarder(),
"ns1/p1_1|c1|8080:8080": newNoOpForwarder(),
"ns1/p2|c1|8080:8080": newNoOpForwarder(),
},
path: "ns1/p1|c1|8081:8080",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.kills, u.ff.Kill(u.path))
})
}
}
type noOpForwarder struct{}
func newNoOpForwarder() noOpForwarder {
return noOpForwarder{}
}
func (noOpForwarder) Start(string, port.PortTunnel) (*portforward.PortForwarder, error) {
return nil, nil
}
func (noOpForwarder) Stop() {}
func (noOpForwarder) ID() string { return "" }
func (noOpForwarder) Container() string { return "" }
func (noOpForwarder) Port() string { return "" }
func (noOpForwarder) FQN() string { return "" }
func (noOpForwarder) Active() bool { return false }
func (noOpForwarder) SetActive(bool) {}
func (noOpForwarder) Age() time.Time { return time.Now() }
func (noOpForwarder) HasPortMapping(string) bool { return false }
func (noOpForwarder) 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/watch/factory.go | internal/watch/factory.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package watch
import (
"fmt"
"log/slog"
"strings"
"sync"
"time"
"github.com/derailed/k9s/internal/client"
"github.com/derailed/k9s/internal/slogs"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
di "k8s.io/client-go/dynamic/dynamicinformer"
"k8s.io/client-go/informers"
)
const (
defaultResync = 10 * time.Minute
defaultWaitTime = 500 * time.Millisecond
)
// Factory tracks various resource informers.
type Factory struct {
factories map[string]di.DynamicSharedInformerFactory
client client.Connection
stopChan chan struct{}
forwarders Forwarders
mx sync.RWMutex
}
// NewFactory returns a new informers factory.
func NewFactory(clt client.Connection) *Factory {
return &Factory{
client: clt,
factories: make(map[string]di.DynamicSharedInformerFactory),
forwarders: NewForwarders(),
}
}
// Start initializes the informers until caller cancels the context.
func (f *Factory) Start(ns string) {
f.mx.Lock()
defer f.mx.Unlock()
slog.Debug("Factory started", slogs.Namespace, ns)
f.stopChan = make(chan struct{})
for ns, fac := range f.factories {
slog.Debug("Starting factory for ns", slogs.Namespace, ns)
fac.Start(f.stopChan)
}
}
// Terminate terminates all watchers and forwards.
func (f *Factory) Terminate() {
f.mx.Lock()
defer f.mx.Unlock()
if f.stopChan != nil {
close(f.stopChan)
f.stopChan = nil
}
for k := range f.factories {
delete(f.factories, k)
}
f.forwarders.DeleteAll()
}
// List returns a resource collection.
func (f *Factory) List(gvr *client.GVR, ns string, wait bool, lbls labels.Selector) ([]runtime.Object, error) {
if client.IsAllNamespace(ns) {
ns = client.BlankNamespace
}
inf, err := f.CanForResource(ns, gvr, client.ListAccess)
if err != nil {
return nil, err
}
var oo []runtime.Object
if client.IsClusterScoped(ns) {
oo, err = inf.Lister().List(lbls)
} else {
oo, err = inf.Lister().ByNamespace(ns).List(lbls)
}
if !wait || (wait && inf.Informer().HasSynced()) {
return oo, err
}
f.waitForCacheSync(ns)
if client.IsClusterScoped(ns) {
return inf.Lister().List(lbls)
}
return inf.Lister().ByNamespace(ns).List(lbls)
}
// HasSynced checks if given informer is up to date.
func (f *Factory) HasSynced(gvr *client.GVR, ns string) (bool, error) {
inf, err := f.CanForResource(ns, gvr, client.ListAccess)
if err != nil {
return false, err
}
return inf.Informer().HasSynced(), nil
}
// Get retrieves a given resource.
func (f *Factory) Get(gvr *client.GVR, fqn string, wait bool, _ labels.Selector) (runtime.Object, error) {
ns, n := namespaced(fqn)
if client.IsAllNamespace(ns) {
ns = client.BlankNamespace
}
inf, err := f.CanForResource(ns, gvr, []string{client.GetVerb})
if err != nil {
return nil, err
}
var o runtime.Object
if client.IsClusterScoped(ns) {
o, err = inf.Lister().Get(n)
} else {
o, err = inf.Lister().ByNamespace(ns).Get(n)
}
if !wait || (wait && inf.Informer().HasSynced()) {
return o, err
}
f.waitForCacheSync(ns)
if client.IsClusterScoped(ns) {
return inf.Lister().Get(n)
}
return inf.Lister().ByNamespace(ns).Get(n)
}
func (f *Factory) waitForCacheSync(ns string) {
if client.IsClusterWide(ns) {
ns = client.BlankNamespace
}
f.mx.RLock()
defer f.mx.RUnlock()
fac, ok := f.factories[ns]
if !ok {
return
}
// Hang for a sec for the cache to refresh if still not done bail out!
c := make(chan struct{})
go func(c chan struct{}) {
<-time.After(defaultWaitTime)
close(c)
}(c)
_ = fac.WaitForCacheSync(c)
}
// WaitForCacheSync waits for all factories to update their cache.
func (f *Factory) WaitForCacheSync() {
for ns, fac := range f.factories {
m := fac.WaitForCacheSync(f.stopChan)
for k, v := range m {
slog.Debug("CACHE `%q Loaded %t:%s",
slogs.Namespace, ns,
slogs.ResGrpVersion, v,
slogs.ResKind, k,
)
}
}
}
// Client return the factory connection.
func (f *Factory) Client() client.Connection {
return f.client
}
// FactoryFor returns a factory for a given namespace.
func (f *Factory) FactoryFor(ns string) di.DynamicSharedInformerFactory {
return f.factories[ns]
}
// SetActiveNS sets the active namespace.
func (f *Factory) SetActiveNS(ns string) error {
if f.isClusterWide() {
return nil
}
_, err := f.ensureFactory(ns)
return err
}
func (f *Factory) isClusterWide() bool {
f.mx.RLock()
defer f.mx.RUnlock()
_, ok := f.factories[client.BlankNamespace]
return ok
}
// CanForResource return an informer is user has access.
func (f *Factory) CanForResource(ns string, gvr *client.GVR, verbs []string) (informers.GenericInformer, error) {
auth, err := f.Client().CanI(ns, gvr, "", verbs)
if err != nil {
return nil, err
}
if !auth {
return nil, fmt.Errorf("%v access denied on resource %q:%q", verbs, ns, gvr)
}
return f.ForResource(ns, gvr)
}
// ForResource returns an informer for a given resource.
func (f *Factory) ForResource(ns string, gvr *client.GVR) (informers.GenericInformer, error) {
fact, err := f.ensureFactory(ns)
if err != nil {
return nil, err
}
inf := fact.ForResource(gvr.GVR())
if inf == nil {
slog.Error("No informer found",
slogs.GVR, gvr,
slogs.Namespace, ns,
)
return inf, nil
}
f.mx.RLock()
defer f.mx.RUnlock()
fact.Start(f.stopChan)
return inf, nil
}
func (f *Factory) ensureFactory(ns string) (di.DynamicSharedInformerFactory, error) {
if client.IsClusterWide(ns) {
ns = client.BlankNamespace
}
f.mx.Lock()
defer f.mx.Unlock()
if fac, ok := f.factories[ns]; ok {
return fac, nil
}
dial, err := f.client.DynDial()
if err != nil {
return nil, err
}
f.factories[ns] = di.NewFilteredDynamicSharedInformerFactory(
dial,
defaultResync,
ns,
nil,
)
return f.factories[ns], nil
}
// AddForwarder registers a new portforward for a given container.
func (f *Factory) AddForwarder(pf Forwarder) {
f.mx.Lock()
defer f.mx.Unlock()
f.forwarders[pf.ID()] = pf
}
// DeleteForwarder deletes portforward for a given container.
func (f *Factory) DeleteForwarder(path string) {
count := f.forwarders.Kill(path)
slog.Warn("Deleted portforward",
slogs.Count, count,
slogs.GVR, path,
)
}
// Forwarders returns all portforwards.
func (f *Factory) Forwarders() Forwarders {
f.mx.RLock()
defer f.mx.RUnlock()
return f.forwarders
}
// ForwarderFor returns a portforward for a given container or nil if none exists.
func (f *Factory) ForwarderFor(path string) (Forwarder, bool) {
f.mx.RLock()
defer f.mx.RUnlock()
fwd, ok := f.forwarders[path]
return fwd, ok
}
// ValidatePortForwards check if pods are still around for portforwards.
// BOZO!! Review!!!
func (f *Factory) ValidatePortForwards() {
for k, fwd := range f.forwarders {
tokens := strings.Split(k, ":")
if len(tokens) != 2 {
slog.Error("Invalid port-forward key", slogs.Key, k)
return
}
paths := strings.Split(tokens[0], "|")
if len(paths) < 1 {
slog.Error("Invalid port-forward path", slogs.Path, tokens[0])
}
o, err := f.Get(client.PodGVR, paths[0], false, labels.Everything())
if err != nil {
fwd.Stop()
delete(f.forwarders, k)
continue
}
var pod v1.Pod
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(o.(*unstructured.Unstructured).Object, &pod); err != nil {
continue
}
if pod.GetCreationTimestamp().Unix() > fwd.Age().Unix() {
fwd.Stop()
delete(f.forwarders, k)
}
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/watch/forwarders.go | internal/watch/forwarders.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package watch
import (
"fmt"
"log/slog"
"strings"
"time"
"github.com/derailed/k9s/internal/port"
"github.com/derailed/k9s/internal/slogs"
"k8s.io/client-go/tools/portforward"
)
// Forwarder represents a port forwarder.
type Forwarder interface {
// Start starts a port-forward.
Start(path string, tunnel port.PortTunnel) (*portforward.PortForwarder, error)
// Stop terminates a port forward.
Stop()
// ID returns the pf id.
ID() string
// Container returns a container name.
Container() string
// Port returns the port mapping.
Port() string
// Address returns the host address.
Address() string
// FQN returns the full port-forward name.
FQN() string
// Active returns forwarder current state.
Active() bool
// SetActive sets port-forward state.
SetActive(bool)
// Age returns forwarder age.
Age() time.Time
// HasPortMapping returns true if port mapping exists.
HasPortMapping(string) bool
}
// Forwarders tracks active port forwards.
type Forwarders map[string]Forwarder
// NewForwarders returns new forwarders.
func NewForwarders() Forwarders {
return make(map[string]Forwarder)
}
// IsPodForwarded checks if pod has a forward.
func (ff Forwarders) IsPodForwarded(fqn string) bool {
fqn += "|"
for k := range ff {
if strings.HasPrefix(k, fqn) {
return true
}
}
return false
}
// IsContainerForwarded checks if pod has a forward.
func (ff Forwarders) IsContainerForwarded(fqn, co string) bool {
fqn += "|" + co
for k := range ff {
if strings.HasPrefix(k, fqn) {
return true
}
}
return false
}
// DeleteAll stops and delete all port-forwards.
func (ff Forwarders) DeleteAll() {
for k, f := range ff {
slog.Debug("Deleting forwarder", slogs.ID, f.ID())
f.Stop()
delete(ff, k)
}
}
// Kill stops and delete a port-forwards associated with pod.
func (ff Forwarders) Kill(path string) int {
var stats int
// The way port forwards are stored is `pod_fqn|container|local_port:container_port`
// The '|' is added to make sure we do not delete port forwards from other pods that have the same prefix
// Without the `|` port forwards for pods, default/web-0 and default/web-0-bla would be both deleted
// even if we want only port forwards for default/web-0 to be deleted
prefix := path + "|"
for k, f := range ff {
if k == path || strings.HasPrefix(k, prefix) {
stats++
slog.Debug("Stop and delete port-forward", slogs.Name, k)
f.Stop()
delete(ff, k)
}
}
return stats
}
// Dump for debug!
func (ff Forwarders) Dump() {
slog.Debug("----------- PORT-FORWARDS --------------")
for k, f := range ff {
slog.Debug(fmt.Sprintf(" %s -- %s", k, f))
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/color/colorize_test.go | internal/color/colorize_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package color_test
import (
"testing"
"github.com/derailed/k9s/internal/color"
"github.com/stretchr/testify/assert"
)
func TestColorize(t *testing.T) {
uu := map[string]struct {
s string
c color.Paint
e string
}{
"white": {"blee", color.LightGray, "\x1b[37mblee\x1b[0m"},
"black": {"blee", color.Black, "\x1b[30mblee\x1b[0m"},
"default": {"blee", 0, "blee"},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, color.Colorize(u.s, u.c))
})
}
}
func TestHighlight(t *testing.T) {
uu := map[string]struct {
text []byte
indices []int
color int
e string
}{
"white": {
text: []byte("the brown fox"),
color: 209,
indices: []int{4, 5, 6, 7, 8},
e: "the \x1b[38;5;209mb\x1b[0m\x1b[38;5;209mr\x1b[0m\x1b[38;5;209mo\x1b[0m\x1b[38;5;209mw\x1b[0m\x1b[38;5;209mn\x1b[0m fox",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, string(color.Highlight(u.text, u.indices, u.color)))
})
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/color/colorize.go | internal/color/colorize.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package color
import (
"fmt"
"strconv"
)
const colorFmt = "\x1b[%dm%s\x1b[0m"
// Paint describes a terminal color.
type Paint int
// Defines basic ANSI colors.
const (
Black Paint = iota + 30 // 30
Red // 31
Green // 32
Yellow // 33
Blue // 34
Magenta // 35
Cyan // 36
LightGray // 37
DarkGray = 90
Bold = 1
)
// Colorize returns an ASCII colored string based on given color.
func Colorize(s string, c Paint) string {
if c == 0 {
return s
}
return fmt.Sprintf(colorFmt, c, s)
}
// ANSIColorize colors a string.
func ANSIColorize(text string, color int) string {
return "\033[38;5;" + strconv.Itoa(color) + "m" + text + "\033[0m"
}
// Highlight colorize bytes at given indices.
func Highlight(bb []byte, ii []int, c int) []byte {
if len(ii) == 0 {
return bb
}
result := make([]byte, 0, len(bb)+len(ii)*20) // Extra space for color codes
// Create a map of byte positions that should be highlighted
highlightMap := make(map[int]bool)
for _, pos := range ii {
highlightMap[pos] = true
}
// Process each byte
for i := 0; i < len(bb); i++ {
if highlightMap[i] {
// Check if this is the start of a UTF-8 character
if (bb[i] & 0xC0) != 0x80 {
// This is the start of a character, find the end
charStart := i
charEnd := i + 1
for charEnd < len(bb) && (bb[charEnd]&0xC0) == 0x80 {
charEnd++
}
// Colorize the entire character
char := string(bb[charStart:charEnd])
colored := ANSIColorize(char, c)
result = append(result, []byte(colored)...)
i = charEnd - 1 // Skip the rest of the character bytes
} else {
// This is a continuation byte, skip it (already handled)
continue
}
} else {
result = append(result, bb[i])
}
}
return result
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/crumbs.go | internal/ui/crumbs.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"fmt"
"strings"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/tview"
)
// Crumbs represents user breadcrumbs.
type Crumbs struct {
*tview.TextView
styles *config.Styles
stack *model.Stack
}
// NewCrumbs returns a new breadcrumb view.
func NewCrumbs(styles *config.Styles) *Crumbs {
c := Crumbs{
stack: model.NewStack(),
styles: styles,
TextView: tview.NewTextView(),
}
c.SetBackgroundColor(styles.BgColor())
c.SetTextAlign(tview.AlignLeft)
c.SetBorderPadding(0, 0, 1, 1)
c.SetDynamicColors(true)
styles.AddListener(&c)
return &c
}
// StylesChanged notifies skin changed.
func (c *Crumbs) StylesChanged(s *config.Styles) {
c.styles = s
c.SetBackgroundColor(s.BgColor())
c.refresh(c.stack.Flatten())
}
// StackPushed indicates a new item was added.
func (c *Crumbs) StackPushed(comp model.Component) {
c.stack.Push(comp)
c.refresh(c.stack.Flatten())
}
// StackPopped indicates an item was deleted.
func (c *Crumbs) StackPopped(_, _ model.Component) {
c.stack.Pop()
c.refresh(c.stack.Flatten())
}
// StackTop indicates the top of the stack.
func (*Crumbs) StackTop(model.Component) {}
// Refresh updates view with new crumbs.
func (c *Crumbs) refresh(crumbs []string) {
c.Clear()
last, bgColor := len(crumbs)-1, c.styles.Frame().Crumb.BgColor
for i, crumb := range crumbs {
if i == last {
bgColor = c.styles.Frame().Crumb.ActiveColor
}
_, _ = fmt.Fprintf(c, "[%s:%s:b] <%s> [-:%s:-] ",
c.styles.Frame().Crumb.FgColor,
bgColor, strings.ReplaceAll(strings.ToLower(crumb), " ", ""),
c.styles.Body().BgColor)
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/tree.go | internal/ui/tree.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"context"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/tcell/v2"
"github.com/derailed/tview"
)
// KeyListenerFunc listens to key presses.
type KeyListenerFunc func()
// Tree represents a tree view.
type Tree struct {
*tview.TreeView
actions *KeyActions
selectedItem string
cmdBuff *model.FishBuff
expandNodes bool
Count int
keyListener KeyListenerFunc
}
// NewTree returns a new view.
func NewTree() *Tree {
return &Tree{
TreeView: tview.NewTreeView(),
expandNodes: true,
actions: NewKeyActions(),
cmdBuff: model.NewFishBuff('/', model.FilterBuffer),
}
}
// Init initializes the view.
func (t *Tree) Init(context.Context) error {
t.BindKeys()
t.SetBorder(true)
t.SetBorderAttributes(tcell.AttrBold)
t.SetBorderPadding(0, 0, 1, 1)
t.SetGraphics(true)
t.SetGraphicsColor(tcell.ColorCadetBlue)
t.SetInputCapture(t.keyboard)
return nil
}
// SetSelectedItem sets the currently selected node.
func (t *Tree) SetSelectedItem(s string) {
t.selectedItem = s
}
// GetSelectedItem returns the currently selected item or blank if none.
func (t *Tree) GetSelectedItem() string {
return t.selectedItem
}
// ExpandNodes returns true if nodes are expanded or false otherwise.
func (t *Tree) ExpandNodes() bool {
return t.expandNodes
}
// CmdBuff returns the filter command.
func (t *Tree) CmdBuff() *model.FishBuff {
return t.cmdBuff
}
// SetKeyListenerFn sets a key entered listener.
func (t *Tree) SetKeyListenerFn(f KeyListenerFunc) {
t.keyListener = f
}
// Actions returns active menu bindings.
func (t *Tree) Actions() *KeyActions {
return t.actions
}
// Hints returns the view hints.
func (t *Tree) Hints() model.MenuHints {
return t.actions.Hints()
}
// ExtraHints returns additional hints.
func (*Tree) ExtraHints() map[string]string {
return nil
}
// BindKeys binds default mnemonics.
func (t *Tree) BindKeys() {
t.Actions().Merge(NewKeyActionsFromMap(KeyMap{
KeySpace: NewKeyAction("Expand/Collapse", t.noopCmd, true),
KeyX: NewKeyAction("Expand/Collapse All", t.toggleCollapseCmd, true),
}))
}
func (t *Tree) keyboard(evt *tcell.EventKey) *tcell.EventKey {
if a, ok := t.actions.Get(AsKey(evt)); ok {
return a.Action(evt)
}
return evt
}
func (*Tree) noopCmd(evt *tcell.EventKey) *tcell.EventKey {
return evt
}
func (t *Tree) toggleCollapseCmd(*tcell.EventKey) *tcell.EventKey {
t.expandNodes = !t.expandNodes
t.GetRoot().Walk(func(node, parent *tview.TreeNode) bool {
if parent != nil {
node.SetExpanded(t.expandNodes)
}
return true
})
return nil
}
// ClearSelection clears the currently selected node.
func (t *Tree) ClearSelection() {
t.selectedItem = ""
t.SetCurrentNode(nil)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/flash_test.go | internal/ui/flash_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui_test
import (
"context"
"testing"
"time"
"github.com/derailed/k9s/internal/config/mock"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/k9s/internal/ui"
"github.com/stretchr/testify/assert"
)
func TestFlash(t *testing.T) {
const delay = 10 * time.Millisecond
uu := map[string]struct {
l model.FlashLevel
i, e string
}{
"info": {l: model.FlashInfo, i: "hello", e: "😎 hello\n"},
"warn": {l: model.FlashWarn, i: "hello", e: "😗 hello\n"},
"err": {l: model.FlashErr, i: "hello", e: "😡 hello\n"},
}
a := ui.NewApp(mock.NewMockConfig(t), "test")
f := ui.NewFlash(a)
f.SetTestMode(true)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go f.Watch(ctx, a.Flash().Channel())
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
a.Flash().SetMessage(u.l, u.i)
time.Sleep(delay)
assert.Equal(t, u.e, f.GetText(false))
})
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/splash_test.go | internal/ui/splash_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui_test
import (
"testing"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/ui"
"github.com/stretchr/testify/assert"
)
func TestNewSplash(t *testing.T) {
s := ui.NewSplash(config.NewStyles(), "bozo")
x, y, w, h := s.GetRect()
assert.Equal(t, 0, x)
assert.Equal(t, 0, y)
assert.Equal(t, 15, w)
assert.Equal(t, 10, h)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/pages.go | internal/ui/pages.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"fmt"
"log/slog"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/k9s/internal/slogs"
"github.com/derailed/tview"
)
// Pages represents a stack of view pages.
type Pages struct {
*tview.Pages
*model.Stack
}
// NewPages return a new view.
func NewPages() *Pages {
p := Pages{
Pages: tview.NewPages(),
Stack: model.NewStack(),
}
p.AddListener(&p)
return &p
}
// IsTopDialog checks if front page is a dialog.
func (p *Pages) IsTopDialog() bool {
_, pa := p.GetFrontPage()
switch pa.(type) {
case *tview.ModalForm, *ModalList:
return true
default:
return false
}
}
// Show displays a given page.
func (p *Pages) Show(c model.Component) {
p.SwitchToPage(componentID(c))
}
// Current returns the current component.
func (p *Pages) Current() model.Component {
c := p.CurrentPage()
if c == nil {
return nil
}
return c.Item.(model.Component)
}
// AddAndShow adds a new page and bring it to front.
func (p *Pages) addAndShow(c model.Component) {
p.add(c)
p.Show(c)
}
// Add adds a new page.
func (p *Pages) add(c model.Component) {
p.AddPage(componentID(c), c, true, true)
}
// Delete removes a page.
func (p *Pages) delete(c model.Component) {
p.RemovePage(componentID(c))
}
// Dump for debug.
func (p *Pages) Dump() {
slog.Debug("Dumping Pages", slogs.Page, p)
for i, c := range p.Peek() {
slog.Debug(fmt.Sprintf("%d -- %s -- %#v", i, componentID(c), p.GetPrimitive(componentID(c))))
}
}
// Stack Protocol...
// StackPushed notifies a new component was pushed.
func (p *Pages) StackPushed(c model.Component) {
p.addAndShow(c)
}
// StackPopped notifies a component was removed.
func (p *Pages) StackPopped(o, _ model.Component) {
p.delete(o)
}
// StackTop notifies a new component is at the top of the stack.
func (p *Pages) StackTop(top model.Component) {
if top == nil {
return
}
p.Show(top)
}
// Helpers...
func componentID(c model.Component) string {
if c.Name() == "" {
slog.Error("Component has no name", slogs.Component, fmt.Sprintf("%T", c))
}
return fmt.Sprintf("%s-%p", c.Name(), c)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/action_test.go | internal/ui/action_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui_test
import (
"testing"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/k9s/internal/ui"
"github.com/stretchr/testify/assert"
)
func TestKeyActionsHints(t *testing.T) {
kk := ui.NewKeyActionsFromMap(ui.KeyMap{
ui.KeyF: ui.NewKeyAction("fred", nil, true),
ui.KeyB: ui.NewKeyAction("blee", nil, true),
ui.KeyZ: ui.NewKeyAction("zorg", nil, false),
})
hh := kk.Hints()
assert.Len(t, hh, 3)
assert.Equal(t, model.MenuHint{Mnemonic: "b", Description: "blee", Visible: true}, hh[0])
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/prompt_test.go | internal/ui/prompt_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui_test
import (
"testing"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/k9s/internal/ui"
"github.com/derailed/tcell/v2"
"github.com/stretchr/testify/assert"
)
func TestCmdNew(t *testing.T) {
uu := map[string]struct {
mode rune
kind model.BufferKind
noIcon bool
e string
}{
"cmd": {
mode: ':',
noIcon: true,
kind: model.CommandBuffer,
e: " > [::b]blee\n",
},
"cmd-ic": {
mode: ':',
kind: model.CommandBuffer,
e: "🐶> [::b]blee\n",
},
"search": {
mode: '/',
kind: model.FilterBuffer,
noIcon: true,
e: " / [::b]blee\n",
},
"search-ic": {
mode: '/',
kind: model.FilterBuffer,
e: "🐩/ [::b]blee\n",
},
}
for k, u := range uu {
t.Run(k, func(t *testing.T) {
v := ui.NewPrompt(nil, u.noIcon, config.NewStyles())
m := model.NewFishBuff(u.mode, u.kind)
v.SetModel(m)
m.AddListener(v)
for _, r := range "blee" {
m.Add(r)
}
m.SetActive(true)
assert.Equal(t, u.e, v.GetText(false))
})
}
}
func TestCmdUpdate(t *testing.T) {
m := model.NewFishBuff(':', model.CommandBuffer)
v := ui.NewPrompt(nil, true, config.NewStyles())
v.SetModel(m)
m.AddListener(v)
m.SetText("blee", "", true)
m.Add('!')
assert.Equal(t, "\x00\x00 [::b]blee!\n", v.GetText(false))
assert.False(t, v.InCmdMode())
}
func TestCmdMode(t *testing.T) {
m := model.NewFishBuff(':', model.CommandBuffer)
v := ui.NewPrompt(&ui.App{}, true, config.NewStyles())
v.SetModel(m)
m.AddListener(v)
for _, f := range []bool{false, true} {
m.SetActive(f)
assert.Equal(t, f, v.InCmdMode())
}
}
func TestPrompt_Deactivate(t *testing.T) {
m := model.NewFishBuff(':', model.CommandBuffer)
v := ui.NewPrompt(&ui.App{}, true, config.NewStyles())
v.SetModel(m)
m.AddListener(v)
m.SetActive(true)
if assert.True(t, v.InCmdMode()) {
v.Deactivate()
assert.False(t, v.InCmdMode())
}
}
// Tests that, when active, the prompt has the appropriate color
func TestPromptColor(t *testing.T) {
styles := config.NewStyles()
app := ui.App{}
// Make sure to have different values to be sure that the prompt color actually changes depending on its type
assert.NotEqual(t,
styles.Prompt().Border.DefaultColor.Color(),
styles.Prompt().Border.CommandColor.Color(),
)
testCases := []struct {
kind model.BufferKind
expectedColor tcell.Color
}{
// Command prompt case
{
kind: model.CommandBuffer,
expectedColor: styles.Prompt().Border.CommandColor.Color(),
},
// Any other prompt type case
{
// Simulate a different type of prompt since no particular constant exists
kind: model.CommandBuffer + 1,
expectedColor: styles.Prompt().Border.DefaultColor.Color(),
},
}
for _, testCase := range testCases {
m := model.NewFishBuff(':', testCase.kind)
prompt := ui.NewPrompt(&app, true, styles)
prompt.SetModel(m)
m.AddListener(prompt)
m.SetActive(true)
assert.Equal(t, testCase.expectedColor, prompt.GetBorderColor())
}
}
// Tests that, when a change of style occurs, the prompt will have the appropriate color when active
func TestPromptStyleChanged(t *testing.T) {
app := ui.App{}
styles := config.NewStyles()
newStyles := config.NewStyles()
newStyles.K9s.Prompt.Border = config.PromptBorder{
DefaultColor: "green",
CommandColor: "yellow",
}
// Check that the prompt won't change the border into the same style
assert.NotEqual(t, styles.Prompt().Border.CommandColor.Color(), newStyles.Prompt().Border.CommandColor.Color())
assert.NotEqual(t, styles.Prompt().Border.DefaultColor.Color(), newStyles.Prompt().Border.DefaultColor.Color())
testCases := []struct {
kind model.BufferKind
expectedColor tcell.Color
}{
// Command prompt case
{
kind: model.CommandBuffer,
expectedColor: newStyles.Prompt().Border.CommandColor.Color(),
},
// Any other prompt type case
{
// Simulate a different type of prompt since no particular constant exists
kind: model.CommandBuffer + 1,
expectedColor: newStyles.Prompt().Border.DefaultColor.Color(),
},
}
for _, testCase := range testCases {
m := model.NewFishBuff(':', testCase.kind)
prompt := ui.NewPrompt(&app, true, styles)
m.SetActive(true)
prompt.SetModel(m)
m.AddListener(prompt)
prompt.StylesChanged(newStyles)
m.SetActive(true)
assert.Equal(t, testCase.expectedColor, prompt.GetBorderColor())
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/table_test.go | internal/ui/table_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui_test
import (
"context"
"testing"
"time"
"github.com/derailed/k9s/internal"
"github.com/derailed/k9s/internal/client"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/dao"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/k9s/internal/model1"
"github.com/derailed/k9s/internal/ui"
"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
)
func TestTableNew(t *testing.T) {
v := ui.NewTable(client.NewGVR("fred"))
v.Init(makeContext())
assert.Equal(t, "fred", v.GVR().String())
}
func TestTableUpdate(t *testing.T) {
v := ui.NewTable(client.NewGVR("fred"))
v.Init(makeContext())
data := makeTableData()
cdata := v.Update(data, false)
v.UpdateUI(cdata, data)
assert.Equal(t, data.RowCount()+1, v.GetRowCount())
assert.Equal(t, data.HeaderCount(), v.GetColumnCount())
}
func TestTableSelection(t *testing.T) {
v := ui.NewTable(client.NewGVR("fred"))
v.Init(makeContext())
m := new(mockModel)
v.SetModel(m)
data := m.Peek()
cdata := v.Update(data, false)
v.UpdateUI(cdata, data)
v.SelectRow(1, 0, true)
r := v.GetSelectedRow("r1")
if r != nil {
assert.Equal(t, model1.Row{ID: "r1", Fields: model1.Fields{"blee", "duh", "fred"}}, *r)
}
assert.Equal(t, "r1", v.GetSelectedItem())
assert.Equal(t, "blee", v.GetSelectedCell(0))
assert.Equal(t, 1, v.GetSelectedRowIndex())
assert.Equal(t, []string{"r1"}, v.GetSelectedItems())
v.ClearSelection()
v.SelectFirstRow()
assert.Equal(t, 1, v.GetSelectedRowIndex())
}
// ----------------------------------------------------------------------------
// Helpers...
type mockModel struct{}
var _ ui.Tabular = &mockModel{}
func (*mockModel) SetViewSetting(context.Context, *config.ViewSetting) {}
func (*mockModel) SetInstance(string) {}
func (*mockModel) SetLabelSelector(labels.Selector) {}
func (*mockModel) GetLabelSelector() labels.Selector { return nil }
func (*mockModel) Empty() bool { return false }
func (*mockModel) RowCount() int { return 1 }
func (*mockModel) HasMetrics() bool { return true }
func (*mockModel) Peek() *model1.TableData { return makeTableData() }
func (*mockModel) Refresh(context.Context) error { return nil }
func (*mockModel) ClusterWide() bool { return false }
func (*mockModel) GetNamespace() string { return "blee" }
func (*mockModel) SetNamespace(string) {}
func (*mockModel) ToggleToast() {}
func (*mockModel) AddListener(model.TableListener) {}
func (*mockModel) RemoveListener(model.TableListener) {}
func (*mockModel) Watch(context.Context) error { return nil }
func (*mockModel) Get(context.Context, string) (runtime.Object, error) { return nil, nil }
func (*mockModel) InNamespace(string) bool { return true }
func (*mockModel) SetRefreshRate(time.Duration) {}
func (*mockModel) Delete(context.Context, string, *metav1.DeletionPropagation, dao.Grace) error {
return nil
}
func (*mockModel) Describe(context.Context, string) (string, error) {
return "", nil
}
func (*mockModel) ToYAML(context.Context, string) (string, error) {
return "", nil
}
func makeTableData() *model1.TableData {
return model1.NewTableDataWithRows(
client.NewGVR("test"),
model1.Header{
model1.HeaderColumn{Name: "A"},
model1.HeaderColumn{Name: "B"},
model1.HeaderColumn{Name: "C"},
},
model1.NewRowEventsWithEvts(
model1.RowEvent{
Row: model1.Row{
ID: "r1",
Fields: model1.Fields{"blee", "duh", "fred"},
},
},
model1.RowEvent{
Row: model1.Row{
ID: "r2",
Fields: model1.Fields{"blee", "duh", "zorg"},
},
},
),
)
}
func makeContext() context.Context {
ctx := context.WithValue(context.Background(), internal.KeyStyles, config.NewStyles())
ctx = context.WithValue(ctx, internal.KeyViewConfig, config.NewCustomView())
return ctx
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/table.go | internal/ui/table.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"context"
"fmt"
"log/slog"
"sync"
"github.com/derailed/k9s/internal"
"github.com/derailed/k9s/internal/client"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/k9s/internal/model1"
"github.com/derailed/k9s/internal/render"
"github.com/derailed/k9s/internal/slogs"
"github.com/derailed/k9s/internal/vul"
"github.com/derailed/tcell/v2"
"github.com/derailed/tview"
)
const maxTruncate = 50
type (
// ColorerFunc represents a row colorer.
ColorerFunc func(ns string, evt model1.RowEvent) tcell.Color
// DecorateFunc represents a row decorator.
DecorateFunc func(*model1.TableData)
// SelectedRowFunc a table selection callback.
SelectedRowFunc func(r int)
)
// Table represents tabular data.
type Table struct {
*SelectTable
gvr *client.GVR
sortCol model1.SortColumn
selectedColIdx int
manualSort bool
Path string
Extras string
actions *KeyActions
cmdBuff *model.FishBuff
styles *config.Styles
viewSetting *config.ViewSetting
colorerFn model1.ColorerFunc
decorateFn DecorateFunc
wide bool
toast bool
hasMetrics bool
ctx context.Context
mx sync.RWMutex
readOnly bool
noIcon bool
fullGVR bool
}
// NewTable returns a new table view.
func NewTable(gvr *client.GVR) *Table {
return &Table{
SelectTable: &SelectTable{
Table: tview.NewTable(),
model: model.NewTable(gvr),
marks: make(map[string]struct{}),
},
ctx: context.Background(),
gvr: gvr,
actions: NewKeyActions(),
cmdBuff: model.NewFishBuff('/', model.FilterBuffer),
sortCol: model1.SortColumn{ASC: true},
}
}
// SetFullGVR toggles full GVR title display.
func (t *Table) SetFullGVR(b bool) {
t.mx.Lock()
defer t.mx.Unlock()
t.fullGVR = b
}
// SetNoIcon toggles no icon mode.
func (t *Table) SetNoIcon(b bool) {
t.mx.Lock()
defer t.mx.Unlock()
t.noIcon = b
}
// SetReadOnly toggles read-only mode.
func (t *Table) SetReadOnly(ro bool) {
t.mx.Lock()
defer t.mx.Unlock()
t.readOnly = ro
}
func (t *Table) setSortCol(sc model1.SortColumn) {
t.mx.Lock()
defer t.mx.Unlock()
t.sortCol = sc
}
func (t *Table) toggleSortCol() {
t.mx.Lock()
defer t.mx.Unlock()
t.sortCol.ASC = !t.sortCol.ASC
}
func (t *Table) getSortCol() model1.SortColumn {
t.mx.RLock()
defer t.mx.RUnlock()
return t.sortCol
}
func (t *Table) setMSort(b bool) {
t.mx.Lock()
defer t.mx.Unlock()
t.manualSort = b
}
func (t *Table) getMSort() bool {
t.mx.RLock()
defer t.mx.RUnlock()
return t.manualSort
}
func (t *Table) getSelectedColIdx() int {
t.mx.RLock()
defer t.mx.RUnlock()
return t.selectedColIdx
}
// initSelectedColumn initializes the selected column index based on current sort column.
func (t *Table) initSelectedColumn() {
data := t.GetFilteredData()
if data == nil || data.HeaderCount() == 0 {
return
}
sc := t.getSortCol()
if sc.Name == "" {
t.mx.Lock()
t.selectedColIdx = 0
t.mx.Unlock()
return
}
// Find the visual column index for the current sort column
header := data.Header()
visibleCol := 0
for _, h := range header {
if t.shouldExcludeColumn(h) {
continue
}
if h.Name == sc.Name {
t.mx.Lock()
t.selectedColIdx = visibleCol
t.mx.Unlock()
return
}
visibleCol++
}
// If sort column not found in visible columns, default to 0
t.mx.Lock()
t.selectedColIdx = 0
t.mx.Unlock()
}
// moveSelectedColumn moves the column selection by delta (-1 for left, +1 for right).
func (t *Table) moveSelectedColumn(delta int) {
data := t.GetFilteredData()
if data == nil || data.HeaderCount() == 0 {
return
}
// Count visible columns
visibleCount := 0
for _, h := range data.Header() {
if !t.shouldExcludeColumn(h) {
visibleCount++
}
}
if visibleCount == 0 {
return
}
t.mx.Lock()
t.selectedColIdx += delta
// Wrap around
if t.selectedColIdx >= visibleCount {
t.selectedColIdx = 0
} else if t.selectedColIdx < 0 {
t.selectedColIdx = visibleCount - 1
}
t.mx.Unlock()
t.Refresh()
}
// SelectNextColumn moves the column selection to the right.
func (t *Table) SelectNextColumn() {
t.moveSelectedColumn(1)
}
// SelectPrevColumn moves the column selection to the left.
func (t *Table) SelectPrevColumn() {
t.moveSelectedColumn(-1)
}
// SortSelectedColumn sorts by the currently selected column.
func (t *Table) SortSelectedColumn() {
data := t.GetFilteredData()
if data == nil || data.HeaderCount() == 0 {
return
}
idx := t.getSelectedColIdx()
if idx < 0 {
return
}
// Map visual column index to actual header column name
// (accounting for hidden columns)
header := data.Header()
visibleCol := 0
var colName string
for _, h := range header {
if t.shouldExcludeColumn(h) {
continue
}
if visibleCol == idx {
colName = h.Name
break
}
visibleCol++
}
if colName == "" {
return
}
sc := t.getSortCol()
// Toggle direction if same column, otherwise default to ascending
asc := true
if sc.Name == colName {
asc = !sc.ASC
}
t.SetSortCol(colName, asc)
t.setMSort(true)
t.Refresh()
}
// SetViewSetting sets custom view config is present.
func (t *Table) SetViewSetting(vs *config.ViewSetting) bool {
t.mx.Lock()
defer t.mx.Unlock()
if !t.viewSetting.Equals(vs) {
t.viewSetting = vs
slog.Debug("Updating custom view setting", slogs.GVR, t.gvr, slogs.ViewSetting, vs)
t.model.SetViewSetting(t.ctx, vs)
return true
}
return false
}
// GetViewSetting return current view settings if any.
func (t *Table) GetViewSetting() *config.ViewSetting {
t.mx.RLock()
defer t.mx.RUnlock()
return t.viewSetting
}
func (t *Table) GetContext() context.Context {
return t.ctx
}
func (t *Table) SetContext(ctx context.Context) {
t.ctx = ctx
}
// Init initializes the component.
func (t *Table) Init(ctx context.Context) {
t.SetFixed(1, 0)
t.SetBorder(true)
t.SetBorderAttributes(tcell.AttrBold)
t.SetBorderPadding(0, 0, 1, 1)
t.SetSelectable(true, false)
t.SetSelectionChangedFunc(t.selectionChanged)
t.SetBackgroundColor(tcell.ColorDefault)
t.Select(1, 0)
t.styles = mustExtractStyles(ctx)
t.StylesChanged(t.styles)
}
// GVR returns a resource descriptor.
func (t *Table) GVR() *client.GVR { return t.gvr }
// ViewSettingsChanged notifies listener the view configuration changed.
func (t *Table) ViewSettingsChanged(vs *config.ViewSetting) {
if t.SetViewSetting(vs) {
if vs == nil {
if !t.getMSort() && !t.sortCol.IsSet() {
t.setSortCol(model1.SortColumn{})
}
} else {
t.setMSort(false)
}
t.Refresh()
}
}
// StylesChanged notifies the skin changed.
func (t *Table) StylesChanged(s *config.Styles) {
t.SetBackgroundColor(s.Table().BgColor.Color())
t.SetBorderColor(s.Frame().Border.FgColor.Color())
t.SetBorderFocusColor(s.Frame().Border.FocusColor.Color())
t.SetSelectedStyle(
tcell.StyleDefault.Foreground(t.styles.Table().CursorFgColor.Color()).
Background(t.styles.Table().CursorBgColor.Color()).Attributes(tcell.AttrBold))
t.selFgColor = s.Table().CursorFgColor.Color()
t.selBgColor = s.Table().CursorBgColor.Color()
t.Refresh()
}
// ResetToast resets toast flag.
func (t *Table) ResetToast() {
t.toast = false
t.Refresh()
}
// ToggleToast toggles to show toast resources.
func (t *Table) ToggleToast() {
t.toast = !t.toast
t.Refresh()
}
// ToggleWide toggles wide col display.
func (t *Table) ToggleWide() {
t.wide = !t.wide
t.Refresh()
}
// Actions returns active menu bindings.
func (t *Table) Actions() *KeyActions {
return t.actions
}
// Styles returns styling configurator.
func (t *Table) Styles() *config.Styles {
return t.styles
}
// FilterInput filters user commands.
func (t *Table) FilterInput(r rune) bool {
if !t.cmdBuff.IsActive() {
return false
}
t.cmdBuff.Add(r)
t.ClearSelection()
t.doUpdate(t.filtered(t.GetModel().Peek()))
t.UpdateTitle()
t.SelectFirstRow()
return true
}
// Filter filters out table data.
func (t *Table) Filter(string) {
t.ClearSelection()
t.doUpdate(t.filtered(t.GetModel().Peek()))
t.UpdateTitle()
t.SelectFirstRow()
}
// Hints returns the view hints.
func (t *Table) Hints() model.MenuHints {
return t.actions.Hints()
}
// ExtraHints returns additional hints.
func (*Table) ExtraHints() map[string]string {
return nil
}
// GetFilteredData fetch filtered tabular data.
func (t *Table) GetFilteredData() *model1.TableData {
return t.filtered(t.GetModel().Peek())
}
// SetDecorateFn specifies the default row decorator.
func (t *Table) SetDecorateFn(f DecorateFunc) {
t.decorateFn = f
}
// SetColorerFn specifies the default colorer.
func (t *Table) SetColorerFn(f model1.ColorerFunc) {
t.colorerFn = f
}
// SetSortCol sets in sort column index and order.
func (t *Table) SetSortCol(name string, asc bool) {
t.setSortCol(model1.SortColumn{Name: name, ASC: asc})
}
// Update table content.
func (t *Table) Update(data *model1.TableData, hasMetrics bool) *model1.TableData {
if t.decorateFn != nil {
t.decorateFn(data)
}
t.hasMetrics = hasMetrics
return t.doUpdate(t.filtered(data))
}
func (t *Table) GetNamespace() string {
if t.GetModel() != nil {
return t.GetModel().GetNamespace()
}
return client.NamespaceAll
}
func (t *Table) doUpdate(data *model1.TableData) *model1.TableData {
if client.IsAllNamespaces(data.GetNamespace()) {
t.actions.Add(
KeyShiftP,
NewKeyAction("Sort Namespace", t.SortColCmd("NAMESPACE", true), false),
)
} else {
t.actions.Delete(KeyShiftP)
}
oldSortCol := t.getSortCol()
t.setSortCol(data.ComputeSortCol(t.GetViewSetting(), t.getSortCol(), t.getMSort()))
// Initialize selected column index to match the current sort column
// This ensures the highlight starts at the sorted column
newSortCol := t.getSortCol()
if oldSortCol.Name != newSortCol.Name {
t.initSelectedColumn()
}
return data
}
func (t *Table) shouldExcludeColumn(h model1.HeaderColumn) bool {
return (h.Hide || (!t.wide && h.Wide)) ||
(h.Name == "NAMESPACE" && !t.GetModel().ClusterWide()) ||
(h.MX && !t.hasMetrics) ||
(h.VS && vul.ImgScanner == nil)
}
func (t *Table) UpdateUI(cdata, data *model1.TableData) {
t.Clear()
fg := t.styles.Table().Header.FgColor.Color()
bg := t.styles.Table().Header.BgColor.Color()
var col int
for _, h := range cdata.Header() {
if t.shouldExcludeColumn(h) {
continue
}
t.AddHeaderCell(col, h)
c := t.GetCell(0, col)
c.SetBackgroundColor(bg)
c.SetTextColor(fg)
col++
}
cdata.Sort(t.getSortCol())
pads := make(MaxyPad, cdata.HeaderCount())
ComputeMaxColumns(pads, t.getSortCol().Name, cdata)
cdata.RowsRange(func(row int, re model1.RowEvent) bool {
ore, ok := data.FindRow(re.Row.ID)
if !ok {
slog.Error("Unable to find original row event", slogs.RowID, re.Row.ID)
return true
}
t.buildRow(row+1, re, ore, cdata.Header(), pads)
return true
})
t.updateSelection(true)
t.UpdateTitle()
}
func (t *Table) buildRow(r int, re, ore model1.RowEvent, h model1.Header, pads MaxyPad) {
color := model1.DefaultColorer
if t.colorerFn != nil {
color = t.colorerFn
}
marked := t.IsMarked(re.Row.ID)
var col int
ns := t.GetModel().GetNamespace()
for c, field := range re.Row.Fields {
if c >= len(h) {
slog.Error("Field/header overflow detected. Check your mappings!",
slogs.GVR, t.GVR(),
slogs.Cell, c,
slogs.HeaderSize, len(h),
)
continue
}
if t.shouldExcludeColumn(h[c]) {
continue
}
if !re.Deltas.IsBlank() && !h.IsTimeCol(c) {
var old string
if c < len(ore.Deltas) {
old = ore.Deltas[c]
}
if c < len(re.Deltas) {
old = re.Deltas[c]
}
field += Deltas(old, field)
}
if h[c].Decorator != nil {
field = h[c].Decorator(field)
}
if h[c].Align == tview.AlignLeft {
field = formatCell(field, pads[c])
}
cell := tview.NewTableCell(field)
cell.SetExpansion(1)
cell.SetAlign(h[c].Align)
fgColor := color(ns, h, &re)
cell.SetTextColor(fgColor)
if marked {
cell.SetTextColor(t.styles.Table().MarkColor.Color())
}
if col == 0 {
cell.SetReference(re.Row.ID)
}
t.SetCell(r, col, cell)
col++
}
}
// SortColCmd designates a sorted column.
func (t *Table) SortColCmd(name string, asc bool) func(evt *tcell.EventKey) *tcell.EventKey {
return func(*tcell.EventKey) *tcell.EventKey {
sc := t.getSortCol()
sc.ASC = !sc.ASC
if sc.Name != name {
sc.ASC = asc
}
sc.Name = name
t.setSortCol(sc)
t.setMSort(true)
// Sync selected column index with the new sort column
t.initSelectedColumn()
t.Refresh()
return nil
}
}
// SortInvertCmd reverses sorting order.
func (t *Table) SortInvertCmd(*tcell.EventKey) *tcell.EventKey {
t.toggleSortCol()
t.Refresh()
return nil
}
// ClearMarks clear out marked items.
func (t *Table) ClearMarks() {
t.SelectTable.ClearMarks()
t.Refresh()
}
// Refresh update the table data.
func (t *Table) Refresh() {
data := t.model.Peek()
if data.HeaderCount() == 0 {
return
}
cdata := t.Update(data, t.hasMetrics)
t.UpdateUI(cdata, data)
}
// GetSelectedRow returns the entire selected row or nil if nothing selected.
func (t *Table) GetSelectedRow(path string) *model1.Row {
data := t.model.Peek()
re, ok := data.FindRow(path)
if !ok {
return nil
}
return &re.Row
}
// NameColIndex returns the index of the resource name column.
func (t *Table) NameColIndex() int {
col := 0
if client.IsClusterScoped(t.GetModel().GetNamespace()) {
return col
}
if t.GetModel().ClusterWide() {
col++
}
return col
}
// AddHeaderCell configures a table cell header.
func (t *Table) AddHeaderCell(col int, h model1.HeaderColumn) {
sc := t.getSortCol()
sortCol := h.Name == sc.Name
selectedCol := col == t.getSelectedColIdx()
styles := t.styles.Table()
c := tview.NewTableCell(columnIndicator(sortCol, selectedCol, sc.ASC, &styles, h.Name))
c.SetExpansion(1)
c.SetSelectable(false)
c.SetAlign(h.Align)
t.SetCell(0, col, c)
}
func (t *Table) filtered(data *model1.TableData) *model1.TableData {
return data.Filter(model1.FilterOpts{
Toast: t.toast,
Filter: t.cmdBuff.GetText(),
})
}
// CmdBuff returns the associated command buffer.
func (t *Table) CmdBuff() *model.FishBuff {
return t.cmdBuff
}
// ShowDeleted marks row as deleted.
func (t *Table) ShowDeleted() {
r, _ := t.GetSelection()
cols := t.GetColumnCount()
for x := range cols {
t.GetCell(r, x).SetAttributes(tcell.AttrDim)
}
}
// UpdateTitle refreshes the table title.
func (t *Table) UpdateTitle() {
t.SetTitle(t.styleTitle())
}
func (t *Table) styleTitle() string {
rc := int64(t.GetRowCount())
if rc > 0 {
rc--
}
ns := t.GetModel().GetNamespace()
if client.IsClusterWide(ns) || ns == client.NotNamespaced {
ns = client.NamespaceAll
}
path := t.Path
if path != "" {
cns, n := client.Namespaced(path)
if cns == client.ClusterScope {
ns = n
} else {
ns = path
}
}
if t.Extras != "" {
ns = t.Extras
}
resource := t.gvr.R()
if t.fullGVR {
resource = t.gvr.String()
}
var (
title string
styles = t.styles.Frame()
)
if ns == client.ClusterScope {
title = SkinTitle(fmt.Sprintf(TitleFmt, resource, render.AsThousands(rc)), &styles)
} else {
title = SkinTitle(fmt.Sprintf(NSTitleFmt, resource, ns, render.AsThousands(rc)), &styles)
}
buff := t.cmdBuff.GetText()
if internal.IsLabelSelector(buff) {
if sel, err := ExtractLabelSelector(buff); err == nil {
buff = render.Truncate(sel.String(), maxTruncate)
}
} else if l := t.GetModel().GetLabelSelector(); l != nil && !l.Empty() {
buff = render.Truncate(l.String(), maxTruncate)
} else if buff != "" {
buff = render.Truncate(buff, maxTruncate)
}
if buff == "" {
return title
}
return title + SkinTitle(fmt.Sprintf(SearchFmt, buff), &styles)
}
// ROIndicator returns an icon showing whether the session is in readonly mode or not.
func ROIndicator(ro, noIC bool) string {
switch {
case noIC:
return ""
case ro:
return lockedIC
default:
return unlockedIC
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/padding.go | internal/ui/padding.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"strings"
"unicode"
"github.com/derailed/k9s/internal/model1"
"github.com/derailed/k9s/internal/render"
)
// MaxyPad tracks uniform column padding.
type MaxyPad []int
// ComputeMaxColumns figures out column max size and necessary padding.
func ComputeMaxColumns(pads MaxyPad, sortColName string, t *model1.TableData) {
const colPadding = 1
for i, n := range t.ColumnNames(true) {
pads[i] = len(n)
if n == sortColName {
pads[i] += 2
}
}
var row int
t.RowsRange(func(_ int, re model1.RowEvent) bool {
for index, field := range re.Row.Fields {
width := len(field) + colPadding
if index < len(pads) && width > pads[index] {
pads[index] = width
}
}
row++
return true
})
}
// IsASCII checks if table cell has all ascii characters.
func IsASCII(s string) bool {
for i := range s {
if s[i] > unicode.MaxASCII {
return false
}
}
return true
}
// 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 render.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/ui/logo_test.go | internal/ui/logo_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui_test
import (
"testing"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/ui"
"github.com/stretchr/testify/assert"
)
func TestNewLogoView(t *testing.T) {
v := ui.NewLogo(config.NewStyles())
v.Reset()
const elogo = "[#ffa500::b] ____ __ ________ \n[#ffa500::b]| |/ / __ \\______\n[#ffa500::b]| /\\____ / ___/\n[#ffa500::b]| \\ \\ / /\\___ \\\n[#ffa500::b]|____|\\__ \\/____//____ /\n[#ffa500::b] \\/ \\/ \n"
assert.Equal(t, elogo, v.Logo().GetText(false))
assert.Empty(t, v.Status().GetText(false))
}
func TestLogoStatus(t *testing.T) {
uu := map[string]struct {
logo, msg, e string
}{
"info": {
"[#008000::b] ____ __ ________ \n[#008000::b]| |/ / __ \\______\n[#008000::b]| /\\____ / ___/\n[#008000::b]| \\ \\ / /\\___ \\\n[#008000::b]|____|\\__ \\/____//____ /\n[#008000::b] \\/ \\/ \n",
"blee",
"[#ffffff::b]blee\n",
},
"warn": {
"[#c71585::b] ____ __ ________ \n[#c71585::b]| |/ / __ \\______\n[#c71585::b]| /\\____ / ___/\n[#c71585::b]| \\ \\ / /\\___ \\\n[#c71585::b]|____|\\__ \\/____//____ /\n[#c71585::b] \\/ \\/ \n",
"blee",
"[#ffffff::b]blee\n",
},
"err": {
"[#ff0000::b] ____ __ ________ \n[#ff0000::b]| |/ / __ \\______\n[#ff0000::b]| /\\____ / ___/\n[#ff0000::b]| \\ \\ / /\\___ \\\n[#ff0000::b]|____|\\__ \\/____//____ /\n[#ff0000::b] \\/ \\/ \n",
"blee",
"[#ffffff::b]blee\n",
},
}
v := ui.NewLogo(config.NewStyles())
for n := range uu {
k, u := n, uu[n]
t.Run(k, func(t *testing.T) {
switch k {
case "info":
v.Info(u.msg)
case "warn":
v.Warn(u.msg)
case "err":
v.Err(u.msg)
}
assert.Equal(t, u.logo, v.Logo().GetText(false))
assert.Equal(t, u.e, v.Status().GetText(false))
})
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/splash.go | internal/ui/splash.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"fmt"
"strings"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/tview"
)
// LogoSmall K9s small log.
var LogoSmall = []string{
` ____ __ ________ `,
`| |/ / __ \______`,
`| /\____ / ___/`,
`| \ \ / /\___ \`,
`|____|\__ \/____//____ /`,
` \/ \/ `,
}
// LogoBig K9s big logo for splash page.
var LogoBig = []string{
` ____ __ ________ _______ ____ ___ `,
`| |/ / __ \______/ ___ \| | | |`,
`| /\____ / ___/ \ \/| | | |`,
`| \ \ / /\___ \ \___| |___| |`,
`|____|\__ \/____//____ /\______ /_______ \___|`,
` \/ \/ \/ \/ `,
}
// Splash represents a splash screen.
type Splash struct {
*tview.Flex
}
// NewSplash instantiates a new splash screen with product and company info.
func NewSplash(styles *config.Styles, version string) *Splash {
s := Splash{Flex: tview.NewFlex()}
s.SetBackgroundColor(styles.BgColor())
logo := tview.NewTextView()
logo.SetDynamicColors(true)
logo.SetTextAlign(tview.AlignCenter)
s.layoutLogo(logo, styles)
vers := tview.NewTextView()
vers.SetDynamicColors(true)
vers.SetTextAlign(tview.AlignCenter)
s.layoutRev(vers, version, styles)
s.SetDirection(tview.FlexRow)
s.AddItem(logo, 10, 1, false)
s.AddItem(vers, 1, 1, false)
return &s
}
func (*Splash) layoutLogo(t *tview.TextView, styles *config.Styles) {
logo := strings.Join(LogoBig, fmt.Sprintf("\n[%s::b]", styles.Body().LogoColor))
_, _ = fmt.Fprintf(t, "%s[%s::b]%s\n",
strings.Repeat("\n", 2),
styles.Body().LogoColor,
logo)
}
func (*Splash) layoutRev(t *tview.TextView, rev string, styles *config.Styles) {
_, _ = fmt.Fprintf(t, "[%s::b]Revision [red::b]%s", styles.Body().FgColor, rev)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/types.go | internal/ui/types.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"context"
"time"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/dao"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/k9s/internal/model1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
)
const (
unlockedIC = "[RW]"
lockedIC = "[R]"
)
// Namespaceable tracks namespaces.
type Namespaceable interface {
// ClusterWide returns true if the model represents resource in all namespaces.
ClusterWide() bool
// GetNamespace returns the model namespace.
GetNamespace() string
// SetNamespace changes the model namespace.
SetNamespace(string)
// InNamespace check if current namespace matches models.
InNamespace(string) bool
}
// Lister tracks resource getter.
type Lister interface {
// Get returns a resource instance.
Get(ctx context.Context, path string) (runtime.Object, error)
}
// Tabular represents a tabular model.
type Tabular interface {
Namespaceable
Lister
// SetInstance sets parent resource path.
SetInstance(string)
// SetLabelSelector sets the label selector.
SetLabelSelector(labels.Selector)
// GetLabelSelector fetch the label filter.
GetLabelSelector() labels.Selector
// Empty returns true if model has no data.
Empty() bool
// RowCount returns the model data count.
RowCount() int
// Peek returns current model data.
Peek() *model1.TableData
// Watch watches a given resource for changes.
Watch(context.Context) error
// Refresh forces a new refresh.
Refresh(context.Context) error
// SetRefreshRate sets the model watch loop rate.
SetRefreshRate(time.Duration)
// AddListener registers a model listener.
AddListener(model.TableListener)
// RemoveListener unregister a model listener.
RemoveListener(model.TableListener)
// Delete a resource.
Delete(context.Context, string, *metav1.DeletionPropagation, dao.Grace) error
// SetViewSetting injects custom cols specification.
SetViewSetting(context.Context, *config.ViewSetting)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/deltas.go | internal/ui/deltas.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"regexp"
"strconv"
"strings"
"time"
"github.com/derailed/k9s/internal/render"
"k8s.io/apimachinery/pkg/api/resource"
)
const (
// DeltaSign signals a diff.
DeltaSign = "Δ"
// PlusSign signals inc.
PlusSign = "[red::b]↑"
// MinusSign signal dec.
MinusSign = "[green::b]↓"
)
var percent = regexp.MustCompile(`\A(\d+)%\z`)
func deltaNumb(o, n string) (string, bool) {
var delta string
i, ok := numerical(o)
if !ok {
return delta, ok
}
j, _ := numerical(n)
switch {
case i < j:
delta = PlusSign
case i > j:
delta = MinusSign
}
return delta, ok
}
func deltaPerc(o, n string) (string, bool) {
var delta string
i, ok := percentage(o)
if !ok {
return delta, ok
}
j, _ := percentage(n)
switch {
case i < j:
delta = PlusSign
case i > j:
delta = MinusSign
}
return delta, ok
}
func deltaQty(o, n string) (string, bool) {
var delta string
q1, err := resource.ParseQuantity(o)
if err != nil {
return delta, false
}
q2, _ := resource.ParseQuantity(n)
switch q1.Cmp(q2) {
case -1:
delta = PlusSign
case 1:
delta = MinusSign
}
return delta, true
}
func deltaDur(o, n string) (string, bool) {
var delta string
d1, err := time.ParseDuration(o)
if err != nil {
return delta, false
}
d2, _ := time.ParseDuration(n)
switch {
case d2-d1 > 0:
delta = PlusSign
case d2-d1 < 0:
delta = MinusSign
}
return delta, true
}
// Deltas signals diffs between 2 strings.
func Deltas(o, n string) string {
o, n = strings.TrimSpace(o), strings.TrimSpace(n)
if o == "" || o == render.NAValue {
return ""
}
if d, ok := deltaNumb(o, n); ok {
return d
}
if d, ok := deltaPerc(o, n); ok {
return d
}
if d, ok := deltaQty(o, n); ok {
return d
}
if d, ok := deltaDur(o, n); ok {
return d
}
switch strings.Compare(o, n) {
case 1, -1:
return DeltaSign
default:
return ""
}
}
func percentage(s string) (int, bool) {
if res := percent.FindStringSubmatch(s); len(res) == 2 {
n, _ := strconv.Atoi(res[1])
return n, true
}
return 0, false
}
func numerical(s string) (int, bool) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, false
}
return n, true
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/action.go | internal/ui/action.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"log/slog"
"slices"
"sync"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/k9s/internal/slogs"
"github.com/derailed/tcell/v2"
)
type (
// RangeFn represents a range iteration callback.
RangeFn func(tcell.Key, KeyAction)
// ActionHandler handles a keyboard command.
ActionHandler func(*tcell.EventKey) *tcell.EventKey
// ActionOpts tracks various action options.
ActionOpts struct {
Visible bool
Shared bool
Plugin bool
HotKey bool
Dangerous bool
}
// KeyAction represents a keyboard action.
KeyAction struct {
Description string
Action ActionHandler
Opts ActionOpts
}
// KeyMap tracks key to action mappings.
KeyMap map[tcell.Key]KeyAction
// KeyActions tracks mappings between keystrokes and actions.
KeyActions struct {
actions KeyMap
mx sync.RWMutex
}
)
// NewKeyAction returns a new keyboard action.
func NewKeyAction(d string, a ActionHandler, visible bool) KeyAction {
return NewKeyActionWithOpts(d, a, ActionOpts{
Visible: visible,
})
}
// NewSharedKeyAction returns a new shared keyboard action.
func NewSharedKeyAction(d string, a ActionHandler, visible bool) KeyAction {
return NewKeyActionWithOpts(d, a, ActionOpts{
Visible: visible,
Shared: true,
})
}
// NewKeyActionWithOpts returns a new keyboard action.
func NewKeyActionWithOpts(d string, a ActionHandler, opts ActionOpts) KeyAction {
return KeyAction{
Description: d,
Action: a,
Opts: opts,
}
}
// NewKeyActions returns a new instance.
func NewKeyActions() *KeyActions {
return &KeyActions{
actions: make(map[tcell.Key]KeyAction),
}
}
// NewKeyActionsFromMap construct actions from key map.
func NewKeyActionsFromMap(mm KeyMap) *KeyActions {
return &KeyActions{actions: mm}
}
// Get fetches an action given a key.
func (a *KeyActions) Get(key tcell.Key) (KeyAction, bool) {
a.mx.RLock()
defer a.mx.RUnlock()
v, ok := a.actions[key]
return v, ok
}
// Len returns action mapping count.
func (a *KeyActions) Len() int {
a.mx.RLock()
defer a.mx.RUnlock()
return len(a.actions)
}
// Reset clears out actions.
func (a *KeyActions) Reset(aa *KeyActions) {
a.Clear()
a.Merge(aa)
}
// Range ranges over all actions and triggers a given function.
func (a *KeyActions) Range(f RangeFn) {
var km KeyMap
a.mx.RLock()
km = a.actions
a.mx.RUnlock()
for k, v := range km {
f(k, v)
}
}
// Add adds a new key action.
func (a *KeyActions) Add(k tcell.Key, ka KeyAction) {
a.mx.Lock()
defer a.mx.Unlock()
a.actions[k] = ka
}
// Bulk bulk insert key mappings.
func (a *KeyActions) Bulk(aa KeyMap) {
a.mx.Lock()
defer a.mx.Unlock()
for k, v := range aa {
a.actions[k] = v
}
}
// Merge merges given actions into existing set.
func (a *KeyActions) Merge(aa *KeyActions) {
a.mx.Lock()
defer a.mx.Unlock()
for k, v := range aa.actions {
a.actions[k] = v
}
}
// Clear remove all actions.
func (a *KeyActions) Clear() {
a.mx.Lock()
defer a.mx.Unlock()
for k := range a.actions {
delete(a.actions, k)
}
}
// ClearDanger remove all dangerous actions.
func (a *KeyActions) ClearDanger() {
a.mx.Lock()
defer a.mx.Unlock()
for k, v := range a.actions {
if v.Opts.Dangerous {
delete(a.actions, k)
}
}
}
// Set replace actions with new ones.
func (a *KeyActions) Set(aa *KeyActions) {
a.mx.Lock()
defer a.mx.Unlock()
for k, v := range aa.actions {
a.actions[k] = v
}
}
// Delete deletes actions by the given keys.
func (a *KeyActions) Delete(kk ...tcell.Key) {
a.mx.Lock()
defer a.mx.Unlock()
for _, k := range kk {
delete(a.actions, k)
}
}
// Hints returns a collection of hints.
func (a *KeyActions) Hints() model.MenuHints {
a.mx.RLock()
defer a.mx.RUnlock()
kk := make([]tcell.Key, 0, len(a.actions))
for k := range a.actions {
if !a.actions[k].Opts.Shared {
kk = append(kk, k)
}
}
slices.Sort(kk)
hh := make(model.MenuHints, 0, len(kk))
for _, k := range kk {
if name, ok := tcell.KeyNames[k]; ok {
hh = append(hh,
model.MenuHint{
Mnemonic: name,
Description: a.actions[k].Description,
Visible: a.actions[k].Opts.Visible,
},
)
} else {
slog.Error("Unable to locate key name", slogs.Key, k)
}
}
return hh
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/flash.go | internal/ui/flash.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"context"
"log/slog"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/tcell/v2"
"github.com/derailed/tview"
)
const (
emoHappy = "😎"
emoDoh = "😗"
emoRed = "😡"
)
// Flash represents a flash message indicator.
type Flash struct {
*tview.TextView
app *App
testMode bool
}
// NewFlash returns a new flash view.
func NewFlash(app *App) *Flash {
f := Flash{
app: app,
TextView: tview.NewTextView(),
}
f.SetTextColor(tcell.ColorAqua)
f.SetDynamicColors(true)
f.SetTextAlign(tview.AlignCenter)
f.SetBorderPadding(0, 0, 1, 1)
f.app.Styles.AddListener(&f)
return &f
}
// SetTestMode for testing ONLY!
func (f *Flash) SetTestMode(b bool) {
f.testMode = b
}
// StylesChanged notifies listener the skin changed.
func (f *Flash) StylesChanged(s *config.Styles) {
f.SetBackgroundColor(s.BgColor())
f.SetTextColor(s.FgColor())
}
// Watch watches for flash changes.
func (f *Flash) Watch(ctx context.Context, c model.FlashChan) {
defer slog.Debug("Flash Watch Canceled!")
for {
select {
case <-ctx.Done():
return
case msg := <-c:
f.SetMessage(msg)
}
}
}
// SetMessage sets flash message and level.
func (f *Flash) SetMessage(m model.LevelMessage) {
fn := func() {
if m.Text == "" {
f.Clear()
return
}
f.SetTextColor(flashColor(m.Level))
f.SetText(f.flashEmoji(m.Level) + " " + m.Text)
}
if f.testMode {
fn()
} else {
f.app.QueueUpdateDraw(fn)
}
}
func (f *Flash) flashEmoji(l model.FlashLevel) string {
if f.app.Config.K9s.UI.NoIcons {
return ""
}
//nolint:exhaustive
switch l {
case model.FlashWarn:
return emoDoh
case model.FlashErr:
return emoRed
default:
return emoHappy
}
}
// Helpers...
func flashColor(l model.FlashLevel) tcell.Color {
//nolint:exhaustive
switch l {
case model.FlashWarn:
return tcell.ColorOrange
case model.FlashErr:
return tcell.ColorOrangeRed
default:
return tcell.ColorNavajoWhite
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/table_helper_test.go | internal/ui/table_helper_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"testing"
"github.com/derailed/k9s/internal/render"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/labels"
)
func TestTruncate(t *testing.T) {
uu := map[string]struct {
s, e string
}{
"empty": {},
"max": {
s: "/app.kubernetes.io/instance=prom,app.kubernetes.io/name=prometheus,app.kubernetes.io/component=server",
e: "/app.kubernetes.io/instance=prom,app.kubernetes.i…",
},
"less": {
s: "app=fred,env=blee",
e: "app=fred,env=blee",
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, render.Truncate(u.s, 50))
})
}
}
func TestExtractLabelSelector(t *testing.T) {
sel, _ := labels.Parse("app=fred,env=blee")
uu := map[string]struct {
sel string
err error
e labels.Selector
}{
"cool": {
sel: "-l app=fred,env=blee",
e: sel,
},
"no-space": {
sel: "-lapp=fred,env=blee",
e: sel,
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
sel, err := ExtractLabelSelector(u.sel)
assert.Equal(t, u.err, err)
assert.Equal(t, u.e, sel)
})
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/menu_test.go | internal/ui/menu_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui_test
import (
"testing"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/k9s/internal/ui"
"github.com/stretchr/testify/assert"
)
func TestNewMenu(t *testing.T) {
v := ui.NewMenu(config.NewStyles())
v.HydrateMenu(model.MenuHints{
{Mnemonic: "a", Description: "bleeA", Visible: true},
{Mnemonic: "b", Description: "bleeB", Visible: true},
{Mnemonic: "0", Description: "zero", Visible: true},
})
assert.Equal(t, " [#ff00ff:-:b]<0> [#ffffff:-:d]zero ", v.GetCell(0, 0).Text)
assert.Equal(t, " [#1e90ff:-:b]<a> [#ffffff:-:d]bleeA ", v.GetCell(0, 1).Text)
assert.Equal(t, " [#1e90ff:-:b]<b> [#ffffff:-:d]bleeB ", v.GetCell(1, 1).Text)
}
func TestActionHints(t *testing.T) {
uu := map[string]struct {
aa *ui.KeyActions
e model.MenuHints
}{
"a": {
aa: ui.NewKeyActionsFromMap(ui.KeyMap{
ui.KeyB: ui.NewKeyAction("bleeB", nil, true),
ui.KeyA: ui.NewKeyAction("bleeA", nil, true),
ui.Key0: ui.NewKeyAction("zero", nil, true),
ui.Key1: ui.NewKeyAction("one", nil, false),
}),
e: model.MenuHints{
{Mnemonic: "0", Description: "zero", Visible: true},
{Mnemonic: "1", Description: "one", Visible: false},
{Mnemonic: "a", Description: "bleeA", Visible: true},
{Mnemonic: "b", Description: "bleeB", Visible: true},
},
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
assert.Equal(t, u.e, u.aa.Hints())
})
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/config.go | internal/ui/config.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"context"
"errors"
"io/fs"
"log/slog"
"os"
"path/filepath"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/k9s/internal/model1"
"github.com/derailed/k9s/internal/slogs"
"github.com/fsnotify/fsnotify"
)
// Synchronizer manages ui event queue.
type synchronizer interface {
Flash() *model.Flash
Logo() *Logo
UpdateClusterInfo()
QueueUpdateDraw(func())
QueueUpdate(func())
}
// Configurator represents an application configuration.
type Configurator struct {
Config *config.Config
Styles *config.Styles
customView *config.CustomView
BenchFile string
skinFile string
}
func (c *Configurator) CustomView() *config.CustomView {
if c.customView == nil {
c.customView = config.NewCustomView()
}
return c.customView
}
// HasSkin returns true if a skin file was located.
func (c *Configurator) HasSkin() bool {
return c.skinFile != ""
}
// CustomViewsWatcher watches for view config file changes.
func (c *Configurator) CustomViewsWatcher(ctx context.Context, s synchronizer) error {
w, err := fsnotify.NewWatcher()
if err != nil {
return err
}
go func() {
for {
select {
case evt := <-w.Events:
if evt.Name == config.AppViewsFile && evt.Op != fsnotify.Chmod {
s.QueueUpdateDraw(func() {
if err := c.RefreshCustomViews(); err != nil {
slog.Warn("Custom views refresh failed", slogs.Error, err)
}
})
}
case err := <-w.Errors:
slog.Warn("CustomView watcher failed", slogs.Error, err)
return
case <-ctx.Done():
slog.Debug("CustomViewWatcher canceled", slogs.FileName, config.AppViewsFile)
if err := w.Close(); err != nil {
slog.Error("Closing CustomView watcher", slogs.Error, err)
}
return
}
}
}()
if err := w.Add(config.AppViewsFile); err != nil {
return err
}
slog.Debug("Loading custom views", slogs.FileName, config.AppViewsFile)
return c.RefreshCustomViews()
}
// RefreshCustomViews load view configuration changes.
func (c *Configurator) RefreshCustomViews() error {
c.CustomView().Reset()
return c.CustomView().Load(config.AppViewsFile)
}
// SkinsDirWatcher watches for skin directory file changes.
func (c *Configurator) SkinsDirWatcher(ctx context.Context, s synchronizer) error {
if _, err := os.Stat(config.AppSkinsDir); errors.Is(err, fs.ErrNotExist) {
return err
}
w, err := fsnotify.NewWatcher()
if err != nil {
return err
}
go func() {
for {
select {
case evt := <-w.Events:
if evt.Op != fsnotify.Chmod && filepath.Base(evt.Name) == filepath.Base(c.skinFile) {
slog.Debug("Skin file changed detected", slogs.FileName, c.skinFile)
s.QueueUpdateDraw(func() {
c.RefreshStyles(s)
})
}
case err := <-w.Errors:
slog.Warn("Skin watcher failed", slogs.Error, err)
return
case <-ctx.Done():
slog.Debug("SkinWatcher canceled", slogs.FileName, c.skinFile)
if err := w.Close(); err != nil {
slog.Error("Closing Skin watcher", slogs.Error, err)
}
return
}
}
}()
slog.Debug("SkinWatcher initialized", slogs.Dir, config.AppSkinsDir)
return w.Add(config.AppSkinsDir)
}
// ConfigWatcher watches for config settings changes.
func (c *Configurator) ConfigWatcher(ctx context.Context, s synchronizer) error {
w, err := fsnotify.NewWatcher()
if err != nil {
return err
}
go func() {
for {
select {
case evt := <-w.Events:
if evt.Has(fsnotify.Create) || evt.Has(fsnotify.Write) {
slog.Debug("ConfigWatcher file changed", slogs.FileName, evt.Name)
if evt.Name == config.AppConfigFile {
if err := c.Config.Load(evt.Name, false); err != nil {
slog.Error("K9s config reload failed", slogs.Error, err)
s.Flash().Warn("k9s config reload failed. Check k9s logs!")
s.Logo().Warn("K9s config reload failed!")
}
} else {
if err := c.Config.K9s.Reload(); err != nil {
slog.Error("K9s context config reload failed", slogs.Error, err)
s.Flash().Warn("Context config reload failed. Check k9s logs!")
s.Logo().Warn("Context config reload failed!")
}
}
s.QueueUpdateDraw(func() {
c.RefreshStyles(s)
})
}
case err := <-w.Errors:
slog.Warn("ConfigWatcher failed", slogs.Error, err)
return
case <-ctx.Done():
slog.Debug("ConfigWatcher canceled")
if err := w.Close(); err != nil {
slog.Error("Canceling ConfigWatcher", slogs.Error, err)
}
return
}
}
}()
slog.Debug("ConfigWatcher watching", slogs.FileName, config.AppConfigFile)
if err := w.Add(config.AppConfigFile); err != nil {
return err
}
cl, ct, ok := c.activeConfig()
if !ok {
return nil
}
ctConfigFile := config.AppContextConfig(cl, ct)
slog.Debug("ConfigWatcher watching", slogs.FileName, ctConfigFile)
return w.Add(ctConfigFile)
}
func (c *Configurator) activeSkin() (string, bool) {
var skin string
if c.Config == nil || c.Config.K9s == nil {
return skin, false
}
if env_skin := os.Getenv("K9S_SKIN"); env_skin != "" {
if _, err := os.Stat(config.SkinFileFromName(env_skin)); err == nil {
skin = env_skin
slog.Debug("Loading env skin", slogs.Skin, skin)
return skin, true
}
}
if ct, err := c.Config.K9s.ActiveContext(); err == nil && ct.Skin != "" {
if _, err := os.Stat(config.SkinFileFromName(ct.Skin)); err == nil {
skin = ct.Skin
slog.Debug("Loading context skin",
slogs.Skin, skin,
slogs.Context, c.Config.K9s.ActiveContextName(),
)
return skin, true
}
}
if sk := c.Config.K9s.UI.Skin; sk != "" {
if _, err := os.Stat(config.SkinFileFromName(sk)); err == nil {
skin = sk
slog.Debug("Loading global skin", slogs.Skin, skin)
return skin, true
}
}
return skin, skin != ""
}
func (c *Configurator) activeConfig() (cluster, contxt string, ok bool) {
if c.Config == nil || c.Config.K9s == nil {
return
}
ct, err := c.Config.K9s.ActiveContext()
if err != nil {
return
}
cluster, contxt = ct.GetClusterName(), c.Config.K9s.ActiveContextName()
if cluster != "" && contxt != "" {
ok = true
}
return
}
// RefreshStyles load for skin configuration changes.
func (c *Configurator) RefreshStyles(s synchronizer) {
s.UpdateClusterInfo()
if c.Styles == nil {
c.Styles = config.NewStyles()
}
defer c.loadSkinFile(s)
cl, ct, ok := c.activeConfig()
if !ok {
return
}
// !!BOZO!! Lame move out!
if bc, err := config.EnsureBenchmarksCfgFile(cl, ct); err != nil {
slog.Warn("No benchmark config file found",
slogs.Cluster, cl,
slogs.Context, ct,
slogs.Error, err,
)
} else {
c.BenchFile = bc
}
}
func (c *Configurator) loadSkinFile(synchronizer) {
skin, ok := c.activeSkin()
if !ok {
slog.Debug("No custom skin found. Using stock skin")
c.updateStyles("")
return
}
skinFile := config.SkinFileFromName(skin)
slog.Debug("Loading skin file", slogs.Skin, skinFile)
if err := c.Styles.Load(skinFile); err != nil {
if errors.Is(err, os.ErrNotExist) {
slog.Warn("Skin file not found in skins dir",
slogs.Skin, filepath.Base(skinFile),
slogs.Dir, config.AppSkinsDir,
slogs.Error, err,
)
c.updateStyles("")
} else {
slog.Error("Failed to parse skin file",
slogs.Path, filepath.Base(skinFile),
slogs.Error, err,
)
c.updateStyles(skinFile)
}
} else {
c.updateStyles(skinFile)
}
}
func (c *Configurator) updateStyles(f string) {
c.skinFile = f
if f == "" {
c.Styles.Reset()
}
c.Styles.Update()
model1.ModColor = c.Styles.Frame().Status.ModifyColor.Color()
model1.AddColor = c.Styles.Frame().Status.AddColor.Color()
model1.ErrColor = c.Styles.Frame().Status.ErrorColor.Color()
model1.StdColor = c.Styles.Frame().Status.NewColor.Color()
model1.PendingColor = c.Styles.Frame().Status.PendingColor.Color()
model1.HighlightColor = c.Styles.Frame().Status.HighlightColor.Color()
model1.KillColor = c.Styles.Frame().Status.KillColor.Color()
model1.CompletedColor = c.Styles.Frame().Status.CompletedColor.Color()
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/prompt_validation_test.go | internal/ui/prompt_validation_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui_test
import (
"fmt"
"testing"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/k9s/internal/ui"
"github.com/derailed/tcell/v2"
"github.com/stretchr/testify/assert"
)
// TestPrompt_FiltersControlCharacters tests that control characters from
// terminal escape sequences are filtered out and not added to the buffer.
func TestPrompt_FiltersControlCharacters(t *testing.T) {
m := model.NewFishBuff(':', model.CommandBuffer)
p := ui.NewPrompt(nil, true, config.NewStyles())
p.SetModel(m)
m.AddListener(p)
m.SetActive(true)
// Test control characters that should be filtered
controlChars := []rune{
0x00, // NULL
0x01, // SOH
0x1B, // ESC (escape character)
0x7F, // DEL
}
for _, c := range controlChars {
t.Run(fmt.Sprintf("control_char_0x%02X", c), func(t *testing.T) {
evt := tcell.NewEventKey(tcell.KeyRune, c, tcell.ModNone)
p.SendKey(evt)
// Control characters should not be added to buffer
assert.Empty(t, m.GetText(), "Control character 0x%02X should be filtered", c)
})
}
}
// TestPrompt_AcceptsPrintableCharacters tests that valid printable
// characters are accepted and added to the buffer.
func TestPrompt_AcceptsPrintableCharacters(t *testing.T) {
m := model.NewFishBuff(':', model.CommandBuffer)
p := ui.NewPrompt(nil, true, config.NewStyles())
p.SetModel(m)
m.AddListener(p)
m.SetActive(true)
// Test valid printable characters
validChars := []rune{
'a', 'Z', '0', '9',
'!', '@', '#', '$',
' ', // space
'[', ']', ';', 'R', // characters from escape sequences (should be accepted if typed)
}
for _, c := range validChars {
t.Run(fmt.Sprintf("valid_char_%c", c), func(t *testing.T) {
evt := tcell.NewEventKey(tcell.KeyRune, c, tcell.ModNone)
p.SendKey(evt)
// Valid characters should be added
assert.Contains(t, m.GetText(), string(c), "Valid character %c should be accepted", c)
// Clear for next test
m.ClearText(true)
})
}
// Test tab separately (it's a control char but should be accepted)
t.Run("valid_char_tab", func(t *testing.T) {
evt := tcell.NewEventKey(tcell.KeyRune, '\t', tcell.ModNone)
p.SendKey(evt)
// Tab should be accepted (it's a special case in the validation)
// Note: Tab might be converted to spaces or handled differently by the buffer
text := m.GetText()
// Tab is accepted by validation, but may be handled specially by the buffer
// Just verify the buffer isn't empty (meaning something was processed)
assert.NotNil(t, text, "Tab character should be processed")
m.ClearText(true)
})
}
// TestPrompt_FiltersEscapeSequencePattern tests that escape sequence
// patterns are not automatically added when they appear as individual runes.
// Note: This test verifies the validation works, but escape sequences
// should ideally be handled by tcell before reaching KeyRune.
func TestPrompt_FiltersEscapeSequencePattern(t *testing.T) {
m := model.NewFishBuff(':', model.CommandBuffer)
p := ui.NewPrompt(nil, true, config.NewStyles())
p.SetModel(m)
m.AddListener(p)
m.SetActive(true)
// Simulate the problematic escape sequence pattern [7;15R
// Each character individually is printable, but we want to ensure
// they don't appear unexpectedly
escapeSequence := "[7;15R"
// Send each character
for _, r := range escapeSequence {
evt := tcell.NewEventKey(tcell.KeyRune, r, tcell.ModNone)
p.SendKey(evt)
}
// The characters themselves are printable, so they will be added
// This test documents the current behavior - the fix prevents
// control characters, but printable escape sequence chars would
// still be added if tcell doesn't filter them first
text := m.GetText()
// If all characters are printable, they will be in the buffer
// This is expected behavior - the fix prevents control chars,
// but can't prevent legitimate printable characters
assert.NotEmpty(t, text, "Printable escape sequence chars may still appear")
// However, we can verify no control characters made it through
for _, r := range text {
assert.False(t, isControlChar(r), "No control characters should be in buffer")
}
}
// Helper function to check if a rune is a control character
func isControlChar(r rune) bool {
return r >= 0x00 && r <= 0x1F || r == 0x7F
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/indicator_test.go | internal/ui/indicator_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui_test
import (
"testing"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/config/mock"
"github.com/derailed/k9s/internal/ui"
"github.com/stretchr/testify/assert"
)
func TestIndicatorReset(t *testing.T) {
i := ui.NewStatusIndicator(ui.NewApp(mock.NewMockConfig(t), ""), config.NewStyles())
i.SetPermanent("Blee")
i.Info("duh")
i.Reset()
assert.Equal(t, "Blee\n", i.GetText(false))
}
func TestIndicatorInfo(t *testing.T) {
i := ui.NewStatusIndicator(ui.NewApp(mock.NewMockConfig(t), ""), config.NewStyles())
i.Info("Blee")
assert.Equal(t, "[lawngreen::b] <Blee> \n", i.GetText(false))
}
func TestIndicatorWarn(t *testing.T) {
i := ui.NewStatusIndicator(ui.NewApp(mock.NewMockConfig(t), ""), config.NewStyles())
i.Warn("Blee")
assert.Equal(t, "[mediumvioletred::b] <Blee> \n", i.GetText(false))
}
func TestIndicatorErr(t *testing.T) {
i := ui.NewStatusIndicator(ui.NewApp(mock.NewMockConfig(t), ""), config.NewStyles())
i.Err("Blee")
assert.Equal(t, "[orangered::b] <Blee> \n", i.GetText(false))
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/padding_test.go | internal/ui/padding_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"testing"
"github.com/derailed/k9s/internal/client"
"github.com/derailed/k9s/internal/model1"
"github.com/stretchr/testify/assert"
)
func TestMaxColumn(t *testing.T) {
uu := map[string]struct {
t *model1.TableData
s string
e MaxyPad
}{
"ascii col 0": {
model1.NewTableDataWithRows(
client.NewGVR("test"),
model1.Header{model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B"}},
model1.NewRowEventsWithEvts(
model1.RowEvent{
Row: model1.Row{
Fields: model1.Fields{"hello", "world"},
},
},
model1.RowEvent{
Row: model1.Row{
Fields: model1.Fields{"yo", "mama"},
},
},
),
),
"A",
MaxyPad{6, 6},
},
"ascii col 1": {
model1.NewTableDataWithRows(
client.NewGVR("test"),
model1.Header{model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B"}},
model1.NewRowEventsWithEvts(
model1.RowEvent{
Row: model1.Row{
Fields: model1.Fields{"hello", "world"},
},
},
model1.RowEvent{
Row: model1.Row{
Fields: model1.Fields{"yo", "mama"},
},
},
),
),
"B",
MaxyPad{6, 6},
},
"non_ascii": {
model1.NewTableDataWithRows(
client.NewGVR("test"),
model1.Header{model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B"}},
model1.NewRowEventsWithEvts(
model1.RowEvent{
Row: model1.Row{
Fields: model1.Fields{"Hello World lord of ipsums 😅", "world"},
},
},
model1.RowEvent{
Row: model1.Row{
Fields: model1.Fields{"o", "mama"},
},
},
),
),
"A",
MaxyPad{32, 6},
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
pads := make(MaxyPad, u.t.HeaderCount())
ComputeMaxColumns(pads, u.s, u.t)
assert.Equal(t, u.e, pads)
})
}
}
func TestIsASCII(t *testing.T) {
uu := []struct {
s string
e bool
}{
{"hello", true},
{"Yo! 😄", false},
{"😄", false},
}
for _, u := range uu {
assert.Equal(t, u.e, IsASCII(u.s))
}
}
func TestPad(t *testing.T) {
uu := []struct {
s string
l int
e string
}{
{"fred", 3, "fr…"},
{"01234567890", 10, "012345678…"},
{"fred", 10, "fred "},
{"fred", 6, "fred "},
{"fred", 4, "fred"},
}
for _, u := range uu {
assert.Equal(t, u.e, Pad(u.s, u.l))
}
}
func BenchmarkMaxColumn(b *testing.B) {
table := model1.NewTableDataWithRows(
client.NewGVR("test"),
model1.Header{model1.HeaderColumn{Name: "A"}, model1.HeaderColumn{Name: "B"}},
model1.NewRowEventsWithEvts(
model1.RowEvent{
Row: model1.Row{
Fields: model1.Fields{"hello", "world"},
},
},
model1.RowEvent{
Row: model1.Row{
Fields: model1.Fields{"yo", "mama"},
},
},
),
)
pads := make(MaxyPad, table.HeaderCount())
b.ReportAllocs()
b.ResetTimer()
for range b.N {
ComputeMaxColumns(pads, "A", table)
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/logo.go | internal/ui/logo.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"fmt"
"strings"
"sync"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/tview"
)
// Logo represents a K9s logo.
type Logo struct {
*tview.Flex
logo, status *tview.TextView
styles *config.Styles
mx sync.Mutex
}
// NewLogo returns a new logo.
func NewLogo(styles *config.Styles) *Logo {
l := Logo{
Flex: tview.NewFlex(),
logo: logo(),
status: status(),
styles: styles,
}
l.SetDirection(tview.FlexRow)
l.AddItem(l.logo, 6, 1, false)
l.AddItem(l.status, 1, 1, false)
l.refreshLogo(styles.Body().LogoColor)
l.SetBackgroundColor(styles.BgColor())
styles.AddListener(&l)
return &l
}
// Logo returns the logo viewer.
func (l *Logo) Logo() *tview.TextView {
return l.logo
}
// Status returns the status viewer.
func (l *Logo) Status() *tview.TextView {
return l.status
}
// StylesChanged notifies the skin changed.
func (l *Logo) StylesChanged(s *config.Styles) {
l.styles = s
l.SetBackgroundColor(l.styles.BgColor())
l.status.SetBackgroundColor(l.styles.BgColor())
l.logo.SetBackgroundColor(l.styles.BgColor())
l.refreshLogo(l.styles.Body().LogoColor)
}
// IsBenchmarking checks if benchmarking is active or not.
func (l *Logo) IsBenchmarking() bool {
txt := l.Status().GetText(true)
return strings.Contains(txt, "Bench")
}
// Reset clears out the logo view and resets colors.
func (l *Logo) Reset() {
l.status.Clear()
l.StylesChanged(l.styles)
}
// Err displays a log error state.
func (l *Logo) Err(msg string) {
l.update(msg, l.styles.Body().LogoColorError)
}
// Warn displays a log warning state.
func (l *Logo) Warn(msg string) {
l.update(msg, l.styles.Body().LogoColorWarn)
}
// Info displays a log info state.
func (l *Logo) Info(msg string) {
l.update(msg, l.styles.Body().LogoColorInfo)
}
func (l *Logo) update(msg string, c config.Color) {
l.refreshStatus(msg, c)
l.refreshLogo(c)
}
func (l *Logo) refreshStatus(msg string, c config.Color) {
l.mx.Lock()
defer l.mx.Unlock()
l.status.SetBackgroundColor(c.Color())
l.status.SetText(
fmt.Sprintf("[%s::b]%s", l.styles.Body().LogoColorMsg, msg),
)
}
func (l *Logo) refreshLogo(c config.Color) {
l.mx.Lock()
defer l.mx.Unlock()
l.logo.Clear()
for i, s := range LogoSmall {
_, _ = fmt.Fprintf(l.logo, "[%s::b]%s", c, s)
if i+1 < len(LogoSmall) {
_, _ = fmt.Fprintf(l.logo, "\n")
}
}
}
func logo() *tview.TextView {
v := tview.NewTextView()
v.SetWordWrap(false)
v.SetWrap(false)
v.SetTextAlign(tview.AlignLeft)
v.SetDynamicColors(true)
return v
}
func status() *tview.TextView {
v := tview.NewTextView()
v.SetWordWrap(false)
v.SetWrap(false)
v.SetTextAlign(tview.AlignCenter)
v.SetDynamicColors(true)
return v
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/modal_list.go | internal/ui/modal_list.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"github.com/derailed/tcell/v2"
"github.com/derailed/tview"
)
type ModalList struct {
*tview.Box
// The list embedded in the modal's frame.
list *tview.List
// The frame embedded in the modal.
frame *tview.Frame
// The optional callback for when the user clicked one of the items. It
// receives the index of the clicked item and the item's text.
done func(int, string)
}
func NewModalList(title string, list *tview.List) *ModalList {
m := &ModalList{Box: tview.NewBox()}
m.list = list
m.list.SetBackgroundColor(tview.Styles.ContrastBackgroundColor).SetBorderPadding(0, 0, 0, 0)
m.list.SetSelectedFunc(func(i int, main string, _ string, _ rune) {
if m.done != nil {
m.done(i, main)
}
})
m.list.SetDoneFunc(func() {
if m.done != nil {
m.done(-1, "")
}
})
m.frame = tview.NewFrame(m.list).SetBorders(0, 0, 1, 0, 0, 0)
m.frame.SetBorder(true).
SetBackgroundColor(tview.Styles.ContrastBackgroundColor).
SetBorderPadding(1, 1, 1, 1)
m.frame.SetTitle(title)
m.frame.SetTitleColor(tcell.ColorAqua)
return m
}
// Draw draws this primitive onto the screen.
func (m *ModalList) Draw(screen tcell.Screen) {
// Calculate the width of this modal.
width := 0
for i := range m.list.GetItemCount() {
main, secondary := m.list.GetItemText(i)
width = max(width, len(main)+len(secondary)+2)
}
screenWidth, screenHeight := screen.Size()
// Set the modal's position and size.
height := m.list.GetItemCount() + 4
width += 2
x := (screenWidth - width) / 2
y := (screenHeight - height) / 2
m.SetRect(x, y, width, height)
// Draw the frame.
m.frame.SetRect(x, y, width, height)
m.frame.Draw(screen)
}
func (m *ModalList) SetDoneFunc(handler func(int, string)) *ModalList {
m.done = handler
return m
}
// Focus is called when this primitive receives focus.
func (m *ModalList) Focus(delegate func(p tview.Primitive)) {
delegate(m.list)
}
// HasFocus returns whether this primitive has focus.
func (m *ModalList) HasFocus() bool {
return m.list.HasFocus()
}
// MouseHandler returns the mouse handler for this primitive.
func (m *ModalList) MouseHandler() func(action tview.MouseAction, event *tcell.EventMouse, setFocus func(p tview.Primitive)) (consumed bool, capture tview.Primitive) {
return m.WrapMouseHandler(func(action tview.MouseAction, event *tcell.EventMouse, setFocus func(p tview.Primitive)) (consumed bool, capture tview.Primitive) {
// Pass mouse events on to the form.
consumed, capture = m.list.MouseHandler()(action, event, setFocus)
if !consumed && action == tview.MouseLeftClick && m.InRect(event.Position()) {
setFocus(m)
consumed = true
}
return
})
}
// InputHandler returns the handler for this primitive.
func (m *ModalList) InputHandler() func(event *tcell.EventKey, setFocus func(p tview.Primitive)) {
return m.WrapInputHandler(func(event *tcell.EventKey, setFocus func(p tview.Primitive)) {
if m.frame.HasFocus() {
if handler := m.frame.InputHandler(); handler != nil {
handler(event, setFocus)
return
}
}
})
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/config_test.go | internal/ui/config_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui_test
import (
"os"
"path/filepath"
"testing"
"time"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/config/data"
"github.com/derailed/k9s/internal/config/mock"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/k9s/internal/model1"
"github.com/derailed/k9s/internal/ui"
"github.com/derailed/tcell/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"k8s.io/cli-runtime/pkg/genericclioptions"
)
func TestSkinnedContext(t *testing.T) {
require.NoError(t, os.Setenv(config.K9sEnvConfigDir, "/tmp/k9s-test"))
require.NoError(t, config.InitLocs())
defer require.NoError(t, os.RemoveAll(config.K9sEnvConfigDir))
sf := filepath.Join("..", "config", "testdata", "skins", "black-and-wtf.yaml")
raw, err := os.ReadFile(sf)
require.NoError(t, err)
tf := filepath.Join(config.AppSkinsDir, "black-and-wtf.yaml")
require.NoError(t, os.WriteFile(tf, raw, data.DefaultFileMod))
var cfg ui.Configurator
cfg.Config = mock.NewMockConfig(t)
cl, ct := "cl-1", "ct-1"
flags := genericclioptions.ConfigFlags{
ClusterName: &cl,
Context: &ct,
}
cfg.Config.K9s = config.NewK9s(
mock.NewMockConnection(),
mock.NewMockKubeSettings(&flags))
_, err = cfg.Config.K9s.ActivateContext("ct-1-1")
require.NoError(t, err)
cfg.Config.K9s.UI = config.UI{Skin: "black-and-wtf"}
cfg.RefreshStyles(newMockSynchronizer())
assert.True(t, cfg.HasSkin())
assert.Equal(t, tcell.ColorGhostWhite.TrueColor(), model1.StdColor)
assert.Equal(t, tcell.ColorWhiteSmoke.TrueColor(), model1.ErrColor)
}
func TestBenchConfig(t *testing.T) {
require.NoError(t, os.Setenv(config.K9sEnvConfigDir, "/tmp/test-config"))
require.NoError(t, config.InitLocs())
defer require.NoError(t, os.RemoveAll(config.K9sEnvConfigDir))
bc, err := config.EnsureBenchmarksCfgFile("cl-1", "ct-1")
require.NoError(t, err)
assert.Equal(t, "/tmp/test-config/clusters/cl-1/ct-1/benchmarks.yaml", bc)
}
// Helpers...
type synchronizer struct{}
func newMockSynchronizer() synchronizer {
return synchronizer{}
}
func (synchronizer) Flash() *model.Flash {
return model.NewFlash(100 * time.Millisecond)
}
func (synchronizer) Logo() *ui.Logo { return nil }
func (synchronizer) UpdateClusterInfo() {}
func (synchronizer) QueueUpdateDraw(func()) {}
func (synchronizer) QueueUpdate(func()) {}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/menu.go | internal/ui/menu.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"fmt"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/tview"
runewidth "github.com/mattn/go-runewidth"
)
const (
menuIndexFmt = " [key:-:b]<%d> [fg:-:fgstyle]%s "
maxRows = 6
)
var menuRX = regexp.MustCompile(`\d`)
// Menu presents menu options.
type Menu struct {
*tview.Table
styles *config.Styles
}
// NewMenu returns a new menu.
func NewMenu(styles *config.Styles) *Menu {
m := Menu{
Table: tview.NewTable(),
styles: styles,
}
m.SetBackgroundColor(styles.BgColor())
styles.AddListener(&m)
return &m
}
// StylesChanged notifies skin changed.
func (m *Menu) StylesChanged(s *config.Styles) {
m.styles = s
m.SetBackgroundColor(s.BgColor())
for row := range m.GetRowCount() {
for col := range m.GetColumnCount() {
if c := m.GetCell(row, col); c != nil {
c.BackgroundColor = s.BgColor()
}
}
}
}
// StackPushed notifies a component was added.
func (m *Menu) StackPushed(c model.Component) {
m.HydrateMenu(c.Hints())
}
// StackPopped notifies a component was removed.
func (m *Menu) StackPopped(_, top model.Component) {
if top != nil {
m.HydrateMenu(top.Hints())
} else {
m.Clear()
}
}
// StackTop notifies the top component.
func (m *Menu) StackTop(t model.Component) {
m.HydrateMenu(t.Hints())
}
// HydrateMenu populate menu ui from hints.
func (m *Menu) HydrateMenu(hh model.MenuHints) {
m.Clear()
sort.Sort(hh)
table := make([]model.MenuHints, maxRows+1)
colCount := (len(hh) / maxRows) + 1
if m.hasDigits(hh) {
colCount++
}
for row := range maxRows {
table[row] = make(model.MenuHints, colCount)
}
t := m.buildMenuTable(hh, table, colCount)
for row := range t {
for col := range len(t[row]) {
c := tview.NewTableCell(t[row][col])
if t[row][col] == "" {
c = tview.NewTableCell("")
}
c.SetBackgroundColor(m.styles.BgColor())
m.SetCell(row, col, c)
}
}
}
func (*Menu) hasDigits(hh model.MenuHints) bool {
for _, h := range hh {
if !h.Visible {
continue
}
if menuRX.MatchString(h.Mnemonic) {
return true
}
}
return false
}
func (m *Menu) buildMenuTable(hh model.MenuHints, table []model.MenuHints, colCount int) [][]string {
var row, col int
firstCmd := true
maxKeys := make([]int, colCount)
for _, h := range hh {
if !h.Visible {
continue
}
if !menuRX.MatchString(h.Mnemonic) && firstCmd {
row, col, firstCmd = 0, col+1, false
if table[0][0].IsBlank() {
col = 0
}
}
if maxKeys[col] < len(h.Mnemonic) {
maxKeys[col] = len(h.Mnemonic)
}
table[row][col] = h
row++
if row >= maxRows {
row, col = 0, col+1
}
}
out := make([][]string, len(table))
for r := range out {
out[r] = make([]string, len(table[r]))
}
m.layout(table, maxKeys, out)
return out
}
func (m *Menu) layout(table []model.MenuHints, mm []int, out [][]string) {
for r := range table {
for c := range table[r] {
out[r][c] = m.formatMenu(table[r][c], mm[c])
}
}
}
func (m *Menu) formatMenu(h model.MenuHint, size int) string {
if h.Mnemonic == "" || h.Description == "" {
return ""
}
styles := m.styles.Frame()
i, err := strconv.Atoi(h.Mnemonic)
if err == nil {
return formatNSMenu(i, h.Description, &styles)
}
return formatPlainMenu(h, size, &styles)
}
// ----------------------------------------------------------------------------
// Helpers...
func keyConv(s string) string {
if s == "" || !strings.Contains(s, "alt") {
return s
}
if runtime.GOOS != "darwin" {
return s
}
return strings.Replace(s, "alt", "opt", 1)
}
// 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 ToMnemonic(s string) string {
if s == "" {
return s
}
return "<" + keyConv(strings.ToLower(s)) + ">"
}
func formatNSMenu(i int, name string, styles *config.Frame) string {
fmat := strings.Replace(menuIndexFmt, "[key", "["+styles.Menu.NumKeyColor.String(), 1)
fmat = strings.ReplaceAll(fmat, ":bg:", ":"+styles.Title.BgColor.String()+":")
fmat = strings.Replace(fmat, "[fg", "["+styles.Menu.FgColor.String(), 1)
fmat = strings.Replace(fmat, "fgstyle]", styles.Menu.FgStyle.ToShortString()+"]", 1)
return fmt.Sprintf(fmat, i, name)
}
func formatPlainMenu(h model.MenuHint, size int, styles *config.Frame) string {
menuFmt := " [key:-:b]%-" + strconv.Itoa(size+2) + "s [fg:-:fgstyle]%s "
fmat := strings.Replace(menuFmt, "[key", "["+styles.Menu.KeyColor.String(), 1)
fmat = strings.Replace(fmat, "[fg", "["+styles.Menu.FgColor.String(), 1)
fmat = strings.ReplaceAll(fmat, ":bg:", ":"+styles.Title.BgColor.String()+":")
fmat = strings.Replace(fmat, "fgstyle]", styles.Menu.FgStyle.ToShortString()+"]", 1)
return fmt.Sprintf(fmat, ToMnemonic(h.Mnemonic), h.Description)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/deltas_test.go | internal/ui/deltas_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"testing"
"github.com/derailed/k9s/internal/render"
"github.com/stretchr/testify/assert"
)
func TestDeltas(t *testing.T) {
uu := []struct {
s1, s2, e string
}{
{"", "", ""},
{render.MissingValue, "", DeltaSign},
{render.NAValue, "", ""},
{"fred", "fred", ""},
{"fred", "blee", DeltaSign},
{"1", "1", ""},
{"1", "2", PlusSign},
{"2", "1", MinusSign},
{"2m33s", "2m33s", ""},
{"2m33s", "1m", MinusSign},
{"33s", "1m", PlusSign},
{"10Gi", "10Gi", ""},
{"10Gi", "20Gi", PlusSign},
{"30Gi", "20Gi", MinusSign},
{"15%", "15%", ""},
{"20%", "40%", PlusSign},
{"5%", "2%", MinusSign},
}
for _, u := range uu {
assert.Equal(t, u.e, Deltas(u.s1, u.s2))
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/config_int_test.go | internal/ui/config_int_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"os"
"testing"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/config/mock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"k8s.io/cli-runtime/pkg/genericclioptions"
)
func Test_activeConfig(t *testing.T) {
require.NoError(t, os.Setenv(config.K9sEnvConfigDir, "/tmp/test-config"))
require.NoError(t, config.InitLocs())
cl, ct := "cl-1", "ct-1-1"
uu := map[string]struct {
cl, ct string
cfg *Configurator
ok bool
}{
"empty": {
cfg: &Configurator{},
},
"plain": {
cfg: &Configurator{Config: config.NewConfig(
mock.NewMockKubeSettings(&genericclioptions.ConfigFlags{
ClusterName: &cl,
Context: &ct,
}))},
cl: cl,
ct: ct,
ok: true,
},
}
for k := range uu {
u := uu[k]
t.Run(k, func(t *testing.T) {
cfg := u.cfg
if cfg.Config != nil {
_, err := cfg.Config.K9s.ActivateContext(ct)
require.NoError(t, err)
}
cl, ct, ok := cfg.activeConfig()
assert.Equal(t, u.ok, ok)
if ok {
assert.Equal(t, u.cl, cl)
assert.Equal(t, u.ct, ct)
}
})
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/prompt.go | internal/ui/prompt.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"fmt"
"sync"
"unicode"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/tcell/v2"
"github.com/derailed/tview"
)
const (
defaultPrompt = "%c%c [::b]%s"
defaultSpacer = 4
)
var (
_ PromptModel = (*model.FishBuff)(nil)
_ Suggester = (*model.FishBuff)(nil)
)
// Suggester provides suggestions.
type Suggester interface {
// CurrentSuggestion returns the current suggestion.
CurrentSuggestion() (string, bool)
// NextSuggestion returns the next suggestion.
NextSuggestion() (string, bool)
// PrevSuggestion returns the prev suggestion.
PrevSuggestion() (string, bool)
// ClearSuggestions clear out all suggestions.
ClearSuggestions()
}
// PromptModel represents a prompt buffer.
type PromptModel interface {
// SetText sets the model text.
SetText(txt, sug string, clear bool)
// GetText returns the current text.
GetText() string
// GetSuggestion returns the current suggestion.
GetSuggestion() string
// ClearText clears out model text.
ClearText(fire bool)
// Notify notifies all listener of current suggestions.
Notify(bool)
// AddListener registers a command listener.
AddListener(model.BuffWatcher)
// RemoveListener removes a listener.
RemoveListener(model.BuffWatcher)
// IsActive returns true if prompt is active.
IsActive() bool
// SetActive sets whether the prompt is active or not.
SetActive(bool)
// Add adds a new char to the prompt.
Add(rune)
// Delete deletes the last prompt character.
Delete()
}
// Prompt captures users free from command input.
type Prompt struct {
*tview.TextView
app *App
noIcons bool
icon rune
prefix rune
styles *config.Styles
model PromptModel
spacer int
mx sync.RWMutex
}
// NewPrompt returns a new command view.
func NewPrompt(app *App, noIcons bool, styles *config.Styles) *Prompt {
p := Prompt{
app: app,
styles: styles,
noIcons: noIcons,
TextView: tview.NewTextView(),
spacer: defaultSpacer,
}
if noIcons {
p.spacer--
}
p.SetWordWrap(true)
p.SetWrap(true)
p.SetDynamicColors(true)
p.SetBorder(true)
p.SetBorderPadding(0, 0, 1, 1)
styles.AddListener(&p)
p.SetInputCapture(p.keyboard)
return &p
}
// SendKey sends a keyboard event (testing only!).
func (p *Prompt) SendKey(evt *tcell.EventKey) {
p.keyboard(evt)
}
// SendStrokes (testing only!)
func (p *Prompt) SendStrokes(s string) {
for _, r := range s {
p.keyboard(tcell.NewEventKey(tcell.KeyRune, r, tcell.ModNone))
}
}
// Deactivate sets the prompt as inactive.
func (p *Prompt) Deactivate() {
if p.model != nil {
p.model.ClearText(true)
p.model.SetActive(false)
}
}
// SetModel sets the prompt buffer model.
func (p *Prompt) SetModel(m PromptModel) {
if p.model != nil {
p.model.RemoveListener(p)
}
p.model = m
p.model.AddListener(p)
}
func (p *Prompt) keyboard(evt *tcell.EventKey) *tcell.EventKey {
m, ok := p.model.(Suggester)
if !ok {
return evt
}
//nolint:exhaustive
switch evt.Key() {
case tcell.KeyBackspace2, tcell.KeyBackspace, tcell.KeyDelete:
p.model.Delete()
case tcell.KeyRune:
r := evt.Rune()
// Filter out control characters and non-printable runes that may come from
// terminal escape sequences (e.g., cursor position reports like [7;15R)
// Only accept printable characters for user input
if isValidInputRune(r) {
p.model.Add(r)
}
case tcell.KeyEscape:
p.model.ClearText(true)
p.model.SetActive(false)
case tcell.KeyEnter, tcell.KeyCtrlE:
p.model.SetText(p.model.GetText(), "", true)
p.model.SetActive(false)
case tcell.KeyCtrlW, tcell.KeyCtrlU:
p.model.ClearText(true)
case tcell.KeyUp:
if s, ok := m.NextSuggestion(); ok {
p.model.SetText(p.model.GetText(), s, true)
}
case tcell.KeyDown:
if s, ok := m.PrevSuggestion(); ok {
p.model.SetText(p.model.GetText(), s, true)
}
case tcell.KeyTab, tcell.KeyRight, tcell.KeyCtrlF:
if s, ok := m.CurrentSuggestion(); ok {
p.model.SetText(p.model.GetText()+s, "", true)
m.ClearSuggestions()
}
}
return nil
}
// StylesChanged notifies skin changed.
func (p *Prompt) StylesChanged(s *config.Styles) {
p.styles = s
p.SetBackgroundColor(s.K9s.Prompt.BgColor.Color())
p.SetTextColor(s.K9s.Prompt.FgColor.Color())
}
// InCmdMode returns true if command is active, false otherwise.
func (p *Prompt) InCmdMode() bool {
if p.model == nil {
return false
}
return p.model.IsActive()
}
func (p *Prompt) activate() {
p.Clear()
p.SetCursorIndex(len(p.model.GetText()))
p.write(p.model.GetText(), p.model.GetSuggestion())
p.model.Notify(false)
}
func (p *Prompt) Clear() {
p.mx.Lock()
defer p.mx.Unlock()
p.TextView.Clear()
}
func (p *Prompt) Draw(sc tcell.Screen) {
p.mx.RLock()
defer p.mx.RUnlock()
p.TextView.Draw(sc)
}
func (p *Prompt) update(text, suggestion string) {
p.Clear()
p.write(text, suggestion)
}
func (p *Prompt) write(text, suggest string) {
p.mx.Lock()
defer p.mx.Unlock()
p.SetCursorIndex(p.spacer + len(text))
if suggest != "" {
text += fmt.Sprintf("[%s::-]%s", p.styles.Prompt().SuggestColor, suggest)
}
p.StylesChanged(p.styles)
_, _ = fmt.Fprintf(p, defaultPrompt, p.icon, p.prefix, text)
}
// ----------------------------------------------------------------------------
// Event Listener protocol...
// BufferCompleted indicates input was accepted.
func (p *Prompt) BufferCompleted(text, suggestion string) {
p.update(text, suggestion)
}
// BufferChanged indicates the buffer was changed.
func (p *Prompt) BufferChanged(text, suggestion string) {
p.update(text, suggestion)
}
// SuggestionChanged notifies the suggestion changed.
func (p *Prompt) SuggestionChanged(text, suggestion string) {
p.update(text, suggestion)
}
// BufferActive indicates the buff activity changed.
func (p *Prompt) BufferActive(activate bool, kind model.BufferKind) {
if activate {
p.ShowCursor(true)
p.SetBorder(true)
p.SetTextColor(p.styles.FgColor())
p.SetBorderColor(p.colorFor(kind))
p.icon, p.prefix = p.prefixesFor(kind)
p.activate()
return
}
p.ShowCursor(false)
p.SetBorder(false)
p.SetBackgroundColor(p.styles.BgColor())
p.Clear()
}
func (p *Prompt) prefixesFor(k model.BufferKind) (ic, prefix rune) {
defer func() {
if p.noIcons {
ic = ' '
}
}()
//nolint:exhaustive
switch k {
case model.CommandBuffer:
return '🐶', '>'
default:
return '🐩', '/'
}
}
// ----------------------------------------------------------------------------
// Helpers...
// isValidInputRune checks if a rune is valid for user input.
// It filters out control characters and non-printable characters that may
// come from terminal escape sequences (e.g., cursor position reports).
func isValidInputRune(r rune) bool {
// Reject control characters (0x00-0x1F, 0x7F) except for common whitespace
if unicode.IsControl(r) && r != '\t' && r != '\n' && r != '\r' {
return false
}
// Only accept printable characters
return unicode.IsPrint(r) || unicode.IsSpace(r)
}
func (p *Prompt) colorFor(k model.BufferKind) tcell.Color {
//nolint:exhaustive
switch k {
case model.CommandBuffer:
return p.styles.Prompt().Border.CommandColor.Color()
default:
return p.styles.Prompt().Border.DefaultColor.Color()
}
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/app_test.go | internal/ui/app_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui_test
import (
"testing"
"github.com/derailed/k9s/internal/config/mock"
"github.com/derailed/k9s/internal/ui"
"github.com/stretchr/testify/assert"
)
func TestAppGetCmd(t *testing.T) {
a := ui.NewApp(mock.NewMockConfig(t), "")
a.Init()
a.CmdBuff().SetText("blee", "", true)
assert.Equal(t, "blee", a.GetCmd())
}
func TestAppInCmdMode(t *testing.T) {
a := ui.NewApp(mock.NewMockConfig(t), "")
a.Init()
a.CmdBuff().SetText("blee", "", true)
assert.False(t, a.InCmdMode())
a.CmdBuff().SetActive(false)
assert.False(t, a.InCmdMode())
}
func TestAppResetCmd(t *testing.T) {
a := ui.NewApp(mock.NewMockConfig(t), "")
a.Init()
a.CmdBuff().SetText("blee", "", true)
a.ResetCmd()
assert.Empty(t, a.CmdBuff().GetText())
}
func TestAppHasCmd(t *testing.T) {
a := ui.NewApp(mock.NewMockConfig(t), "")
a.Init()
a.ActivateCmd(true)
assert.False(t, a.HasCmd())
a.CmdBuff().SetText("blee", "", true)
assert.True(t, a.InCmdMode())
}
func TestAppGetActions(t *testing.T) {
a := ui.NewApp(mock.NewMockConfig(t), "")
a.Init()
a.GetActions().Add(ui.KeyZ, ui.KeyAction{Description: "zorg"})
assert.Equal(t, 6, a.GetActions().Len())
}
func TestAppViews(t *testing.T) {
a := ui.NewApp(mock.NewMockConfig(t), "")
a.Init()
vv := []string{"crumbs", "logo", "prompt", "menu"}
for i := range vv {
v := vv[i]
t.Run(v, func(t *testing.T) {
assert.NotNil(t, a.Views()[v])
})
}
assert.NotNil(t, a.Crumbs())
assert.NotNil(t, a.Logo())
assert.NotNil(t, a.Prompt())
assert.NotNil(t, a.Menu())
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/crumbs_test.go | internal/ui/crumbs_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui_test
import (
"context"
"log/slog"
"testing"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/k9s/internal/ui"
"github.com/derailed/k9s/internal/view/cmd"
"github.com/derailed/tcell/v2"
"github.com/derailed/tview"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/labels"
)
func init() {
slog.SetDefault(slog.New(slog.DiscardHandler))
}
func TestNewCrumbs(t *testing.T) {
v := ui.NewCrumbs(config.NewStyles())
v.StackPushed(makeComponent("c1"))
v.StackPushed(makeComponent("c2"))
v.StackPushed(makeComponent("c3"))
assert.Equal(t, "[#000000:#00ffff:b] <c1> [-:#000000:-] [#000000:#00ffff:b] <c2> [-:#000000:-] [#000000:#ffa500:b] <c3> [-:#000000:-] \n", v.GetText(false))
}
// Helpers...
type c struct {
name string
}
func makeComponent(n string) c {
return c{name: n}
}
func (c) SetCommand(*cmd.Interpreter) {}
func (c) InCmdMode() bool { return false }
func (c) HasFocus() bool { return true }
func (c) Hints() model.MenuHints { return nil }
func (c) ExtraHints() map[string]string { return nil }
func (c c) Name() string { return c.name }
func (c) Draw(tcell.Screen) {}
func (c) InputHandler() func(*tcell.EventKey, func(tview.Primitive)) { return nil }
func (c) MouseHandler() func(action tview.MouseAction, event *tcell.EventMouse, setFocus func(p tview.Primitive)) (consumed bool, capture tview.Primitive) {
return nil
}
func (c) SetRect(int, int, int, int) {}
func (c) GetRect() (a, b, c, d int) { return 0, 0, 0, 0 }
func (c c) GetFocusable() tview.Focusable { return c }
func (c) Focus(func(tview.Primitive)) {}
func (c) Blur() {}
func (c) Start() {}
func (c) Stop() {}
func (c) Init(context.Context) error { return nil }
func (c) SetFilter(string, bool) {}
func (c) SetLabelSelector(labels.Selector, bool) {}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/table_helper.go | internal/ui/table_helper.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"context"
"fmt"
"log/slog"
"os"
"strings"
"github.com/derailed/k9s/internal"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/slogs"
"k8s.io/apimachinery/pkg/labels"
)
const (
// DefaultColorName indicator to keep term colors.
DefaultColorName = "default"
// SearchFmt represents a filter view title.
SearchFmt = "<[filter:bg:r]/%s[fg:bg:-]> "
// NSTitleFmt represents a namespaced view title.
NSTitleFmt = " [fg:bg:b]%s([hilite:bg:b]%s[fg:bg:-])[fg:bg:-][[count:bg:b]%s[fg:bg:-]][fg:bg:-] "
// TitleFmt represents a standard view title.
TitleFmt = " [fg:bg:b]%s[fg:bg:-][[count:bg:b]%s[fg:bg:-]][fg:bg:-] "
descIndicator = "↓"
ascIndicator = "↑"
// FullFmat specifies a namespaced dump file name.
FullFmat = "%s-%s-%d.csv"
// NoNSFmat specifies a cluster wide dump file name.
NoNSFmat = "%s-%d.csv"
)
func mustExtractStyles(ctx context.Context) *config.Styles {
styles, ok := ctx.Value(internal.KeyStyles).(*config.Styles)
if !ok {
slog.Error("Expecting valid styles. Exiting!")
os.Exit(1)
}
return styles
}
// TrimCell removes superfluous padding.
func TrimCell(tv *SelectTable, row, col int) string {
c := tv.GetCell(row, col)
if c == nil {
slog.Error("Trim cell failed", slogs.Error, fmt.Errorf("no cell at [%d:%d]", row, col))
return ""
}
return strings.TrimSpace(c.Text)
}
// ExtractLabelSelector extracts label query.
func ExtractLabelSelector(s string) (labels.Selector, error) {
selStr := s
if strings.Index(s, "-l") == 0 {
selStr = strings.TrimSpace(s[2:])
}
return labels.Parse(selStr)
}
// SkinTitle decorates a title.
func SkinTitle(fmat string, style *config.Frame) string {
bgColor := style.Title.BgColor
if bgColor == config.DefaultColor {
bgColor = config.TransparentColor
}
fmat = strings.ReplaceAll(fmat, "[fg:bg", "["+style.Title.FgColor.String()+":"+bgColor.String())
fmat = strings.Replace(fmat, "[hilite", "["+style.Title.HighlightColor.String(), 1)
fmat = strings.Replace(fmat, "[key", "["+style.Menu.NumKeyColor.String(), 1)
fmat = strings.Replace(fmat, "[filter", "["+style.Title.FilterColor.String(), 1)
fmat = strings.Replace(fmat, "[count", "["+style.Title.CounterColor.String(), 1)
fmat = strings.ReplaceAll(fmat, ":bg:", ":"+bgColor.String()+":")
return fmat
}
func columnIndicator(sort, selected, asc bool, style *config.Table, name string) string {
// Build the column name with selection indicator
displayName := name
if selected {
// Make selected column bold
displayName = fmt.Sprintf("[::b]%s[::-]", name)
}
// Add sort indicator if this column is sorted
suffix := ""
if sort {
order := descIndicator
if asc {
order = ascIndicator
}
suffix = fmt.Sprintf("[%s::b]%s[::]", style.Header.SorterColor, order)
}
return displayName + suffix
}
func formatCell(field string, padding int) string {
if IsASCII(field) {
return Pad(field, padding)
}
return field
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/indicator.go | internal/ui/indicator.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"context"
"fmt"
"time"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/k9s/internal/render"
"github.com/derailed/tview"
)
// StatusIndicator represents a status indicator when main header is collapsed.
type StatusIndicator struct {
*tview.TextView
app *App
styles *config.Styles
permanent string
cancel context.CancelFunc
}
// NewStatusIndicator returns a new status indicator.
func NewStatusIndicator(app *App, styles *config.Styles) *StatusIndicator {
s := StatusIndicator{
TextView: tview.NewTextView(),
app: app,
styles: styles,
}
s.SetTextAlign(tview.AlignCenter)
s.SetTextColor(styles.FgColor())
s.SetBackgroundColor(styles.BgColor())
s.SetDynamicColors(true)
styles.AddListener(&s)
return &s
}
// StylesChanged notifies the skins changed.
func (s *StatusIndicator) StylesChanged(styles *config.Styles) {
s.styles = styles
s.SetBackgroundColor(styles.BgColor())
s.SetTextColor(styles.FgColor())
}
const statusIndicatorFmt = "[%s::b]K9s [%s::]%s [%s::]%s:%s:%s [%s::]%s[%s::]::[%s::]%s"
// ClusterInfoUpdated notifies the cluster meta was updated.
func (s *StatusIndicator) ClusterInfoUpdated(data *model.ClusterMeta) {
s.app.QueueUpdateDraw(func() {
s.SetPermanent(fmt.Sprintf(
statusIndicatorFmt,
s.styles.Body().LogoColor.String(),
s.styles.K9s.Info.K9sRevColor.String(),
data.K9sVer,
s.styles.K9s.Info.FgColor.String(),
data.Context,
data.Cluster,
data.K8sVer,
s.styles.K9s.Info.CPUColor.String(),
render.PrintPerc(data.Cpu),
s.styles.Body().FgColor.String(),
s.styles.K9s.Info.MEMColor.String(),
render.PrintPerc(data.Mem),
))
})
}
// ClusterInfoChanged notifies the cluster meta was changed.
func (s *StatusIndicator) ClusterInfoChanged(prev, cur *model.ClusterMeta) {
if !s.app.IsRunning() {
return
}
s.app.QueueUpdateDraw(func() {
s.SetPermanent(fmt.Sprintf(
statusIndicatorFmt,
s.styles.Body().LogoColor.String(),
s.styles.K9s.Info.K9sRevColor.String(),
cur.K9sVer,
s.styles.K9s.Info.FgColor.String(),
cur.Context,
cur.Cluster,
cur.K8sVer,
s.styles.K9s.Info.CPUColor.String(),
AsPercDelta(prev.Cpu, cur.Cpu),
s.styles.Body().FgColor.String(),
s.styles.K9s.Info.MEMColor.String(),
AsPercDelta(prev.Cpu, cur.Mem),
))
})
}
// SetPermanent sets permanent title to be reset to after updates.
func (s *StatusIndicator) SetPermanent(info string) {
s.permanent = info
s.SetText(info)
}
// Reset clears out the logo view and resets colors.
func (s *StatusIndicator) Reset() {
s.Clear()
s.SetPermanent(s.permanent)
}
// Err displays a log error state.
func (s *StatusIndicator) Err(msg string) {
s.update(msg, "orangered")
}
// Warn displays a log warning state.
func (s *StatusIndicator) Warn(msg string) {
s.update(msg, "mediumvioletred")
}
// Info displays a log info state.
func (s *StatusIndicator) Info(msg string) {
s.update(msg, "lawngreen")
}
func (s *StatusIndicator) update(msg, c string) {
s.setText(fmt.Sprintf("[%s::b] <%s> ", c, msg))
}
func (s *StatusIndicator) setText(msg string) {
if s.cancel != nil {
s.cancel()
}
s.SetText(msg)
var ctx context.Context
ctx, s.cancel = context.WithCancel(context.Background())
go func(ctx context.Context) {
select {
case <-ctx.Done():
return
case <-time.After(5 * time.Second):
s.app.QueueUpdateDraw(func() {
s.Reset()
})
}
}(ctx)
}
// Helpers...
// AsPercDelta represents a percentage with a delta indicator.
func AsPercDelta(ov, nv int) string {
prev, cur := render.IntToStr(ov), render.IntToStr(nv)
return cur + "%" + Deltas(prev, cur)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/pages_test.go | internal/ui/pages_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui_test
import (
"testing"
"github.com/derailed/k9s/internal/ui"
"github.com/stretchr/testify/assert"
)
func TestPagesPush(t *testing.T) {
c1, c2 := makeComponent("c1"), makeComponent("c2")
p := ui.NewPages()
p.Push(c1)
p.Push(c2)
assert.Equal(t, 2, p.GetPageCount())
assert.Equal(t, c2, p.CurrentPage().Item)
}
func TestPagesPop(t *testing.T) {
c1, c2 := makeComponent("c1"), makeComponent("c2")
p := ui.NewPages()
p.Push(c1)
p.Push(c2)
p.Pop()
assert.Equal(t, 1, p.GetPageCount())
assert.Equal(t, c1, p.CurrentPage().Item)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/key.go | internal/ui/key.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import "github.com/derailed/tcell/v2"
func init() {
initKeys()
}
func initKeys() {
tcell.KeyNames[KeyHelp] = "?"
tcell.KeyNames[KeySlash] = "/"
tcell.KeyNames[KeySpace] = "space"
initNumbKeys()
initStdKeys()
initShiftKeys()
initShiftNumKeys()
}
// Defines numeric keys for container actions.
const (
Key0 tcell.Key = iota + 48
Key1
Key2
Key3
Key4
Key5
Key6
Key7
Key8
Key9
)
// Defines numeric keys for container actions.
const (
KeyShift0 tcell.Key = 41
KeyShift1 tcell.Key = 33
KeyShift2 tcell.Key = 64
KeyShift3 tcell.Key = 35
KeyShift4 tcell.Key = 36
KeyShift5 tcell.Key = 37
KeyShift6 tcell.Key = 94
KeyShift7 tcell.Key = 38
KeyShift8 tcell.Key = 42
KeyShift9 tcell.Key = 40
)
// Defines char keystrokes.
const (
KeyA tcell.Key = iota + 97
KeyB
KeyC
KeyD
KeyE
KeyF
KeyG
KeyH
KeyI
KeyJ
KeyK
KeyL
KeyM
KeyN
KeyO
KeyP
KeyQ
KeyR
KeyS
KeyT
KeyU
KeyV
KeyW
KeyX
KeyY
KeyZ
KeyHelp = 63
KeySlash = 47
KeyColon = 58
KeySpace = 32
KeyDash = 45
KeyLeftBracket = 91
KeyRightBracket = 93
)
// Define Shift Keys.
const (
KeyShiftA tcell.Key = iota + 65
KeyShiftB
KeyShiftC
KeyShiftD
KeyShiftE
KeyShiftF
KeyShiftG
KeyShiftH
KeyShiftI
KeyShiftJ
KeyShiftK
KeyShiftL
KeyShiftM
KeyShiftN
KeyShiftO
KeyShiftP
KeyShiftQ
KeyShiftR
KeyShiftS
KeyShiftT
KeyShiftU
KeyShiftV
KeyShiftW
KeyShiftX
KeyShiftY
KeyShiftZ
)
// NumKeys tracks number keys.
var NumKeys = map[int]tcell.Key{
0: Key0,
1: Key1,
2: Key2,
3: Key3,
4: Key4,
5: Key5,
6: Key6,
7: Key7,
8: Key8,
9: Key9,
}
func initNumbKeys() {
tcell.KeyNames[Key0] = "0"
tcell.KeyNames[Key1] = "1"
tcell.KeyNames[Key2] = "2"
tcell.KeyNames[Key3] = "3"
tcell.KeyNames[Key4] = "4"
tcell.KeyNames[Key5] = "5"
tcell.KeyNames[Key6] = "6"
tcell.KeyNames[Key7] = "7"
tcell.KeyNames[Key8] = "8"
tcell.KeyNames[Key9] = "9"
}
func initStdKeys() {
tcell.KeyNames[KeyA] = "a"
tcell.KeyNames[KeyB] = "b"
tcell.KeyNames[KeyC] = "c"
tcell.KeyNames[KeyD] = "d"
tcell.KeyNames[KeyE] = "e"
tcell.KeyNames[KeyF] = "f"
tcell.KeyNames[KeyG] = "g"
tcell.KeyNames[KeyH] = "h"
tcell.KeyNames[KeyI] = "i"
tcell.KeyNames[KeyJ] = "j"
tcell.KeyNames[KeyK] = "k"
tcell.KeyNames[KeyL] = "l"
tcell.KeyNames[KeyM] = "m"
tcell.KeyNames[KeyN] = "n"
tcell.KeyNames[KeyO] = "o"
tcell.KeyNames[KeyP] = "p"
tcell.KeyNames[KeyQ] = "q"
tcell.KeyNames[KeyR] = "r"
tcell.KeyNames[KeyS] = "s"
tcell.KeyNames[KeyT] = "t"
tcell.KeyNames[KeyU] = "u"
tcell.KeyNames[KeyV] = "v"
tcell.KeyNames[KeyW] = "w"
tcell.KeyNames[KeyX] = "x"
tcell.KeyNames[KeyY] = "y"
tcell.KeyNames[KeyZ] = "z"
}
func initShiftNumKeys() {
tcell.KeyNames[KeyShift0] = "Shift-0"
tcell.KeyNames[KeyShift1] = "Shift-1"
tcell.KeyNames[KeyShift2] = "Shift-2"
tcell.KeyNames[KeyShift3] = "Shift-3"
tcell.KeyNames[KeyShift4] = "Shift-4"
tcell.KeyNames[KeyShift5] = "Shift-5"
tcell.KeyNames[KeyShift6] = "Shift-6"
tcell.KeyNames[KeyShift7] = "Shift-7"
tcell.KeyNames[KeyShift8] = "Shift-8"
tcell.KeyNames[KeyShift9] = "Shift-9"
}
func initShiftKeys() {
tcell.KeyNames[KeyShiftA] = "Shift-A"
tcell.KeyNames[KeyShiftB] = "Shift-B"
tcell.KeyNames[KeyShiftC] = "Shift-C"
tcell.KeyNames[KeyShiftD] = "Shift-D"
tcell.KeyNames[KeyShiftE] = "Shift-E"
tcell.KeyNames[KeyShiftF] = "Shift-F"
tcell.KeyNames[KeyShiftG] = "Shift-G"
tcell.KeyNames[KeyShiftH] = "Shift-H"
tcell.KeyNames[KeyShiftI] = "Shift-I"
tcell.KeyNames[KeyShiftJ] = "Shift-J"
tcell.KeyNames[KeyShiftK] = "Shift-K"
tcell.KeyNames[KeyShiftL] = "Shift-L"
tcell.KeyNames[KeyShiftM] = "Shift-M"
tcell.KeyNames[KeyShiftN] = "Shift-N"
tcell.KeyNames[KeyShiftO] = "Shift-O"
tcell.KeyNames[KeyShiftP] = "Shift-P"
tcell.KeyNames[KeyShiftQ] = "Shift-Q"
tcell.KeyNames[KeyShiftR] = "Shift-R"
tcell.KeyNames[KeyShiftS] = "Shift-S"
tcell.KeyNames[KeyShiftT] = "Shift-T"
tcell.KeyNames[KeyShiftU] = "Shift-U"
tcell.KeyNames[KeyShiftV] = "Shift-V"
tcell.KeyNames[KeyShiftW] = "Shift-W"
tcell.KeyNames[KeyShiftX] = "Shift-X"
tcell.KeyNames[KeyShiftY] = "Shift-Y"
tcell.KeyNames[KeyShiftZ] = "Shift-Z"
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/select_table.go | internal/ui/select_table.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"github.com/derailed/tcell/v2"
"github.com/derailed/tview"
)
// SelectTable represents a table with selections.
type SelectTable struct {
*tview.Table
model Tabular
selectedFn func(string) string
marks map[string]struct{}
selFgColor tcell.Color
selBgColor tcell.Color
}
// SetModel sets the table model.
func (s *SelectTable) SetModel(m Tabular) {
s.model = m
}
// GetModel returns the current model.
func (s *SelectTable) GetModel() Tabular {
return s.model
}
// ClearSelection reset selected row.
func (s *SelectTable) ClearSelection() {
s.Select(0, 0)
s.ScrollToBeginning()
}
// SelectFirstRow select first data row if any.
func (s *SelectTable) SelectFirstRow() {
if s.GetRowCount() > 0 {
s.Select(1, 0)
}
}
// GetSelectedItems return currently marked or selected items names.
func (s *SelectTable) GetSelectedItems() []string {
if len(s.marks) == 0 {
if item := s.GetSelectedItem(); item != "" {
return []string{item}
}
return nil
}
items := make([]string, 0, len(s.marks))
for item := range s.marks {
items = append(items, item)
}
return items
}
// GetRowID returns the row id at given location.
func (s *SelectTable) GetRowID(index int) (string, bool) {
cell := s.GetCell(index, 0)
if cell == nil {
return "", false
}
id, ok := cell.GetReference().(string)
return id, ok
}
// GetSelectedItem returns the currently selected item name.
func (s *SelectTable) GetSelectedItem() string {
if s.GetSelectedRowIndex() == 0 || s.model.Empty() {
return ""
}
sel, ok := s.GetCell(s.GetSelectedRowIndex(), 0).GetReference().(string)
if !ok {
return ""
}
if s.selectedFn != nil {
return s.selectedFn(sel)
}
return sel
}
// GetSelectedCell returns the content of a cell for the currently selected row.
func (s *SelectTable) GetSelectedCell(col int) string {
r, _ := s.GetSelection()
return TrimCell(s, r, col)
}
// SetSelectedFn defines a function that cleanse the current selection.
func (s *SelectTable) SetSelectedFn(f func(string) string) {
s.selectedFn = f
}
// GetSelectedRowIndex fetch the currently selected row index.
func (s *SelectTable) GetSelectedRowIndex() int {
r, _ := s.GetSelection()
return r
}
// SelectRow select a given row by index.
func (s *SelectTable) SelectRow(r, c int, broadcast bool) {
if !broadcast {
s.SetSelectionChangedFunc(nil)
}
if count := s.model.RowCount(); count > 0 && r-1 > count {
r = count + 1
}
defer s.SetSelectionChangedFunc(s.selectionChanged)
s.Select(r, c)
}
// UpdateSelection refresh selected row.
func (s *SelectTable) updateSelection(broadcast bool) {
r, c := s.GetSelection()
s.SelectRow(r, c, broadcast)
}
func (s *SelectTable) selectionChanged(r, c int) {
if r < 0 {
return
}
if cell := s.GetCell(r, c); cell != nil {
s.SetSelectedStyle(
tcell.StyleDefault.Foreground(s.selFgColor).
Background(cell.Color).Attributes(tcell.AttrBold))
}
}
// ClearMarks delete all marked items.
func (s *SelectTable) ClearMarks() {
for k := range s.marks {
delete(s.marks, k)
}
}
// DeleteMark delete a marked item.
func (s *SelectTable) DeleteMark(k string) {
delete(s.marks, k)
}
// ToggleMark toggles marked row.
func (s *SelectTable) ToggleMark() {
sel := s.GetSelectedItem()
if sel == "" {
return
}
if _, ok := s.marks[sel]; ok {
delete(s.marks, s.GetSelectedItem())
} else {
s.marks[sel] = struct{}{}
}
if cell := s.GetCell(s.GetSelectedRowIndex(), 0); cell != nil {
s.SetSelectedStyle(tcell.StyleDefault.Foreground(cell.BackgroundColor).Background(cell.Color).Attributes(tcell.AttrBold))
}
}
// SpanMark toggles marked row.
func (s *SelectTable) SpanMark() {
selIndex, prev := s.GetSelectedRowIndex(), -1
if selIndex <= 0 {
return
}
// Look back to find previous mark
for i := selIndex - 1; i > 0; i-- {
id, ok := s.GetRowID(i)
if !ok {
break
}
if _, ok := s.marks[id]; ok {
prev = i
break
}
}
if prev != -1 {
s.markRange(prev, selIndex)
return
}
// Look forward to see if we have a mark
for i := selIndex; i < s.GetRowCount(); i++ {
id, ok := s.GetRowID(i)
if !ok {
break
}
if _, ok := s.marks[id]; ok {
prev = i
break
}
}
s.markRange(prev, selIndex)
}
func (s *SelectTable) markRange(prev, curr int) {
if prev < 0 {
return
}
if prev > curr {
prev, curr = curr, prev
}
for i := prev + 1; i <= curr; i++ {
id, ok := s.GetRowID(i)
if !ok {
break
}
s.marks[id] = struct{}{}
cell := s.GetCell(s.GetSelectedRowIndex(), 0)
if cell == nil {
break
}
s.SetSelectedStyle(tcell.StyleDefault.Foreground(cell.BackgroundColor).Background(cell.Color).Attributes(tcell.AttrBold))
}
}
// IsMarked returns true if this item was marked.
func (s *SelectTable) IsMarked(item string) bool {
_, ok := s.marks[item]
return ok
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/app.go | internal/ui/app.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package ui
import (
"log/slog"
"os"
"sync"
"github.com/derailed/k9s/internal/client"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/model"
"github.com/derailed/k9s/internal/slogs"
"github.com/derailed/tcell/v2"
"github.com/derailed/tview"
)
// App represents an application.
type App struct {
*tview.Application
Configurator
Main *Pages
flash *model.Flash
actions *KeyActions
views map[string]tview.Primitive
cmdBuff *model.FishBuff
running bool
mx sync.RWMutex
}
// NewApp returns a new app.
func NewApp(cfg *config.Config, _ string) *App {
a := App{
Application: tview.NewApplication(),
actions: NewKeyActions(),
Configurator: Configurator{Config: cfg, Styles: config.NewStyles()},
Main: NewPages(),
flash: model.NewFlash(model.DefaultFlashDelay),
cmdBuff: model.NewFishBuff(':', model.CommandBuffer),
}
a.views = map[string]tview.Primitive{
"menu": NewMenu(a.Styles),
"logo": NewLogo(a.Styles),
"prompt": NewPrompt(&a, a.Config.K9s.UI.NoIcons, a.Styles),
"crumbs": NewCrumbs(a.Styles),
}
return &a
}
// Init initializes the application.
func (a *App) Init() {
a.bindKeys()
a.Prompt().SetModel(a.cmdBuff)
a.cmdBuff.AddListener(a)
a.Styles.AddListener(a)
a.SetRoot(a.Main, true).EnableMouse(a.Config.K9s.UI.EnableMouse)
}
// QueueUpdate queues up a ui action.
func (a *App) QueueUpdate(f func()) {
if a.Application == nil {
return
}
go func() {
a.Application.QueueUpdate(f)
}()
}
// QueueUpdateDraw queues up a ui action and redraw the ui.
func (a *App) QueueUpdateDraw(f func()) {
if a.Application == nil {
return
}
go func() {
a.Application.QueueUpdateDraw(f)
}()
}
// IsRunning checks if app is actually running.
func (a *App) IsRunning() bool {
a.mx.RLock()
defer a.mx.RUnlock()
return a.running
}
// SetRunning sets the app run state.
func (a *App) SetRunning(f bool) {
a.mx.Lock()
defer a.mx.Unlock()
a.running = f
}
// BufferCompleted indicates input was accepted.
func (*App) BufferCompleted(_, _ string) {}
// BufferChanged indicates the buffer was changed.
func (*App) BufferChanged(_, _ string) {}
// BufferActive indicates the buff activity changed.
func (a *App) BufferActive(state bool, _ model.BufferKind) {
flex, ok := a.Main.GetPrimitive("main").(*tview.Flex)
if !ok {
return
}
if state && flex.ItemAt(1) != a.Prompt() {
flex.AddItemAtIndex(1, a.Prompt(), 3, 1, false)
} else if !state && flex.ItemAt(1) == a.Prompt() {
flex.RemoveItemAtIndex(1)
a.SetFocus(flex)
}
}
// SuggestionChanged notifies of update to command suggestions.
func (*App) SuggestionChanged([]string) {}
// StylesChanged notifies the skin changed.
func (a *App) StylesChanged(s *config.Styles) {
a.Main.SetBackgroundColor(s.BgColor())
if f, ok := a.Main.GetPrimitive("main").(*tview.Flex); ok {
f.SetBackgroundColor(s.BgColor())
if !a.Config.K9s.IsHeadless() {
if h, ok := f.ItemAt(0).(*tview.Flex); ok {
h.SetBackgroundColor(s.BgColor())
} else {
slog.Warn("Header not found", slogs.Subsys, "styles", slogs.Component, "app")
}
}
} else {
slog.Error("Main panel not found", slogs.Subsys, "styles", slogs.Component, "app")
}
}
// Conn returns an api server connection.
func (a *App) Conn() client.Connection {
return a.Config.GetConnection()
}
func (a *App) bindKeys() {
a.actions = NewKeyActionsFromMap(KeyMap{
KeyColon: NewKeyAction("Cmd", a.activateCmd, false),
tcell.KeyCtrlR: NewKeyAction("Redraw", a.redrawCmd, false),
tcell.KeyCtrlP: NewKeyAction("Persist", a.saveCmd, false),
tcell.KeyCtrlU: NewSharedKeyAction("Clear Filter", a.clearCmd, false),
tcell.KeyCtrlQ: NewSharedKeyAction("Clear Filter", a.clearCmd, false),
})
}
// BailOut exits the application.
func (a *App) BailOut(exitCode int) {
if err := a.Config.Save(true); err != nil {
slog.Error("Config save failed!", slogs.Error, err)
}
a.Stop()
os.Exit(exitCode)
}
// ResetPrompt reset the prompt model and marks buffer as active.
func (a *App) ResetPrompt(m PromptModel) {
m.ClearText(false)
a.Prompt().SetModel(m)
a.SetFocus(a.Prompt())
m.SetActive(true)
}
// ResetCmd clear out user command.
func (a *App) ResetCmd() {
a.cmdBuff.Reset()
}
func (a *App) saveCmd(*tcell.EventKey) *tcell.EventKey {
if err := a.Config.Save(true); err != nil {
a.Flash().Err(err)
}
a.Flash().Info("current context config saved")
return nil
}
// ActivateCmd toggle command mode.
func (a *App) ActivateCmd(b bool) {
a.cmdBuff.SetActive(b)
}
// GetCmd retrieves user command.
func (a *App) GetCmd() string {
return a.cmdBuff.GetText()
}
// CmdBuff returns the app cmd model.
func (a *App) CmdBuff() *model.FishBuff {
return a.cmdBuff
}
// HasCmd check if cmd buffer is active and has a command.
func (a *App) HasCmd() bool {
return a.cmdBuff.IsActive() && !a.cmdBuff.Empty()
}
// InCmdMode check if command mode is active.
func (a *App) InCmdMode() bool {
return a.Prompt().InCmdMode()
}
// HasAction checks if key matches a registered binding.
func (a *App) HasAction(key tcell.Key) (KeyAction, bool) {
return a.actions.Get(key)
}
// GetActions returns a collection of actions.
func (a *App) GetActions() *KeyActions {
return a.actions
}
// AddActions returns the application actions.
func (a *App) AddActions(aa *KeyActions) {
a.actions.Merge(aa)
}
// Views return the application root views.
func (a *App) Views() map[string]tview.Primitive {
return a.views
}
func (a *App) clearCmd(evt *tcell.EventKey) *tcell.EventKey {
if !a.cmdBuff.IsActive() {
return evt
}
a.cmdBuff.ClearText(true)
return nil
}
func (a *App) activateCmd(evt *tcell.EventKey) *tcell.EventKey {
if a.InCmdMode() {
return evt
}
a.ResetPrompt(a.cmdBuff)
a.cmdBuff.ClearText(true)
return nil
}
// RedrawCmd forces a redraw.
func (a *App) redrawCmd(evt *tcell.EventKey) *tcell.EventKey {
a.QueueUpdateDraw(func() {})
return evt
}
// View Accessors...
// Crumbs return app crumbs.
func (a *App) Crumbs() *Crumbs {
return a.views["crumbs"].(*Crumbs)
}
// Logo return the app logo.
func (a *App) Logo() *Logo {
return a.views["logo"].(*Logo)
}
// Prompt returns command prompt.
func (a *App) Prompt() *Prompt {
return a.views["prompt"].(*Prompt)
}
// Menu returns app menu.
func (a *App) Menu() *Menu {
return a.views["menu"].(*Menu)
}
// Flash returns a flash model.
func (a *App) Flash() *model.Flash {
return a.flash
}
// ----------------------------------------------------------------------------
// Helpers...
// AsKey converts rune to keyboard key.
func AsKey(evt *tcell.EventKey) tcell.Key {
if evt.Key() != tcell.KeyRune {
return evt.Key()
}
key := tcell.Key(evt.Rune())
if evt.Modifiers() == tcell.ModAlt {
key = tcell.Key(int16(evt.Rune()) * int16(evt.Modifiers()))
}
return key
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/dialog/prompt_test.go | internal/ui/dialog/prompt_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package dialog
import (
"context"
"testing"
"time"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/ui"
"github.com/derailed/tcell/v2"
"github.com/derailed/tview"
"github.com/stretchr/testify/assert"
)
func TestShowPrompt(t *testing.T) {
t.Run("waiting done", func(t *testing.T) {
a := tview.NewApplication()
p := ui.NewPages()
a.SetRoot(p, false)
ShowPrompt(new(config.Dialog), p, "Running", "Pod", func(context.Context) {
time.Sleep(time.Millisecond)
}, func() {
t.Errorf("unexpected cancellations")
})
})
t.Run("canceled", func(t *testing.T) {
a := tview.NewApplication()
p := ui.NewPages()
a.SetRoot(p, false)
go ShowPrompt(new(config.Dialog), p, "Running", "Pod", func(ctx context.Context) {
select {
case <-time.After(time.Second):
t.Errorf("expected cancellations")
case <-ctx.Done():
}
}, func() {})
time.Sleep(time.Second / 2)
d := p.GetPrimitive(dialogKey).(*tview.ModalForm)
if assert.NotNil(t, d) {
d.InputHandler()(tcell.NewEventKey(tcell.KeyEnter, '\n', 0), func(tview.Primitive) {})
}
})
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/dialog/error.go | internal/ui/dialog/error.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package dialog
import (
"fmt"
"strings"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/ui"
"github.com/derailed/tcell/v2"
"github.com/derailed/tview"
)
// ShowError pops an error dialog.
func ShowError(styles *config.Dialog, pages *ui.Pages, msg string) {
f := tview.NewForm()
f.SetItemPadding(0)
f.SetButtonsAlign(tview.AlignCenter).
SetButtonBackgroundColor(styles.ButtonBgColor.Color()).
SetButtonTextColor(styles.ButtonFgColor.Color()).
SetLabelColor(styles.LabelFgColor.Color()).
SetFieldTextColor(tcell.ColorIndianRed)
f.AddButton("Dismiss", func() {
dismiss(pages)
})
if b := f.GetButton(0); b != nil {
b.SetBackgroundColorActivated(styles.ButtonFocusBgColor.Color())
b.SetLabelColorActivated(styles.ButtonFocusFgColor.Color())
}
f.SetFocus(0)
modal := tview.NewModalForm("<error>", f)
modal.SetText(cowTalk(msg))
modal.SetTextColor(tcell.ColorOrangeRed)
modal.SetDoneFunc(func(int, string) {
dismiss(pages)
})
pages.AddPage(dialogKey, modal, false, false)
pages.ShowPage(dialogKey)
}
func cowTalk(says string) string {
msg := fmt.Sprintf("< Ruroh? %s >", strings.TrimSuffix(says, "\n"))
buff := make([]string, 0, len(cow)+3)
buff = append(buff, msg)
buff = append(buff, cow...)
return strings.Join(buff, "\n")
}
var cow = []string{
`\ ^__^ `,
` \ (oo)\_______ `,
` (__)\ )\/\`,
` ||----w | `,
` || || `,
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/dialog/delete.go | internal/ui/dialog/delete.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package dialog
import (
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/ui"
"github.com/derailed/tview"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
noDeletePropagation = "None"
defaultPropagationIdx = 0
)
type (
okFunc func(propagation *metav1.DeletionPropagation, force bool)
cancelFunc func()
)
var propagationOptions []string = []string{
string(metav1.DeletePropagationBackground),
string(metav1.DeletePropagationForeground),
string(metav1.DeletePropagationOrphan),
noDeletePropagation,
}
// ShowDelete pops a resource deletion dialog.
func ShowDelete(styles *config.Dialog, pages *ui.Pages, msg string, ok okFunc, cancel cancelFunc) {
propagation, force := "", false
f := tview.NewForm()
f.SetItemPadding(0)
f.SetButtonsAlign(tview.AlignCenter).
SetButtonBackgroundColor(styles.ButtonBgColor.Color()).
SetButtonTextColor(styles.ButtonFgColor.Color()).
SetLabelColor(styles.LabelFgColor.Color()).
SetFieldTextColor(styles.FieldFgColor.Color())
f.AddDropDown("Propagation:", propagationOptions, defaultPropagationIdx, func(_ string, optionIndex int) {
propagation = propagationOptions[optionIndex]
})
propField := f.GetFormItemByLabel("Propagation:").(*tview.DropDown)
propField.SetListStyles(
styles.FgColor.Color(), styles.BgColor.Color(),
styles.ButtonFocusFgColor.Color(), styles.ButtonFocusBgColor.Color(),
)
f.AddCheckbox("Force:", force, func(_ string, checked bool) {
force = checked
})
f.AddButton("Cancel", func() {
dismiss(pages)
cancel()
})
f.AddButton("OK", func() {
switch propagation {
case noDeletePropagation:
ok(nil, force)
default:
p := metav1.DeletionPropagation(propagation)
ok(&p, force)
}
dismiss(pages)
cancel()
})
for i := range 2 {
b := f.GetButton(i)
if b == nil {
continue
}
b.SetBackgroundColorActivated(styles.ButtonFocusBgColor.Color())
b.SetLabelColorActivated(styles.ButtonFocusFgColor.Color())
}
f.SetFocus(2)
confirm := tview.NewModalForm("<Delete>", f)
confirm.SetText(msg)
confirm.SetDoneFunc(func(int, string) {
dismiss(pages)
cancel()
})
pages.AddPage(dialogKey, confirm, false, false)
pages.ShowPage(dialogKey)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/dialog/error_test.go | internal/ui/dialog/error_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package dialog
import (
"testing"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/ui"
"github.com/derailed/tview"
"github.com/stretchr/testify/assert"
)
func TestErrorDialog(t *testing.T) {
p := ui.NewPages()
ShowError(new(config.Dialog), p, "Yo")
d := p.GetPrimitive(dialogKey).(*tview.ModalForm)
assert.NotNil(t, d)
dismiss(p)
assert.Nil(t, p.GetPrimitive(dialogKey))
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/dialog/delete_test.go | internal/ui/dialog/delete_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package dialog
import (
"testing"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/ui"
"github.com/derailed/tview"
"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func TestDeleteDialog(t *testing.T) {
p := ui.NewPages()
okFunc := func(p *metav1.DeletionPropagation, f bool) {
assert.Equal(t, propagationOptions[defaultPropagationIdx], p)
assert.True(t, f)
}
ShowDelete(new(config.Dialog), p, "Yo", okFunc, func() {})
d := p.GetPrimitive(dialogKey).(*tview.ModalForm)
assert.NotNil(t, d)
dismiss(p)
assert.Nil(t, p.GetPrimitive(dialogKey))
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/dialog/restart.go | internal/ui/dialog/restart.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package dialog
import (
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/ui"
"github.com/derailed/tview"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type RestartFn func(*metav1.PatchOptions) bool
type RestartDialogOpts struct {
Title, Message string
FieldManager string
Ack RestartFn
Cancel cancelFunc
}
func ShowRestart(styles *config.Dialog, pages *ui.Pages, opts *RestartDialogOpts) {
f := tview.NewForm()
f.SetItemPadding(0)
f.SetButtonsAlign(tview.AlignCenter).
SetButtonBackgroundColor(styles.ButtonBgColor.Color()).
SetButtonTextColor(styles.ButtonFgColor.Color()).
SetLabelColor(styles.LabelFgColor.Color()).
SetFieldTextColor(styles.FieldFgColor.Color())
f.AddButton("Cancel", func() {
dismissConfirm(pages)
opts.Cancel()
})
modal := tview.NewModalForm("<"+opts.Title+">", f)
args := metav1.PatchOptions{
FieldManager: opts.FieldManager,
}
f.AddInputField("FieldManager:", args.FieldManager, 40, nil, func(v string) {
args.FieldManager = v
})
f.AddButton("OK", func() {
if !opts.Ack(&args) {
return
}
dismissConfirm(pages)
opts.Cancel()
})
for i := range 2 {
b := f.GetButton(i)
if b == nil {
continue
}
b.SetBackgroundColorActivated(styles.ButtonFocusBgColor.Color())
b.SetLabelColorActivated(styles.ButtonFocusFgColor.Color())
}
f.SetFocus(1)
message := opts.Message
modal.SetText(message)
modal.SetTextColor(styles.FgColor.Color())
modal.SetDoneFunc(func(int, string) {
dismissConfirm(pages)
opts.Cancel()
})
pages.AddPage(confirmKey, modal, false, false)
pages.ShowPage(confirmKey)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.