-
Notifications
You must be signed in to change notification settings - Fork 61
/
pty.go
53 lines (44 loc) · 1.13 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
package main
import (
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"github.com/caarlos0/go-shellwords"
"github.com/charmbracelet/x/term"
"github.com/charmbracelet/x/xpty"
)
func executeCommand(config Config) (string, error) {
args, err := shellwords.Parse(config.Execute)
if err != nil {
return "", fmt.Errorf("could not execute: %w", err)
}
ctx, cancel := context.WithTimeout(context.Background(), config.ExecuteTimeout)
defer cancel()
width, height, err := term.GetSize(os.Stdout.Fd())
if err != nil {
width = 80
height = 24
}
pty, err := xpty.NewPty(width, height)
if err != nil {
return "", fmt.Errorf("could not execute: %w", err)
}
defer func() { _ = pty.Close() }()
cmd := exec.CommandContext(ctx, args[0], args[1:]...) //nolint: gosec
if err := pty.Start(cmd); err != nil {
return "", fmt.Errorf("could not execute: %w", err)
}
var out bytes.Buffer
var errorOut bytes.Buffer
go func() {
_, _ = io.Copy(&out, pty)
errorOut.Write(out.Bytes())
}()
if err := xpty.WaitProcess(ctx, cmd); err != nil {
return errorOut.String(), fmt.Errorf("could not execute: %w", err)
}
return out.String(), nil
}