executable_kubectl_complete-namespace 1.1 KB

12345678910111213141516171819202122232425
  1. #!/usr/bin/env bash
  2. # If we are completing a flag, use Cobra's builtin completion system.
  3. # To know if we are completing a flag we need the last argument starts with a `-` and does not contain an `=`
  4. args=("$@")
  5. lastArg=${args[((${#args[@]}-1))]}
  6. if [[ "$lastArg" == -* ]]; then
  7. if [[ "$lastArg" != *=* ]]; then
  8. kubectl ns __complete "$@"
  9. fi
  10. else
  11. # TODO Make sure we are not completing the value of a flag.
  12. # TODO Only complete a single argument.
  13. # Both are pretty hard to do in a shell script. The better way to do this would be to let
  14. # Cobra do all the completions by using `cobra.ValidArgsFunction` in the program.
  15. # But the below, although imperfect, is a nice example for plugins that don't use Cobra.
  16. # We are probably completing an argument. This plugin only accepts namespaces, let's fetch them.
  17. kubectl get namespaces --output go-template='{{ range .items }}{{ .metadata.name }}{{"\n"}}{{ end }}'
  18. # Turn off file completion. See the ShellCompDirective documentation within
  19. # https://github.com/spf13/cobra/blob/main/shell_completions.md#completion-of-nouns
  20. echo :4
  21. fi