forked from charmbracelet/freeze
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pty_windows.go
78 lines (67 loc) · 1.57 KB
/
pty_windows.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
//go:build windows
// +build windows
package main
import (
"bytes"
"context"
"io"
"os"
"syscall"
"github.com/caarlos0/go-shellwords"
"github.com/charmbracelet/log"
"github.com/charmbracelet/x/exp/term/conpty"
"golang.org/x/sys/windows"
)
func executeCommand(config Config) (string, error) {
args, err := shellwords.Parse(config.Execute)
if err != nil {
log.Error(err)
printErrorFatal("Something went wrong", err)
}
ctx, cancel := context.WithTimeout(context.Background(), config.ExecuteTimeout)
defer cancel()
cpty, err := conpty.New(80, 10, 0)
if err != nil {
return "", err
}
defer cpty.Close()
pid, proc, err := cpty.Spawn(args[0], args, &syscall.ProcAttr{Env: os.Environ()})
if err != nil {
return "", err
}
process, err := os.FindProcess(pid)
if err != nil {
// If we can't find the process via os.FindProcess, terminate the
// process as that's what we rely on for all further operations on the
// object.
if tErr := windows.TerminateProcess(windows.Handle(proc), 1); tErr != nil {
return "", tErr
}
return "", err
}
type result struct {
*os.ProcessState
error
}
donec := make(chan result, 1)
go func() {
state, err := process.Wait()
donec <- result{state, err}
}()
ctx, cancelFunc := context.WithTimeout(context.Background(), config.ExecuteTimeout)
defer cancelFunc()
var out bytes.Buffer
go func() {
_, _ = io.Copy(&out, cpty)
}()
select {
case <-ctx.Done():
err = windows.TerminateProcess(windows.Handle(proc), 1)
case r := <-donec:
err = r.error
}
if err != nil {
return "", err
}
return out.String(), nil
}