|
1 | 1 | package completion
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "bytes" |
| 5 | + "errors" |
4 | 6 | "fmt"
|
5 | 7 | "io"
|
| 8 | + "io/fs" |
6 | 9 | "os"
|
7 | 10 | "os/user"
|
8 | 11 | "path/filepath"
|
| 12 | + "runtime" |
9 | 13 | "strings"
|
10 | 14 | "text/template"
|
11 | 15 |
|
12 | 16 | "github.com/coder/serpent"
|
| 17 | + |
| 18 | + "github.com/natefinch/atomic" |
13 | 19 | )
|
14 | 20 |
|
15 | 21 | const (
|
16 |
| - BashShell string = "bash" |
17 |
| - FishShell string = "fish" |
18 |
| - ZShell string = "zsh" |
19 |
| - Powershell string = "powershell" |
| 22 | + completionStartTemplate = `# ============ BEGIN {{.Name}} COMPLETION ============` |
| 23 | + completionEndTemplate = `# ============ END {{.Name}} COMPLETION ==============` |
20 | 24 | )
|
21 | 25 |
|
22 |
| -var shellCompletionByName = map[string]func(io.Writer, string) error{ |
23 |
| - BashShell: generateCompletion(bashCompletionTemplate), |
24 |
| - FishShell: generateCompletion(fishCompletionTemplate), |
25 |
| - ZShell: generateCompletion(zshCompletionTemplate), |
26 |
| - Powershell: generateCompletion(pshCompletionTemplate), |
| 26 | +type Shell interface { |
| 27 | + Name() string |
| 28 | + InstallPath() (string, error) |
| 29 | + WriteCompletion(io.Writer) error |
| 30 | + ProgramName() string |
27 | 31 | }
|
28 | 32 |
|
29 |
| -func ShellOptions(choice *string) *serpent.Enum { |
30 |
| - return serpent.EnumOf(choice, BashShell, FishShell, ZShell, Powershell) |
31 |
| -} |
| 33 | +const ( |
| 34 | + ShellBash string = "bash" |
| 35 | + ShellFish string = "fish" |
| 36 | + ShellZsh string = "zsh" |
| 37 | + ShellPowershell string = "powershell" |
| 38 | +) |
32 | 39 |
|
33 |
| -func WriteCompletion(writer io.Writer, shell string, cmdName string) error { |
34 |
| - fn, ok := shellCompletionByName[shell] |
35 |
| - if !ok { |
36 |
| - return fmt.Errorf("unknown shell %q", shell) |
| 40 | +func ShellByName(shell, programName string) (Shell, error) { |
| 41 | + switch shell { |
| 42 | + case ShellBash: |
| 43 | + return Bash(runtime.GOOS, programName), nil |
| 44 | + case ShellFish: |
| 45 | + return Fish(runtime.GOOS, programName), nil |
| 46 | + case ShellZsh: |
| 47 | + return Zsh(runtime.GOOS, programName), nil |
| 48 | + case ShellPowershell: |
| 49 | + return Powershell(runtime.GOOS, programName), nil |
| 50 | + default: |
| 51 | + return nil, fmt.Errorf("unsupported shell %q", shell) |
37 | 52 | }
|
38 |
| - fn(writer, cmdName) |
39 |
| - return nil |
40 | 53 | }
|
41 | 54 |
|
42 |
| -func DetectUserShell() (string, error) { |
| 55 | +func ShellOptions(choice *string) *serpent.Enum { |
| 56 | + return serpent.EnumOf(choice, ShellBash, ShellFish, ShellZsh, ShellPowershell) |
| 57 | +} |
| 58 | + |
| 59 | +func DetectUserShell(programName string) (Shell, error) { |
43 | 60 | // Attempt to get the SHELL environment variable first
|
44 | 61 | if shell := os.Getenv("SHELL"); shell != "" {
|
45 |
| - return filepath.Base(shell), nil |
| 62 | + return ShellByName(filepath.Base(shell), "") |
46 | 63 | }
|
47 | 64 |
|
48 | 65 | // Fallback: Look up the current user and parse /etc/passwd
|
49 | 66 | currentUser, err := user.Current()
|
50 | 67 | if err != nil {
|
51 |
| - return "", err |
| 68 | + return nil, err |
52 | 69 | }
|
53 | 70 |
|
54 | 71 | // Open and parse /etc/passwd
|
55 | 72 | passwdFile, err := os.ReadFile("/etc/passwd")
|
56 | 73 | if err != nil {
|
57 |
| - return "", err |
| 74 | + return nil, err |
58 | 75 | }
|
59 | 76 |
|
60 | 77 | lines := strings.Split(string(passwdFile), "\n")
|
61 | 78 | for _, line := range lines {
|
62 | 79 | if strings.HasPrefix(line, currentUser.Username+":") {
|
63 | 80 | parts := strings.Split(line, ":")
|
64 | 81 | if len(parts) > 6 {
|
65 |
| - return filepath.Base(parts[6]), nil // The shell is typically the 7th field |
| 82 | + return ShellByName(filepath.Base(parts[6]), programName) // The shell is typically the 7th field |
66 | 83 | }
|
67 | 84 | }
|
68 | 85 | }
|
69 | 86 |
|
70 |
| - return "", fmt.Errorf("default shell not found") |
| 87 | + return nil, fmt.Errorf("default shell not found") |
71 | 88 | }
|
72 | 89 |
|
73 |
| -func generateCompletion( |
74 |
| - scriptTemplate string, |
75 |
| -) func(io.Writer, string) error { |
76 |
| - return func(w io.Writer, rootCmdName string) error { |
77 |
| - tmpl, err := template.New("script").Parse(scriptTemplate) |
78 |
| - if err != nil { |
79 |
| - return fmt.Errorf("parse template: %w", err) |
80 |
| - } |
| 90 | +func writeConfig( |
| 91 | + w io.Writer, |
| 92 | + cfgTemplate string, |
| 93 | + programName string, |
| 94 | +) error { |
| 95 | + tmpl, err := template.New("script").Parse(cfgTemplate) |
| 96 | + if err != nil { |
| 97 | + return fmt.Errorf("parse template: %w", err) |
| 98 | + } |
81 | 99 |
|
82 |
| - err = tmpl.Execute( |
83 |
| - w, |
84 |
| - map[string]string{ |
85 |
| - "Name": rootCmdName, |
86 |
| - }, |
87 |
| - ) |
88 |
| - if err != nil { |
89 |
| - return fmt.Errorf("execute template: %w", err) |
90 |
| - } |
| 100 | + err = tmpl.Execute( |
| 101 | + w, |
| 102 | + map[string]string{ |
| 103 | + "Name": programName, |
| 104 | + }, |
| 105 | + ) |
| 106 | + if err != nil { |
| 107 | + return fmt.Errorf("execute template: %w", err) |
| 108 | + } |
| 109 | + |
| 110 | + return nil |
| 111 | +} |
| 112 | + |
| 113 | +func InstallShellCompletion(shell Shell) error { |
| 114 | + path, err := shell.InstallPath() |
| 115 | + if err != nil { |
| 116 | + return fmt.Errorf("get install path: %w", err) |
| 117 | + } |
| 118 | + var headerBuf bytes.Buffer |
| 119 | + err = writeConfig(&headerBuf, completionStartTemplate, shell.ProgramName()) |
| 120 | + if err != nil { |
| 121 | + return fmt.Errorf("generate header: %w", err) |
| 122 | + } |
| 123 | + |
| 124 | + var footerBytes bytes.Buffer |
| 125 | + err = writeConfig(&footerBytes, completionEndTemplate, shell.ProgramName()) |
| 126 | + if err != nil { |
| 127 | + return fmt.Errorf("generate footer: %w", err) |
| 128 | + } |
91 | 129 |
|
92 |
| - return nil |
| 130 | + err = os.MkdirAll(filepath.Dir(path), 0o755) |
| 131 | + if err != nil { |
| 132 | + return fmt.Errorf("create directories: %w", err) |
| 133 | + } |
| 134 | + |
| 135 | + f, err := os.ReadFile(path) |
| 136 | + if err != nil && !errors.Is(err, fs.ErrNotExist) { |
| 137 | + return fmt.Errorf("read ssh config failed: %w", err) |
| 138 | + } |
| 139 | + |
| 140 | + before, after, err := templateConfigSplit(headerBuf.Bytes(), footerBytes.Bytes(), f) |
| 141 | + if err != nil { |
| 142 | + return err |
| 143 | + } |
| 144 | + |
| 145 | + outBuf := bytes.Buffer{} |
| 146 | + _, _ = outBuf.Write(before) |
| 147 | + if len(before) > 0 { |
| 148 | + _, _ = outBuf.Write([]byte("\n")) |
| 149 | + } |
| 150 | + _, _ = outBuf.Write(headerBuf.Bytes()) |
| 151 | + err = shell.WriteCompletion(&outBuf) |
| 152 | + if err != nil { |
| 153 | + return fmt.Errorf("generate completion: %w", err) |
| 154 | + } |
| 155 | + _, _ = outBuf.Write(footerBytes.Bytes()) |
| 156 | + _, _ = outBuf.Write([]byte("\n")) |
| 157 | + _, _ = outBuf.Write(after) |
| 158 | + |
| 159 | + err = atomic.WriteFile(path, &outBuf) |
| 160 | + if err != nil { |
| 161 | + return fmt.Errorf("write completion: %w", err) |
| 162 | + } |
| 163 | + |
| 164 | + return nil |
| 165 | +} |
| 166 | + |
| 167 | +func templateConfigSplit(header, footer, data []byte) (before, after []byte, err error) { |
| 168 | + startCount := bytes.Count(data, header) |
| 169 | + endCount := bytes.Count(data, footer) |
| 170 | + if startCount > 1 || endCount > 1 { |
| 171 | + return nil, nil, fmt.Errorf("Malformed config file: multiple config sections") |
| 172 | + } |
| 173 | + |
| 174 | + startIndex := bytes.Index(data, header) |
| 175 | + endIndex := bytes.Index(data, footer) |
| 176 | + if startIndex == -1 && endIndex != -1 { |
| 177 | + return data, nil, fmt.Errorf("Malformed config file: missing completion header") |
| 178 | + } |
| 179 | + if startIndex != -1 && endIndex == -1 { |
| 180 | + return data, nil, fmt.Errorf("Malformed config file: missing completion footer") |
| 181 | + } |
| 182 | + if startIndex != -1 && endIndex != -1 { |
| 183 | + if startIndex > endIndex { |
| 184 | + return data, nil, fmt.Errorf("Malformed config file: completion header after footer") |
| 185 | + } |
| 186 | + // Include leading and trailing newline, if present |
| 187 | + start := startIndex |
| 188 | + if start > 0 { |
| 189 | + start-- |
| 190 | + } |
| 191 | + end := endIndex + len(footer) |
| 192 | + if end < len(data) { |
| 193 | + end++ |
| 194 | + } |
| 195 | + return data[:start], data[end:], nil |
93 | 196 | }
|
| 197 | + return data, nil, nil |
94 | 198 | }
|
0 commit comments