/
cmd.go
182 lines (160 loc) · 4.07 KB
/
cmd.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
package gosh
import (
"context"
"errors"
"io"
"strings"
"golang.org/x/crypto/ssh"
)
var ErrNilSession = errors.New("could not start with nil session, use SetSession() to set a session")
// Cmd represents an external command being prepared or run.
//
// A Cmd cannot be reused after calling its Run, Output or CombinedOutput
// methods.
type Cmd struct {
// Path is the path of the command to run.
//
// This is the only field that must be set to a non-zero
// value. If Path is relative, it is evaluated relative
// to Dir.
Path string
// Args holds command line arguments.
// If the Args field is empty or nil, Run uses {Path}.
//
// In typical use, both Path and Args are set by calling Command.
Args []string
session *ssh.Session
ctx context.Context
}
// newCommand returns the Cmd struct to execute the named program with.
func newCommand(session *ssh.Session, name string, args ...string) *Cmd {
return &Cmd{
Path: name,
Args: args,
session: session,
}
}
// newCommandContext is like newCommand but includes a context.
func newCommandContext(ctx context.Context, session *ssh.Session, name string, args ...string) *Cmd {
if ctx == nil {
panic("nil Context")
}
cmd := newCommand(session, name, args...)
cmd.ctx = ctx
return cmd
}
// CombinedOutput runs cmd on the remote host and returns its combined
// standard output and standard error.
func (c *Cmd) CombinedOutput() ([]byte, error) {
if c.session == nil {
return nil, ErrNilSession
}
defer func() { _ = c.session.Close() }()
return c.execute(func() ([]byte, error) {
return c.session.CombinedOutput(c.String())
})
}
// Output runs cmd on the remote host and returns its standard output.
func (c *Cmd) Output() ([]byte, error) {
if c.session == nil {
return nil, ErrNilSession
}
defer func() { _ = c.session.Close() }()
return c.execute(func() ([]byte, error) {
return c.session.Output(c.String())
})
}
// OutputPipe runs cmd on the remote host.
// The reader is a pipe that will be connected to the
// remote command's standard output when the command starts.
func (c *Cmd) OutputPipe(fn func(reader io.Reader) error) error {
if c.session == nil {
return ErrNilSession
}
defer func() { _ = c.session.Close() }()
stdout, err := c.session.StdoutPipe()
if err != nil {
return err
}
err = c.session.Start(c.String())
if err != nil {
return err
}
err = fn(stdout)
if err != nil {
return err
}
return c.session.Wait()
}
// Run runs cmd on the remote host.
func (c *Cmd) Run() error {
if c.session == nil {
return ErrNilSession
}
defer func() { _ = c.session.Close() }()
_, err := c.execute(func() ([]byte, error) {
return nil, c.session.Run(c.String())
})
return err
}
// String returns a human-readable description of c.
func (c *Cmd) String() string {
b := new(strings.Builder)
b.WriteString(c.Path)
for _, a := range c.Args {
b.WriteByte(' ')
b.WriteString(a)
}
return b.String()
}
// Setenv sets session env vars.
// env specifies the environment of the process.
// Each entry is of the form "key=value", and will be ignored if it is not.
// Note: the server must be configured to `AcceptEnv line`.
func (c *Cmd) Setenv(env []string) (err error) {
if c.session == nil {
return ErrNilSession
}
var kv []string
for _, value := range env {
kv = strings.SplitN(value, "=", 2)
if len(kv) < 2 {
continue
}
if err = c.session.Setenv(kv[0], kv[1]); err != nil {
return
}
}
return
}
// SetSession sets ssh.Session of the command.
func (c *Cmd) SetSession(session *ssh.Session) {
c.session = session
}
type results struct {
output []byte
err error
}
func (c *Cmd) execute(callback func() ([]byte, error)) ([]byte, error) {
if c.ctx == nil {
return callback()
}
return c.executeWithCtx(callback)
}
func (c *Cmd) executeWithCtx(callback func() ([]byte, error)) ([]byte, error) {
done := make(chan results)
go func() {
output, err := callback()
done <- results{
output: output,
err: err,
}
}()
select {
case <-c.ctx.Done():
_ = c.session.Signal(ssh.SIGINT)
return nil, c.ctx.Err()
case result := <-done:
return result.output, result.err
}
}