Skip to content

Commit b91d64f

Browse files
committed
paste: preserve readable columns after input errors
1 parent 19e48ff commit b91d64f

3 files changed

Lines changed: 227 additions & 40 deletions

File tree

‎src/uu/paste/Cargo.toml‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ readme.workspace = true
1313

1414
[lib]
1515
path = "src/paste.rs"
16-
test = false
1716
doctest = false
1817

1918
[dependencies]

‎src/uu/paste/src/paste.rs‎

Lines changed: 142 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use uucore::error::{FromIo, UResult, USimpleError};
1717
use uucore::format_usage;
1818
use uucore::i18n::charmap::mb_char_len;
1919
use uucore::line_ending::LineEnding;
20-
use uucore::translate;
20+
use uucore::{show_if_err, translate};
2121

2222
mod options {
2323
pub const DELIMITER: &str = "delimiters";
@@ -142,10 +142,13 @@ fn paste(
142142
for input_source in &mut input_source_vec {
143143
output.clear();
144144

145-
while let read @ 1.. = input_source.read_until(line_ending_byte, &mut output)? {
146-
remove_trailing_line_ending_byte(line_ending_byte, read, &mut output);
145+
let mut read_error = Ok(());
146+
while read_error.is_ok()
147+
&& input_source.read_field(line_ending_byte, &mut output, &mut read_error)
148+
{
147149
delimiter_state.write_delimiter(&mut output);
148150
}
151+
show_if_err!(read_error);
149152

150153
delimiter_state.remove_trailing_delimiter(&mut output);
151154

@@ -158,32 +161,24 @@ fn paste(
158161
delimiter_state.reset_to_first_delimiter();
159162
}
160163
} else {
161-
let mut eof = vec![false; input_source_vec_len];
164+
let mut columns: Vec<_> = input_source_vec
165+
.into_iter()
166+
.map(|source| Column {
167+
source: Some(source),
168+
read_error: Ok(()),
169+
})
170+
.collect();
162171

163172
loop {
164173
output.clear();
165174

166-
let mut eof_count = 0;
167-
168-
for (i, input_source) in input_source_vec.iter_mut().enumerate() {
169-
if eof[i] {
170-
eof_count += 1;
171-
} else {
172-
match input_source.read_until(line_ending_byte, &mut output)? {
173-
0 => {
174-
eof[i] = true;
175-
eof_count += 1;
176-
}
177-
read => {
178-
remove_trailing_line_ending_byte(line_ending_byte, read, &mut output);
179-
}
180-
}
181-
}
182-
175+
let mut has_record = false;
176+
for column in &mut columns {
177+
has_record |= column.read_field(line_ending_byte, &mut output);
183178
delimiter_state.write_delimiter(&mut output);
184179
}
185180

186-
if eof_count == input_source_vec_len {
181+
if !has_record {
187182
break;
188183
}
189184

@@ -204,27 +199,63 @@ fn paste(
204199
Ok(())
205200
}
206201

202+
struct Column<R> {
203+
source: Option<InputSource<R>>,
204+
// Report the last read error once, when the column runs out of input.
205+
read_error: UResult<()>,
206+
}
207+
208+
impl<R: Read> Column<R> {
209+
/// Append this column's next field and return whether the row has input here.
210+
fn read_field(&mut self, line_ending: u8, output: &mut Vec<u8>) -> bool {
211+
let Some(source) = &mut self.source else {
212+
return false;
213+
};
214+
215+
// A partial field ends the row. GNU paste reads this column again on
216+
// the next row so a transient error does not discard the rest of the file.
217+
if source.read_field(line_ending, output, &mut self.read_error) {
218+
return true;
219+
}
220+
self.source = None;
221+
show_if_err!(&self.read_error);
222+
false
223+
}
224+
}
225+
207226
fn write_single_input_source(
208227
writer: &mut impl Write,
209-
mut input_source: InputSource,
228+
mut input_source: InputSource<impl Read>,
210229
line_ending_byte: u8,
211230
) -> UResult<()> {
212231
let mut buffer = [0_u8; 8 * 1024];
213-
let mut has_data = false;
214-
let mut last_byte = line_ending_byte;
215-
216-
while let bytes_read @ 1.. = input_source.read(&mut buffer)? {
217-
has_data = true;
218-
last_byte = buffer[bytes_read - 1];
219-
220-
writer.write_all(&buffer[..bytes_read])?;
232+
let mut needs_terminator = false;
233+
let mut read_error = Ok(());
234+
235+
loop {
236+
match input_source.read(&mut buffer) {
237+
Ok(0) => break,
238+
Ok(n) => {
239+
writer.write_all(&buffer[..n])?;
240+
needs_terminator = buffer[n - 1] != line_ending_byte;
241+
}
242+
Err(err) => {
243+
read_error = Err(err);
244+
if !needs_terminator {
245+
break;
246+
}
247+
// As in the multi-column case, an error after a partial field
248+
// terminates that field but need not be the end of the input.
249+
writer.write_all(&[line_ending_byte])?;
250+
needs_terminator = false;
251+
}
252+
}
221253
}
222254

223-
if has_data && last_byte != line_ending_byte {
255+
if needs_terminator {
224256
writer.write_all(&[line_ending_byte])?;
225257
}
226-
227-
Ok(())
258+
read_error
228259
}
229260

230261
fn parse_delimiters(delimiters: &OsString) -> UResult<Box<[Box<[u8]>]>> {
@@ -376,13 +407,13 @@ impl<'a> DelimiterState<'a> {
376407
}
377408
}
378409

379-
enum InputSource {
410+
enum InputSource<R> {
380411
/// An opened file and the name it was given as, for error messages.
381-
File(BufReader<File>, OsString),
412+
File(BufReader<R>, OsString),
382413
StandardInput(Rc<RefCell<Stdin>>),
383414
}
384415

385-
impl InputSource {
416+
impl<R: Read> InputSource<R> {
386417
fn read(&mut self, buf: &mut [u8]) -> UResult<usize> {
387418
let us = match self {
388419
Self::File(bu, name) => bu
@@ -394,12 +425,35 @@ impl InputSource {
394425
USimpleError::new(1, translate!("paste-error-stdin-borrow", "error" => bo))
395426
})?
396427
.lock()
397-
.read(buf)?,
428+
.read(buf)
429+
.map_err_context(|| "-".to_string())?,
398430
};
399431

400432
Ok(us)
401433
}
402434

435+
/// Keep bytes appended by `read_until` even when it fails partway through a field.
436+
fn read_field(
437+
&mut self,
438+
ending: u8,
439+
output: &mut Vec<u8>,
440+
read_error: &mut UResult<()>,
441+
) -> bool {
442+
let start = output.len();
443+
let read = match self.read_until(ending, output) {
444+
Ok(n) => n,
445+
Err(err) => {
446+
*read_error = Err(err);
447+
output.len() - start
448+
}
449+
};
450+
if read == 0 {
451+
return false;
452+
}
453+
remove_trailing_line_ending_byte(ending, read, output);
454+
true
455+
}
456+
403457
fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> UResult<usize> {
404458
let us = match self {
405459
Self::File(bu, name) => bu
@@ -411,9 +465,58 @@ impl InputSource {
411465
USimpleError::new(1, translate!("paste-error-stdin-borrow", "error" => bo))
412466
})?
413467
.lock()
414-
.read_until(byte, buf)?,
468+
.read_until(byte, buf)
469+
.map_err_context(|| "-".to_string())?,
415470
};
416471

417472
Ok(us)
418473
}
419474
}
475+
476+
#[cfg(test)]
477+
mod tests {
478+
use super::*;
479+
480+
/// One error between two chunks of data, followed by EOF.
481+
fn recovering_input() -> InputSource<impl Read> {
482+
struct FailOnce(bool);
483+
484+
impl Read for FailOnce {
485+
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
486+
if std::mem::take(&mut self.0) {
487+
Err(std::io::Error::other("read failed"))
488+
} else {
489+
Ok(0)
490+
}
491+
}
492+
}
493+
494+
let reader = b"partial"
495+
.as_slice()
496+
.chain(FailOnce(true))
497+
.chain(b"next\n".as_slice());
498+
InputSource::File(BufReader::new(reader), "input".into())
499+
}
500+
501+
#[test]
502+
fn column_reads_the_next_field_after_a_transient_error() {
503+
let mut column = Column {
504+
source: Some(recovering_input()),
505+
read_error: Ok(()),
506+
};
507+
let mut field = Vec::new();
508+
assert!(column.read_field(b'\n', &mut field));
509+
assert_eq!(field, b"partial");
510+
field.clear();
511+
assert!(column.read_field(b'\n', &mut field));
512+
assert_eq!(field, b"next");
513+
}
514+
515+
#[test]
516+
fn single_input_reads_the_next_field_after_a_transient_error() {
517+
let mut output = Vec::new();
518+
let result = write_single_input_source(&mut output, recovering_input(), b'\n');
519+
assert!(result.is_err());
520+
assert_eq!(output, b"partial\nnext\n");
521+
}
522+
}

‎tests/by-util/test_paste.rs‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -629,3 +629,88 @@ fn test_read_error_names_the_file() {
629629
.fails_with_code(1)
630630
.stderr_only("paste: sub: Is a directory\n");
631631
}
632+
633+
#[uutests::wasi_ignore(ErrnoMessageMismatch)]
634+
#[test]
635+
#[cfg(not(windows))]
636+
fn test_parallel_read_errors_preserve_other_columns() {
637+
let (at, mut ucmd) = at_and_ucmd!();
638+
at.mkdir("dir1");
639+
at.mkdir("dir2");
640+
at.write("left", "one\ntwo\n");
641+
at.write("right", "three\nfour\nfive\n");
642+
643+
ucmd.args(&["left", "dir1", "right", "dir2"])
644+
.fails_with_code(1)
645+
.stdout_is("one\t\tthree\t\ntwo\t\tfour\t\n\t\tfive\t\n")
646+
.stderr_is("paste: dir1: Is a directory\npaste: dir2: Is a directory\n");
647+
}
648+
649+
#[cfg(target_os = "linux")]
650+
#[test]
651+
fn test_serial_read_error_emits_empty_record() {
652+
let (at, mut ucmd) = at_and_ucmd!();
653+
at.write("left", "one\ntwo\n");
654+
at.mkdir("dir");
655+
at.write("right", "three\nfour\n");
656+
let error = if cfg!(all(wasi_runner, not(wasip2_runner))) {
657+
"Bad file descriptor"
658+
} else {
659+
"Is a directory"
660+
};
661+
ucmd.args(&["-s", "left", "dir", "right"])
662+
.fails_with_code(1)
663+
.stdout_is("one\ttwo\n\nthree\tfour\n")
664+
.stderr_is(format!("paste: dir: {error}\n"));
665+
}
666+
667+
#[cfg(target_os = "linux")]
668+
#[test]
669+
fn test_serial_read_error_preserves_partial_record() {
670+
use std::io::Write;
671+
use uutests::util::pty_path;
672+
673+
let (at, mut ucmd) = at_and_ucmd!();
674+
at.write("next", "green\0white\0black");
675+
let (_, controller, mut replica) = pty_path();
676+
replica.write_all(b"red\0blue").unwrap();
677+
// Closing the replica makes the controller return EIO after the partial record.
678+
drop(replica);
679+
680+
let error = if cfg!(wasi_runner) {
681+
"I/O error".to_owned()
682+
} else {
683+
uucore::error::strip_errno(&std::io::Error::from_raw_os_error(libc::EIO))
684+
};
685+
ucmd.args(&["-s", "-z", "-d", ":|", "-", "next"])
686+
.set_stdin(controller)
687+
.fails_with_code(1)
688+
.stdout_is("red:blue\0green:white|black\0")
689+
.stderr_is(format!("paste: -: {error}\n"));
690+
}
691+
692+
#[cfg(all(target_os = "linux", not(wasi_runner)))]
693+
#[test]
694+
fn test_partial_field_before_read_error() {
695+
use std::io::Write;
696+
use uutests::util::pty_path;
697+
698+
let error = uucore::error::strip_errno(&std::io::Error::from_raw_os_error(libc::EIO));
699+
for (inputs, expected) in [
700+
(&["-"][..], "first\0last\0"),
701+
(&["-", "-"][..], "first\tlast\0"),
702+
] {
703+
let (_, controller, mut replica) = pty_path();
704+
replica.write_all(b"first\0last").unwrap();
705+
// The controller yields the pending bytes, then EIO when the replica closes.
706+
drop(replica);
707+
708+
new_ucmd!()
709+
.arg("-z")
710+
.args(inputs)
711+
.set_stdin(controller)
712+
.fails_with_code(1)
713+
.stdout_is(expected)
714+
.stderr_is(format!("paste: -: {error}\n").repeat(inputs.len()));
715+
}
716+
}

0 commit comments

Comments
 (0)