Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add k8s segment to show context and namespace info #545

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions powerline_shell/segments/k8s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import os
import subprocess
from ..utils import BasicSegment
from ..colortrans import rgb2short
from ..color_compliment import stringToHashToColorAndOpposite


EMPTY = ''


def kube_info(cmd):
try:
p = subprocess.Popen(cmd.split(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=os.environ.copy())
except OSError:
return EMPTY

data = p.communicate()
if p.returncode:
return EMPTY

return data[0].decode('utf-8').splitlines()[0]


def ellipse(s, length):
if length > 0:
return (s[:length] + '~') if len(s) > length else s
else:
return EMPTY


class Segment(BasicSegment):
def add_to_powerline(self):
kctx = kube_info('kubectl-ctx -c')
if not kctx:
return # no context, nothing to do

powerline = self.powerline
conf = lambda key: powerline.segment_conf('k8s', key)

kctx = ellipse(kctx, conf('max_context'))
kns = ellipse(kube_info("kubectl-ns -c"), conf('max_namespace'))
status = f"{kctx}{'|' if kctx and kns else EMPTY}{kns}"

# the symbol and separator can be themed too
bg = powerline.theme.K8S_BG
fg = powerline.theme.K8S_FG
sym_fg = powerline.theme.K8S_SYMBOL_FG

if conf('colorize'):
bg, fg = stringToHashToColorAndOpposite(status)
fg, bg = (rgb2short(*color) for color in [fg, bg])

if conf('colorize_symbol'):
sym_fg = fg

lspace = EMPTY if conf('ltrim') else ' '
rspace = EMPTY if conf('rtrim') else ' '

if conf('symbol'):
powerline.append(f"{lspace}\U0001F578 ", sym_fg, bg)
powerline.append(f"{status}{rspace}", fg, bg)
else:
powerline.append(f"{lspace}{status}{rspace}", fg, bg)
4 changes: 4 additions & 0 deletions powerline_shell/themes/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ class DefaultColor(object):
AWS_PROFILE_FG = 39
AWS_PROFILE_BG = 238

K8S_FG = 57
K8S_BG = 7
K8S_SYMBOL_FG = 57

TIME_FG = 250
TIME_BG = 238

Expand Down