Skip to content

Commit 4694641

Browse files
committed
cut: preserve partial records when an input read fails
Let each selection mode finish the bytes already read before reporting the error against the input operand. Continue with later operands, including another read from standard input. On Linux and Android use the read error for directories.
1 parent f88b235 commit 4694641

2 files changed

Lines changed: 168 additions & 72 deletions

File tree

‎src/uu/cut/src/cut.rs‎

Lines changed: 104 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,11 @@
88
use bstr::io::BufReadExt;
99
use clap::builder::{PossibleValue, ValueParser};
1010
use clap::{Arg, ArgAction, ArgMatches, Command};
11-
use std::ffi::OsString;
11+
use std::ffi::{OsStr, OsString};
1212
use std::fs::File;
1313
use std::io::{BufRead, BufReader, BufWriter, IsTerminal, Read, Write, stdin, stdout};
14-
use std::path::Path;
1514
use uucore::display::Quotable;
16-
use uucore::error::{FromIo, UResult, USimpleError, UUsageError, set_exit_code, strip_errno};
15+
use uucore::error::{FromIo, UResult, USimpleError, UUsageError, strip_errno};
1716
use uucore::i18n::charmap::{Encoding, locale_encoding, mb_char_len};
1817
use uucore::line_ending::LineEnding;
1918
use uucore::os_str_as_bytes;
@@ -23,7 +22,7 @@ use self::searcher::Searcher;
2322
use matcher::{ExactMatcher, Matcher, MbExactMatcher, WhitespaceMatcher};
2423
use uucore::ranges::{Range, RangeError, RangeErrorKind};
2524
use uucore::translate;
26-
use uucore::{format_usage, show_error, show_if_err};
25+
use uucore::{format_usage, show_if_err};
2726

2827
mod matcher;
2928
mod searcher;
@@ -338,7 +337,7 @@ fn write_line_bytes<W: Write>(
338337
Ok(())
339338
}
340339

