CopyGuardedContent writes external content from r to w under the safety model used by byte-moving commands: binary content is refused when w targets a terminal and streamed verbatim otherwise, while textual content is refused when it carries terminal escape sequences. Binary content streams without
(w io.Writer, r io.Reader, isTTY bool)
| 61 | // command-specific guidance. Callers that must stream verbatim (an explicit |
| 62 | // opt-out, or output bound for a file) should copy directly instead. |
| 63 | func CopyGuardedContent(w io.Writer, r io.Reader, isTTY bool) error { |
| 64 | head := make([]byte, contentSniffLen) |
| 65 | n, err := io.ReadFull(r, head) |
| 66 | if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) { |
| 67 | return err |
| 68 | } |
| 69 | head = head[:n] |
| 70 | |
| 71 | if mime, ok := BinaryContentType(head); ok { |
| 72 | if isTTY { |
| 73 | return BinaryTerminalError{MIME: mime} |
| 74 | } |
| 75 | if _, err := w.Write(head); err != nil { |
| 76 | return err |
| 77 | } |
| 78 | _, err := io.Copy(w, r) |
| 79 | return err |
| 80 | } |
| 81 | |
| 82 | rest, err := io.ReadAll(r) |
| 83 | if err != nil { |
| 84 | return err |
| 85 | } |
| 86 | content := append(head, rest...) |
| 87 | if ContainsEscapeSequence(content) { |
| 88 | return ErrEscapeSequence |
| 89 | } |
| 90 | _, err = w.Write(content) |
| 91 | return err |
| 92 | } |