From 722936021747ec25df26f32e1aa17e3fe07c33b2 Mon Sep 17 00:00:00 2001 From: Michael Debertol Date: Sat, 7 Aug 2021 21:31:05 +0200 Subject: [PATCH] cat: remove all per-file state cat cannot keep per-file state, so move all remaining state (one_blank_kept) to the global state. --- src/uu/cat/src/cat.rs | 11 +++++++---- tests/by-util/test_cat.rs | 12 ++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/uu/cat/src/cat.rs b/src/uu/cat/src/cat.rs index 6b6f68b13..c71f60a7e 100644 --- a/src/uu/cat/src/cat.rs +++ b/src/uu/cat/src/cat.rs @@ -126,6 +126,9 @@ struct OutputState { /// Whether we skipped a \r, which still needs to be printed skipped_carriage_return: bool, + + /// Whether we have already printed a blank line + one_blank_kept: bool, } /// Represents an open file handle, stream, or other device @@ -343,6 +346,7 @@ fn cat_files(files: Vec, options: &OutputOptions) -> UResult<()> { line_number: 1, at_line_start: true, skipped_carriage_return: false, + one_blank_kept: false, }; let mut error_messages: Vec = Vec::new(); @@ -431,7 +435,6 @@ fn write_lines( let mut in_buf = [0; 1024 * 31]; let stdout = io::stdout(); let mut writer = stdout.lock(); - let mut one_blank_kept = false; while let Ok(n) = handle.reader.read(&mut in_buf) { if n == 0 { @@ -447,8 +450,8 @@ fn write_lines( writer.write_all(b"^M")?; state.skipped_carriage_return = false; } - if !state.at_line_start || !options.squeeze_blank || !one_blank_kept { - one_blank_kept = true; + if !state.at_line_start || !options.squeeze_blank || !state.one_blank_kept { + state.one_blank_kept = true; if state.at_line_start && options.number == NumberingMode::All { write!(&mut writer, "{0:6}\t", state.line_number)?; state.line_number += 1; @@ -467,7 +470,7 @@ fn write_lines( state.skipped_carriage_return = false; state.at_line_start = false; } - one_blank_kept = false; + state.one_blank_kept = false; if state.at_line_start && options.number != NumberingMode::None { write!(&mut writer, "{0:6}\t", state.line_number)?; state.line_number += 1; diff --git a/tests/by-util/test_cat.rs b/tests/by-util/test_cat.rs index eb50d7dce..e0bc49339 100644 --- a/tests/by-util/test_cat.rs +++ b/tests/by-util/test_cat.rs @@ -273,6 +273,18 @@ fn test_stdin_show_ends() { .stdout_only("\t\0$\n\t"); } } + +#[test] +fn squeeze_all_files() { + // empty lines at the end of a file are "squeezed" together with empty lines at the beginning + let (at, mut ucmd) = at_and_ucmd!(); + at.write("input1", "a\n\n"); + at.write("input2", "\n\nb"); + ucmd.args(&["input1", "input2", "-s"]) + .succeeds() + .stdout_only("a\n\nb"); +} + #[test] fn test_show_ends_crlf() { new_ucmd!()