github.com/buildpacks/pack@v0.33.3-0.20240516162812-884dd1837311/internal/commands/completion.go (about) 1 package commands 2 3 import ( 4 "os" 5 "path/filepath" 6 7 "github.com/pkg/errors" 8 "github.com/spf13/cobra" 9 10 "github.com/buildpacks/pack/pkg/logging" 11 ) 12 13 type CompletionFlags struct { 14 Shell string 15 } 16 17 type completionFunc func(packHome string, cmd *cobra.Command) (path string, err error) 18 19 var shellExtensions = map[string]completionFunc{ 20 "bash": func(packHome string, cmd *cobra.Command) (path string, err error) { 21 p := filepath.Join(packHome, "completion.sh") 22 return p, cmd.GenBashCompletionFile(p) 23 }, 24 "fish": func(packHome string, cmd *cobra.Command) (path string, err error) { 25 p := filepath.Join(packHome, "completion.fish") 26 return p, cmd.GenFishCompletionFile(p, true) 27 }, 28 "powershell": func(packHome string, cmd *cobra.Command) (path string, err error) { 29 p := filepath.Join(packHome, "completion.ps1") 30 return p, cmd.GenPowerShellCompletionFile(p) 31 }, 32 "zsh": func(packHome string, cmd *cobra.Command) (path string, err error) { 33 p := filepath.Join(packHome, "completion.zsh") 34 return p, cmd.GenZshCompletionFile(p) 35 }, 36 } 37 38 func CompletionCommand(logger logging.Logger, packHome string) *cobra.Command { 39 var flags CompletionFlags 40 var completionCmd = &cobra.Command{ 41 Use: "completion", 42 Short: "Outputs completion script location", 43 Long: `Generates completion script and outputs its location. 44 45 To configure your bash shell to load completions for each session, add the following to your '.bashrc' or '.bash_profile': 46 47 . $(pack completion) 48 49 To configure your fish shell to load completions for each session, add the following to your '~/.config/fish/config.fish': 50 51 source (pack completion --shell fish) 52 53 To configure your powershell to load completions for each session, add the following to your '$Home\[My ]Documents\PowerShell\ 54 Microsoft.PowerShell_profile.ps1': 55 56 . $(pack completion --shell powershell) 57 58 To configure your zsh shell to load completions for each session, add the following to your '.zshrc': 59 60 . $(pack completion --shell zsh) 61 62 63 `, 64 RunE: logError(logger, func(cmd *cobra.Command, args []string) error { 65 completionFunc, ok := shellExtensions[flags.Shell] 66 if !ok { 67 return errors.Errorf("%s is unsupported shell", flags.Shell) 68 } 69 70 if err := os.MkdirAll(packHome, os.ModePerm); err != nil { 71 return err 72 } 73 74 completionPath, err := completionFunc(packHome, cmd.Parent()) 75 if err != nil { 76 return err 77 } 78 79 logger.Info(completionPath) 80 return nil 81 }), 82 } 83 84 completionCmd.Flags().StringVarP(&flags.Shell, "shell", "s", "bash", "Generates completion file for [bash|fish|powershell|zsh]") 85 return completionCmd 86 }