use std::{
io,
path::{Path, PathBuf},
};
use tez::{Body, BodyExt as _, HeaderMap, StatusCode, Version, header};
use tokio::io::{AsyncWrite, AsyncWriteExt};
use crate::error::{Error, Result};
const JSON_PRETTY_LIMIT: usize = 1024 * 1024;
const SNIFF_LIMIT: usize = 4 * 1024;
const BINARY_NOTICE: &[u8] = b"[binary response body omitted]\n";
const STDOUT_ERROR: &str = "response could not be written";
const STDERR_ERROR: &str = "request details could not be written";
const FILE_OPEN_ERROR: &str = "output file could not be opened";
const FILE_WRITE_ERROR: &str = "output file could not be written";
const DOWNLOAD_NAME: &str = "download";
pub(crate) struct Output {
headers_only: bool,
body_only: bool,
output: Option<PathBuf>,
stdout_is_terminal: bool,
download: bool,
continue_download: bool,
stream: bool,
}
impl Output {
pub(crate) fn new(
headers_only: bool,
body_only: bool,
output: Option<PathBuf>,
stdout_is_terminal: bool,
download: bool,
continue_download: bool,
stream: bool,
) -> Self {
Self {
headers_only,
body_only,
output,
stdout_is_terminal,
download,
continue_download,
stream,
}
}
fn mode(&self) -> Mode {
output_mode(
self.headers_only,
self.body_only,
self.stdout_is_terminal,
self.output.is_some() || self.download,
)
}
}
pub(crate) async fn write(response: tez::Response, options: &Output) -> Result<()> {
let mode = options.mode();
if mode.includes_headers() {
let mut stdout = tokio::io::stdout();
write_head(
&mut stdout,
response.version(),
response.status(),
response.headers(),
)
.await?;
}
if !mode.includes_body() {
return Ok(());
}
if options.download {
return write_download(response, options).await;
}
if let Some(path) = &options.output {
let mut file = tokio::fs::File::create(path)
.await
.map_err(|error| Error::io(FILE_OPEN_ERROR, &error))?;
let _ = stream_raw(response.into_body(), &mut file, FILE_WRITE_ERROR).await?;
return Ok(());
}
let mut stdout = tokio::io::stdout();
if options.stdout_is_terminal {
write_terminal_body(response, &mut stdout, options.stream).await
} else {
let _ = stream_raw(response.into_body(), &mut stdout, STDOUT_ERROR).await?;
Ok(())
}
}
pub(crate) async fn write_request(request: tez::Request) -> Result<()> {
let (parts, body) = request.into_parts();
let mut stdout = tokio::io::stdout();
let line = format!("{} {} HTTP/1.1\n", parts.method, parts.uri);
write_bytes(&mut stdout, line.as_bytes(), STDOUT_ERROR).await?;
write_headers(&mut stdout, &parts.headers, false, STDOUT_ERROR).await?;
let _ = stream_raw(body, &mut stdout, STDOUT_ERROR).await?;
Ok(())
}
pub(crate) async fn write_request_head(request: &tez::Request) -> Result<()> {
let mut stderr = tokio::io::stderr();
let line = format!("{} {} HTTP/1.1\n", request.method(), request.uri());
write_bytes(&mut stderr, line.as_bytes(), STDERR_ERROR).await?;
write_headers(&mut stderr, request.headers(), true, STDERR_ERROR).await
}
async fn write_download(response: tez::Response, options: &Output) -> Result<()> {
let path = options.download_path(&response);
let append = options.continue_download
&& response.status() == StatusCode::PARTIAL_CONTENT
&& tokio::fs::metadata(&path)
.await
.is_ok_and(|metadata| metadata.len() > 0);
let mut file = tokio::fs::OpenOptions::new()
.create(true)
.write(true)
.append(append)
.truncate(!append)
.open(&path)
.await
.map_err(|error| Error::io(FILE_OPEN_ERROR, &error))?;
let bytes = stream_raw(response.into_body(), &mut file, FILE_WRITE_ERROR).await?;
let mut stderr = tokio::io::stderr();
let verb = if append { "Resumed" } else { "Saved" };
let message = format!("{verb} {bytes} bytes to {}\n", path.display());
write_bytes(&mut stderr, message.as_bytes(), FILE_WRITE_ERROR).await?;
flush(&mut stderr, FILE_WRITE_ERROR).await
}
pub(crate) fn status_exit(status: StatusCode, check: bool) -> u8 {
if !check {
return 0;
}
if status.is_redirection() {
3
} else if status.is_client_error() {
4
} else if status.is_server_error() {
5
} else {
0
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Mode {
Headers,
Body,
Both,
}
impl Mode {
const fn includes_headers(self) -> bool {
matches!(self, Self::Headers | Self::Both)
}
const fn includes_body(self) -> bool {
matches!(self, Self::Body | Self::Both)
}
}
const fn output_mode(
headers_only: bool,
body_only: bool,
stdout_is_terminal: bool,
has_output_file: bool,
) -> Mode {
match (headers_only, body_only) {
(true, true) => Mode::Both,
(true, false) => Mode::Headers,
(false, true) => Mode::Body,
(false, false) if stdout_is_terminal && !has_output_file => Mode::Both,
(false, false) => Mode::Body,
}
}
async fn write_head<W>(
writer: &mut W,
version: Version,
status: StatusCode,
headers: &HeaderMap,
) -> Result<()>
where
W: AsyncWrite + Unpin,
{
write_bytes(
writer,
status_line(version, status).as_bytes(),
STDOUT_ERROR,
)
.await?;
write_headers(writer, headers, false, STDOUT_ERROR).await
}
async fn write_headers<W>(
writer: &mut W,
headers: &HeaderMap,
redact: bool,
message: &'static str,
) -> Result<()>
where
W: AsyncWrite + Unpin,
{
let mut ordered: Vec<_> = headers.iter().enumerate().collect();
ordered.sort_by(|(_, (left, _)), (_, (right, _))| left.as_str().cmp(right.as_str()));
for (_, (name, value)) in ordered {
write_bytes(writer, name.as_str().as_bytes(), message).await?;
write_bytes(writer, b": ", message).await?;
let value = if redact && (name == header::AUTHORIZATION || value.is_sensitive()) {
"[redacted]".to_owned()
} else {
display_header_value(value.as_bytes())
};
write_bytes(writer, value.as_bytes(), message).await?;
write_bytes(writer, b"\n", message).await?;
}
write_bytes(writer, b"\n", message).await?;
flush(writer, message).await
}
fn status_line(version: Version, status: StatusCode) -> String {
let version = version_name(version);
match status.canonical_reason() {
Some(reason) => format!("{version} {} {reason}\n", status.as_u16()),
None => format!("{version} {}\n", status.as_u16()),
}
}
fn version_name(version: Version) -> &'static str {
match version {
Version::HTTP_09 => "HTTP/0.9",
Version::HTTP_10 => "HTTP/1.0",
Version::HTTP_11 => "HTTP/1.1",
Version::HTTP_2 => "HTTP/2",
Version::HTTP_3 => "HTTP/3",
_ => "HTTP/?",
}
}
fn display_header_value(value: &[u8]) -> String {
let mut display = String::with_capacity(value.len());
for byte in value {
match byte {
b'\t' => display.push('\t'),
b' '..=b'~' => display.push(char::from(*byte)),
_ => {
const HEX: &[u8; 16] = b"0123456789ABCDEF";
display.push('\\');
display.push('x');
display.push(char::from(HEX[usize::from(*byte >> 4)]));
display.push(char::from(HEX[usize::from(*byte & 0x0f)]));
}
}
}
display
}
async fn write_terminal_body<W>(response: tez::Response, writer: &mut W, stream: bool) -> Result<()>
where
W: AsyncWrite + Unpin,
{
match terminal_body(response.headers()) {
TerminalBody::Json if stream => {
stream_terminal_text(response.into_body(), writer, true).await
}
TerminalBody::Json => write_terminal_json(response.into_body(), writer).await,
TerminalBody::LiveText => stream_terminal_text(response.into_body(), writer, true).await,
TerminalBody::Text => stream_terminal_text(response.into_body(), writer, stream).await,
TerminalBody::Binary => {
write_bytes(writer, BINARY_NOTICE, STDOUT_ERROR).await?;
flush(writer, STDOUT_ERROR).await?;
Ok(())
}
TerminalBody::Unknown => write_terminal_unknown(response.into_body(), writer).await,
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum TerminalBody {
Json,
LiveText,
Text,
Binary,
Unknown,
}
fn terminal_body(headers: &HeaderMap) -> TerminalBody {
let Some(content_type) = headers
.get(header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.split(';').next())
.map(str::trim)
.filter(|value| !value.is_empty())
else {
return TerminalBody::Unknown;
};
let content_type = content_type.to_ascii_lowercase();
if content_type == "text/event-stream"
|| content_type == "application/x-ndjson"
|| content_type == "application/ndjson"
|| content_type == "application/x-jsonl"
|| content_type == "application/jsonl"
{
TerminalBody::LiveText
} else if content_type == "application/json" || content_type.ends_with("+json") {
TerminalBody::Json
} else if content_type.starts_with("text/")
|| content_type == "application/xml"
|| content_type.ends_with("+xml")
|| content_type == "application/javascript"
|| content_type == "application/x-javascript"
|| content_type == "application/x-www-form-urlencoded"
|| content_type == "application/graphql"
|| content_type == "application/yaml"
|| content_type == "application/x-yaml"
{
TerminalBody::Text
} else if content_type.starts_with("image/")
|| content_type.starts_with("audio/")
|| content_type.starts_with("video/")
|| content_type.starts_with("font/")
|| content_type.starts_with("model/")
|| content_type.starts_with("multipart/")
|| content_type == "application/octet-stream"
|| content_type == "application/pdf"
|| content_type == "application/zip"
|| content_type == "application/gzip"
|| content_type == "application/x-tar"
|| content_type == "application/wasm"
{
TerminalBody::Binary
} else {
TerminalBody::Unknown
}
}
async fn stream_raw<W>(mut body: Body, writer: &mut W, message: &'static str) -> Result<u64>
where
W: AsyncWrite + Unpin,
{
let mut written = 0_u64;
while let Some(frame) = body.frame().await {
let frame = frame?;
if let Ok(data) = frame.into_data() {
write_bytes(writer, &data, message).await?;
written = written.saturating_add(data.len() as u64);
}
}
flush(writer, message).await?;
Ok(written)
}
impl Output {
fn download_path(&self, response: &tez::Response) -> PathBuf {
self.output
.clone()
.unwrap_or_else(|| available_download_path(download_name(response)))
}
}
fn download_name(response: &tez::Response) -> String {
let from_header = response
.headers()
.get(header::CONTENT_DISPOSITION)
.and_then(|value| value.to_str().ok())
.and_then(content_disposition_filename)
.map(ToOwned::to_owned);
from_header
.or_else(|| {
response
.url()
.path()
.rsplit('/')
.find(|segment| !segment.is_empty())
.map(ToOwned::to_owned)
})
.and_then(safe_file_name)
.unwrap_or_else(|| DOWNLOAD_NAME.to_owned())
}
fn content_disposition_filename(value: &str) -> Option<&str> {
value.split(';').skip(1).find_map(|parameter| {
let (name, value) = parameter.trim().split_once('=')?;
name.eq_ignore_ascii_case("filename")
.then(|| value.trim_matches('"'))
})
}
fn safe_file_name(value: String) -> Option<String> {
Path::new(&value)
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.filter(|name| !name.is_empty() && name != "." && name != "..")
}
fn available_download_path(name: String) -> PathBuf {
let path = PathBuf::from(&name);
if !path.exists() {
return path;
}
let stem = path
.file_stem()
.and_then(|stem| stem.to_str())
.unwrap_or(DOWNLOAD_NAME);
let extension = path.extension().and_then(|extension| extension.to_str());
for index in 1.. {
let candidate = match extension {
Some(extension) => format!("{stem}-{index}.{extension}"),
None => format!("{stem}-{index}"),
};
let candidate = PathBuf::from(candidate);
if !candidate.exists() {
return candidate;
}
}
unreachable!("an available download filename is eventually found")
}
async fn stream_terminal_text<W>(body: Body, writer: &mut W, flush_each_frame: bool) -> Result<()>
where
W: AsyncWrite + Unpin,
{
stream_terminal_text_with(body, writer, flush_each_frame, TerminalText::default()).await
}
async fn stream_terminal_text_with<W>(
mut body: Body,
writer: &mut W,
flush_each_frame: bool,
mut text: TerminalText,
) -> Result<()>
where
W: AsyncWrite + Unpin,
{
while let Some(frame) = body.frame().await {
let frame = frame?;
if let Ok(data) = frame.into_data() {
text.write(writer, &data).await?;
if flush_each_frame {
flush(writer, STDOUT_ERROR).await?;
}
}
}
text.finish(writer).await?;
flush(writer, STDOUT_ERROR).await
}
async fn write_terminal_unknown<W>(mut body: Body, writer: &mut W) -> Result<()>
where
W: AsyncWrite + Unpin,
{
let mut prefix = Vec::new();
while let Some(frame) = body.frame().await {
let frame = frame?;
let Ok(data) = frame.into_data() else {
continue;
};
if prefix.len().saturating_add(data.len()) < SNIFF_LIMIT {
prefix.extend_from_slice(&data);
continue;
}
let remaining = SNIFF_LIMIT.saturating_sub(prefix.len());
prefix.extend_from_slice(&data[..remaining]);
if is_probably_binary(&prefix) {
write_bytes(writer, BINARY_NOTICE, STDOUT_ERROR).await?;
flush(writer, STDOUT_ERROR).await?;
return Ok(());
}
let mut text = TerminalText::default();
text.write(writer, &prefix).await?;
text.write(writer, &data[remaining..]).await?;
return stream_terminal_text_with(body, writer, false, text).await;
}
if is_probably_binary(&prefix) {
write_bytes(writer, BINARY_NOTICE, STDOUT_ERROR).await?;
} else {
write_terminal_text(writer, &prefix).await?;
}
flush(writer, STDOUT_ERROR).await
}
async fn write_terminal_json<W>(mut body: Body, writer: &mut W) -> Result<()>
where
W: AsyncWrite + Unpin,
{
let mut buffered = Vec::new();
while let Some(frame) = body.frame().await {
let frame = frame?;
let Ok(data) = frame.into_data() else {
continue;
};
if buffered.len().saturating_add(data.len()) > JSON_PRETTY_LIMIT {
if json_prefix_is_binary(&buffered, &data) {
write_bytes(writer, BINARY_NOTICE, STDOUT_ERROR).await?;
flush(writer, STDOUT_ERROR).await?;
return Ok(());
}
let mut text = TerminalText::default();
text.write(writer, &buffered).await?;
text.write(writer, &data).await?;
return stream_terminal_text_with(body, writer, false, text).await;
}
buffered.extend_from_slice(&data);
}
let pretty = serde_json::from_slice::<serde_json::Value>(&buffered)
.ok()
.and_then(|value| serde_json::to_vec_pretty(&value).ok());
if let Some(pretty) = pretty {
write_terminal_text(writer, &pretty).await?;
write_bytes(writer, b"\n", STDOUT_ERROR).await?;
} else if is_probably_binary(&buffered) {
write_bytes(writer, BINARY_NOTICE, STDOUT_ERROR).await?;
} else {
write_terminal_text(writer, &buffered).await?;
}
flush(writer, STDOUT_ERROR).await
}
fn json_prefix_is_binary(buffered: &[u8], next: &[u8]) -> bool {
if buffered.len() >= SNIFF_LIMIT {
return is_probably_binary(&buffered[..SNIFF_LIMIT]);
}
let mut prefix = Vec::with_capacity(SNIFF_LIMIT.min(buffered.len().saturating_add(next.len())));
prefix.extend_from_slice(buffered);
prefix.extend_from_slice(&next[..next.len().min(SNIFF_LIMIT - prefix.len())]);
is_probably_binary(&prefix)
}
fn is_probably_binary(bytes: &[u8]) -> bool {
if bytes.iter().copied().any(is_terminal_control) {
return true;
}
match str::from_utf8(bytes) {
Ok(_) => false,
Err(error) => error.error_len().is_some(),
}
}
#[derive(Default)]
struct TerminalText {
pending: Vec<u8>,
}
impl TerminalText {
async fn write<W>(&mut self, writer: &mut W, bytes: &[u8]) -> Result<()>
where
W: AsyncWrite + Unpin,
{
let safe = self.sanitize(bytes, false);
write_bytes(writer, &safe, STDOUT_ERROR).await
}
async fn finish<W>(&mut self, writer: &mut W) -> Result<()>
where
W: AsyncWrite + Unpin,
{
let safe = self.sanitize(&[], true);
write_bytes(writer, &safe, STDOUT_ERROR).await
}
fn sanitize(&mut self, bytes: &[u8], finish: bool) -> Vec<u8> {
self.pending.extend_from_slice(bytes);
let mut safe = Vec::with_capacity(self.pending.len());
let mut consumed = 0;
while consumed < self.pending.len() {
match str::from_utf8(&self.pending[consumed..]) {
Ok(text) => {
push_terminal_text(&mut safe, text);
consumed = self.pending.len();
}
Err(error) => {
let valid_end = consumed + error.valid_up_to();
let valid = str::from_utf8(&self.pending[consumed..valid_end])
.expect("UTF-8 validation identified a valid prefix");
push_terminal_text(&mut safe, valid);
consumed = valid_end;
let Some(length) = error.error_len() else {
break;
};
for byte in self.pending[consumed..(consumed + length)].iter().copied() {
push_hex_escape(&mut safe, byte);
}
consumed += length;
}
}
}
if finish {
for byte in self.pending[consumed..].iter().copied() {
push_hex_escape(&mut safe, byte);
}
consumed = self.pending.len();
}
self.pending.drain(..consumed);
safe
}
}
async fn write_terminal_text<W>(writer: &mut W, bytes: &[u8]) -> Result<()>
where
W: AsyncWrite + Unpin,
{
let mut text = TerminalText::default();
text.write(writer, bytes).await?;
text.finish(writer).await
}
fn push_terminal_text(safe: &mut Vec<u8>, text: &str) {
for character in text.chars() {
if matches!(character, '\t' | '\r' | '\n') {
safe.push(character as u8);
} else if character.is_control() {
push_hex_escape(safe, character as u8);
} else {
let mut encoded = [0; 4];
safe.extend_from_slice(character.encode_utf8(&mut encoded).as_bytes());
}
}
}
fn push_hex_escape(safe: &mut Vec<u8>, byte: u8) {
const HEX: &[u8; 16] = b"0123456789ABCDEF";
safe.extend_from_slice(&[
b'\\',
b'x',
HEX[usize::from(byte >> 4)],
HEX[usize::from(byte & 0x0f)],
]);
}
const fn is_terminal_control(byte: u8) -> bool {
matches!(byte, 0..=8 | 11 | 12 | 14..=31 | 127)
}
async fn write_bytes<W>(writer: &mut W, bytes: &[u8], message: &'static str) -> Result<()>
where
W: AsyncWrite + Unpin,
{
writer
.write_all(bytes)
.await
.map_err(|error| map_io_error(message, &error))
}
async fn flush<W>(writer: &mut W, message: &'static str) -> Result<()>
where
W: AsyncWrite + Unpin,
{
writer
.flush()
.await
.map_err(|error| map_io_error(message, &error))
}
fn map_io_error(message: &'static str, error: &io::Error) -> Error {
Error::io(message, error)
}
#[cfg(test)]
mod tests {
use super::*;
use http_body_util::StreamBody;
use tez::{Bytes, Frame, HeaderValue, header};
#[test]
fn default_output_follows_the_destination() {
assert_eq!(output_mode(false, false, true, false), Mode::Both);
assert_eq!(output_mode(false, false, false, false), Mode::Body);
assert_eq!(output_mode(false, false, true, true), Mode::Body);
}
#[test]
fn explicit_output_modes_win() {
assert_eq!(output_mode(true, false, false, false), Mode::Headers);
assert_eq!(output_mode(false, true, true, false), Mode::Body);
assert_eq!(output_mode(true, true, false, true), Mode::Both);
}
#[test]
fn status_errors_are_opt_in() {
assert_eq!(status_exit(StatusCode::MOVED_PERMANENTLY, false), 0);
assert_eq!(status_exit(StatusCode::MOVED_PERMANENTLY, true), 3);
assert_eq!(status_exit(StatusCode::NOT_FOUND, true), 4);
assert_eq!(status_exit(StatusCode::BAD_GATEWAY, true), 5);
assert_eq!(status_exit(StatusCode::NO_CONTENT, true), 0);
}
#[test]
fn status_lines_include_versions_and_reasons() {
assert_eq!(
status_line(Version::HTTP_11, StatusCode::OK),
"HTTP/1.1 200 OK\n"
);
assert_eq!(
status_line(Version::HTTP_2, StatusCode::IM_A_TEAPOT),
"HTTP/2 418 I'm a teapot\n"
);
}
#[test]
fn header_bytes_are_safe_to_display() {
assert_eq!(
display_header_value(b"plain\tvalue\x80"),
"plain\tvalue\\x80"
);
}
#[test]
fn media_types_choose_terminal_presentation() {
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/problem+json; charset=utf-8"),
);
assert_eq!(terminal_body(&headers), TerminalBody::Json);
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/event-stream"),
);
assert_eq!(terminal_body(&headers), TerminalBody::LiveText);
for media_type in [
"application/x-ndjson",
"application/ndjson",
"application/x-jsonl",
"application/jsonl",
] {
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_str(media_type).unwrap(),
);
assert_eq!(terminal_body(&headers), TerminalBody::LiveText);
}
headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("image/png"));
assert_eq!(terminal_body(&headers), TerminalBody::Binary);
}
#[test]
fn binary_sniffing_allows_incomplete_utf8_suffixes() {
assert!(!is_probably_binary("plain text".as_bytes()));
assert!(!is_probably_binary(&[b'a', 0xe2, 0x82]));
assert!(is_probably_binary(b"plain\0binary"));
assert!(is_probably_binary(&[0xff, 0xfe]));
assert!(!json_prefix_is_binary(&[b'a', 0xe2], &[0x82, 0xac]));
}
#[test]
fn broken_pipe_mapping_stays_quiet() {
let error = map_io_error(STDOUT_ERROR, &io::Error::from(io::ErrorKind::BrokenPipe));
assert!(error.is_broken_pipe());
}
#[tokio::test]
async fn raw_streams_are_byte_exact() {
let expected = b"body\x1b[31m\0\x7f without a trailing newline";
let mut written = Vec::new();
stream_raw(Body::from(expected.as_slice()), &mut written, STDOUT_ERROR)
.await
.unwrap();
assert_eq!(written, expected);
}
#[tokio::test]
async fn text_terminal_streams_escape_controls() {
let mut headers = HeaderMap::new();
headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("text/plain"));
assert_eq!(terminal_body(&headers), TerminalBody::Text);
let mut written = Vec::new();
stream_terminal_text(
Body::from(b"plain\x1b[31mred\x07\x7f\t\r\n".as_slice()),
&mut written,
false,
)
.await
.unwrap();
assert_eq!(written, b"plain\\x1B[31mred\\x07\\x7F\t\r\n");
}
#[tokio::test]
async fn terminal_text_is_utf8_safe_across_frames() {
let frames = futures_util::stream::iter([
Ok::<_, io::Error>(Frame::data(Bytes::from_static(
b"snow: \xe9\x9b\xaa c1:\xc2",
))),
Ok(Frame::data(Bytes::from_static(
b"\x9b invalid:\xff emoji:\xf0\x9f",
))),
Ok(Frame::data(Bytes::from_static(b"\x98\x80"))),
]);
let mut written = Vec::new();
stream_terminal_text(Body::wrap(StreamBody::new(frames)), &mut written, false)
.await
.unwrap();
assert_eq!(
written,
"snow: 雪 c1:\\x9B invalid:\\xFF emoji:😀".as_bytes()
);
}
#[tokio::test]
async fn unknown_text_escapes_controls_after_the_sniff_prefix() {
let mut body = vec![b'a'; SNIFF_LIMIT];
body.extend_from_slice(b"\x1b[2Jtail");
let mut written = Vec::new();
write_terminal_unknown(Body::from(body), &mut written)
.await
.unwrap();
let mut expected = vec![b'a'; SNIFF_LIMIT];
expected.extend_from_slice(b"\\x1B[2Jtail");
assert_eq!(written, expected);
}
#[tokio::test]
async fn ndjson_is_streamed_without_whole_document_formatting() {
let expected = b"{\"first\":true}\n{\"second\":true}\n";
let mut written = Vec::new();
stream_terminal_text(Body::from(expected.as_slice()), &mut written, true)
.await
.unwrap();
assert_eq!(written, expected);
}
#[tokio::test]
async fn terminal_json_is_pretty_with_a_final_newline() {
let mut written = Vec::new();
write_terminal_json(
Body::from(r#"{"tez":true,"precise":123456789012345678901234567890}"#),
&mut written,
)
.await
.unwrap();
assert_eq!(
written,
b"{\n \"tez\": true,\n \"precise\": 123456789012345678901234567890\n}\n"
);
}
#[tokio::test]
async fn oversized_json_falls_back_to_streaming() {
let expected = vec![b'x'; JSON_PRETTY_LIMIT + 1];
let mut written = Vec::new();
write_terminal_json(Body::from(expected.clone()), &mut written)
.await
.unwrap();
assert_eq!(written, expected);
}
}