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
175 changes: 104 additions & 71 deletions src/uu/cut/src/cut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,11 @@
use bstr::io::BufReadExt;
use clap::builder::{PossibleValue, ValueParser};
use clap::{Arg, ArgAction, ArgMatches, Command};
use std::ffi::OsString;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, IsTerminal, Read, Write, stdin, stdout};
use std::path::Path;
use uucore::display::Quotable;
use uucore::error::{FromIo, UResult, USimpleError, UUsageError, set_exit_code, strip_errno};
use uucore::error::{FromIo, UResult, USimpleError, UUsageError, strip_errno};
use uucore::i18n::charmap::{Encoding, locale_encoding, mb_char_len};
use uucore::line_ending::LineEnding;
use uucore::os_str_as_bytes;
Expand All @@ -23,7 +22,7 @@ use self::searcher::Searcher;
use matcher::{ExactMatcher, Matcher, MbExactMatcher, WhitespaceMatcher};
use uucore::ranges::{Range, RangeError, RangeErrorKind};
use uucore::translate;
use uucore::{format_usage, show_error, show_if_err};
use uucore::{format_usage, show_if_err};

mod matcher;
mod searcher;
Expand Down Expand Up @@ -338,7 +337,7 @@ fn write_line_bytes<W: Write>(
Ok(())
}

