tale-ndjson 0.4.0

A tail-compatible tool for pretty-printing ndjson files, especially logs.
Documentation
//! CLI-level integration tests: run the built binary the way a user would,
//! over the checked-in fixtures and inline temp files, and assert on its
//! stdout/stderr/exit code.
//!
//! Assertions are structural (message content, headers, passthrough) rather
//! than byte-for-byte goldens: the elastic-tabstop column widths depend on
//! layout metrics that may legitimately change. One test guards that the
//! debug-only JSON profile report never leaks into stdout — it belongs on
//! stderr.

use std::io::Write;
use std::process::{Command, Output, Stdio};

/// Strip ANSI escape sequences so assertions can match on plain content.
fn strip_ansi(bytes: &[u8]) -> String {
    let text = String::from_utf8_lossy(bytes);
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // Consume the escape sequence: CSI (ESC [ ... final byte) or OSC.
            if chars.peek() == Some(&'[') {
                chars.next();
                for c in chars.by_ref() {
                    if ('\x40'..='\x7e').contains(&c) {
                        break;
                    }
                }
            }
        } else {
            out.push(c);
        }
    }
    out
}

/// Run the tale binary with the given args, optionally feeding stdin.
fn run(args: &[&str], stdin: Option<&[u8]>) -> Output {
    let mut child = Command::new(env!("CARGO_BIN_EXE_tale"))
        .args(args)
        .stdin(if stdin.is_some() { Stdio::piped() } else { Stdio::null() })
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("failed to spawn tale");

    if let Some(input) = stdin {
        child
            .stdin
            .take()
            .expect("stdin was piped")
            .write_all(input)
            .expect("failed to write stdin");
        // Dropping the handle closes the pipe so tale sees EOF.
    }

    child.wait_with_output().expect("failed to collect output")
}

fn stdout(out: &Output) -> String {
    strip_ansi(&out.stdout)
}

fn stderr(out: &Output) -> String {
    strip_ansi(&out.stderr)
}

fn fixture(name: &str) -> String {
    format!("{}/fixtures/{name}", env!("CARGO_MANIFEST_DIR"))
}

#[track_caller]
fn assert_success(out: &Output) {
    assert!(
        out.status.success(),
        "tale exited with {:?}\nstderr:\n{}",
        out.status.code(),
        stderr(out)
    );
}

/// The debug-only profile report is diagnostics: it must never land in stdout,
/// where it would corrupt piped output. (In release builds it doesn't print at
/// all, so this holds in both profiles.)
#[track_caller]
fn assert_stdout_free_of_diagnostics(out: &Output) {
    assert!(
        !stdout(out).contains("JSON Parsing Profile Report"),
        "profile report leaked into stdout:\n{}",
        stdout(out)
    );
}

/// When stdout is not a TTY, no ANSI escapes may appear in stdout, so piped
/// output is clean text for downstream tools.
#[test]
fn piped_output_has_no_ansi_colors() {
    let out = run(&[&fixture("mixed_json_types.log")], None);
    assert_success(&out);
    assert!(
        !out.stdout.contains(&0x1b),
        "stdout contains ANSI escapes while piped:\n{}",
        stdout(&out)
    );
    // The content itself is unchanged, just uncolored.
    assert!(stdout(&out).contains("Service starting up"), ":\n{}", stdout(&out));
}

#[test]
fn reads_entire_file() {
    let out = run(&[&fixture("just_loglines.log")], None);
    assert_success(&out);
    assert_stdout_free_of_diagnostics(&out);

    let text = stdout(&out);
    for message in [
        "Application startup initiated",
        "Loading Spring context",
        "Failed to initialize database connection",
    ] {
        assert!(text.contains(message), "output missing {message:?}:\n{text}");
    }
}

#[test]
fn stdin_formats_json_and_passes_text_through() {
    let input = std::fs::read(fixture("mixed_text_json.log")).expect("fixture readable");
    let out = run(&[], Some(&input));
    assert_success(&out);
    assert_stdout_free_of_diagnostics(&out);

    let text = stdout(&out);
    // Formatted JSON line...
    assert!(text.contains("Application server started on port 8080"), ":\n{text}");
    // ...and untouched plain text.
    assert!(text.contains("Starting application server..."), ":\n{text}");
    // Stdin mode must not print file headers.
    assert!(!text.contains("==>"), "stdin output has a file header:\n{text}");
}

#[test]
fn positive_offset_skips_lines() {
    // -n 2 means "start two lines in": the first two messages are skipped.
    let path = fixture("mixed_json_types.log");
    let out = run(&["-n", "2", &path], None);
    assert_success(&out);

    let text = stdout(&out);
    assert!(text.contains("User authentication successful"), ":\n{text}");
    assert!(!text.contains("Service starting up"), ":\n{text}");
}

#[test]
fn negative_offset_shows_last_lines() {
    // -n -2 means "last two lines".
    let path = fixture("mixed_json_types.log");
    let out = run(&["-n", "-2", &path], None);
    assert_success(&out);

    let text = stdout(&out);
    assert!(text.contains("Cache warming completed"), ":\n{text}");
    assert!(!text.contains("Service starting up"), ":\n{text}");
}

#[test]
fn byte_offset_skips_garbage_prefix() {
    // The garbage line is 58 bytes + newline, so -c 59 starts exactly at the
    // first valid JSON line.
    let path = fixture("garbage_prefix.log");
    let out = run(&["-c", "59", &path], None);
    assert_success(&out);

    let text = stdout(&out);
    assert!(text.contains("First valid log line"), ":\n{text}");
    assert!(text.contains("Fourth valid log line"), ":\n{text}");
    assert!(!text.contains("GARBAGE_BYTES"), ":\n{text}");
}

