-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui.go
109 lines (97 loc) · 2.45 KB
/
ui.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
package main
import (
"bufio"
"errors"
"fmt"
"os"
"slices"
"strings"
"time"
"github.com/gdamore/tcell/v2"
tv "github.com/rivo/tview"
)
func loadServerTree(mountPoint *tv.TreeNode, sshEntries []*SSHEntry) error {
if mountPoint == nil {
return errors.New("mountPoint is nil")
}
for _, entry := range sshEntries {
parts := strings.Split(entry.displayName, ":")
parent := mountPoint
for i, part := range parts {
var curNode *tv.TreeNode
existNodes := parent.GetChildren()
index := slices.IndexFunc(existNodes, func(node *tv.TreeNode) bool {
return node.GetText() == part
})
if index < 0 {
curNode = tv.NewTreeNode(part)
parent.AddChild(curNode)
} else {
curNode = existNodes[index]
}
if i == len(parts)-1 {
curNode.SetReference(entry)
} else {
curNode.SetColor(tcell.ColorBlue)
}
curNode.SetSelectable(true)
parent = curNode
}
}
return nil
}
func createServerTree(configFiles ...string) (*tv.TreeView, error) {
serverTree := tv.NewTreeView()
serverTree.SetBorder(true)
serverTree.SetTitle("available servers")
rootNode := tv.NewTreeNode("servers")
serverTree.SetRoot(rootNode).SetCurrentNode(rootNode)
for _, configFile := range configFiles {
entries, err := loadSSHConfigFile(configFile)
if err != nil {
return serverTree, err
}
loadServerTree(rootNode, entries)
}
serverTree.SetChangedFunc(func(node *tv.TreeNode) {
if len(node.GetChildren()) != 0 {
return
}
// for leaf node
serverView.SetText(fmt.Sprint(node.GetReference().(*SSHEntry)))
})
serverTree.SetSelectedFunc(func(node *tv.TreeNode) {
// for non-leaf node
if len(node.GetChildren()) != 0 {
node.SetExpanded(!node.IsExpanded())
return
}
// for leaf node
entry := node.GetReference().(*SSHEntry)
msg := errView.GetText(true)
msg += logMsg(fmt.Sprintf("connecting to %s...", entry.displayName))
errView.SetText(msg)
errView.ScrollToEnd()
// run command
app.Suspend(func() {
// at this time, the terminal is used by this function
if isTmuxRunning() {
sshShellTmux(entry)
} else {
err := sshShell2(entry)
if err != nil {
fmt.Println(err)
fmt.Print("Press 'Enter' to continue...")
bufio.NewReader(os.Stdin).ReadBytes('\n')
}
}
})
})
return serverTree, nil
}
func logMsg(msg string) string {
now := time.Now()
return fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d %s\n",
now.Year(), now.Month(), now.Day(),
now.Hour(), now.Minute(), now.Second(), msg)
}