fn cut_bytes<R: Read, W: Write>(
fn cut_bytes<R: BufRead, W: Write>(
reader: R,
out: &mut W,
ranges: &[Range],
Expand All @@ -351,7 +350,7 @@ fn cut_bytes<R: Read, W: Write>(
let mut offset = 0usize;
let mut progress = SelectionProgress::default();
for_each_record_or_piece(
BufReader::new(reader),
reader,
newline,
out,
|out, line| {
Expand Down Expand Up @@ -545,8 +544,8 @@ impl CharCut<'_> {
/// plain byte path. Otherwise each character is emitted whole when its 1-based
/// position falls in a range: the character index for `-c`, or the offset of
/// its last byte for `-b -n` (matching GNU).
fn cut_chars<R: Read, W: Write>(
reader: R,
fn cut_chars<R: BufRead, W: Write>(
mut reader: R,
out: &mut W,
ranges: &[Range],
opts: &Options,
Expand All @@ -560,7 +559,6 @@ fn cut_chars<R: Read, W: Write>(
}

let newline_char = opts.line_ending.into();
let mut buf_in = BufReader::new(reader);
let cut = CharCut {
ranges,
out_delim: opts.out_delimiter.unwrap_or(b"\t"),
Expand All @@ -576,7 +574,7 @@ fn cut_chars<R: Read, W: Write>(
if let Some(limit) = ranges.last().and_then(|r| r.high.checked_mul(4)) {
let mut prefix = Vec::new();
return for_each_record_or_piece(
buf_in,
reader,
newline_char,
out,
|out, line| {
Expand All @@ -597,7 +595,7 @@ fn cut_chars<R: Read, W: Write>(
.map_err(|e| USimpleError::new(1, strip_errno(&e)));
}

buf_in
reader
.for_byte_record(newline_char, |line| {
cut.write_line(line, out)?;
out.write_all(&[newline_char])?;
Expand Down Expand Up @@ -682,18 +680,16 @@ fn write_fields_line<W: Write, M: Matcher>(
}

/// Output delimiter is explicitly specified
fn cut_fields_explicit_out_delim<R: Read, W: Write, M: Matcher>(
reader: R,
fn cut_fields_explicit_out_delim<R: BufRead, W: Write, M: Matcher>(
mut reader: R,
out: &mut W,
matcher: &M,
ranges: &[Range],
only_delimited: bool,
newline_char: u8,
out_delim: &[u8],
) -> UResult<()> {
let mut buf_in = BufReader::new(reader);

buf_in
reader
.for_byte_record_with_terminator(newline_char, |line| {
write_fields_line(
line,
Expand Down Expand Up @@ -767,17 +763,15 @@ fn write_fields_line_implicit<W: Write, M: Matcher>(
}

/// Output delimiter is the same as input delimiter
fn cut_fields_implicit_out_delim<R: Read, W: Write, M: Matcher>(
reader: R,
fn cut_fields_implicit_out_delim<R: BufRead, W: Write, M: Matcher>(
mut reader: R,
out: &mut W,
matcher: &M,
ranges: &[Range],
only_delimited: bool,
newline_char: u8,
) -> UResult<()> {
let mut buf_in = BufReader::new(reader);

buf_in
reader
.for_byte_record_with_terminator(newline_char, |line| {
write_fields_line_implicit(line, out, matcher, ranges, only_delimited, newline_char)?;
Ok(true)
Expand All @@ -787,15 +781,14 @@ fn cut_fields_implicit_out_delim<R: Read, W: Write, M: Matcher>(

/// Streams and filters fields where the record terminator and
/// field delimiter are the same character (specified by `newline_char`)
fn cut_fields_newline_char_delim<R: Read, W: Write>(
reader: R,
fn cut_fields_newline_char_delim<R: BufRead, W: Write>(
mut reader: R,
out: &mut W,
ranges: &[Range],
newline_char: u8,
out_delim: &[u8],
only_delimited: bool,
) -> UResult<()> {
let mut reader = BufReader::new(reader);
let mut line = Vec::new();

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

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

/// Run field cutting with the given matcher, choosing the explicit- or
/// implicit-output-delimiter routine.
fn cut_fields_with_matcher<R: Read, W: Write, M: Matcher>(
fn cut_fields_with_matcher<R: BufRead, W: Write, M: Matcher>(
reader: R,
out: &mut W,
matcher: &M,
Expand Down Expand Up @@ -1110,7 +1102,7 @@ impl<'a> FieldPieces<'a> {
}

/// Stream single-byte fields, buffering only an ambiguous first field.
fn cut_fields_stream<R: Read, W: Write>(
fn cut_fields_stream<R: BufRead, W: Write>(
reader: R,
out: &mut W,
ranges: &[Range],
Expand Down Expand Up @@ -1139,11 +1131,11 @@ fn cut_fields_stream<R: Read, W: Write>(
};
let part =
|out: &mut W, piece: &[u8], record_end: bool| pieces.write_piece(out, piece, record_end);
for_each_record_or_piece(BufReader::new(reader), newline, out, whole, part)
for_each_record_or_piece(reader, newline, out, whole, part)
.map_err(|e| USimpleError::new(1, strip_errno(&e)))
}

fn cut_fields<R: Read, W: Write>(
fn cut_fields<R: BufRead, W: Write>(
reader: R,
out: &mut W,
ranges: &[Range],
Expand Down Expand Up @@ -1210,59 +1202,100 @@ fn cut_fields<R: Read, W: Write>(
}
}

/// Let each selection mode finish the record it has already read, then report
/// the underlying error once for this operand.
struct CutInput<R> {
reader: R,
error: Option<std::io::Error>,
}

impl<R: BufRead> Read for CutInput<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = self.fill_buf()?.read(buf)?;
self.consume(n);
Ok(n)
}
}

impl<R: BufRead> BufRead for CutInput<R> {
fn fill_buf(&mut self) -> std::io::Result<&[u8]> {
if self.error.is_some() {
return Ok(&[]);
}
match self.reader.fill_buf() {
Ok(buf) => Ok(buf),
Err(err) => {
self.error = Some(err);
Ok(&[])
}
}
}

fn consume(&mut self, amt: usize) {
self.reader.consume(amt);
}
}

fn cut_input(reader: impl BufRead, out: &mut impl Write, mode: &Mode) -> std::io::Result<()> {
let mut input = CutInput {
reader,
error: None,
};
show_if_err!(match mode {
Mode::Bytes(ranges, opts) => cut_chars(&mut input, out, ranges, opts, false),
Mode::Characters(ranges, opts) => cut_chars(&mut input, out, ranges, opts, true),
Mode::Fields(ranges, opts) => cut_fields(&mut input, out, ranges, opts),
});
input.error.map_or(Ok(()), Err)
}

fn open_input(filename: &OsStr) -> std::io::Result<File> {
let file = File::open(filename);
// Linux and Android reliably reject directory reads. Some other platforms
// can return directory data or a different error for the same operation.
#[cfg(not(any(target_os = "linux", target_os = "android")))]
{
let is_dir = match &file {
Ok(file) => file.metadata().is_ok_and(|m| m.is_dir()),
// Windows rejects the open itself with access denied.
Err(err) => {
cfg!(windows)
&& err.kind() == std::io::ErrorKind::PermissionDenied
&& std::path::Path::new(filename).is_dir()
}
};
if is_dir {
return Err(std::io::Error::other(translate!("cut-error-is-directory")));
}
}
file
}

fn cut_files<'a, I>(filenames: I, mode: &Mode)
where
I: IntoIterator<Item = &'a OsString>,
{
let mut stdin_read = false;
let mut out: Box<dyn Write> = if stdout().is_terminal() {
Box::new(stdout())
} else {
Box::new(BufWriter::new(stdout())) as Box<dyn Write>
};

let mut stdin_done = false;
for filename in filenames {
if filename == "-" {
if stdin_read {
let result = if filename == "-" {
if stdin_done {
continue;
}

show_if_err!(match mode {
Mode::Bytes(ranges, opts) => cut_chars(stdin(), &mut out, ranges, opts, false),
Mode::Characters(ranges, opts) => cut_chars(stdin(), &mut out, ranges, opts, true),
Mode::Fields(ranges, opts) => cut_fields(stdin(), &mut out, ranges, opts),
});

stdin_read = true;
let result = cut_input(stdin().lock(), &mut out, mode);
// A later '-' retries a read error, but must not restart a field
// selection that already stopped at its last requested range.
stdin_done = result.is_ok();
result
} else {
let path = Path::new(filename);

if path.is_dir() {
show_error!(
"{}: {}",
filename.maybe_quote(),
translate!("cut-error-is-directory")
);
set_exit_code(1);
continue;
}

show_if_err!(
File::open(path)
.map_err_context(|| filename.maybe_quote().to_string())
.and_then(|file| {
match &mode {
Mode::Bytes(ranges, opts) => {
cut_chars(file, &mut out, ranges, opts, false)
}
Mode::Characters(ranges, opts) => {
cut_chars(file, &mut out, ranges, opts, true)
}
Mode::Fields(ranges, opts) => cut_fields(file, &mut out, ranges, opts),
}
})
);
}
open_input(filename).and_then(|file| cut_input(BufReader::new(file), &mut out, mode))
};
show_if_err!(result.map_err_context(|| filename.maybe_quote().to_string()));
}

show_if_err!(
Expand Down
Loading
Loading