forked from charmbracelet/freeze
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pty.go
54 lines (47 loc) · 1.12 KB
/
pty.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
//go:build !windows
// +build !windows
package main
import (
"bytes"
"context"
"io"
"os"
"os/exec"
"syscall"
"github.com/caarlos0/go-shellwords"
"github.com/creack/pty"
)
// runInPty opens a new pty and runs the given command in it.
// The returned file is the pty's file descriptor and must be closed by the
// caller.
func (cfg Config) runInPty(c *exec.Cmd) (*os.File, error) {
//nolint: wrapcheck
return pty.StartWithAttrs(c, &pty.Winsize{
Cols: 80,
Rows: 10,
X: uint16(cfg.Width),
}, &syscall.SysProcAttr{})
}
func executeCommand(config Config) (string, error) {
args, err := shellwords.Parse(config.Execute)
if err != nil {
return "", err //nolint: wrapcheck
}
ctx, cancel := context.WithTimeout(context.Background(), config.ExecuteTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, args[0], args[1:]...) //nolint: gosec
pty, err := config.runInPty(cmd)
if err != nil {
return "", err
}
defer pty.Close() //nolint: errcheck
var out bytes.Buffer
go func() {
_, _ = io.Copy(&out, pty)
}()
err = cmd.Wait()
if err != nil {
return "", err //nolint: wrapcheck
}
return out.String(), nil
}