Files
iknowyou/back/internal/tools/ptyrun.go
2026-04-11 22:27:13 +02:00

37 lines
1.0 KiB
Go

package tools
import (
"context"
"io"
"os/exec"
"regexp"
"github.com/anotherhadi/iknowyou/internal/proxy"
"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.
// If a proxychains config path is stored in ctx, the command is transparently
// wrapped with proxychains4.
func RunWithPTY(ctx context.Context, cmd *exec.Cmd) (string, error) {
if confPath := proxy.ProxychainsConfFromContext(ctx); confPath != "" {
args := append([]string{"-q", "-f", confPath, cmd.Path}, cmd.Args[1:]...)
cmd = exec.CommandContext(ctx, "proxychains4", args...)
}
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()
}