Parent directory

kube-ps1.plugin.zsh

13917 bytes
  1#!/usr/bin/env bash
  2
  3# Kubernetes prompt helper for bash/zsh
  4# Displays current context and namespace
  5
  6# Copyright 2026 Jon Mosco
  7#
  8#  Licensed under the Apache License, Version 2.0 (the "License");
  9# you may not use this file except in compliance with the License.
 10# You may obtain a copy of the License at
 11#
 12#     http://www.apache.org/licenses/LICENSE-2.0
 13#
 14# Unless required by applicable law or agreed to in writing, software
 15# distributed under the License is distributed on an "AS IS" BASIS,
 16# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 17# See the License for the specific language governing permissions and
 18# limitations under the License.
 19
 20# Debug
 21[[ -n $DEBUG ]] && set -x
 22
 23# Default values for the prompt
 24# Override these values in ~/.zshrc or ~/.bashrc
 25KUBE_PS1_BINARY="${KUBE_PS1_BINARY:-kubectl}"
 26KUBE_PS1_SYMBOL_ENABLE="${KUBE_PS1_SYMBOL_ENABLE:-true}"
 27KUBE_PS1_SYMBOL_PADDING="${KUBE_PS1_SYMBOL_PADDING:-false}"
 28KUBE_PS1_SYMBOL_COLOR="${KUBE_PS1_SYMBOL_COLOR:-}"
 29
 30KUBE_PS1_NS_ENABLE="${KUBE_PS1_NS_ENABLE:-true}"
 31KUBE_PS1_CONTEXT_ENABLE="${KUBE_PS1_CONTEXT_ENABLE:-true}"
 32KUBE_PS1_PREFIX="${KUBE_PS1_PREFIX-(}"
 33KUBE_PS1_SEPARATOR="${KUBE_PS1_SEPARATOR-|}"
 34KUBE_PS1_DIVIDER="${KUBE_PS1_DIVIDER-:}"
 35KUBE_PS1_SUFFIX="${KUBE_PS1_SUFFIX-)}"
 36
 37KUBE_PS1_HIDE_IF_NOCONTEXT="${KUBE_PS1_HIDE_IF_NOCONTEXT:-false}"
 38
 39_KUBE_PS1_KUBECONFIG_CACHE="${KUBECONFIG}"
 40_KUBE_PS1_DISABLE_PATH="${HOME}/.kube/kube-ps1/disabled"
 41_KUBE_PS1_LAST_TIME=0
 42
 43# Determine our shell
 44_kube_ps1_shell_type() {
 45  local _KUBE_PS1_SHELL_TYPE
 46
 47  if [ "${ZSH_VERSION-}" ]; then
 48    _KUBE_PS1_SHELL_TYPE="zsh"
 49  elif [ "${BASH_VERSION-}" ]; then
 50    _KUBE_PS1_SHELL_TYPE="bash"
 51  fi
 52  echo "$_KUBE_PS1_SHELL_TYPE"
 53}
 54
 55_kube_ps1_init() {
 56  [[ -f "${_KUBE_PS1_DISABLE_PATH}" ]] && KUBE_PS1_ENABLED=off
 57
 58  # Detect shell type once and cache it
 59  _KUBE_PS1_SHELL="$(_kube_ps1_shell_type)"
 60
 61  # Check tput availability once
 62  if tput setaf 1 &> /dev/null; then
 63    _KUBE_PS1_TPUT_AVAILABLE=true
 64  else
 65    _KUBE_PS1_TPUT_AVAILABLE=false
 66  fi
 67
 68  # Detect stat type once (not needed for zsh which uses zstat builtin)
 69  if [[ "${_KUBE_PS1_SHELL}" != "zsh" ]]; then
 70    if stat -c "%s" /dev/null &> /dev/null; then
 71      _KUBE_PS1_STAT_TYPE="gnu"
 72    else
 73      _KUBE_PS1_STAT_TYPE="bsd"
 74    fi
 75  fi
 76
 77  case "${_KUBE_PS1_SHELL}" in
 78    "zsh")
 79      _KUBE_PS1_OPEN_ESC="%{"
 80      _KUBE_PS1_CLOSE_ESC="%}"
 81      _KUBE_PS1_DEFAULT_BG="%k"
 82      _KUBE_PS1_DEFAULT_FG="%f"
 83      setopt PROMPT_SUBST
 84      autoload -U add-zsh-hook
 85      add-zsh-hook precmd _kube_ps1_prompt_update
 86      zmodload -F zsh/stat b:zstat
 87      zmodload zsh/datetime
 88      ;;
 89    "bash")
 90      _KUBE_PS1_OPEN_ESC=$'\001'
 91      _KUBE_PS1_CLOSE_ESC=$'\002'
 92      _KUBE_PS1_DEFAULT_BG=$'\033[49m'
 93      _KUBE_PS1_DEFAULT_FG=$'\033[39m'
 94      [[ $PROMPT_COMMAND =~ _kube_ps1_prompt_update ]] || PROMPT_COMMAND="_kube_ps1_prompt_update;${PROMPT_COMMAND:-:}"
 95      ;;
 96  esac
 97}
 98
 99_kube_ps1_color_fg() {
100  local _KUBE_PS1_FG_CODE
101  case "${1}" in
102    black) _KUBE_PS1_FG_CODE=0;;
103    red) _KUBE_PS1_FG_CODE=1;;
104    green) _KUBE_PS1_FG_CODE=2;;
105    yellow) _KUBE_PS1_FG_CODE=3;;
106    blue) _KUBE_PS1_FG_CODE=4;;
107    magenta) _KUBE_PS1_FG_CODE=5;;
108    cyan) _KUBE_PS1_FG_CODE=6;;
109    white) _KUBE_PS1_FG_CODE=7;;
110    # 256 colors
111    [0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]) _KUBE_PS1_FG_CODE="${1}";;
112    *) _KUBE_PS1_FG_CODE=default
113  esac
114
115  if [[ "${_KUBE_PS1_FG_CODE}" == "default" ]]; then
116    _KUBE_PS1_FG_CODE="${_KUBE_PS1_DEFAULT_FG}"
117    return
118  elif [[ "${_KUBE_PS1_SHELL}" == "zsh" ]]; then
119    _KUBE_PS1_FG_CODE="%F{$_KUBE_PS1_FG_CODE}"
120  elif [[ "${_KUBE_PS1_SHELL}" == "bash" ]]; then
121    if [[ "${_KUBE_PS1_TPUT_AVAILABLE}" == "true" ]]; then
122      _KUBE_PS1_FG_CODE="$(tput setaf "${_KUBE_PS1_FG_CODE}")"
123    elif [[ $_KUBE_PS1_FG_CODE -ge 0 ]] && [[ $_KUBE_PS1_FG_CODE -le 255 ]]; then
124      _KUBE_PS1_FG_CODE="\033[38;5;${_KUBE_PS1_FG_CODE}m"
125    else
126      _KUBE_PS1_FG_CODE="${_KUBE_PS1_DEFAULT_FG}"
127    fi
128  fi
129  echo "${_KUBE_PS1_OPEN_ESC}${_KUBE_PS1_FG_CODE}${_KUBE_PS1_CLOSE_ESC}"
130}
131
132_kube_ps1_color_bg() {
133  local _KUBE_PS1_BG_CODE
134  case "${1}" in
135    black) _KUBE_PS1_BG_CODE=0;;
136    red) _KUBE_PS1_BG_CODE=1;;
137    green) _KUBE_PS1_BG_CODE=2;;
138    yellow) _KUBE_PS1_BG_CODE=3;;
139    blue) _KUBE_PS1_BG_CODE=4;;
140    magenta) _KUBE_PS1_BG_CODE=5;;
141    cyan) _KUBE_PS1_BG_CODE=6;;
142    white) _KUBE_PS1_BG_CODE=7;;
143    # 256 colors
144    [0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]) _KUBE_PS1_BG_CODE="${1}";;
145    *) _KUBE_PS1_BG_CODE=default
146  esac
147
148  if [[ "${_KUBE_PS1_BG_CODE}" == "default" ]]; then
149    _KUBE_PS1_BG_CODE="${_KUBE_PS1_DEFAULT_BG}"
150    return
151  elif [[ "${_KUBE_PS1_SHELL}" == "zsh" ]]; then
152    _KUBE_PS1_BG_CODE="%K{$_KUBE_PS1_BG_CODE}"
153  elif [[ "${_KUBE_PS1_SHELL}" == "bash" ]]; then
154    if [[ "${_KUBE_PS1_TPUT_AVAILABLE}" == "true" ]]; then
155      _KUBE_PS1_BG_CODE="$(tput setab "${_KUBE_PS1_BG_CODE}")"
156    elif [[ $_KUBE_PS1_BG_CODE -ge 0 ]] && [[ $_KUBE_PS1_BG_CODE -le 255 ]]; then
157      _KUBE_PS1_BG_CODE="\033[48;5;${_KUBE_PS1_BG_CODE}m"
158    else
159      _KUBE_PS1_BG_CODE="${_KUBE_PS1_DEFAULT_BG}"
160    fi
161  fi
162  echo "${_KUBE_PS1_OPEN_ESC}${_KUBE_PS1_BG_CODE}${_KUBE_PS1_CLOSE_ESC}"
163}
164
165_kube_ps1_binary_check() {
166  command -v "$1" >/dev/null
167}
168
169_kube_ps1_symbol() {
170  # Exit early if symbol display is disabled
171  [[ "${KUBE_PS1_SYMBOL_ENABLE}" == false ]] && return
172
173  local symbol_arg="${KUBE_PS1_SYMBOL_CUSTOM}"
174
175  local symbol=""
176  local symbol_default=$'\u2388'
177  local symbol_img="☸️" 
178  local k8s_glyph=$'\Uf10fe'
179  local k8s_symbol_color=blue
180  local oc_glyph=$'\ue7b7'
181  local oc_symbol_color=red
182  local custom_symbol_color="${KUBE_PS1_SYMBOL_COLOR:-$k8s_symbol_color}"
183  local KUBE_PS1_RESET_COLOR="${_KUBE_PS1_OPEN_ESC}${_KUBE_PS1_DEFAULT_FG}${_KUBE_PS1_CLOSE_ESC}"
184
185  # Choose the symbol based on the provided argument or environment variable
186  case "${symbol_arg}" in
187    "img")
188      symbol="${symbol_img}"
189      ;;
190    "k8s")
191      symbol="$(_kube_ps1_color_fg "${custom_symbol_color}")${k8s_glyph}${KUBE_PS1_RESET_COLOR}"
192      ;;
193    "oc")
194      symbol="$(_kube_ps1_color_fg ${oc_symbol_color})${oc_glyph}${KUBE_PS1_RESET_COLOR}"
195      ;;
196    *)
197      case "${_KUBE_PS1_SHELL}" in
198        bash)
199          if ((BASH_VERSINFO[0] >= 4)) && [[ $'\u2388' != "\\u2388" ]]; then
200            symbol="$(_kube_ps1_color_fg $custom_symbol_color)${symbol_default}${KUBE_PS1_RESET_COLOR}"
201            symbol_img=$'\u2638\ufe0f'
202          else
203            symbol=$'\xE2\x8E\x88'
204            symbol_img=$'\xE2\x98\xB8'
205          fi
206          ;;
207        zsh)
208          symbol="$(_kube_ps1_color_fg $custom_symbol_color)${symbol_default}${KUBE_PS1_RESET_COLOR}"
209          symbol_img="☸️"
210          ;;
211        *)
212          symbol="k8s"
213      esac
214  esac
215
216  # Append padding if enabled
217  if [[ "${KUBE_PS1_SYMBOL_PADDING}" == true ]]; then
218    echo "${symbol} "
219  else
220    echo "${symbol}"
221  fi
222}
223
224_kube_ps1_split_config() {
225  type setopt >/dev/null 2>&1 && setopt SH_WORD_SPLIT
226  local IFS=$1
227  echo $2
228}
229
230_kube_ps1_file_newer_than() {
231  local mtime
232  local file=$1
233  local check_time=$2
234
235  if [[ "${_KUBE_PS1_SHELL}" == "zsh" ]]; then
236    # Use zstat '-F %s.%s' to make it compatible with low zsh version (eg: 5.0.2)
237    mtime=$(zstat -L +mtime -F %s.%s "${file}")
238  elif [[ "${_KUBE_PS1_STAT_TYPE}" == "gnu" ]]; then
239    mtime=$(stat -L -c %Y "${file}")
240  else
241    mtime=$(stat -L -f %m "$file")
242  fi
243
244  [[ "${mtime}" -gt "${check_time}" ]] && return 0
245
246  # If the path is a symlink, also check the symlink's own mtime
247  if [[ -L "${file}" ]]; then
248    if [[ "${_KUBE_PS1_SHELL}" == "zsh" ]]; then
249      mtime=$(zstat +mtime -F %s.%s "${file}")
250    elif [[ "${_KUBE_PS1_STAT_TYPE}" == "gnu" ]]; then
251      mtime=$(stat -c %Y "${file}")
252    else
253      mtime=$(stat -f %m "$file")
254    fi
255    [[ "${mtime}" -gt "${check_time}" ]] && return 0
256  fi
257
258  return 1
259}
260
261_kube_ps1_prompt_update() {
262  local return_code=$?
263
264  [[ "${KUBE_PS1_ENABLED}" == "off" ]] && return $return_code
265
266  if ! _kube_ps1_binary_check "${KUBE_PS1_BINARY}"; then
267    # No ability to fetch context/namespace; display N/A.
268    KUBE_PS1_CONTEXT="BINARY-N/A"
269    KUBE_PS1_NAMESPACE="N/A"
270    return $return_code
271  fi
272
273  if [[ "${KUBECONFIG}" != "${_KUBE_PS1_KUBECONFIG_CACHE}" ]]; then
274    # User changed KUBECONFIG; unconditionally refetch.
275    _KUBE_PS1_KUBECONFIG_CACHE=${KUBECONFIG}
276    _kube_ps1_get_context_ns
277    return $return_code
278  fi
279
280  # kubectl will read the environment variable $KUBECONFIG
281  # otherwise set it to ~/.kube/config
282  local conf
283  local config_file_cache
284
285  for conf in $(_kube_ps1_split_config : "${KUBECONFIG:-${HOME}/.kube/config}"); do
286    [[ -r "${conf}" ]] || continue
287    config_file_cache+=":${conf}"
288    if _kube_ps1_file_newer_than "${conf}" "${_KUBE_PS1_LAST_TIME}"; then
289      _kube_ps1_get_context_ns
290      return $return_code
291    fi
292  done
293
294  if [[ "${config_file_cache}" != "${_KUBE_PS1_CFGFILES_READ_CACHE}" ]]; then
295    _kube_ps1_get_context_ns
296    return $return_code
297  fi
298
299  return $return_code
300}
301
302_kube_ps1_get_context() {
303  if [[ "${KUBE_PS1_CONTEXT_ENABLE}" == true ]]; then
304    KUBE_PS1_CONTEXT="$(${KUBE_PS1_BINARY} config current-context 2>/dev/null)"
305    KUBE_PS1_CONTEXT="${KUBE_PS1_CONTEXT:-N/A}"
306
307    if [[ -n "${KUBE_PS1_CLUSTER_FUNCTION}" ]]; then
308      KUBE_PS1_CONTEXT="$("${KUBE_PS1_CLUSTER_FUNCTION}" "${KUBE_PS1_CONTEXT}")"
309    fi
310  fi
311}
312
313_kube_ps1_get_ns() {
314  if [[ "${KUBE_PS1_NS_ENABLE}" == true ]]; then
315    KUBE_PS1_NAMESPACE="$(${KUBE_PS1_BINARY} config view --minify --output 'jsonpath={..namespace}' 2>/dev/null)"
316    KUBE_PS1_NAMESPACE="${KUBE_PS1_NAMESPACE:-N/A}"
317
318    if [[ -n "${KUBE_PS1_NAMESPACE_FUNCTION}" ]]; then
319        KUBE_PS1_NAMESPACE="$("${KUBE_PS1_NAMESPACE_FUNCTION}" "${KUBE_PS1_NAMESPACE}")"
320    fi
321  fi
322}
323
324_kube_ps1_get_context_ns() {
325  # Set the command time
326  if [[ "${_KUBE_PS1_SHELL}" == "bash" ]]; then
327    if ((BASH_VERSINFO[0] > 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] >= 2))); then
328      _KUBE_PS1_LAST_TIME=$(printf '%(%s)T')
329    else
330      _KUBE_PS1_LAST_TIME=$(date +%s)
331    fi
332  elif [[ "${_KUBE_PS1_SHELL}" == "zsh" ]]; then
333    _KUBE_PS1_LAST_TIME=$EPOCHREALTIME
334  fi
335
336  # Cache which cfgfiles we can read in case they change.
337  local conf
338  _KUBE_PS1_CFGFILES_READ_CACHE=
339  for conf in $(_kube_ps1_split_config : "${KUBECONFIG:-${HOME}/.kube/config}"); do
340    [[ -r $conf ]] && _KUBE_PS1_CFGFILES_READ_CACHE+=":$conf"
341  done
342
343  _kube_ps1_get_context
344  _kube_ps1_get_ns
345}
346
347# Set kube-ps1 shell defaults
348_kube_ps1_init
349
350_kubeon_usage() {
351  cat <<"EOF"
352Toggle kube-ps1 prompt on
353
354Usage: kubeon [-g | --global] [-h | --help]
355
356With no arguments, turn on kube-ps1 status for this shell instance (default).
357
358  -g --global  turn on kube-ps1 status globally
359  -h --help    print this message
360EOF
361}
362
363_kubeoff_usage() {
364  cat <<"EOF"
365Toggle kube-ps1 prompt off
366
367Usage: kubeoff [-g | --global] [-h | --help]
368
369With no arguments, turn off kube-ps1 status for this shell instance (default).
370
371  -g --global turn off kube-ps1 status globally
372  -h --help   print this message
373EOF
374}
375
376kubeon() {
377  if [[ "${1}" == '-h' || "${1}" == '--help' ]]; then
378    _kubeon_usage
379    return 0
380  elif [[ "${1}" == '-g' || "${1}" == '--global' ]]; then
381    rm -f -- "${_KUBE_PS1_DISABLE_PATH}"
382  elif [[ "$#" -ne 0 ]]; then
383    echo -e "error: unrecognized flag ${1}\\n" >&2
384    _kubeon_usage
385    return 1
386  fi
387
388  KUBE_PS1_ENABLED=on
389}
390
391kubeoff() {
392  if [[ "${1}" == '-h' || "${1}" == '--help' ]]; then
393    _kubeoff_usage
394    return 0
395  elif [[ "${1}" == '-g' || "${1}" == '--global' ]]; then
396    mkdir -p -- "$(dirname "${_KUBE_PS1_DISABLE_PATH}")"
397    touch -- "${_KUBE_PS1_DISABLE_PATH}"
398  elif [[ $# -ne 0 ]]; then
399    echo -e "error: unrecognized flag ${1}\\n" >&2
400    _kubeoff_usage
401    return 1
402  fi
403
404  KUBE_PS1_ENABLED=off
405}
406
407# Build our prompt
408kube_ps1() {
409  [[ "${KUBE_PS1_ENABLED}" == "off" ]] && return
410  [[ -z "${KUBE_PS1_CONTEXT}" ]] && [[ "${KUBE_PS1_CONTEXT_ENABLE}" == true ]] && return
411  [[ "${KUBE_PS1_CONTEXT}" == "N/A" ]] && [[ ${KUBE_PS1_HIDE_IF_NOCONTEXT} == true ]] && return
412
413  local KUBE_PS1
414  local KUBE_PS1_RESET_COLOR="${_KUBE_PS1_OPEN_ESC}${_KUBE_PS1_DEFAULT_FG}${_KUBE_PS1_CLOSE_ESC}"
415
416  # Background Color
417  [[ -n "${KUBE_PS1_BG_COLOR}" ]] && KUBE_PS1+="$(_kube_ps1_color_bg "${KUBE_PS1_BG_COLOR}")"
418
419  # Prefix
420  if [[ -z "${KUBE_PS1_PREFIX_COLOR:-}" ]] && [[ -n "${KUBE_PS1_PREFIX}" ]]; then
421      KUBE_PS1+="${KUBE_PS1_PREFIX}"
422  else
423      KUBE_PS1+="$(_kube_ps1_color_fg "${KUBE_PS1_PREFIX_COLOR}")${KUBE_PS1_PREFIX}${KUBE_PS1_RESET_COLOR}"
424  fi
425
426  # Symbol
427  KUBE_PS1+="$(_kube_ps1_symbol)"
428
429  if [[ -n "${KUBE_PS1_SEPARATOR}" ]] && [[ "${KUBE_PS1_SYMBOL_ENABLE}" == true ]]; then
430    KUBE_PS1+="${KUBE_PS1_SEPARATOR}"
431  fi
432
433  # Context
434  if [[ "${KUBE_PS1_CONTEXT_ENABLE}" == true ]]; then
435    local ctx_color="${KUBE_PS1_CTX_COLOR:-red}"
436
437    # Allow custom function to override color based on context
438    if [[ -n "${KUBE_PS1_CTX_COLOR_FUNCTION}" ]]; then
439      ctx_color="$("${KUBE_PS1_CTX_COLOR_FUNCTION}" "${KUBE_PS1_CONTEXT}")"
440    fi
441
442    KUBE_PS1+="$(_kube_ps1_color_fg "${ctx_color}")${KUBE_PS1_CONTEXT}${KUBE_PS1_RESET_COLOR}"
443  fi
444
445  # Namespace
446  if [[ "${KUBE_PS1_NS_ENABLE}" == true ]]; then
447    if [[ -n "${KUBE_PS1_DIVIDER}" ]] && [[ "${KUBE_PS1_CONTEXT_ENABLE}" == true ]]; then
448      KUBE_PS1+="${KUBE_PS1_DIVIDER}"
449    fi
450    KUBE_PS1+="$(_kube_ps1_color_fg "${KUBE_PS1_NS_COLOR:-cyan}")${KUBE_PS1_NAMESPACE}${KUBE_PS1_RESET_COLOR}"
451  fi
452
453  # Suffix
454  if [[ -z "${KUBE_PS1_SUFFIX_COLOR:-}" ]] && [[ -n "${KUBE_PS1_SUFFIX}" ]]; then
455      KUBE_PS1+="${KUBE_PS1_SUFFIX}"
456  else
457      KUBE_PS1+="$(_kube_ps1_color_fg "${KUBE_PS1_SUFFIX_COLOR}")${KUBE_PS1_SUFFIX}${KUBE_PS1_RESET_COLOR}"
458  fi
459
460  # Close Background color if defined
461  [[ -n "${KUBE_PS1_BG_COLOR}" ]] && KUBE_PS1+="${_KUBE_PS1_OPEN_ESC}${_KUBE_PS1_DEFAULT_BG}${_KUBE_PS1_CLOSE_ESC}"
462
463  echo "${KUBE_PS1}"
464}