forked from charmbracelet/wishlist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
74 lines (63 loc) · 1.5 KB
/
client.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 wishlist
import (
"errors"
"fmt"
"io"
"log"
gossh "golang.org/x/crypto/ssh"
)
// SSHClient is a SSH client.
type SSHClient interface {
Connect(e *Endpoint) error
}
func createSession(conf *gossh.ClientConfig, e *Endpoint) (*gossh.Session, *gossh.Client, closers, error) {
var cl closers
conn, err := gossh.Dial("tcp", e.Address, conf)
if err != nil {
return nil, nil, cl, fmt.Errorf("connection failed: %w", err)
}
cl = append(cl, conn.Close)
session, err := conn.NewSession()
if err != nil {
return nil, conn, cl, fmt.Errorf("failed to open session: %w", err)
}
cl = append(cl, session.Close)
return session, conn, cl, nil
}
func shellAndWait(session *gossh.Session) error {
log.Println("requesting shell")
if err := session.Shell(); err != nil {
return fmt.Errorf("failed to start shell: %w", err)
}
if err := session.Wait(); err != nil {
return fmt.Errorf("session failed: %w", err)
}
return nil
}
func runAndWait(session *gossh.Session, cmd string) error {
log.Printf("running %q", cmd)
if err := session.Run(cmd); err != nil {
return fmt.Errorf("failed to run %q: %w", cmd, err)
}
return nil
}
type closers []func() error
func (c closers) close() {
for _, closer := range c {
if err := closer(); err != nil {
if errors.Is(err, io.EOF) {
// do not print EOF errors... not a big deal anyway
continue
}
log.Println("failed to close:", err)
}
}
}
func firstNonEmpty(ss ...string) string {
for _, s := range ss {
if s != "" {
return s
}
}
return ""
}