feat(kubernetes): Guard kubectl initialization and completions

Ensures kubectl-related aliases and functions are only sourced if the `kubectl` command is available.
This commit is contained in:
2026-04-16 19:21:35 +02:00
parent 2c0ac0f6ab
commit 5e4a8464c5

View File

@@ -1,7 +1,8 @@
source <(kubectl completion bash) if command -v kubectl >/dev/null 2>&1; then
alias k="kubectl" source <(kubectl completion bash)
alias kcontext="kubectl config use-context" alias k="kubectl"
kns() { alias kcontext="kubectl config use-context"
kns() {
if [[ $# -eq 0 ]]; then if [[ $# -eq 0 ]]; then
printf '%s\n' "$(kubectl config view --minify -o jsonpath='{.contexts[0].context.namespace}')" printf '%s\n' "$(kubectl config view --minify -o jsonpath='{.contexts[0].context.namespace}')"
else else
@@ -9,17 +10,18 @@ kns() {
kubectl config set-context --current --namespace "$ns" kubectl config set-context --current --namespace "$ns"
printf 'Switched current context to namespace: %s\n' "$ns" printf 'Switched current context to namespace: %s\n' "$ns"
fi fi
} }
_kns_completion() { _kns_completion() {
local cur local cur
cur=${COMP_WORDS[COMP_CWORD]} cur=${COMP_WORDS[COMP_CWORD]}
COMPREPLY=( $(compgen -W "$(kubectl get namespaces -o name | sed 's|namespace/||')" -- "$cur") ) COMPREPLY=( $(compgen -W "$(kubectl get namespaces -o name | sed 's|namespace/||')" -- "$cur") )
} }
_kcontext_completion() { _kcontext_completion() {
local cur local cur
cur=${COMP_WORDS[COMP_CWORD]} cur=${COMP_WORDS[COMP_CWORD]}
COMPREPLY=( $(compgen -W "$(kubectl config get-contexts -o name)" -- $cur) ) COMPREPLY=( $(compgen -W "$(kubectl config get-contexts -o name)" -- $cur) )
} }
complete -F __start_kubectl k complete -F __start_kubectl k
complete -F _kns_completion kns complete -F _kns_completion kns
complete -F _kcontext_completion kcontext complete -F _kcontext_completion kcontext
fi