Parent directory

kc.zsh

2483 bytes
  1#!/bin/zsh
  2
  3usage() {
  4  local SELF
  5  SELF="kc"
  6
  7  cat <<EOF
  8USAGE:
  9  $SELF                       : list the configs
 10  $SELF <NAME>                : switch to config <NAME>
 11  $SELF -c, --current         : show the current context name
 12  $SELF -u, --unset           : unset the current kubeconfig
 13
 14  $SELF -h,--help             : show this message
 15EOF
 16}
 17
 18exit_err() {
 19   echo >&2 "${1}"
 20   exit 1
 21}
 22
 23current_context() {
 24  kubectl config view -o=jsonpath='{.current-context}'
 25}
 26
 27get_configs() {
 28  #kubectl config get-contexts -o=name | sort -n
 29  \ls -p --color=never -1 $HOME/.kube | \grep -v '/$'
 30}
 31
 32list_configs() {
 33  set -u pipefail
 34  local cur ctx_list
 35  cur="$(current_context)" || exit_err "error getting current context"
 36  ctx_list=$(get_configs) || exit_err "error getting context list"
 37
 38  local yellow darkbg normal
 39  yellow=$(tput setaf 3 || true)
 40  darkbg=$(tput setab 0 || true)
 41  normal=$(tput sgr0 || true)
 42
 43  local cur_ctx_fg cur_ctx_bg
 44  cur_ctx_fg=${KUBECTX_CURRENT_FGCOLOR:-$yellow}
 45  cur_ctx_bg=${KUBECTX_CURRENT_BGCOLOR:-$darkbg}
 46
 47  for c in $ctx_list; do
 48  if [[ -n "${_KUBECTX_FORCE_COLOR:-}" || \
 49       -t 1 && -z "${NO_COLOR:-}" ]]; then
 50    # colored output mode
 51    if [[ "${c}" = "${cur}" ]]; then
 52      echo "${cur_ctx_bg}${cur_ctx_fg}${c}${normal}"
 53    else
 54      echo "${c}"
 55    fi
 56  else
 57    echo "${c}"
 58  fi
 59  done
 60}
 61
 62choose_context_interactive() {
 63  local choice
 64  choice="$(get_configs | _KUBECTX_FORCE_COLOR=1 fzf --ansi --no-preview || true)"
 65  if [[ -z "${choice}" ]]; then
 66    echo 2>&1 "error: you did not choose any of the options"
 67    exit 1
 68  else
 69    set_context "${choice}"
 70  fi
 71}
 72
 73set_context() {
 74  export KUBECONFIG="$HOME/.kube/${1}"
 75}
 76
 77unset_context() {
 78  unset KUBECONFIG
 79}
 80
 81kc() {
 82  if [[ "$#" -eq 0 ]]; then
 83    if [[ -t 1 &&  -z "${KUBECTX_IGNORE_FZF:-}" && "$(type fzf &>/dev/null; echo $?)" -eq 0 ]]; then
 84      choose_context_interactive
 85    else
 86      list_configs
 87    fi
 88  elif [[ "$#" -gt 1 ]]; then
 89    echo "error: too many arguments" >&2
 90    usage
 91    exit 1
 92  elif [[ "$#" -eq 1 ]]; then
 93    if [[ "${1}" == '-c' || "${1}" == '--current' ]]; then
 94      kubectl config current-context
 95    elif [[ "${1}" == '-u' || "${1}" == '--unset' ]]; then
 96      unset_context
 97    elif [[ "${1}" == '-h' || "${1}" == '--help' ]]; then
 98      usage
 99    elif [[ "${1}" =~ ^-(.*) ]]; then
100      echo "error: unrecognized flag \"${1}\"" >&2
101      usage
102      exit 1
103    else
104      set_context "${1}"
105    fi
106  else
107    usage
108    exit 1
109  fi
110}