-
Notifications
You must be signed in to change notification settings - Fork 0
/
localhost.go
119 lines (95 loc) · 2.25 KB
/
localhost.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
package sup
import (
"fmt"
"io"
"os"
"os/exec"
"os/user"
"github.com/pkg/errors"
)
// Client is a wrapper over the SSH connection/sessions.
type LocalhostClient struct {
cmd *exec.Cmd
user string
stdin io.WriteCloser
stdout io.Reader
stderr io.Reader
running bool
env string //export FOO="bar"; export BAR="baz";
}
func (c *LocalhostClient) Connect(_ string) error {
u, err := user.Current()
if err != nil {
return err
}
c.user = u.Username
return nil
}
func (c *LocalhostClient) Run(task *Task) error {
var err error
if c.running {
return fmt.Errorf("Command already running")
}
cmd := exec.Command("bash", "-c", c.env+task.Run)
c.cmd = cmd
c.stdout, err = cmd.StdoutPipe()
if err != nil {
return err
}
c.stderr, err = cmd.StderrPipe()
if err != nil {
return err
}
c.stdin, err = cmd.StdinPipe()
if err != nil {
return err
}
if err := c.cmd.Start(); err != nil {
return ErrTask{task, err.Error()}
}
c.running = true
return nil
}
func (c *LocalhostClient) Wait() error {
if !c.running {
return fmt.Errorf("Trying to wait on stopped command")
}
err := c.cmd.Wait()
c.running = false
return err
}
func (c *LocalhostClient) Close() error {
return nil
}
func (c *LocalhostClient) Stdin() io.WriteCloser {
return c.stdin
}
func (c *LocalhostClient) Stderr() io.Reader {
return c.stderr
}
func (c *LocalhostClient) Stdout() io.Reader {
return c.stdout
}
func (c *LocalhostClient) Prefix() (string, int) {
host := c.user + "@localhost" + " | "
return ResetColor + host, len(host)
}
func (c *LocalhostClient) Write(p []byte) (n int, err error) {
return c.stdin.Write(p)
}
func (c *LocalhostClient) WriteClose() error {
return c.stdin.Close()
}
func (c *LocalhostClient) Signal(sig os.Signal) error {
return c.cmd.Process.Signal(sig)
}
func ResolveLocalPath(cwd, path, env string) (string, error) {
// Check if file exists first. Use bash to resolve $ENV_VARs.
cmd := exec.Command("bash", "-c", env+"echo -n "+path)
cmd.Dir = cwd
resolvedFilename, err := cmd.Output()
if err != nil {
return "", errors.Wrap(err, "resolving path failed")
}
return string(resolvedFilename), nil
}