-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
502 lines (417 loc) · 9.97 KB
/
main.go
File metadata and controls
502 lines (417 loc) · 9.97 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
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/log"
"github.com/sahilm/fuzzy"
"gopkg.in/yaml.v3"
)
const version = "1.1.0"
type Shell struct {
Name string `yaml:"name"`
Command string `yaml:"command"`
Default bool `yaml:"default"`
}
type Config struct {
Shells []Shell `yaml:"shells"`
ShowSearch bool `yaml:"show_search"`
}
type model struct {
shells []Shell
filtered []Shell
cursor int
selected *Shell
query string
width int
height int
quitting bool
showError bool
showSearch bool
}
type clearErrorMsg struct{}
var (
normalStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("252"))
selectedStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("30")).
Bold(true)
borderStyle = lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("240")).
Padding(1, 3)
errorBorderStyle = lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("124")).
Padding(1, 3)
errorTextStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("124")).
Bold(true)
dimStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("240"))
inputStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("252"))
)
func getConfigPath() string {
configDir := os.Getenv("XDG_CONFIG_HOME")
if configDir == "" {
home, err := os.UserHomeDir()
if err != nil {
log.Fatal("Could not determine home directory", "error", err)
}
configDir = filepath.Join(home, ".config")
}
return filepath.Join(configDir, "session-picker", "config.yaml")
}
func ensureConfigDir() error {
configPath := getConfigPath()
configDir := filepath.Dir(configPath)
return os.MkdirAll(configDir, 0755)
}
func loadConfig() (Config, error) {
var config Config
configPath := getConfigPath()
data, err := os.ReadFile(configPath)
if err != nil {
return config, err
}
err = yaml.Unmarshal(data, &config)
return config, err
}
func validateConfig(config Config) error {
if len(config.Shells) == 0 {
return fmt.Errorf("no shells configured")
}
defaultCount := 0
names := make(map[string]bool)
for i, shell := range config.Shells {
if shell.Name == "" {
return fmt.Errorf("shell at index %d has no name", i)
}
if shell.Command == "" {
return fmt.Errorf("shell '%s' has no command", shell.Name)
}
if names[shell.Name] {
return fmt.Errorf("duplicate shell name: '%s'", shell.Name)
}
names[shell.Name] = true
if shell.Default {
defaultCount++
}
}
if defaultCount > 1 {
return fmt.Errorf("multiple shells marked as default (only one allowed)")
}
return nil
}
func createDefaultConfig() error {
if err := ensureConfigDir(); err != nil {
return err
}
configPath := getConfigPath()
if _, err := os.Stat(configPath); err == nil {
return nil // Config already exists
}
defaultConfig := `# Show the search input box (fuzzy search works regardless)
show_search: false
shells:
- name: "Local"
command: "exec $SHELL"
default: true
# - name: "Server"
# command: "ssh user@server"
`
return os.WriteFile(configPath, []byte(defaultConfig), 0644)
}
func sortShellsWithDefaultFirst(shells []Shell) []Shell {
result := make([]Shell, 0, len(shells))
var others []Shell
for _, s := range shells {
if s.Default {
result = append(result, s)
} else {
others = append(others, s)
}
}
return append(result, others...)
}
func initialModel(config Config) model {
sorted := sortShellsWithDefaultFirst(config.Shells)
return model{
shells: sorted,
filtered: sorted,
cursor: 0,
showSearch: config.ShowSearch,
}
}
func (m model) Init() tea.Cmd {
return nil
}
func clearErrorAfter(d time.Duration) tea.Cmd {
return tea.Tick(d, func(t time.Time) tea.Msg {
return clearErrorMsg{}
})
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case clearErrorMsg:
m.showError = false
return m, nil
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
return m, nil
case tea.KeyMsg:
switch msg.Type {
case tea.KeyCtrlC:
m.quitting = true
return m, tea.Quit
case tea.KeyEsc:
if m.query != "" {
m.query = ""
m.filterShells()
return m, nil
}
m.showError = true
return m, clearErrorAfter(700 * time.Millisecond)
case tea.KeyEnter:
if len(m.filtered) > 0 && m.cursor < len(m.filtered) {
m.selected = &m.filtered[m.cursor]
}
return m, tea.Quit
case tea.KeyUp:
if m.cursor > 0 {
m.cursor--
}
return m, nil
case tea.KeyDown:
if m.cursor < len(m.filtered)-1 {
m.cursor++
}
return m, nil
case tea.KeyBackspace:
if len(m.query) > 0 {
m.query = m.query[:len(m.query)-1]
m.filterShells()
}
return m, nil
default:
if msg.Type == tea.KeyRunes {
m.query += string(msg.Runes)
m.filterShells()
}
return m, nil
}
}
return m, nil
}
func (m *model) filterShells() {
if m.query == "" {
m.filtered = m.shells
m.cursor = 0
return
}
names := make([]string, len(m.shells))
for i, s := range m.shells {
names[i] = s.Name
}
matches := fuzzy.Find(m.query, names)
matched := make([]Shell, len(matches))
for i, match := range matches {
matched[i] = m.shells[match.Index]
}
m.filtered = sortShellsWithDefaultFirst(matched)
if m.cursor >= len(m.filtered) {
m.cursor = max(0, len(m.filtered)-1)
}
}
func (m model) View() string {
if m.quitting && m.selected == nil {
return ""
}
var b strings.Builder
// Show search box if enabled
if m.showSearch && !m.showError {
if m.query == "" {
b.WriteString(dimStyle.Render("> type to search..."))
} else {
b.WriteString(inputStyle.Render("> " + m.query))
}
b.WriteString("\n\n")
}
if m.showError {
b.WriteString(errorTextStyle.Render("ERROR: You have to pick a shell"))
} else if len(m.filtered) == 0 {
b.WriteString(dimStyle.Render("no matches"))
} else {
for i, shell := range m.filtered {
style := normalStyle
if i == m.cursor {
style = selectedStyle
}
b.WriteString(style.Render(shell.Name))
if i < len(m.filtered)-1 {
b.WriteString("\n")
}
}
}
border := borderStyle
if m.showError {
border = errorBorderStyle
}
content := border.Render(b.String())
if m.width > 0 && m.height > 0 {
return lipgloss.Place(
m.width,
m.height,
lipgloss.Center,
lipgloss.Center,
content,
)
}
return content
}
func printHelp() {
help := `sp - Session Picker v` + version + `
A simple, configurable terminal session picker TUI for quickly
connecting to different shells and remote hosts.
Usage:
sp Launch the session picker
sp help Show this help message
sp config Open config file in $EDITOR
sp config -v Validate config file
sp version Show version
Config location: ` + getConfigPath() + `
Config format:
show_search: false # Show/hide the search input box
shells:
- name: "Local"
command: "exec $SHELL"
default: true
- name: "Server"
command: "ssh user@server"
Controls:
Up/Down Navigate
Enter Select session
Esc Clear search / Show error if empty
Type Fuzzy search
Ctrl+C Quit
`
fmt.Print(help)
}
func printVersion() {
fmt.Printf("sp version %s\n", version)
}
func openConfig() {
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "vi"
}
configPath := getConfigPath()
// Create default config if it doesn't exist
if err := createDefaultConfig(); err != nil {
log.Error("Failed to create config directory", "error", err)
os.Exit(1)
}
// Create empty config if file doesn't exist
if _, err := os.Stat(configPath); os.IsNotExist(err) {
if err := createDefaultConfig(); err != nil {
log.Error("Failed to create default config", "error", err)
os.Exit(1)
}
}
cmd := exec.Command(editor, configPath)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Error("Failed to open editor", "error", err)
os.Exit(1)
}
// Validate after editing
config, err := loadConfig()
if err != nil {
log.Error("Failed to load config after editing", "error", err)
os.Exit(1)
}
if err := validateConfig(config); err != nil {
log.Error("Config validation failed", "error", err)
os.Exit(1)
}
log.Info("Config is valid", "shells", len(config.Shells))
}
func validateConfigCmd() {
config, err := loadConfig()
if err != nil {
log.Error("Failed to load config", "error", err)
os.Exit(1)
}
if err := validateConfig(config); err != nil {
log.Error("Config validation failed", "error", err)
os.Exit(1)
}
log.Info("Config is valid", "shells", len(config.Shells))
}
func main() {
args := os.Args[1:]
if len(args) > 0 {
switch args[0] {
case "help", "-h", "--help":
printHelp()
return
case "version", "-v", "--version":
printVersion()
return
case "config":
if len(args) > 1 && (args[1] == "-v" || args[1] == "--validate") {
validateConfigCmd()
return
}
openConfig()
return
default:
fmt.Fprintf(os.Stderr, "Unknown command: %s\n", args[0])
fmt.Fprintln(os.Stderr, "Run 'sp help' for usage.")
os.Exit(1)
}
}
// Create default config if none exists
if err := createDefaultConfig(); err != nil {
log.Error("Failed to create config", "error", err)
os.Exit(1)
}
config, err := loadConfig()
if err != nil {
log.Error("Failed to load config", "error", err, "path", getConfigPath())
log.Info("Run 'sp config' to create a config file")
os.Exit(1)
}
if err := validateConfig(config); err != nil {
log.Error("Invalid config", "error", err)
os.Exit(1)
}
p := tea.NewProgram(
initialModel(config),
tea.WithAltScreen(),
)
result, err := p.Run()
if err != nil {
log.Error("Failed to run", "error", err)
os.Exit(1)
}
m := result.(model)
if m.selected != nil {
shell := os.Getenv("SHELL")
if shell == "" {
shell = "/bin/sh"
}
args := []string{shell, "-c", m.selected.Command}
syscall.Exec(shell, args, os.Environ())
}
}