vcom/internal/preview/tools.go

79 lines
2 KiB
Go
Raw Normal View History

package preview
import (
"bytes"
"context"
"errors"
"fmt"
"os/exec"
"syscall"
"time"
)
// Tools are the external utilities, looked up once at start.
type Tools struct {
PdfToText string
PdfInfo string
FFProbe string
Timeout time.Duration // per run; default 3 s
}
// FindTools looks the utilities up in $PATH.
func FindTools() *Tools {
look := func(name string) string {
p, _ := exec.LookPath(name)
return p
}
return &Tools{PdfToText: look("pdftotext"), PdfInfo: look("pdfinfo"), FFProbe: look("ffprobe"), Timeout: 3 * time.Second}
}
// ErrToolTimeout: the tool was killed after Tools.Timeout.
var ErrToolTimeout = errors.New("timed out")
// run executes prog with a timeout. The tool gets its own process group and
// the whole group is killed on timeout or cancel, so a child holding stdout
// open cannot make Wait hang. Output beyond max bytes is discarded.
func (t *Tools) run(ctx context.Context, max int64, prog string, args ...string) ([]byte, error) {
timeout := t.Timeout
if timeout <= 0 {
timeout = 3 * time.Second
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
cmd := exec.CommandContext(ctx, prog, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) }
cmd.WaitDelay = 200 * time.Millisecond
out := &capped{max: max}
cmd.Stdout = out
err := cmd.Run()
if ctx.Err() == context.DeadlineExceeded {
return nil, fmt.Errorf("%s: %w after %v", prog, ErrToolTimeout, timeout)
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
if err != nil {
return nil, fmt.Errorf("%s: %w", prog, err)
}
return out.b.Bytes(), nil
}
// capped keeps the first max bytes and swallows the rest (the tool is not
// killed by a broken pipe halfway through).
type capped struct {
b bytes.Buffer
max int64
}
func (c *capped) Write(p []byte) (int, error) {
if room := c.max - int64(c.b.Len()); room > 0 {
if int64(len(p)) > room {
c.b.Write(p[:room])
} else {
c.b.Write(p)
}
}
return len(p), nil
}