-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathcompletion.go
More file actions
97 lines (91 loc) · 2.6 KB
/
completion.go
File metadata and controls
97 lines (91 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package cli
import (
"fmt"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/serpent"
"github.com/coder/serpent/completion"
)
func (*RootCmd) completion() *serpent.Command {
var shellName string
var printOutput bool
shellOptions := completion.ShellOptions(&shellName)
return &serpent.Command{
Use: "completion",
Short: "Install or update shell completion scripts for the detected or chosen shell.",
Options: []serpent.Option{
{
Flag: "shell",
FlagShorthand: "s",
Description: "The shell to install completion for.",
Value: shellOptions,
},
{
Flag: "print",
Description: "Print the completion script instead of installing it.",
FlagShorthand: "p",
Value: serpent.BoolOf(&printOutput),
},
},
Handler: func(inv *serpent.Invocation) error {
if shellName != "" {
shell, err := completion.ShellByName(shellName, inv.Command.Parent.Name())
if err != nil {
return err
}
if printOutput {
return shell.WriteCompletion(inv.Stdout)
}
return installCompletion(inv, shell)
}
shell, err := completion.DetectUserShell(inv.Command.Parent.Name())
if err == nil {
return installCompletion(inv, shell)
}
if !isTTYOut(inv) {
return xerrors.New("could not detect the current shell, please specify one with --shell or run interactively")
}
// Silently continue to the shell selection if detecting failed in interactive mode
choice, err := cliui.Select(inv, cliui.SelectOptions{
Message: "Select a shell to install completion for:",
Options: shellOptions.Choices,
})
if err != nil {
return err
}
shellChoice, err := completion.ShellByName(choice, inv.Command.Parent.Name())
if err != nil {
return err
}
if printOutput {
return shellChoice.WriteCompletion(inv.Stdout)
}
return installCompletion(inv, shellChoice)
},
}
}
func installCompletion(inv *serpent.Invocation, shell completion.Shell) error {
path, err := shell.InstallPath()
if err != nil {
cliui.Error(inv.Stderr, fmt.Sprintf("Failed to determine completion path %v", err))
return shell.WriteCompletion(inv.Stdout)
}
if !isTTYOut(inv) {
return shell.WriteCompletion(inv.Stdout)
}
choice, err := cliui.Select(inv, cliui.SelectOptions{
Options: []string{
"Confirm",
"Print to terminal",
},
Message: fmt.Sprintf("Install completion for %s at %s?", shell.Name(), path),
HideSearch: true,
})
if err != nil {
return err
}
if choice == "Print to terminal" {
return shell.WriteCompletion(inv.Stdout)
}
return completion.InstallShellCompletion(shell)
}