-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathall.go
198 lines (172 loc) · 4.7 KB
/
all.go
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package completion
import (
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
"text/template"
"github.com/coder/serpent"
"github.com/natefinch/atomic"
)
const (
completionStartTemplate = `# ============ BEGIN {{.Name}} COMPLETION ============`
completionEndTemplate = `# ============ END {{.Name}} COMPLETION ==============`
)
type Shell interface {
Name() string
InstallPath() (string, error)
WriteCompletion(io.Writer) error
ProgramName() string
}
const (
ShellBash string = "bash"
ShellFish string = "fish"
ShellZsh string = "zsh"
ShellPowershell string = "powershell"
)
func ShellByName(shell, programName string) (Shell, error) {
switch shell {
case ShellBash:
return Bash(runtime.GOOS, programName), nil
case ShellFish:
return Fish(runtime.GOOS, programName), nil
case ShellZsh:
return Zsh(runtime.GOOS, programName), nil
case ShellPowershell:
return Powershell(runtime.GOOS, programName), nil
default:
return nil, fmt.Errorf("unsupported shell %q", shell)
}
}
func ShellOptions(choice *string) *serpent.Enum {
return serpent.EnumOf(choice, ShellBash, ShellFish, ShellZsh, ShellPowershell)
}
func DetectUserShell(programName string) (Shell, error) {
// Attempt to get the SHELL environment variable first
if shell := os.Getenv("SHELL"); shell != "" {
return ShellByName(filepath.Base(shell), "")
}
// Fallback: Look up the current user and parse /etc/passwd
currentUser, err := user.Current()
if err != nil {
return nil, err
}
// Open and parse /etc/passwd
passwdFile, err := os.ReadFile("/etc/passwd")
if err != nil {
return nil, err
}
lines := strings.Split(string(passwdFile), "\n")
for _, line := range lines {
if strings.HasPrefix(line, currentUser.Username+":") {
parts := strings.Split(line, ":")
if len(parts) > 6 {
return ShellByName(filepath.Base(parts[6]), programName) // The shell is typically the 7th field
}
}
}
return nil, fmt.Errorf("default shell not found")
}
func writeConfig(
w io.Writer,
cfgTemplate string,
programName string,
) error {
tmpl, err := template.New("script").Parse(cfgTemplate)
if err != nil {
return fmt.Errorf("parse template: %w", err)
}
err = tmpl.Execute(
w,
map[string]string{
"Name": programName,
},
)
if err != nil {
return fmt.Errorf("execute template: %w", err)
}
return nil
}
func InstallShellCompletion(shell Shell) error {
path, err := shell.InstallPath()
if err != nil {
return fmt.Errorf("get install path: %w", err)
}
var headerBuf bytes.Buffer
err = writeConfig(&headerBuf, completionStartTemplate, shell.ProgramName())
if err != nil {
return fmt.Errorf("generate header: %w", err)
}
var footerBytes bytes.Buffer
err = writeConfig(&footerBytes, completionEndTemplate, shell.ProgramName())
if err != nil {
return fmt.Errorf("generate footer: %w", err)
}
err = os.MkdirAll(filepath.Dir(path), 0o755)
if err != nil {
return fmt.Errorf("create directories: %w", err)
}
f, err := os.ReadFile(path)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("read ssh config failed: %w", err)
}
before, after, err := templateConfigSplit(headerBuf.Bytes(), footerBytes.Bytes(), f)
if err != nil {
return err
}
outBuf := bytes.Buffer{}
_, _ = outBuf.Write(before)
if len(before) > 0 {
_, _ = outBuf.Write([]byte("\n"))
}
_, _ = outBuf.Write(headerBuf.Bytes())
err = shell.WriteCompletion(&outBuf)
if err != nil {
return fmt.Errorf("generate completion: %w", err)
}
_, _ = outBuf.Write(footerBytes.Bytes())
_, _ = outBuf.Write([]byte("\n"))
_, _ = outBuf.Write(after)
err = atomic.WriteFile(path, &outBuf)
if err != nil {
return fmt.Errorf("write completion: %w", err)
}
return nil
}
func templateConfigSplit(header, footer, data []byte) (before, after []byte, err error) {
startCount := bytes.Count(data, header)
endCount := bytes.Count(data, footer)
if startCount > 1 || endCount > 1 {
return nil, nil, fmt.Errorf("Malformed config file: multiple config sections")
}
startIndex := bytes.Index(data, header)
endIndex := bytes.Index(data, footer)
if startIndex == -1 && endIndex != -1 {
return data, nil, fmt.Errorf("Malformed config file: missing completion header")
}
if startIndex != -1 && endIndex == -1 {
return data, nil, fmt.Errorf("Malformed config file: missing completion footer")
}
if startIndex != -1 && endIndex != -1 {
if startIndex > endIndex {
return data, nil, fmt.Errorf("Malformed config file: completion header after footer")
}
// Include leading and trailing newline, if present
start := startIndex
if start > 0 {
start--
}
end := endIndex + len(footer)
if end < len(data) {
end++
}
return data[:start], data[end:], nil
}
return data, nil, nil
}