sbstp / kubie

A more powerful alternative to kubectx and kubens
https://blog.sbstp.ca/introducing-kubie/
zlib License
1.96k stars 100 forks source link

kubie does not seem to be reading xonshrc #243

Open rickysarraf opened 2 months ago

rickysarraf commented 2 months ago

I have xonsh installed and configured as my user shell, in just my terminal config (kitty).

I also have xonsh specified in my kubie config like:

@ cat ~/.kube/kubie.yaml
# Force kubie to use a particular shell, if unset detect shell currently in use.
# Possible values: bash, dash, fish, xonsh, zsh
# Default: unset
shell: xonsh

# Configure where to look for kubernetes config files.
configs:
  # Include these globs.
  # Default: values listed below.
  include:
    - ~/.kube/config
    - ~/.kube/*.yml
    - ~/.kube/*.yaml
    - ~/.kube/configs/*.yml
    - ~/.kube/configs/*.yaml
    - ~/.kube/kubie/*.yml
    - ~/.kube/kubie/*.yaml

  # Exclude these globs.
  # Default: values listed below.
  # Note: kubie's own config file is always excluded.
  exclude:
    - ~/.kube/kubie.yaml

# Prompt settings.
prompt:
  # Disable kubie's custom prompt inside of a kubie shell. This is useful
  # when you already have a prompt displaying kubernetes information.
  # Default: false
  #disable: true

  # When using recursive contexts, show depth when larger than 1.
  # Default: true
  show_depth: true

  # When using zsh, show context and namespace on the right-hand side using RPS1.
  # Default: false
  zsh_use_rps1: false

  # When using fish, show context and namespace on the right-hand side.
  # Default: false
  fish_use_rprompt: false

  # When using xonsh, show context and namespace on the right-hand side.
  # Default: false
  xonsh_use_right_prompt: true

# Behavior
behavior:
  # Make sure the namespace exists with `kubectl get namespaces` when switching
  # namespaces. If you do not have the right to list namespaces, disable this.
  # Default: true
  validate_namespaces: true

  # Enable or disable the printing of the 'CONTEXT => ...' headers when running
  # `kubie exec`.
  # Valid values:
  #   auto:   Prints context headers only if stdout is a TTY. Piping/redirecting
  #           kubie output will auto-disable context headers.
  #   always: Always prints context headers, even if stdout is not a TTY.
  #   never:  Never prints context headers.
  # Default: auto
  print_context_in_exec: auto

# Optional start and stop hooks
hooks:
  # A command hook to run when a CTX is started.
  # This example re-labels your terminal window
  # Default: none
  start_ctx: >
    echo -en "\033]1; `kubie info ctx`|`kubie info ns` \007"

  # A command hook to run when a CTX is stopped
  # This example sets the terminal back to the shell name
  # Default: none
  stop_ctx: >
    echo -en "\033]1; $SHELL \007"
⛢ 21:02:23 rrs@priyasi .../ansible-playb...   main|+1

On my standard shell prompt, I have:

♒︎ 17:30:24 rrs@priyasi ~/r/d/ap/apt-offline   master|✓
@ xontrib list
abbrevs             loaded      manual
autojump            loaded      manual
cmd_done            not-loaded
coreutils           loaded      manual
hist_navigator      loaded      manual
histcpy             loaded      manual
notifypy            not-loaded
output_search       not-loaded
powerline           not-loaded
powerline2          not-loaded
powerline3          not-loaded
readable-traceback  loaded      manual
sh                  loaded      manual

while inside kubie ctx, I have:

@ kubie ctx
rrs@priyasi .../ansible-playb... main @ xontrib list                                                                                                                                                                         [lab000188|default]
abbrevs             not-loaded
autojump            not-loaded
cmd_done            not-loaded
coreutils           not-loaded
hist_navigator      not-loaded
histcpy             not-loaded
notifypy            not-loaded
output_search       not-loaded
powerline           not-loaded
powerline2          not-loaded
powerline3          not-loaded
readable-traceback  not-loaded
sh                  not-loaded

I guess this is because kubie didn't initialize ~/.xonshrc. It would also imply that no history is saved to the xonsh history backend.

I have:

@ kubie --help
Usage: kubie <COMMAND>

Commands:
  ctx          Spawn a shell in the given context. The shell is isolated from other shells. Kubie shells can be spawned recursively without any issue
  ns           Change the namespace in which the current shell operates. The namespace change does not affect other shells
  info         View info about the current kubie shell, such as the context name and the current namespace
  exec         Execute a command inside of the given context and namespace
  export       Prints the path to an isolated configuration file for a context and namespace
  lint         Check the Kubernetes config files for issues
  edit         Edit the given context
  edit-config  Edit kubie's config file
  update       Check for a Kubie update and replace Kubie's binary if needed. This function can ask for sudo-mode
  delete       Delete a context. Automatic garbage collection will be performed. Dangling users and clusters will be removed
  help         Print this message or the help of the given subcommand(s)

Options:
  -h, --help     Print help
  -V, --version  Print version
♄ 21:06:21 rrs@priyasi ~/pu/researchut-hugo   researchut|…2

@ kubie --version
kubie 0.23.1

And:

@ pipx list
venvs are in /home/rrs/.local/share/pipx/venvs
apps are exposed on your $PATH at /home/rrs/.local/bin
manual pages are exposed at /home/rrs/.local/share/man
   package mackup 0.8.40, installed using Python 3.12.4
    - mackup
   package powerline-shell 0.7.0, installed using Python 3.12.4
    - powerline-shell
   package xonsh 0.17.0, installed using Python 3.12.4
    - xonsh
    - xonsh-cat
    - xonsh-uname
    - xonsh-uptime
   package xxh-xxh 0.8.14, installed using Python 3.12.4
    - xxh
    - xxh.bash
    - xxh.xsh
    - xxh.zsh
rickysarraf commented 5 days ago

The below script that kubie generates, when sourced (see logs further below), is the cause of the trouble.

@ cat /tmp/kubie-xonshrc1ChrXE.xsh

# https://xon.sh/xonshrc.html
from pathlib import Path

files = [
    "/etc/xonshrc",
    "~/.xonshrc",
    "~/.config/xonsh/rc.xsh",
]
for file in files:
    if Path(file).is_file():
        source @(file)
if Path("~/.config/xonsh/rc.d").is_dir():
    for file in path.glob('*.xsh'):
        source @(file)

@events.on_precommand
def __kubie_cmd_pre_exec__(cmd):
    $KUBECONFIG = $KUBIE_KUBECONFIG

$KUBIE_PROMPT='[\033[31m$(/home/rrs/bin/kubie info ctx)\033[0m|\033[32m$(/home/rrs/bin/kubie info ns)\033[0m]'
import re

# Fanciful prompt-command replacement as xonsh forces the use of PROMPT_FIELDS
for match in re.finditer(r'\$\(([^)]*)\)', $KUBIE_PROMPT):
    command = match.group(1)
    name = command.split().pop()
    $PROMPT_FIELDS[name] = evalx(f'lambda: $({command}).strip()')
    $KUBIE_PROMPT = $KUBIE_PROMPT.replace(f'$({command})', '{' + name + '}')

if $KUBIE_XONSH_USE_RIGHT_PROMPT == "1":
    $RIGHT_PROMPT = $KUBIE_PROMPT + $RIGHT_PROMPT
else:
    $PROMPT = $KUBIE_PROMPT + $PROMPT

del $KUBIE_PROMPT
@ source @(file)
Exception in {'cls': 'ProcProxy', 'name': None, 'func': FuncAlias({'name': 'source', 'func': 'source_alias', '__xonsh_threadable__': False, 'return_what': 'result'}), 'alias': 'source', 'pid': 1159896}
xonsh: To log full traceback to a file set: $XONSH_TRACEBACK_LOGFILE = <filename>
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/xonsh/procs/proxies.py", line 784, in wait
    r = run_with_partial_args(
        ^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3/dist-packages/xonsh/cli_utils.py", line 381, in run_with_partial_args
    return func(**kwargs)
           ^^^^^^^^^^^^^^
  File "/usr/lib/python3/dist-packages/xonsh/aliases.py", line 95, in __call__
    return run_alias_by_params(
           ^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3/dist-packages/xonsh/aliases.py", line 555, in run_alias_by_params
    return func(**kwargs)
           ^^^^^^^^^^^^^^
  File "/usr/lib/python3/dist-packages/xonsh/aliases.py", line 765, in source_alias
    raise RuntimeError(
RuntimeError: must source at least one file, ~/.xonshrc does not exist.

If I source my ~/.xonshrc as the very first step after kubie ctx, then I don't run into any problems.

When I reported the issue, it was just an observation that xontribs were missing. But now, given that it doesn't source the ~/.xonshrc as well, it hinders in my exceptional config.

rickysarraf commented 5 days ago

This is the current workaround.

@ kubie ctx
rrs@priyasi ~ @ xontrib list                                                                                                                               [cs00114-we-01-aks|default]
abbrevs            not-loaded
autojump           not-loaded
coreutils          not-loaded
fzf-widgets        not-loaded
hist_navigator     not-loaded
output_search      not-loaded
powerline_binding  not-loaded
sh                 not-loaded
term_integration   not-loaded

rrs@priyasi ~ @ source ~/.xonshrc                                                                                                                          [cs00114-we-01-aks|default]
Loaded function prompt:  stock_prompt

♒︎ 20:34:49 rrs@priyasi ~                                                                                                                                  [cs00114-we-01-aks|default ]
@ xontrib list
abbrevs            loaded      manual
autojump           loaded      manual
coreutils          loaded      manual
fzf-widgets        loaded      manual
hist_navigator     not-loaded
output_search      loaded      manual
powerline_binding  not-loaded
sh                 loaded      manual
term_integration   loaded      manual

⛢ 20:34:54 rrs@priyasi ~                                                                                                                                   [cs00114-we-01-aks|default]
@