Files
iknowyou/back/internal/tools/ptyrun.go
2026-04-06 15:12:34 +02:00

29 lines
698 B
Go

package tools
import (
"context"
"io"
"os/exec"
"regexp"
"github.com/creack/pty"
)
// oscRe strips OSC terminal sequences emitted by the PTY (e.g. colour queries).
var oscRe = regexp.MustCompile(`\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)`)
// RunWithPTY runs cmd under a pseudo-terminal (preserving ANSI colours) and
// returns the full output once the process exits.
func RunWithPTY(ctx context.Context, cmd *exec.Cmd) (string, error) {
ptmx, err := pty.StartWithSize(cmd, &pty.Winsize{Rows: 50, Cols: 220})
if err != nil {
return "", err
}
defer func() { _ = ptmx.Close() }()
output, _ := io.ReadAll(ptmx)
_ = cmd.Wait()
return oscRe.ReplaceAllString(string(output), ""), ctx.Err()
}