-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
74 lines (62 loc) · 1.99 KB
/
main.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
package main
import (
"fmt"
"os"
"os/exec"
"syscall"
tea "github.com/charmbracelet/bubbletea"
)
// sshExecutableName is the name of the SSH executable present on the local system.
const sshExecutableName = "ssh"
var (
sshConfigPath = fmt.Sprintf("%s/%s", userHomeDir(), ".ssh/config")
recentlyUsedPath = fmt.Sprintf("%s/%s", userHomeDir(), ".ssh/recent.json")
sshControlPath = "/dev/shm/control:%h:%p:%r"
sshControlChildOpts = []string{"-S", sshControlPath}
sshControlParentOpts = []string{"-T", "-o", "ControlMaster=yes", "-o", "ControlPersist=5s", "-o", fmt.Sprintf("ControlPath=%s", sshControlPath)}
)
func main() {
sshExecutablePath := verifyExecutable(sshExecutableName)
items, err := sshConfigHosts(sshConfigPath)
if err != nil {
fmt.Println("failed to read SSH configuration: %w", err)
os.Exit(1)
}
itemsToJson(recentlyUsedPath, items, false)
sortedItems, err := itemsFromJson(recentlyUsedPath)
if err != nil {
fmt.Println("failed to sort items: %w", err)
os.Exit(1)
}
p := tea.NewProgram(newModel(items, sortedItems), tea.WithAltScreen())
m, err := p.Run()
if err != nil {
fmt.Println("failed to execute: %w", err)
os.Exit(1)
}
if m, ok := m.(model); ok && m.choice != "" {
fmt.Printf("Connected in %v\n", m.connection.startupTime)
fmt.Println(m.connection.output)
runExecutable(sshExecutablePath, append([]string{sshExecutableName, m.choice}, sshControlChildOpts...))
} else if m.err != "" {
fmt.Printf("Unable to connect:\n\n")
fmt.Print(m.err)
os.Exit(1)
}
}
func verifyExecutable(execName string) string {
path, err := exec.LookPath(execName)
// using 'panic()' as it's supposedly acceptable during initialization phases
// https://go.dev/doc/effective_go#panic
if err != nil {
panic(err)
}
return path
}
func runExecutable(execPath string, args []string) error {
err := syscall.Exec(execPath, args, os.Environ())
if err != nil {
return fmt.Errorf("unable to run executable '%s' with args '%v': %w", execPath, args, err)
}
return nil
}