|
| 1 | +//go:build windows |
| 2 | +// +build windows |
| 3 | + |
| 4 | +package ssh |
| 5 | + |
| 6 | +import ( |
| 7 | + "fmt" |
| 8 | + "os" |
| 9 | + "os/exec" |
| 10 | + "syscall" |
| 11 | + |
| 12 | + "github.com/charmbracelet/x/term/conpty" |
| 13 | + "golang.org/x/crypto/ssh" |
| 14 | + "golang.org/x/sys/windows" |
| 15 | +) |
| 16 | + |
| 17 | +type impl struct { |
| 18 | + Context |
| 19 | + *conpty.ConPty |
| 20 | +} |
| 21 | + |
| 22 | +func (i *impl) Read(p []byte) (n int, err error) { |
| 23 | + return i.ConPty.Read(p) |
| 24 | +} |
| 25 | + |
| 26 | +func (i *impl) Write(p []byte) (n int, err error) { |
| 27 | + return i.ConPty.Write(p) |
| 28 | +} |
| 29 | + |
| 30 | +func (i *impl) Resize(w int, h int) error { |
| 31 | + return i.ConPty.Resize(w, h) |
| 32 | +} |
| 33 | + |
| 34 | +func (i *impl) Close() error { |
| 35 | + return i.ConPty.Close() |
| 36 | +} |
| 37 | + |
| 38 | +func (i *impl) start(c *exec.Cmd) error { |
| 39 | + pid, process, err := i.Spawn(c.Path, c.Args, &syscall.ProcAttr{ |
| 40 | + Dir: c.Dir, |
| 41 | + Env: c.Env, |
| 42 | + Sys: c.SysProcAttr, |
| 43 | + }) |
| 44 | + if err != nil { |
| 45 | + return err |
| 46 | + } |
| 47 | + |
| 48 | + c.Process, err = os.FindProcess(pid) |
| 49 | + if err != nil { |
| 50 | + // If we can't find the process via os.FindProcess, terminate the |
| 51 | + // process as that's what we rely on for all further operations on the |
| 52 | + // object. |
| 53 | + if tErr := windows.TerminateProcess(process, 1); tErr != nil { |
| 54 | + return fmt.Errorf("failed to terminate process after process not found: %w", tErr) |
| 55 | + } |
| 56 | + return fmt.Errorf("failed to find process after starting: %w", err) |
| 57 | + } |
| 58 | + |
| 59 | + type result struct { |
| 60 | + *os.ProcessState |
| 61 | + error |
| 62 | + } |
| 63 | + donec := make(chan result, 1) |
| 64 | + go func() { |
| 65 | + state, err := c.Process.Wait() |
| 66 | + donec <- result{state, err} |
| 67 | + }() |
| 68 | + go func() { |
| 69 | + select { |
| 70 | + case <-i.Context.Done(): |
| 71 | + c.Err = windows.TerminateProcess(process, 1) |
| 72 | + case r := <-donec: |
| 73 | + c.ProcessState = r.ProcessState |
| 74 | + c.Err = r.error |
| 75 | + } |
| 76 | + }() |
| 77 | + |
| 78 | + return nil |
| 79 | +} |
| 80 | + |
| 81 | +func newPty(ctx Context, _ string, win Window, _ ssh.TerminalModes) (impl, error) { |
| 82 | + c, err := conpty.New(win.Width, win.Height, 0) |
| 83 | + if err != nil { |
| 84 | + return impl{}, err |
| 85 | + } |
| 86 | + |
| 87 | + return impl{ctx, c}, nil |
| 88 | +} |
0 commit comments