// Package runner supervises local commands while retaining terminal I/O. package runner import ( "context" "fmt" "io" "os" "os/exec" "os/signal" "syscall" "time" "github.com/charmbracelet/x/term" ) type Options struct { Stdin io.Reader Stdout, Stderr io.Writer Env []string Timeout time.Duration Status bool Label string } type Result struct { Code int Started bool Duration time.Duration } func Run(ctx context.Context, argv []string, o Options) Result { if o.Stderr == nil { o.Stderr = io.Discard } if o.Stdout == nil { o.Stdout = io.Discard } start := time.Now() result := Result{Code: 1} if ctx.Err() != nil { result.Code = 130 return result } if len(argv) == 0 { return result } cmd := exec.Command(argv[0], argv[1:]...) cmd.Stdin, cmd.Stdout, cmd.Stderr = o.Stdin, o.Stdout, o.Stderr cmd.Env = append(os.Environ(), o.Env...) interactive := false if f, ok := o.Stdin.(*os.File); ok { interactive = term.IsTerminal(f.Fd()) } // Interactive SSH must share the foreground terminal process group. // Background jobs get an isolated group so cancellation reaches descendants. cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: !interactive} if err := cmd.Start(); err != nil { fmt.Fprintf(o.Stderr, "%s: %v\n", argv[0], err) return result } result.Started = true done := make(chan error, 1) go func() { done <- cmd.Wait() }() sigs := make(chan os.Signal, 4) signal.Notify(sigs, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT) defer signal.Stop(sigs) var timeout <-chan time.Time if o.Timeout > 0 { timer := time.NewTimer(o.Timeout) defer timer.Stop() timeout = timer.C } ticker := time.NewTicker(time.Second) defer ticker.Stop() var killTimer *time.Timer var kill <-chan time.Time defer func() { if killTimer != nil { killTimer.Stop() } }() send := func(sig syscall.Signal) { if interactive { _ = cmd.Process.Signal(sig) } else { _ = syscall.Kill(-cmd.Process.Pid, sig) } } forced := 0 cancelCh := ctx.Done() stop := func(code int, sig syscall.Signal) { if forced != 0 { return } forced = code send(sig) killTimer = time.NewTimer(2 * time.Second) kill = killTimer.C } for { select { case err := <-done: result.Duration = time.Since(start) result.Code = 0 if err != nil { result.Code = 1 if e, ok := err.(*exec.ExitError); ok { result.Code = e.ExitCode() if s, ok := e.Sys().(syscall.WaitStatus); ok && s.Signaled() { result.Code = 128 + int(s.Signal()) } } } if forced != 0 { result.Code = forced } // Kill descendants left behind after cancellation even if the parent exited. if forced != 0 && !interactive { send(syscall.SIGKILL) } if o.Status { fmt.Fprintf(o.Stderr, "[%s] finished in %s (exit %d)\n", o.Label, result.Duration.Round(time.Millisecond), result.Code) } return result case sig := <-sigs: s := sig.(syscall.Signal) if interactive && (s == syscall.SIGINT || s == syscall.SIGQUIT) { continue } // terminal delivered it to child too stop(128+int(s), s) case <-cancelCh: cancelCh = nil stop(130, syscall.SIGTERM) case <-timeout: timeout = nil stop(124, syscall.SIGTERM) case <-kill: kill = nil send(syscall.SIGKILL) case <-ticker.C: if o.Status { fmt.Fprintf(o.Stderr, "[%s] running %s (Ctrl+C cancels)\n", o.Label, time.Since(start).Round(time.Second)) } } } }