-
Notifications
You must be signed in to change notification settings - Fork 132
/
cmd.go
121 lines (97 loc) · 2.51 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
// Copyright 2020 Mohammed El Bahja. All rights reserved.
// Use of this source code is governed by a MIT license.
package goph
import (
"context"
"fmt"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
"strings"
)
// Cmd it's like os/exec.Cmd but for ssh session.
type Cmd struct {
// Path to command executable filename
Path string
// Command args.
Args []string
// Session env vars.
Env []string
// SSH session.
*ssh.Session
// Context for cancellation
Context context.Context
}
// CombinedOutput runs cmd on the remote host and returns its combined stdout and stderr.
func (c *Cmd) CombinedOutput() ([]byte, error) {
if err := c.init(); err != nil {
return nil, errors.Wrap(err, "cmd init")
}
return c.runWithContext(func() ([]byte, error) {
return c.Session.CombinedOutput(c.String())
})
}
// Output runs cmd on the remote host and returns its stdout.
func (c *Cmd) Output() ([]byte, error) {
if err := c.init(); err != nil {
return nil, errors.Wrap(err, "cmd init")
}
return c.runWithContext(func() ([]byte, error) {
return c.Session.Output(c.String())
})
}
// Run runs cmd on the remote host.
func (c *Cmd) Run() error {
if err := c.init(); err != nil {
return errors.Wrap(err, "cmd init")
}
_, err := c.runWithContext(func() ([]byte, error) {
return nil, c.Session.Run(c.String())
})
return err
}
// Start runs the command on the remote host.
func (c *Cmd) Start() error {
if err := c.init(); err != nil {
return errors.Wrap(err, "cmd init")
}
return c.Session.Start(c.String())
}
// String return the command line string.
func (c *Cmd) String() string {
return fmt.Sprintf("%s %s", c.Path, strings.Join(c.Args, " "))
}
// Init inits and sets session env vars.
func (c *Cmd) init() (err error) {
// Set session env vars
var env []string
for _, value := range c.Env {
env = strings.Split(value, "=")
if err = c.Setenv(env[0], strings.Join(env[1:], "=")); err != nil {
return
}
}
return nil
}
// Command with context output.
type ctxCmdOutput struct {
output []byte
err error
}
// Executes the given callback within session. Sends SIGINT when the context is canceled.
func (c *Cmd) runWithContext(callback func() ([]byte, error)) ([]byte, error) {
outputChan := make(chan ctxCmdOutput)
go func() {
output, err := callback()
outputChan <- ctxCmdOutput{
output: output,
err: err,
}
}()
select {
case <-c.Context.Done():
_ = c.Session.Signal(ssh.SIGINT)
return nil, c.Context.Err()
case result := <-outputChan:
return result.output, result.err
}
}