| 1 | //go:build windows |
| 2 | |
| 3 | package main |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "errors" |
| 8 | "sync" |
| 9 | |
| 10 | "github.com/UserExistsError/conpty" |
| 11 | "golang.org/x/sys/windows" |
| 12 | ) |
| 13 | |
| 14 | type windowsTerminalProcess struct { |
| 15 | pty *conpty.ConPty |
| 16 | closeOnce sync.Once |
| 17 | } |
| 18 | |
| 19 | func terminalPlatformAvailable() (bool, string) { |
| 20 | if !conpty.IsConPtyAvailable() { |
| 21 | return false, "integrated terminal requires Windows 10 version 1809 or newer" |
| 22 | } |
| 23 | return true, "" |
| 24 | } |
| 25 | |
| 26 | func startTerminalProcess(spec terminalStartSpec) (terminalProcess, error) { |
| 27 | if !conpty.IsConPtyAvailable() { |
| 28 | return nil, conpty.ErrConPtyUnsupported |
| 29 | } |
| 30 | commandLine := windows.ComposeCommandLine(append([]string{spec.command.path}, spec.command.args...)) |
| 31 | p, err := conpty.Start( |
| 32 | commandLine, |
| 33 | conpty.ConPtyDimensions(spec.cols, spec.rows), |
| 34 | conpty.ConPtyWorkDir(spec.dir), |
| 35 | conpty.ConPtyEnv(spec.env), |
| 36 | ) |
| 37 | if err != nil { |
| 38 | return nil, err |
| 39 | } |
| 40 | return &windowsTerminalProcess{pty: p}, nil |
| 41 | } |
| 42 | |
| 43 | func (p *windowsTerminalProcess) Read(data []byte) (int, error) { |
| 44 | return p.pty.Read(data) |
| 45 | } |
| 46 | |
| 47 | func (p *windowsTerminalProcess) Write(data []byte) (int, error) { |
| 48 | return p.pty.Write(data) |
| 49 | } |
| 50 | |
| 51 | func (p *windowsTerminalProcess) Resize(cols, rows int) error { |
| 52 | return p.pty.Resize(cols, rows) |
| 53 | } |
| 54 | |
| 55 | func (p *windowsTerminalProcess) Wait() (int, error) { |
| 56 | code, err := p.pty.Wait(context.Background()) |
| 57 | if err != nil && errors.Is(err, context.Canceled) { |
| 58 | return -1, err |
| 59 | } |
| 60 | return int(code), err |
| 61 | } |
| 62 | |
| 63 | func (p *windowsTerminalProcess) Close() error { |
| 64 | var closeErr error |
| 65 | p.closeOnce.Do(func() { |
| 66 | // Closing the pseudo console terminates the attached process tree and |
| 67 | // releases all ConPTY handles. |
| 68 | closeErr = p.pty.Close() |
| 69 | }) |
| 70 | return closeErr |
| 71 | } |
| 72 |