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)
| 73 | // command-specific guidance. Callers that must stream verbatim (an explicit |
| 74 | // opt-out, or output bound for a file) should copy directly instead. |
| 75 | func CopyGuardedContent(w io.Writer, r io.Reader, isTTY bool) error { |
| 76 | head := make([]byte, contentSniffLen) |
| 77 | n, err := io.ReadFull(r, head) |
| 78 | if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) { |
| 79 | return err |
| 80 | } |
| 81 | head = head[:n] |
| 82 | |
| 83 | if mime, ok := BinaryContentType(head); ok { |
| 84 | if isTTY { |
| 85 | return BinaryTerminalError{MIME: mime} |
| 86 | } |
| 87 | if _, err := w.Write(head); err != nil { |
| 88 | return err |
| 89 | } |
| 90 | _, err := io.Copy(w, r) |
| 91 | return err |
| 92 | } |
| 93 | |
| 94 | rest, err := io.ReadAll(r) |
| 95 | if err != nil { |
| 96 | return err |
| 97 | } |
| 98 | content := append(head, rest...) |
| 99 | if ContainsEscapeSequence(content) { |
| 100 | return ErrEscapeSequence |
| 101 | } |
| 102 | _, err = w.Write(content) |
| 103 | return err |
| 104 | } |