#[test]
fn blocks_flag_is_accepted_and_ignored() {
    // -b exists for tail compatibility; it must change nothing.
    let path = fixture("mixed_json_types.log");
    let plain = run(&[&path], None);
    let blocked = run(&["-b", "3", &path], None);
    assert_success(&plain);
    assert_success(&blocked);
    assert_eq!(stdout(&plain), stdout(&blocked));
}

#[test]
fn multi_file_static_prints_headers() {
    let out = run(
        &[&fixture("mixed_text_json.log"), &fixture("windows_line_endings.log")],
        None,
    );
    assert_success(&out);
    assert_stdout_free_of_diagnostics(&out);

    let text = stdout(&out);
    assert!(text.contains("==> mixed_text_json.log <=="), ":\n{text}");
    assert!(text.contains("==> windows_line_endings.log <=="), ":\n{text}");
    // Content from both files appears.
    assert!(text.contains("Application server started on port 8080"), ":\n{text}");
    assert!(text.contains("Windows service started"), ":\n{text}");
}

#[test]
fn missing_file_fails_with_error_on_stderr() {
    let out = run(&["/nonexistent/path/really-not-here.log"], None);
    assert_eq!(out.status.code(), Some(1), "missing file should exit 1");
    assert!(stdout(&out).is_empty(), "stdout should be empty:\n{}", stdout(&out));

    let err = stderr(&out);
    assert!(err.contains("File not found"), "stderr:\n{err}");
}

#[test]
fn windows_line_endings_are_handled() {
    let out = run(&[&fixture("windows_line_endings.log")], None);
    assert_success(&out);

    let text = stdout(&out);
    assert!(text.contains("Windows service started"), ":\n{text}");
    assert!(text.contains("Processing batch job"), ":\n{text}");
    // The \r must not survive into the formatted output.
    assert!(!text.contains('\r'), "CR made it into output:\n{text:?}");
}

#[test]
fn bare_logfmt_lines_are_parsed() {
    // Heroku-style logfmt: not valid JSON, so it only parses through the
    // non-JSON fallback. It must be pretty-printed, not passed through raw.
    let line = b"at=info method=GET path=/ status=200 duration=12ms\n";
    let out = run(&[], Some(line));
    assert_success(&out);

    let text = stdout(&out);
    assert!(text.contains("status=200"), ":\n{text}");
    // The raw line with single spaces must not survive intact.
    assert!(
        !text.contains("at=info method=GET path=/ status=200"),
        "logfmt line passed through raw:\n{text}"
    );
}

#[test]
fn quoted_logfmt_json_strings_still_parse() {
    let line = b"\"at=info method=GET path=/ status=200\"\n";
    let out = run(&[], Some(line));
    assert_success(&out);

    let text = stdout(&out);
    assert!(text.contains("status=200"), ":\n{text}");
}

#[test]
fn plain_text_without_key_value_pairs_passes_through() {
    let line = b"this is just a sentence with no equals signs\n";
    let out = run(&[], Some(line));
    assert_success(&out);

    let text = stdout(&out);
    assert!(
        text.contains("this is just a sentence with no equals signs"),
        ":\n{text}"
    );
}

#[test]
fn stdin_negative_offset_shows_last_lines() {
    // Exercises StdinProcessor's backtrack path over a pipe.
    let mut input = Vec::new();
    for i in 0..50_usize {
        input.extend_from_slice(format!(r#"{{"level":"INFO","message":"msg-{i:02}"}}"#).as_bytes());
        input.push(b'\n');
    }
    let out = run(&["-n", "-5"], Some(&input));
    assert_success(&out);

    let text = stdout(&out);
    assert!(text.contains("msg-49"), ":\n{text}");
    assert!(text.contains("msg-45"), ":\n{text}");
    assert!(!text.contains("msg-44"), ":\n{text}");
    assert!(!text.contains("msg-00"), ":\n{text}");
}

/// When the downstream consumer closes the pipe (`tale big.log | head`),
/// tale must die quietly with 141 (128 + SIGPIPE, matching tail) instead of
/// printing a broken-pipe error report.
#[test]
fn closed_pipe_exits_quietly() {
    // The formatted output of this fixture is ~7.5MB, far more than the 64KB
    // pipe buffer, so tale is guaranteed to hit the closed pipe.
    let mut child = Command::new(env!("CARGO_BIN_EXE_tale"))
        .arg(fixture("benchmarks/test_mixed_50000_lines.log"))
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("failed to spawn tale");

    // Read a little, then close the pipe by dropping our end.
    let mut stdout = child.stdout.take().expect("stdout was piped");
    let mut buffer = [0u8; 4096];
    use std::io::Read;
    let _ = stdout.read(&mut buffer);
    drop(stdout);

    let status = child.wait().expect("failed to wait for tale");
    assert_eq!(status.code(), Some(141), "expected exit 141, got {status:?}");

    // The stderr pipe may still have the child's end open; read what we can
    // without blocking on a process that has exited.
    if let Some(mut stderr) = child.stderr.take() {
        let mut collected = Vec::new();
        let _ = stderr.read_to_end(&mut collected);
        let err = String::from_utf8_lossy(&collected);
        assert!(!err.contains("Broken pipe"), "broken pipe leaked to stderr:\n{err}");
    }
}

#[test]
fn help_exits_successfully() {
    let out = run(&["--help"], None);
    assert_success(&out);
    assert!(stdout(&out).contains("Usage:"), ":\n{}", stdout(&out));
}