1// Copyright 2019 CUE Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package cmd
16
17import (
18	"fmt"
19
20	"github.com/spf13/cobra"
21)
22
23var validCompletionArgs = []string{"bash", "zsh", "fish", "powershell"}
24
25const completionExample = `
26Bash:
27
28$ source <(cue completion bash)
29
30# To load completions for each session, execute once:
31Linux:
32  $ cue completion bash > /etc/bash_completion.d/cue
33MacOS:
34  $ cue completion bash > /usr/local/etc/bash_completion.d/cue
35
36Zsh:
37
38$ source <(cue completion zsh)
39
40# To load completions for each session, execute once:
41$ cue completion zsh > "${fpath[1]}/_cue"
42
43Fish:
44
45$ cue completion fish | source
46
47# To load completions for each session, execute once:
48$ cue completion fish > ~/.config/fish/completions/cue.fish
49`
50
51func newCompletionCmd(c *Command) *cobra.Command {
52	cmd := &cobra.Command{
53		Use:       fmt.Sprintf("completion %s", validCompletionArgs),
54		Short:     "Generate completion script",
55		Long:      ``,
56		Example:   completionExample,
57		ValidArgs: validCompletionArgs,
58		Args:      cobra.ExactValidArgs(1),
59		RunE:      mkRunE(c, runCompletion),
60	}
61	return cmd
62}
63
64func runCompletion(cmd *Command, args []string) error {
65	w := cmd.OutOrStdout()
66	switch args[0] {
67	case "bash":
68		cmd.Root().GenBashCompletion(w)
69	case "zsh":
70		cmd.Root().GenZshCompletion(w)
71	case "fish":
72		cmd.Root().GenFishCompletion(w, true)
73	case "powershell":
74		cmd.Root().GenPowerShellCompletion(w)
75	default:
76		return fmt.Errorf("%s is not a supported shell", args[0])
77	}
78	return nil
79}
80