Add overwriting to rename

rename now deletes the context (soft-delete, as in does not delete user or
cluster of the context) if the specified name exists.

Fixes #25.

Signed-off-by: Ahmet Alp Balkan <ahmetb@google.com>
This commit is contained in:
Ahmet Alp Balkan 2018-04-02 23:27:51 -07:00
parent 6610d70ca8
commit fbce3de6b9
No known key found for this signature in database
GPG Key ID: 5C02521D7B216AD6

13
kubectx
View File

@ -103,28 +103,39 @@ swap_context() {
}
user_of_context() {
# TODO(ahmetb) no longer used, consider deleting
kubectl config view \
-o=jsonpath="{.contexts[?(@.name==\"${1}\")].context.user}"
}
cluster_of_context() {
# TODO(ahmetb) no longer used, consider deleting
kubectl config view \
-o=jsonpath="{.contexts[?(@.name==\"${1}\")].context.cluster}"
}
context_exists() {
grep -q ^"${1}"\$ <(kubectl config get-contexts -o=name)
}
rename_context() {
local old_name="${1}"
local new_name="${2}"
# TODO(ahmetb) old_user and old_cluster are no longer used, clean up
local old_user old_cluster
old_user="$(user_of_context "${old_name}")"
old_cluster="$(cluster_of_context "${old_name}")"
if [[ -z "$old_user" || -z "$old_cluster" ]]; then
echo "error: Cannot retrieve context ${old_name}." >&2
exit 1
fi
if context_exists "${new_name}"; then
echo "Context \"${new_name}\" exists, deleting." >&2
kubectl config delete-context "${new_name}" 1>/dev/null 2>&1
fi
kubectl config rename-context "${old_name}" "${new_name}"
}