341-
fn cut_bytes<R: Read, W: Write>(
340+
fn cut_bytes<R: BufRead, W: Write>(
342341
reader: R,
343342
out: &mut W,
344343
ranges: &[Range],
@@ -351,7 +350,7 @@ fn cut_bytes<R: Read, W: Write>(
351350
let mut offset = 0usize;
352351
let mut progress = SelectionProgress::default();
353352
for_each_record_or_piece(
354-
BufReader::new(reader),
353+
reader,
355354
newline,
356355
out,
357356
|out, line| {
@@ -545,8 +544,8 @@ impl CharCut<'_> {
545544
/// plain byte path. Otherwise each character is emitted whole when its 1-based
546545
/// position falls in a range: the character index for `-c`, or the offset of
547546
/// its last byte for `-b -n` (matching GNU).
548-
fn cut_chars<R: Read, W: Write>(
549-
reader: R,
547+
fn cut_chars<R: BufRead, W: Write>(
548+
mut reader: R,
550549
out: &mut W,
551550
ranges: &[Range],
552551
opts: &Options,
@@ -560,7 +559,6 @@ fn cut_chars<R: Read, W: Write>(
560559
}
561560

562561
let newline_char = opts.line_ending.into();
563-
let mut buf_in = BufReader::new(reader);
564562
let cut = CharCut {
565563
ranges,
566564
out_delim: opts.out_delimiter.unwrap_or(b"\t"),
@@ -576,7 +574,7 @@ fn cut_chars<R: Read, W: Write>(
576574
if let Some(limit) = ranges.last().and_then(|r| r.high.checked_mul(4)) {
577575
let mut prefix = Vec::new();
578576
return for_each_record_or_piece(
579-
buf_in,
577+
reader,
580578
newline_char,
581579
out,
582580
|out, line| {
@@ -597,7 +595,7 @@ fn cut_chars<R: Read, W: Write>(
597595
.map_err(|e| USimpleError::new(1, strip_errno(&e)));
598596
}
599597

600-
buf_in
598+
reader
601599
.for_byte_record(newline_char, |line| {
602600
cut.write_line(line, out)?;
603601
out.write_all(&[newline_char])?;
@@ -682,18 +680,16 @@ fn write_fields_line<W: Write, M: Matcher>(
682680
}
683681

684682
/// Output delimiter is explicitly specified
685-
fn cut_fields_explicit_out_delim<R: Read, W: Write, M: Matcher>(
686-
reader: R,
683+
fn cut_fields_explicit_out_delim<R: BufRead, W: Write, M: Matcher>(
684+
mut reader: R,
687685
out: &mut W,
688686
matcher: &M,
689687
ranges: &[Range],
690688
only_delimited: bool,
691689
newline_char: u8,
692690
out_delim: &[u8],
693691
) -> UResult<()> {
694-
let mut buf_in = BufReader::new(reader);
695-
696-
buf_in
692+
reader
697693
.for_byte_record_with_terminator(newline_char, |line| {
698694
write_fields_line(
699695
line,
@@ -767,17 +763,15 @@ fn write_fields_line_implicit<W: Write, M: Matcher>(
767763
}
768764

769765
/// Output delimiter is the same as input delimiter
770-
fn cut_fields_implicit_out_delim<R: Read, W: Write, M: Matcher>(
771-
reader: R,
766+
fn cut_fields_implicit_out_delim<R: BufRead, W: Write, M: Matcher>(
767+
mut reader: R,
772768
out: &mut W,
773769
matcher: &M,
774770
ranges: &[Range],
775771
only_delimited: bool,
776772
newline_char: u8,
777773
) -> UResult<()> {
778-
let mut buf_in = BufReader::new(reader);
779-
780-
buf_in
774+
reader
781775
.for_byte_record_with_terminator(newline_char, |line| {
782776
write_fields_line_implicit(line, out, matcher, ranges, only_delimited, newline_char)?;
783777
Ok(true)
@@ -787,15 +781,14 @@ fn cut_fields_implicit_out_delim<R: Read, W: Write, M: Matcher>(
787781

788782
/// Streams and filters fields where the record terminator and
789783
/// field delimiter are the same character (specified by `newline_char`)
790-
fn cut_fields_newline_char_delim<R: Read, W: Write>(
791-
reader: R,
784+
fn cut_fields_newline_char_delim<R: BufRead, W: Write>(
785+
mut reader: R,
792786
out: &mut W,
793787
ranges: &[Range],
794788
newline_char: u8,
795789
out_delim: &[u8],
796790
only_delimited: bool,
797791
) -> UResult<()> {
798-
let mut reader = BufReader::new(reader);
799792
let mut line = Vec::new();
800793

801794
// We start at 1 because 'cut' field indexing is 1-based
@@ -918,23 +911,22 @@ fn cut_fields_newline_char_delim<R: Read, W: Write>(
918911
/// `--whitespace-delimited=trimmed`: strip leading/trailing blanks from each
919912
/// line, then split on runs of blanks. With no internal blank the line is
920913
/// undelimited (suppressed under `-s`).
921-
fn cut_fields_whitespace_trimmed<R: Read, W: Write>(
922-
reader: R,
914+
fn cut_fields_whitespace_trimmed<R: BufRead, W: Write>(
915+
mut reader: R,
923916
out: &mut W,
924917
ranges: &[Range],
925918
only_delimited: bool,
926919
newline_char: u8,
927920
out_delim: &[u8],
928921
) -> UResult<()> {
929922
let matcher = WhitespaceMatcher {};
930-
let mut buf_in = BufReader::new(reader);
931923

932924
// Trimming is the only difference from the plain whitespace path: once the
933925
// outer blanks are gone, the remaining blank runs are ordinary delimiters.
934926
// The ends are trimmed with the same matcher that splits the fields, so
935927
// in a UTF-8 locale a Unicode blank at either end is trimmed rather than
936928
// turned into a leading or trailing delimiter.
937-
buf_in
929+
reader
938930
.for_byte_record(newline_char, |line| {
939931
let start = match matcher.next_match(line) {
940932
Some((0, run_end)) => run_end,
@@ -968,7 +960,7 @@ fn cut_fields_whitespace_trimmed<R: Read, W: Write>(
968960

969961
/// Run field cutting with the given matcher, choosing the explicit- or
970962
/// implicit-output-delimiter routine.
971-
fn cut_fields_with_matcher<R: Read, W: Write, M: Matcher>(
963+
fn cut_fields_with_matcher<R: BufRead, W: Write, M: Matcher>(
972964
reader: R,
973965
out: &mut W,
974966
matcher: &M,
@@ -1110,7 +1102,7 @@ impl<'a> FieldPieces<'a> {
11101102
}
11111103

11121104
/// Stream single-byte fields, buffering only an ambiguous first field.
1113-
fn cut_fields_stream<R: Read, W: Write>(
1105+
fn cut_fields_stream<R: BufRead, W: Write>(
11141106
reader: R,
11151107
out: &mut W,
11161108
ranges: &[Range],
@@ -1139,11 +1131,11 @@ fn cut_fields_stream<R: Read, W: Write>(
11391131
};
11401132
let part =
11411133
|out: &mut W, piece: &[u8], record_end: bool| pieces.write_piece(out, piece, record_end);
1142-
for_each_record_or_piece(BufReader::new(reader), newline, out, whole, part)
1134+
for_each_record_or_piece(reader, newline, out, whole, part)
11431135
.map_err(|e| USimpleError::new(1, strip_errno(&e)))
11441136
}
11451137

1146-
fn cut_fields<R: Read, W: Write>(
1138+
fn cut_fields<R: BufRead, W: Write>(
11471139
reader: R,
11481140
out: &mut W,
11491141
ranges: &[Range],
@@ -1210,59 +1202,100 @@ fn cut_fields<R: Read, W: Write>(
12101202
}
12111203
}
12121204

1205+
/// Let each selection mode finish the record it has already read, then report
1206+
/// the underlying error once for this operand.
1207+
struct CutInput<R> {
1208+
reader: R,
1209+
error: Option<std::io::Error>,
1210+
}
1211+
1212+
impl<R: BufRead> Read for CutInput<R> {
1213+
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
1214+
let n = self.fill_buf()?.read(buf)?;
1215+
self.consume(n);
1216+
Ok(n)
1217+
}
1218+
}
1219+
1220+
impl<R: BufRead> BufRead for CutInput<R> {
1221+
fn fill_buf(&mut self) -> std::io::Result<&[u8]> {
1222+
if self.error.is_some() {
1223+
return Ok(&[]);
1224+
}
1225+
match self.reader.fill_buf() {
1226+
Ok(buf) => Ok(buf),
1227+
Err(err) => {
1228+
self.error = Some(err);
1229+
Ok(&[])
1230+
}
1231+
}
1232+
}
1233+
1234+
fn consume(&mut self, amt: usize) {
1235+
self.reader.consume(amt);
1236+
}
1237+
}
1238+
1239+
fn cut_input(reader: impl BufRead, out: &mut impl Write, mode: &Mode) -> std::io::Result<()> {
1240+
let mut input = CutInput {
1241+
reader,
1242+
error: None,
1243+
};
1244+
show_if_err!(match mode {
1245+
Mode::Bytes(ranges, opts) => cut_chars(&mut input, out, ranges, opts, false),
1246+
Mode::Characters(ranges, opts) => cut_chars(&mut input, out, ranges, opts, true),
1247+
Mode::Fields(ranges, opts) => cut_fields(&mut input, out, ranges, opts),
1248+
});
1249+
input.error.map_or(Ok(()), Err)
1250+
}
1251+
1252+
fn open_input(filename: &OsStr) -> std::io::Result<File> {
1253+
let file = File::open(filename);
1254+
// Linux and Android reliably reject directory reads. Some other platforms
1255+
// can return directory data or a different error for the same operation.
1256+
#[cfg(not(any(target_os = "linux", target_os = "android")))]
1257+
{
1258+
let is_dir = match &file {
1259+
Ok(file) => file.metadata().is_ok_and(|m| m.is_dir()),
1260+
// Windows rejects the open itself with access denied.
1261+
Err(err) => {
1262+
cfg!(windows)
1263+
&& err.kind() == std::io::ErrorKind::PermissionDenied
1264+
&& std::path::Path::new(filename).is_dir()
1265+
}
1266+
};
1267+
if is_dir {
1268+
return Err(std::io::Error::other(translate!("cut-error-is-directory")));
1269+
}
1270+
}
1271+
file
1272+
}
1273+
12131274
fn cut_files<'a, I>(filenames: I, mode: &Mode)
12141275
where
12151276
I: IntoIterator<Item = &'a OsString>,
12161277
{
1217-
let mut stdin_read = false;
12181278
let mut out: Box<dyn Write> = if stdout().is_terminal() {
12191279
Box::new(stdout())
12201280
} else {
12211281
Box::new(BufWriter::new(stdout())) as Box<dyn Write>
12221282
};
12231283

1284+
let mut stdin_done = false;
12241285
for filename in filenames {
1225-
if filename == "-" {
1226-
if stdin_read {
1286+
let result = if filename == "-" {
1287+
if stdin_done {
12271288
continue;
12281289
}
1229-
1230-
show_if_err!(match mode {
1231-
Mode::Bytes(ranges, opts) => cut_chars(stdin(), &mut out, ranges, opts, false),
1232-
Mode::Characters(ranges, opts) => cut_chars(stdin(), &mut out, ranges, opts, true),
1233-
Mode::Fields(ranges, opts) => cut_fields(stdin(), &mut out, ranges, opts),
1234-
});
1235-
1236-
stdin_read = true;
1290+
let result = cut_input(stdin().lock(), &mut out, mode);
1291+
// A later '-' retries a read error, but must not restart a field
1292+
// selection that already stopped at its last requested range.
1293+
stdin_done = result.is_ok();
1294+
result
12371295
} else {
1238-
let path = Path::new(filename);
1239-
1240-
if path.is_dir() {
1241-
show_error!(
1242-
"{}: {}",
1243-
filename.maybe_quote(),
1244-
translate!("cut-error-is-directory")
1245-
);
1246-
set_exit_code(1);
1247-
continue;
1248-
}
1249-
1250-
show_if_err!(
1251-
File::open(path)
1252-
.map_err_context(|| filename.maybe_quote().to_string())
1253-
.and_then(|file| {
1254-
match &mode {
1255-
Mode::Bytes(ranges, opts) => {
1256-
cut_chars(file, &mut out, ranges, opts, false)
1257-
}
1258-
Mode::Characters(ranges, opts) => {
1259-
cut_chars(file, &mut out, ranges, opts, true)
1260-
}
1261-
Mode::Fields(ranges, opts) => cut_fields(file, &mut out, ranges, opts),
1262-
}
1263-
})
1264-
);
1265-
}
1296+
open_input(filename).and_then(|file| cut_input(BufReader::new(file), &mut out, mode))
1297+
};
1298+
show_if_err!(result.map_err_context(|| filename.maybe_quote().to_string()));
12661299
}
12671300

12681301
show_if_err!(

0 commit comments

Comments
 (0)