Serge Bazanski | be538db | 2020-11-12 00:22:42 +0100 | [diff] [blame] | 1 | // Copyright 2018 The kubecfg authors |
| 2 | // |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | package cmd |
| 17 | |
| 18 | import ( |
| 19 | "fmt" |
| 20 | "os" |
| 21 | "path/filepath" |
| 22 | "strings" |
| 23 | "unicode" |
| 24 | |
| 25 | "github.com/spf13/cobra" |
| 26 | ) |
| 27 | |
| 28 | const ( |
| 29 | flagShell = "shell" |
| 30 | ) |
| 31 | |
| 32 | func guessShell(path string) string { |
| 33 | ret := filepath.Base(path) |
| 34 | ret = strings.TrimRightFunc(ret, unicode.IsNumber) |
| 35 | return ret |
| 36 | } |
| 37 | |
| 38 | func init() { |
| 39 | RootCmd.AddCommand(completionCmd) |
| 40 | completionCmd.PersistentFlags().String(flagShell, "", "Shell variant for which to generate completions. Supported values are bash,zsh") |
| 41 | } |
| 42 | |
| 43 | var completionCmd = &cobra.Command{ |
| 44 | Use: "completion", |
| 45 | Short: "Generate shell completions for kubecfg", |
| 46 | Args: cobra.NoArgs, |
| 47 | RunE: func(cmd *cobra.Command, args []string) error { |
| 48 | flags := cmd.Flags() |
| 49 | |
| 50 | shell, err := flags.GetString(flagShell) |
| 51 | if err != nil { |
| 52 | return err |
| 53 | } |
| 54 | if shell == "" { |
| 55 | shell = guessShell(os.Getenv("SHELL")) |
| 56 | } |
| 57 | |
| 58 | out := cmd.OutOrStdout() |
| 59 | |
| 60 | switch shell { |
| 61 | case "bash": |
| 62 | if err := RootCmd.GenBashCompletion(out); err != nil { |
| 63 | return err |
| 64 | } |
| 65 | case "zsh": |
| 66 | if err := RootCmd.GenZshCompletion(out); err != nil { |
| 67 | return err |
| 68 | } |
| 69 | default: |
| 70 | return fmt.Errorf("Unknown shell %q, try --%s", shell, flagShell) |
| 71 | } |
| 72 | |
| 73 | return nil |
| 74 | }, |
| 75 | } |