github.com/cozy/cozy-stack@v0.0.0-20240327093429-939e4a21320e/cmd/completion.go (about)

     1  package cmd
     2  
     3  import (
     4  	"errors"
     5  	"os"
     6  
     7  	"github.com/spf13/cobra"
     8  )
     9  
    10  var completionCmd = &cobra.Command{
    11  	Use:   "completion <shell>",
    12  	Short: "Output shell completion code for the specified shell",
    13  	Long: `
    14  Output shell completion code for the specified shell (bash, zsh, or fish). The
    15  shell code must be evalutated to provide interactive completion of cozy-stack
    16  commands.
    17  
    18  Bash:
    19  
    20    $ source <(cozy-stack completion bash)
    21  
    22    # To load completions for each session, execute once:
    23    # Linux:
    24    $ cozy-stack completion bash > /etc/bash_completion.d/cozy-stack
    25    # macOS:
    26    $ cozy-stack completion bash > $(brew --prefix)/etc/bash_completion.d/cozy-stack
    27  
    28  Note: this requires the bash-completion framework, which is not installed by
    29  default on Mac.  This can be installed by using homebrew:
    30  
    31      $ brew install bash-completion
    32  
    33  Once installed, bash_completion must be evaluated.  This can be done by adding the
    34  following line to the .bash_profile
    35  
    36      $ source $(brew --prefix)/etc/bash_completion
    37  
    38  Zsh:
    39  
    40    # If shell completion is not already enabled in your environment,
    41    # you will need to enable it.  You can execute the following once:
    42  
    43    $ echo "autoload -U compinit; compinit" >> ~/.zshrc
    44  
    45    # To load completions for each session, execute once:
    46    $ cozy-stack completion zsh > "${fpath[1]}/_cozy-stack"
    47  
    48    # You will need to start a new shell for this setup to take effect.
    49  
    50  fish:
    51  
    52    $ cozy-stack completion fish | source
    53  
    54    # To load completions for each session, execute once:
    55    $ cozy-stack completion fish > /etc/fish/completions/cozy-stack.fish
    56  `,
    57  	ValidArgs: []string{"bash", "zsh", "fish"},
    58  	RunE: func(cmd *cobra.Command, args []string) error {
    59  		if len(args) != 1 {
    60  			return cmd.Usage()
    61  		}
    62  		switch args[0] {
    63  		case "bash":
    64  			return RootCmd.GenBashCompletion(os.Stdout)
    65  		case "zsh":
    66  			return RootCmd.GenZshCompletion(os.Stdout)
    67  		case "fish":
    68  			includeDescription := true
    69  			return RootCmd.GenFishCompletion(os.Stdout, includeDescription)
    70  		}
    71  		return errors.New("Unsupported shell")
    72  	},
    73  }
    74  
    75  func init() {
    76  	RootCmd.AddCommand(completionCmd)
    77  }