Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 70 additions & 33 deletions src/uu/paste/src/paste.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use uucore::error::{FromIo, UResult, USimpleError};
use uucore::format_usage;
use uucore::i18n::charmap::mb_char_len;
use uucore::line_ending::LineEnding;
use uucore::translate;
use uucore::{show_if_err, translate};

mod options {
pub const DELIMITER: &str = "delimiters";
Expand Down Expand Up @@ -158,32 +158,24 @@ fn paste(
delimiter_state.reset_to_first_delimiter();
}
} else {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what about -s? paste -s left dir1 right still stops at dir1

let mut eof = vec![false; input_source_vec_len];
let mut columns: Vec<_> = input_source_vec
.into_iter()
.map(|source| Column {
source: Some(source),
read_error: Ok(()),
})
.collect();

loop {
output.clear();

let mut eof_count = 0;

for (i, input_source) in input_source_vec.iter_mut().enumerate() {
if eof[i] {
eof_count += 1;
} else {
match input_source.read_until(line_ending_byte, &mut output)? {
0 => {
eof[i] = true;
eof_count += 1;
}
read => {
remove_trailing_line_ending_byte(line_ending_byte, read, &mut output);
}
}
}

let mut has_record = false;
for column in &mut columns {
has_record |= column.read_field(line_ending_byte, &mut output);
delimiter_state.write_delimiter(&mut output);
}

if eof_count == input_source_vec_len {
if !has_record {
break;
}

Expand All @@ -204,27 +196,70 @@ fn paste(
Ok(())
}

struct Column {
source: Option<InputSource>,
read_error: UResult<()>,
}

impl Column {
/// Append this column's next field and return whether the row has input here.
fn read_field(&mut self, line_ending: u8, output: &mut Vec<u8>) -> bool {
let Some(source) = &mut self.source else {
return false;
};

let start = output.len();
let read = match source.read_until(line_ending, output) {
Ok(read) => read,
Err(err) => {
// Keep any bytes read before the error as this row's field.
// The next row can still get data if the error was transient.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why keep reading after an error? closing the column and showing the error right away would drop the read_error field, no?
the tests only cover a persistent error anyway

self.read_error = Err(err);
output.len() - start
}
};
if read == 0 {
self.source = None;
show_if_err!(&self.read_error);
return false;
}
remove_trailing_line_ending_byte(line_ending, read, output);
true
}
}

fn write_single_input_source(
writer: &mut impl Write,
mut input_source: InputSource,
line_ending_byte: u8,
) -> UResult<()> {
let mut buffer = [0_u8; 8 * 1024];
let mut has_data = false;
let mut last_byte = line_ending_byte;

while let bytes_read @ 1.. = input_source.read(&mut buffer)? {
has_data = true;
last_byte = buffer[bytes_read - 1];

writer.write_all(&buffer[..bytes_read])?;
let mut needs_terminator = false;
let mut read_error = Ok(());

loop {
match input_source.read(&mut buffer) {
Ok(0) => break,
Ok(n) => {
writer.write_all(&buffer[..n])?;
needs_terminator = buffer[n - 1] != line_ending_byte;
}
Err(err) => {
read_error = Err(err);
if !needs_terminator {
break;
}
// Finish the partial record and try reading the next one.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here, a break would be enough, the needs_terminator check after the loop already finishes the record

writer.write_all(&[line_ending_byte])?;
needs_terminator = false;
}
}
}

if has_data && last_byte != line_ending_byte {
if needs_terminator {
writer.write_all(&[line_ending_byte])?;
}

Ok(())
read_error
}

fn parse_delimiters(delimiters: &OsString) -> UResult<Box<[Box<[u8]>]>> {
Expand Down Expand Up @@ -394,7 +429,8 @@ impl InputSource {
USimpleError::new(1, translate!("paste-error-stdin-borrow", "error" => bo))
})?
.lock()
.read(buf)?,
.read(buf)
.map_err_context(|| "-".to_string())?,
};

Ok(us)
Expand All @@ -411,7 +447,8 @@ impl InputSource {
USimpleError::new(1, translate!("paste-error-stdin-borrow", "error" => bo))
})?
.lock()
.read_until(byte, buf)?,
.read_until(byte, buf)
.map_err_context(|| "-".to_string())?,
};

Ok(us)
Expand Down
42 changes: 42 additions & 0 deletions tests/by-util/test_paste.rs
Original file line number Diff line number Diff line change
Expand Up @@ -629,3 +629,45 @@ fn test_read_error_names_the_file() {
.fails_with_code(1)
.stderr_only("paste: sub: Is a directory\n");
}

#[uutests::wasi_ignore(ErrnoMessageMismatch)]
#[test]
#[cfg(not(windows))]
fn test_parallel_read_errors_preserve_other_columns() {
let (at, mut ucmd) = at_and_ucmd!();
at.mkdir("dir1");
at.mkdir("dir2");
at.write("left", "one\ntwo\n");
at.write("right", "three\nfour\nfive\n");

ucmd.args(&["left", "dir1", "right", "dir2"])
.fails_with_code(1)
.stdout_is("one\t\tthree\t\ntwo\t\tfour\t\n\t\tfive\t\n")
.stderr_is("paste: dir1: Is a directory\npaste: dir2: Is a directory\n");
}

#[cfg(all(target_os = "linux", not(wasi_runner)))]
#[test]
fn test_partial_field_before_read_error() {
use std::io::Write;
use uutests::util::pty_path;

let error = uucore::error::strip_errno(&std::io::Error::from_raw_os_error(libc::EIO));
for (inputs, expected) in [
(&["-"][..], "first\0last\0"),
(&["-", "-"][..], "first\tlast\0"),
] {
let (_, controller, mut replica) = pty_path();
replica.write_all(b"first\0last").unwrap();
// The controller yields the pending bytes, then EIO when the replica closes.
drop(replica);

new_ucmd!()
.arg("-z")
.args(inputs)
.set_stdin(controller)
.fails_with_code(1)
.stdout_is(expected)
.stderr_is(format!("paste: -: {error}\n").repeat(inputs.len()));
}
}
Loading