fishで現在のkubernetesクラスターの接続先を表示する方法

2021年11月28日2022年08月13日

zshからfishに乗り換えたときに、kube_ps1がサポートされていなくて困りました。
kube_ps1はkubectlで今kubernetesのどこのクラスターに接続されているか、表示してくれるzshの拡張機能です。

https://github.com/jonmosco/kube-ps1

kubectlを標準サポート

fish配下の関数に tide_item_kubectl.fish があることに気づいた私。
「もしかして標準で装備されているのか?」

$ cat .config/fish/functions/tide_item_kubectl.fish
function _tide_item_kubectl
  set -l context (kubectl config view --minify --output 'jsonpath={.current-context}/{..namespace}' 2>/dev/null) &&
    _tide_print_item kubectl $tide_kubectl_icon' ' (string replace --regex '/(|default)$' '' $context)
end

表示方法

私は右側に表示したかったので tide_right_prompt_items に設定しました。

$ cat .config/fish/conf.d/tide.fish
set -g tide_kubectl_bg_color 268bd2 # ←背景色
set -g tide_kubectl_color 000000 # ←文字色
set -g tide_left_prompt_frame_enabled true
set -g tide_left_prompt_items pwd git newline
set -g tide_left_prompt_prefix \ue0b6
set -g tide_left_prompt_separator_diff_color \ue0bc
set -g tide_left_prompt_separator_same_color \ue0b1
set -g tide_left_prompt_suffix \ue0b0
set -g tide_prompt_add_newline_before false
set -g tide_prompt_pad_items true
set -g tide_pwd_bg_color 444444
set -g tide_pwd_color_anchors E4E4E4
set -g tide_pwd_color_dirs a4a4a4
set -g tide_pwd_color_truncated_dirs BCBCBC
set -g tide_right_prompt_items status cmd_duration kubectl context jobs node virtual_env rustc php vi_mode time # ←この順で表示
set -g tide_right_prompt_prefix \ue0b2
set -g tide_right_prompt_separator_diff_color \ue0ba
set -g tide_right_prompt_separator_same_color \ue0b3
set -g tide_right_prompt_suffix \ue0b4

tide.fishで宣言するこの名前は ~/.config/fish/functions/tide_item_名前 となっている。
ちなみに tide名前bg_color RBGコード と指定すると背景色 tide_名前_color RBGコード と指定すると文字色を変更することができる。

仕組み

fishはconfig.fish(zshでいう.zshrc)が荒れないよう関数で設定を追加することが多いです。
プロンプト表示のベストプラクティスは、 ~/.config/fish/conf.d/tide.fish で表示したい tide_item_left(right)_prompt_items で表示したい関数を追加していくことです。
色も柔軟に対応しているのでかなり使いやすくできるのではないでしょうか。

まとめ

fishの表示はtide.fishを使え。
これたどり着くのに1日掛かった。
でも解決してくれて、よかった。