From b99643e52432ea227cfbb659368e1866071b5e3a Mon Sep 17 00:00:00 2001 From: Aaron Ang Date: Sat, 28 Nov 2026 12:12:40 -0500 Subject: [PATCH 1/6] more: copy input unpaged when stdout is not a terminal Piped stdin comes first, and a header with the file name comes before each file when there is more than one input. -F and -P still pick the first line written. --- src/uu/more/src/more.rs | 135 ++++++++++++++++++++++++++++++------- tests/by-util/test_more.rs | 96 ++++++++++++++++++++++++++ 2 files changed, 208 insertions(+), 23 deletions(-) diff --git a/src/uu/more/src/more.rs b/src/uu/more/src/more.rs index ca9a6045120..2c47d130692 100644 --- a/src/uu/more/src/more.rs +++ b/src/uu/more/src/more.rs @@ -142,28 +142,28 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { })); let matches = uucore::clap_localization::handle_clap_result(uu_app(), args)?; let mut options = Options::from(&matches); - if let Some(files) = matches.get_many::(options::FILES) { + let files: Vec<&OsString> = matches + .get_many::(options::FILES) + .map(Iterator::collect) + .unwrap_or_default(); + if !stdout().is_terminal() { + return copy_to_stdout(&files, &options); + } + if files.is_empty() { + let stdin = stdin(); + if stdin.is_terminal() { + // stdin is not a pipe + return Err(UUsageError::new(1, MoreError::BadUsage.to_string())); + } + more(Input::from_stdin(stdin), false, None, None, &mut options)?; + } else { let length = files.len(); - let mut files_iter = files.peekable(); + let mut files_iter = files.into_iter().peekable(); while let (Some(file_os), next_file) = (files_iter.next(), files_iter.peek()) { let file = Path::new(file_os); - if file.is_dir() { - show!(UUsageError::new( - 0, - MoreError::IsDirectory(file.into()).to_string(), - )); + let Some(opened_file) = open_file(file_os) else { continue; - } - let opened_file = match File::open(file) { - Err(why) => { - show!(USimpleError::new( - 0, - MoreError::CannotOpen(file_os.into(), why).to_string(), - )); - continue; - } - Ok(opened_file) => opened_file, }; let next_file_str = next_file.map(|f| f.to_string_lossy().into_owned()); more( @@ -174,18 +174,107 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { &mut options, )?; } - } else { - let stdin = stdin(); - if stdin.is_terminal() { - // stdin is not a pipe - return Err(UUsageError::new(1, MoreError::BadUsage.to_string())); + } + + Ok(()) +} + +/// Open `file_os` for reading, reporting why it can't be shown if it fails. +fn open_file(file_os: &OsString) -> Option { + let file = Path::new(file_os); + if file.is_dir() { + show!(UUsageError::new( + 0, + MoreError::IsDirectory(file.into()).to_string(), + )); + return None; + } + match File::open(file) { + Err(why) => { + show!(USimpleError::new( + 0, + MoreError::CannotOpen(file_os.into(), why).to_string(), + )); + None } - more(Input::from_stdin(stdin), false, None, None, &mut options)?; + Ok(opened_file) => Some(opened_file), } +} +/// Write the input to stdout unpaged, for when stdout is not a terminal. +/// +/// Piped stdin is written first. A header with the file name comes before +/// each file when there is more than one input. +fn copy_to_stdout(files: &[&OsString], options: &Options) -> UResult<()> { + let stdin = stdin(); + let read_stdin = !stdin.is_terminal(); + if files.is_empty() && !read_stdin { + return Err(UUsageError::new(1, MoreError::BadUsage.to_string())); + } + let mut out = stdout().lock(); + // Only the first input starts at the requested line + let mut from_line = options.from_line; + if read_stdin { + std::io::copy(&mut stdin.lock(), &mut out)?; + from_line = 0; + } + let show_header = read_stdin || files.len() > 1; + for file_os in files { + let Some(file) = open_file(file_os) else { + continue; + }; + if show_header { + out.write_all(b"::::::::::::::\n")?; + out.write_all(file_os.as_encoded_bytes())?; + out.write_all(b"\n::::::::::::::\n")?; + } + let mut reader = BufReader::new(file); + let copied = skip_to_start(&mut reader, from_line, options.pattern.as_deref()) + .and_then(|start| out.write_all(&start)) + .and_then(|()| std::io::copy(&mut reader, &mut out)); + if let Err(e) = copied { + show!(USimpleError::new( + 0, + format!("{}: {}", file_os.maybe_quote(), strip_errno(&e)) + )); + } + from_line = 0; + } + out.flush()?; Ok(()) } +/// Skip `from_line` lines, then up to the first line containing `pattern`. +/// +/// Returns the lines read past that point, to be written before the rest of +/// `reader`. When no line matches, nothing more is skipped. +fn skip_to_start( + reader: &mut impl BufRead, + from_line: usize, + pattern: Option<&str>, +) -> std::io::Result> { + let mut line = Vec::new(); + for _ in 0..from_line { + line.clear(); + if reader.read_until(b'\n', &mut line)? == 0 { + return Ok(Vec::new()); + } + } + let Some(pattern) = pattern else { + return Ok(Vec::new()); + }; + let mut scanned = Vec::new(); + loop { + let line_start = scanned.len(); + if reader.read_until(b'\n', &mut scanned)? == 0 { + return Ok(scanned); + } + if String::from_utf8_lossy(&scanned[line_start..]).contains(pattern) { + return Ok(scanned.split_off(line_start)); + } + } +} + pub fn uu_app() -> Command { Command::new("more") .about(translate!("more-about")) diff --git a/tests/by-util/test_more.rs b/tests/by-util/test_more.rs index 6a119213290..3dbcde68a4a 100644 --- a/tests/by-util/test_more.rs +++ b/tests/by-util/test_more.rs @@ -273,3 +273,99 @@ fn test_lines_option_max_u16_no_overflow() { assert!(output.contains("line1")); quit_more(&mut controller, child); } + +#[cfg(unix)] +fn more_to_pipe(args: &[&str]) -> uutests::util::CmdResult { + // stdin is a terminal so only the files are copied + let (path, _controller, _replica) = pty_path(); + let (at, mut ucmd) = at_and_ucmd!(); + at.write("a.txt", "a1\n\n\na2\n"); + at.write("b.txt", "b1\nb2"); + ucmd.set_stdin(File::open(&path).unwrap()).args(args).run() +} + +#[test] +#[cfg(unix)] +fn test_pipe_output_single_file() { + more_to_pipe(&["-s", "-n", "1", "a.txt"]) + .success() + .stdout_only("a1\n\n\na2\n"); +} + +#[test] +#[cfg(unix)] +fn test_pipe_output_multiple_files() { + more_to_pipe(&["b.txt", "missing.txt", "a.txt"]) + .success() + .stdout_is( + "::::::::::::::\nb.txt\n::::::::::::::\nb1\nb2\ + ::::::::::::::\na.txt\n::::::::::::::\na1\n\n\na2\n", + ) + .stderr_contains("missing.txt"); +} + +#[test] +#[cfg(unix)] +fn test_pipe_output_from_line() { + // Only the first file starts at the requested line + more_to_pipe(&["-F", "4", "a.txt", "b.txt"]) + .success() + .stdout_only( + "::::::::::::::\na.txt\n::::::::::::::\na2\n\ + ::::::::::::::\nb.txt\n::::::::::::::\nb1\nb2", + ); +} + +#[test] +#[cfg(unix)] +fn test_pipe_output_pattern() { + more_to_pipe(&["-P", "a2", "a.txt"]) + .success() + .stdout_only("a2\n"); + more_to_pipe(&["-P", "none", "a.txt"]) + .success() + .stdout_only("a1\n\n\na2\n"); +} + +#[test] +#[cfg(unix)] +fn test_pipe_output_piped_stdin() { + new_ucmd!() + .pipe_in("piped\n") + .succeeds() + .stdout_only("piped\n"); + + let (at, mut ucmd) = at_and_ucmd!(); + at.write("a.txt", "a1\n"); + ucmd.arg("a.txt") + .pipe_in("piped\n") + .succeeds() + .stdout_only("piped\n::::::::::::::\na.txt\n::::::::::::::\na1\n"); +} + +#[test] +#[cfg(unix)] +fn test_pipe_output_pattern_fifo() { + let (path, _controller, _replica) = pty_path(); + let (at, mut ucmd) = at_and_ucmd!(); + at.mkfifo("fifo"); + let fifo = at.plus("fifo"); + let writer = std::thread::spawn(move || std::fs::write(fifo, "x\ny\nz\n").unwrap()); + ucmd.set_stdin(File::open(&path).unwrap()) + .args(&["-P", "y", "fifo"]) + .succeeds() + .stdout_only("y\nz\n"); + writer.join().unwrap(); +} + +#[test] +#[cfg(unix)] +fn test_pipe_output_piped_stdin_is_first_input() { + // stdin is the first input, so the file is shown from its first line + let (at, mut ucmd) = at_and_ucmd!(); + at.write("a.txt", "a1\na2\n"); + ucmd.args(&["-F", "2", "a.txt"]) + .pipe_in("p1\np2\n") + .succeeds() + .stdout_only("p1\np2\n::::::::::::::\na.txt\n::::::::::::::\na1\na2\n"); +} From bd101fc62b7ab4c7d76e90f86cea1961c61a3516 Mon Sep 17 00:00:00 2001 From: Aaron Ang Date: Sun, 29 Nov 2026 10:15:21 -0500 Subject: [PATCH 2/6] more: stop on write errors when copying to a pipe Read errors are still reported per input, including piped stdin, and the next input is shown. Add a CannotRead error and share the header rule with the pager. --- src/uu/more/locales/en-US.ftl | 1 + src/uu/more/locales/fr-FR.ftl | 1 + src/uu/more/src/more.rs | 85 ++++++++++++++++++++++++++--------- tests/by-util/test_more.rs | 42 +++++++++++++++++ 4 files changed, 108 insertions(+), 21 deletions(-) diff --git a/src/uu/more/locales/en-US.ftl b/src/uu/more/locales/en-US.ftl index 7587b1e2e00..1803a6773bb 100644 --- a/src/uu/more/locales/en-US.ftl +++ b/src/uu/more/locales/en-US.ftl @@ -4,6 +4,7 @@ more-usage = more [OPTIONS] FILE... # Error messages more-error-is-directory = {$path}: Is a directory more-error-cannot-open = cannot open {$path}: {$error} +more-error-cannot-read = {$path}: {$error} more-error-bad-usage = bad usage more-error-cannot-seek-to-line = Cannot seek to line number {$line} more-error-pattern-not-found = Pattern not found diff --git a/src/uu/more/locales/fr-FR.ftl b/src/uu/more/locales/fr-FR.ftl index 1bec9de5889..f157d047e2a 100644 --- a/src/uu/more/locales/fr-FR.ftl +++ b/src/uu/more/locales/fr-FR.ftl @@ -4,6 +4,7 @@ more-usage = more [OPTIONS] FICHIER... # Messages d'erreur more-error-is-directory = {$path} : est un répertoire more-error-cannot-open = impossible d'ouvrir {$path} : {$error} +more-error-cannot-read = {$path} : {$error} more-error-bad-usage = mauvaise utilisation more-error-cannot-seek-to-line = Impossible d'atteindre la ligne numéro {$line} more-error-pattern-not-found = Motif non trouvé diff --git a/src/uu/more/src/more.rs b/src/uu/more/src/more.rs index 2c47d130692..f75e9323662 100644 --- a/src/uu/more/src/more.rs +++ b/src/uu/more/src/more.rs @@ -32,6 +32,7 @@ use uucore::translate; enum MoreError { IsDirectory(PathBuf), CannotOpen(PathBuf, std::io::Error), + CannotRead(PathBuf, std::io::Error), BadUsage, } @@ -59,6 +60,17 @@ impl std::fmt::Display for MoreError { ) ) } + Self::CannotRead(path, error) => { + write!( + f, + "{}", + translate!( + "more-error-cannot-read", + "path" => path.maybe_quote(), + "error" => strip_errno(error) + ) + ) + } Self::BadUsage => { write!(f, "{}", translate!("more-error-bad-usage")) } @@ -70,9 +82,11 @@ impl std::error::Error for MoreError {} const BELL: char = '\x07'; // Printing this character will ring the bell -/// The prompt to be displayed at the top of the screen when viewing multiple files, -/// with the file name in the middle -const MULTI_FILE_TOP_PROMPT: &str = "\r::::::::::::::\n\r{}\n\r::::::::::::::\n"; +/// The line above and below the file name in the header shown before each +/// file when there are several +const HEADER_RULE: &str = "::::::::::::::"; +/// Number of rows the header takes +const HEADER_ROWS: usize = 3; pub mod options { pub const SILENT: &str = "silent"; @@ -215,7 +229,16 @@ fn copy_to_stdout(files: &[&OsString], options: &Options) -> UResult<()> { // Only the first input starts at the requested line let mut from_line = options.from_line; if read_stdin { - std::io::copy(&mut stdin.lock(), &mut out)?; + if let Some(e) = copy_until_read_error(&mut stdin.lock(), &mut out)? { + show!(USimpleError::new( + 0, + translate!( + "more-error-cannot-read", + "path" => "standard input", + "error" => strip_errno(&e) + ) + )); + } from_line = 0; } let show_header = read_stdin || files.len() > 1; @@ -224,18 +247,23 @@ fn copy_to_stdout(files: &[&OsString], options: &Options) -> UResult<()> { continue; }; if show_header { - out.write_all(b"::::::::::::::\n")?; + writeln!(out, "{HEADER_RULE}")?; out.write_all(file_os.as_encoded_bytes())?; - out.write_all(b"\n::::::::::::::\n")?; + writeln!(out, "\n{HEADER_RULE}")?; } let mut reader = BufReader::new(file); - let copied = skip_to_start(&mut reader, from_line, options.pattern.as_deref()) - .and_then(|start| out.write_all(&start)) - .and_then(|()| std::io::copy(&mut reader, &mut out)); - if let Err(e) = copied { + // A read error only skips the rest of this file, a write error stops + let read_error = match skip_to_start(&mut reader, from_line, options.pattern.as_deref()) { + Ok(start) => { + out.write_all(&start)?; + copy_until_read_error(&mut reader, &mut out)? + } + Err(e) => Some(e), + }; + if let Some(e) = read_error { show!(USimpleError::new( 0, - format!("{}: {}", file_os.maybe_quote(), strip_errno(&e)) + MoreError::CannotRead(file_os.into(), e).to_string() )); } from_line = 0; @@ -244,6 +272,25 @@ fn copy_to_stdout(files: &[&OsString], options: &Options) -> UResult<()> { Ok(()) } +/// Copy `reader` to `out`. A read error is returned as `Ok(Some(_))` so the +/// caller can tell it from a write error. +fn copy_until_read_error( + reader: &mut impl BufRead, + out: &mut impl Write, +) -> std::io::Result> { + loop { + let buf = match reader.fill_buf() { + Ok([]) => return Ok(None), + Ok(buf) => buf, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(e) => return Ok(Some(e)), + }; + let len = buf.len(); + out.write_all(buf)?; + reader.consume(len); + } +} + /// Skip `from_line` lines, then up to the first line containing `pattern`. /// /// Returns the lines read past that point, to be written before the rest of @@ -694,21 +741,17 @@ impl<'a> Pager<'a> { fn display_multi_file_header(&mut self) -> UResult<()> { self.clear_line()?; - self.stdout.write_all( - MULTI_FILE_TOP_PROMPT - .replace("{}", self.file_name.unwrap_or_default()) - .as_bytes(), + write!( + self.stdout, + "\r{HEADER_RULE}\n\r{}\n\r{HEADER_RULE}\n", + self.file_name.unwrap_or_default() )?; - self.content_rows = self - .content_rows - .saturating_sub(MULTI_FILE_TOP_PROMPT.lines().count()); + self.content_rows = self.content_rows.saturating_sub(HEADER_ROWS); Ok(()) } fn reset_multi_file_header(&mut self) { - self.content_rows = self - .content_rows - .saturating_add(MULTI_FILE_TOP_PROMPT.lines().count()); + self.content_rows = self.content_rows.saturating_add(HEADER_ROWS); } fn update_display(&mut self, options: &Options) -> UResult<()> { diff --git a/tests/by-util/test_more.rs b/tests/by-util/test_more.rs index 3dbcde68a4a..c0dc321f889 100644 --- a/tests/by-util/test_more.rs +++ b/tests/by-util/test_more.rs @@ -369,3 +369,45 @@ fn test_pipe_output_piped_stdin_is_first_input() { .succeeds() .stdout_only("p1\np2\n::::::::::::::\na.txt\n::::::::::::::\na1\na2\n"); } + +#[test] +#[cfg(target_os = "linux")] +fn test_pipe_output_write_error_stops() { + // A write error is not blamed on the file being read + let (path, _controller, _replica) = pty_path(); + let (at, mut ucmd) = at_and_ucmd!(); + at.write("a.txt", "a\n"); + // A terminal on stdin, so the file is the only input and has no header + ucmd.arg("a.txt") + .set_stdin(File::open(&path).unwrap()) + .set_stdout(File::create("/dev/full").unwrap()) + .fails() + .stderr_does_not_contain("a.txt") + .stderr_contains("No space left on device"); +} + +#[test] +#[cfg(target_os = "linux")] +fn test_pipe_output_read_error_continues() { + // Reading /proc/self/mem at offset 0 fails, the next file is still shown + let (at, mut ucmd) = at_and_ucmd!(); + at.write("a.txt", "a\n"); + ucmd.args(&["/proc/self/mem", "a.txt"]) + .succeeds() + .stderr_is("more: /proc/self/mem: Input/output error\n") + .stdout_contains("a.txt\n::::::::::::::\na\n"); +} + +#[test] +#[cfg(target_os = "linux")] +fn test_pipe_output_stdin_read_error_continues() { + // Reading a directory fails, the file is still shown + let (at, mut ucmd) = at_and_ucmd!(); + at.mkdir("dir"); + at.write("a.txt", "a\n"); + ucmd.arg("a.txt") + .set_stdin(File::open(at.plus("dir")).unwrap()) + .succeeds() + .stderr_is("more: standard input: Is a directory\n") + .stdout_contains("a.txt\n::::::::::::::\na\n"); +} From f6ee017984c5fce2da107507bcf0fa1c4fb2630f Mon Sep 17 00:00:00 2001 From: Aaron Ang Date: Sun, 29 Nov 2026 11:31:12 -0500 Subject: [PATCH 3/6] test_more.rs: match the C library's EIO message musl says "I/O error" where glibc says "Input/output error", so build the expected message from the platform's strerror. --- tests/by-util/test_more.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/by-util/test_more.rs b/tests/by-util/test_more.rs index c0dc321f889..3badd72261b 100644 --- a/tests/by-util/test_more.rs +++ b/tests/by-util/test_more.rs @@ -392,9 +392,10 @@ fn test_pipe_output_read_error_continues() { // Reading /proc/self/mem at offset 0 fails, the next file is still shown let (at, mut ucmd) = at_and_ucmd!(); at.write("a.txt", "a\n"); + let eio = uucore::error::strip_errno(&std::io::Error::from_raw_os_error(libc::EIO)); ucmd.args(&["/proc/self/mem", "a.txt"]) .succeeds() - .stderr_is("more: /proc/self/mem: Input/output error\n") + .stderr_is(format!("more: /proc/self/mem: {eio}\n")) .stdout_contains("a.txt\n::::::::::::::\na\n"); } From 15488e24e8f5478ea13802797521cec7ef0b7147 Mon Sep 17 00:00:00 2001 From: Aaron Ang Date: Sun, 29 Nov 2026 14:03:14 -0500 Subject: [PATCH 4/6] more: seek back when the pattern isn't found Searching for the pattern kept every line read, so a file without a match ended up in memory. Hold one line at a time and seek back to where the search started; a FIFO can't seek, so nothing is shown. Report stdin read errors with MoreError::CannotRead like files. --- src/uu/more/src/more.rs | 64 +++++++++++++++++++++----------------- tests/by-util/test_more.rs | 16 ++++++++++ 2 files changed, 52 insertions(+), 28 deletions(-) diff --git a/src/uu/more/src/more.rs b/src/uu/more/src/more.rs index f75e9323662..4f1f90398f4 100644 --- a/src/uu/more/src/more.rs +++ b/src/uu/more/src/more.rs @@ -4,9 +4,11 @@ // file that was distributed with this source code. use std::{ - ffi::OsString, + ffi::{OsStr, OsString}, fs::File, - io::{BufRead, BufReader, IsTerminal as _, Stdin, Stdout, Write, stdin, stdout}, + io::{ + BufRead, BufReader, IsTerminal as _, Seek, SeekFrom, Stdin, Stdout, Write, stdin, stdout, + }, panic::set_hook, path::{Path, PathBuf}, time::Duration, @@ -29,14 +31,14 @@ use uucore::{display::Quotable, show}; use uucore::translate; #[derive(Debug)] -enum MoreError { +enum MoreError<'a> { IsDirectory(PathBuf), CannotOpen(PathBuf, std::io::Error), - CannotRead(PathBuf, std::io::Error), + CannotRead(Option<&'a OsStr>, std::io::Error), BadUsage, } -impl std::fmt::Display for MoreError { +impl std::fmt::Display for MoreError<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::IsDirectory(path) => { @@ -61,15 +63,21 @@ impl std::fmt::Display for MoreError { ) } Self::CannotRead(path, error) => { - write!( - f, - "{}", + let error = strip_errno(error); + let message = if let Some(path) = path { translate!( - "more-error-cannot-read", - "path" => path.maybe_quote(), - "error" => strip_errno(error) + "more-error-cannot-read", + "path" => path.maybe_quote(), + "error" => error ) - ) + } else { + translate!( + "more-error-cannot-read", + "path" => "standard input", + "error" => error + ) + }; + write!(f, "{message}") } Self::BadUsage => { write!(f, "{}", translate!("more-error-bad-usage")) @@ -78,7 +86,7 @@ impl std::fmt::Display for MoreError { } } -impl std::error::Error for MoreError {} +impl std::error::Error for MoreError<'_> {} const BELL: char = '\x07'; // Printing this character will ring the bell @@ -232,11 +240,7 @@ fn copy_to_stdout(files: &[&OsString], options: &Options) -> UResult<()> { if let Some(e) = copy_until_read_error(&mut stdin.lock(), &mut out)? { show!(USimpleError::new( 0, - translate!( - "more-error-cannot-read", - "path" => "standard input", - "error" => strip_errno(&e) - ) + MoreError::CannotRead(None, e).to_string() )); } from_line = 0; @@ -263,7 +267,7 @@ fn copy_to_stdout(files: &[&OsString], options: &Options) -> UResult<()> { if let Some(e) = read_error { show!(USimpleError::new( 0, - MoreError::CannotRead(file_os.into(), e).to_string() + MoreError::CannotRead(Some(file_os), e).to_string() )); } from_line = 0; @@ -293,10 +297,11 @@ fn copy_until_read_error( /// Skip `from_line` lines, then up to the first line containing `pattern`. /// -/// Returns the lines read past that point, to be written before the rest of -/// `reader`. When no line matches, nothing more is skipped. +/// Returns the matching line, to be written before the rest of `reader`. +/// When no line matches, `reader` goes back to where the search started if +/// it can seek, so only one line is held in memory at a time. fn skip_to_start( - reader: &mut impl BufRead, + reader: &mut (impl BufRead + Seek), from_line: usize, pattern: Option<&str>, ) -> std::io::Result> { @@ -310,14 +315,17 @@ fn skip_to_start( let Some(pattern) = pattern else { return Ok(Vec::new()); }; - let mut scanned = Vec::new(); + let search_start = reader.stream_position().ok(); loop { - let line_start = scanned.len(); - if reader.read_until(b'\n', &mut scanned)? == 0 { - return Ok(scanned); + line.clear(); + if reader.read_until(b'\n', &mut line)? == 0 { + if let Some(position) = search_start { + reader.seek(SeekFrom::Start(position))?; + } + return Ok(Vec::new()); } - if String::from_utf8_lossy(&scanned[line_start..]).contains(pattern) { - return Ok(scanned.split_off(line_start)); + if String::from_utf8_lossy(&line).contains(pattern) { + return Ok(line); } } } diff --git a/tests/by-util/test_more.rs b/tests/by-util/test_more.rs index 3badd72261b..6df8737740f 100644 --- a/tests/by-util/test_more.rs +++ b/tests/by-util/test_more.rs @@ -358,6 +358,22 @@ fn test_pipe_output_pattern_fifo() { writer.join().unwrap(); } +#[test] +#[cfg(unix)] +fn test_pipe_output_pattern_fifo_not_found() { + // A FIFO can't be read again, so nothing is kept to show when no line matches + let (path, _controller, _replica) = pty_path(); + let (at, mut ucmd) = at_and_ucmd!(); + at.mkfifo("fifo"); + let fifo = at.plus("fifo"); + let writer = std::thread::spawn(move || std::fs::write(fifo, "x\ny\nz\n").unwrap()); + ucmd.set_stdin(File::open(&path).unwrap()) + .args(&["-P", "none", "fifo"]) + .succeeds() + .no_output(); + writer.join().unwrap(); +} + #[test] #[cfg(unix)] fn test_pipe_output_piped_stdin_is_first_input() { From 1f1553d33dd8d3e23ef730a99bf5f32ff6bad65f Mon Sep 17 00:00:00 2001 From: Aaron Ang Date: Sun, 29 Nov 2026 14:47:47 -0500 Subject: [PATCH 5/6] more: copy piped output whole, ignoring the start line and pattern When stdout isn't a terminal, write every input unchanged, the way less does, so the output can be used as data. The start line and pattern still apply when paging. --- src/uu/more/src/more.rs | 72 ++++++------------------------------- tests/by-util/test_more.rs | 73 +++++++++----------------------------- 2 files changed, 27 insertions(+), 118 deletions(-) diff --git a/src/uu/more/src/more.rs b/src/uu/more/src/more.rs index 4f1f90398f4..136814a93e0 100644 --- a/src/uu/more/src/more.rs +++ b/src/uu/more/src/more.rs @@ -6,9 +6,7 @@ use std::{ ffi::{OsStr, OsString}, fs::File, - io::{ - BufRead, BufReader, IsTerminal as _, Seek, SeekFrom, Stdin, Stdout, Write, stdin, stdout, - }, + io::{BufRead, BufReader, IsTerminal as _, Stdin, Stdout, Write, stdin, stdout}, panic::set_hook, path::{Path, PathBuf}, time::Duration, @@ -169,7 +167,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { .map(Iterator::collect) .unwrap_or_default(); if !stdout().is_terminal() { - return copy_to_stdout(&files, &options); + return copy_to_stdout(&files); } if files.is_empty() { let stdin = stdin(); @@ -226,24 +224,20 @@ fn open_file(file_os: &OsString) -> Option { /// Write the input to stdout unpaged, for when stdout is not a terminal. /// /// Piped stdin is written first. A header with the file name comes before -/// each file when there is more than one input. -fn copy_to_stdout(files: &[&OsString], options: &Options) -> UResult<()> { +/// each file when there is more than one input. The start line and pattern +/// are ignored, so every input is copied whole. +fn copy_to_stdout(files: &[&OsString]) -> UResult<()> { let stdin = stdin(); let read_stdin = !stdin.is_terminal(); if files.is_empty() && !read_stdin { return Err(UUsageError::new(1, MoreError::BadUsage.to_string())); } let mut out = stdout().lock(); - // Only the first input starts at the requested line - let mut from_line = options.from_line; - if read_stdin { - if let Some(e) = copy_until_read_error(&mut stdin.lock(), &mut out)? { - show!(USimpleError::new( - 0, - MoreError::CannotRead(None, e).to_string() - )); - } - from_line = 0; + if read_stdin && let Some(e) = copy_until_read_error(&mut stdin.lock(), &mut out)? { + show!(USimpleError::new( + 0, + MoreError::CannotRead(None, e).to_string() + )); } let show_header = read_stdin || files.len() > 1; for file_os in files { @@ -255,22 +249,13 @@ fn copy_to_stdout(files: &[&OsString], options: &Options) -> UResult<()> { out.write_all(file_os.as_encoded_bytes())?; writeln!(out, "\n{HEADER_RULE}")?; } - let mut reader = BufReader::new(file); // A read error only skips the rest of this file, a write error stops - let read_error = match skip_to_start(&mut reader, from_line, options.pattern.as_deref()) { - Ok(start) => { - out.write_all(&start)?; - copy_until_read_error(&mut reader, &mut out)? - } - Err(e) => Some(e), - }; - if let Some(e) = read_error { + if let Some(e) = copy_until_read_error(&mut BufReader::new(file), &mut out)? { show!(USimpleError::new( 0, MoreError::CannotRead(Some(file_os), e).to_string() )); } - from_line = 0; } out.flush()?; Ok(()) @@ -295,41 +280,6 @@ fn copy_until_read_error( } } -/// Skip `from_line` lines, then up to the first line containing `pattern`. -/// -/// Returns the matching line, to be written before the rest of `reader`. -/// When no line matches, `reader` goes back to where the search started if -/// it can seek, so only one line is held in memory at a time. -fn skip_to_start( - reader: &mut (impl BufRead + Seek), - from_line: usize, - pattern: Option<&str>, -) -> std::io::Result> { - let mut line = Vec::new(); - for _ in 0..from_line { - line.clear(); - if reader.read_until(b'\n', &mut line)? == 0 { - return Ok(Vec::new()); - } - } - let Some(pattern) = pattern else { - return Ok(Vec::new()); - }; - let search_start = reader.stream_position().ok(); - loop { - line.clear(); - if reader.read_until(b'\n', &mut line)? == 0 { - if let Some(position) = search_start { - reader.seek(SeekFrom::Start(position))?; - } - return Ok(Vec::new()); - } - if String::from_utf8_lossy(&line).contains(pattern) { - return Ok(line); - } - } -} - pub fn uu_app() -> Command { Command::new("more") .about(translate!("more-about")) diff --git a/tests/by-util/test_more.rs b/tests/by-util/test_more.rs index 6df8737740f..72e29ef72d1 100644 --- a/tests/by-util/test_more.rs +++ b/tests/by-util/test_more.rs @@ -306,25 +306,27 @@ fn test_pipe_output_multiple_files() { #[test] #[cfg(unix)] -fn test_pipe_output_from_line() { - // Only the first file starts at the requested line - more_to_pipe(&["-F", "4", "a.txt", "b.txt"]) +fn test_pipe_output_ignores_start() { + // The start line and pattern only apply when paging + more_to_pipe(&["-F", "4", "-P", "a2", "a.txt", "b.txt"]) .success() .stdout_only( - "::::::::::::::\na.txt\n::::::::::::::\na2\n\ + "::::::::::::::\na.txt\n::::::::::::::\na1\n\n\na2\n\ ::::::::::::::\nb.txt\n::::::::::::::\nb1\nb2", ); -} -#[test] -#[cfg(unix)] -fn test_pipe_output_pattern() { - more_to_pipe(&["-P", "a2", "a.txt"]) - .success() - .stdout_only("a2\n"); - more_to_pipe(&["-P", "none", "a.txt"]) - .success() - .stdout_only("a1\n\n\na2\n"); + let (at, mut ucmd) = at_and_ucmd!(); + at.write("a.txt", "a1\na2\n"); + ucmd.args(&["-F", "2", "a.txt"]) + .pipe_in("p1\np2\n") + .succeeds() + .stdout_only("p1\np2\n::::::::::::::\na.txt\n::::::::::::::\na1\na2\n"); + + new_ucmd!() + .args(&["-F", "2", "-P", "p2"]) + .pipe_in("p1\np2\n") + .succeeds() + .stdout_only("p1\np2\n"); } #[test] @@ -343,49 +345,6 @@ fn test_pipe_output_piped_stdin() { .stdout_only("piped\n::::::::::::::\na.txt\n::::::::::::::\na1\n"); } -#[test] -#[cfg(unix)] -fn test_pipe_output_pattern_fifo() { - let (path, _controller, _replica) = pty_path(); - let (at, mut ucmd) = at_and_ucmd!(); - at.mkfifo("fifo"); - let fifo = at.plus("fifo"); - let writer = std::thread::spawn(move || std::fs::write(fifo, "x\ny\nz\n").unwrap()); - ucmd.set_stdin(File::open(&path).unwrap()) - .args(&["-P", "y", "fifo"]) - .succeeds() - .stdout_only("y\nz\n"); - writer.join().unwrap(); -} - -#[test] -#[cfg(unix)] -fn test_pipe_output_pattern_fifo_not_found() { - // A FIFO can't be read again, so nothing is kept to show when no line matches - let (path, _controller, _replica) = pty_path(); - let (at, mut ucmd) = at_and_ucmd!(); - at.mkfifo("fifo"); - let fifo = at.plus("fifo"); - let writer = std::thread::spawn(move || std::fs::write(fifo, "x\ny\nz\n").unwrap()); - ucmd.set_stdin(File::open(&path).unwrap()) - .args(&["-P", "none", "fifo"]) - .succeeds() - .no_output(); - writer.join().unwrap(); -} - -#[test] -#[cfg(unix)] -fn test_pipe_output_piped_stdin_is_first_input() { - // stdin is the first input, so the file is shown from its first line - let (at, mut ucmd) = at_and_ucmd!(); - at.write("a.txt", "a1\na2\n"); - ucmd.args(&["-F", "2", "a.txt"]) - .pipe_in("p1\np2\n") - .succeeds() - .stdout_only("p1\np2\n::::::::::::::\na.txt\n::::::::::::::\na1\na2\n"); -} - #[test] #[cfg(target_os = "linux")] fn test_pipe_output_write_error_stops() { From 54a8acf9e4307183a2c6a07db6e99a1be79ae2e7 Mon Sep 17 00:00:00 2001 From: Aaron Ang Date: Sun, 29 Nov 2026 14:50:11 -0500 Subject: [PATCH 6/6] Revert "more: copy piped output whole, ignoring the start line and pattern" This reverts commit 1f1553d33. util-linux applies the start line and pattern to piped output too, and compatibility with it comes first. --- src/uu/more/src/more.rs | 72 +++++++++++++++++++++++++++++++------ tests/by-util/test_more.rs | 73 +++++++++++++++++++++++++++++--------- 2 files changed, 118 insertions(+), 27 deletions(-) diff --git a/src/uu/more/src/more.rs b/src/uu/more/src/more.rs index 136814a93e0..4f1f90398f4 100644 --- a/src/uu/more/src/more.rs +++ b/src/uu/more/src/more.rs @@ -6,7 +6,9 @@ use std::{ ffi::{OsStr, OsString}, fs::File, - io::{BufRead, BufReader, IsTerminal as _, Stdin, Stdout, Write, stdin, stdout}, + io::{ + BufRead, BufReader, IsTerminal as _, Seek, SeekFrom, Stdin, Stdout, Write, stdin, stdout, + }, panic::set_hook, path::{Path, PathBuf}, time::Duration, @@ -167,7 +169,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { .map(Iterator::collect) .unwrap_or_default(); if !stdout().is_terminal() { - return copy_to_stdout(&files); + return copy_to_stdout(&files, &options); } if files.is_empty() { let stdin = stdin(); @@ -224,20 +226,24 @@ fn open_file(file_os: &OsString) -> Option { /// Write the input to stdout unpaged, for when stdout is not a terminal. /// /// Piped stdin is written first. A header with the file name comes before -/// each file when there is more than one input. The start line and pattern -/// are ignored, so every input is copied whole. -fn copy_to_stdout(files: &[&OsString]) -> UResult<()> { +/// each file when there is more than one input. +fn copy_to_stdout(files: &[&OsString], options: &Options) -> UResult<()> { let stdin = stdin(); let read_stdin = !stdin.is_terminal(); if files.is_empty() && !read_stdin { return Err(UUsageError::new(1, MoreError::BadUsage.to_string())); } let mut out = stdout().lock(); - if read_stdin && let Some(e) = copy_until_read_error(&mut stdin.lock(), &mut out)? { - show!(USimpleError::new( - 0, - MoreError::CannotRead(None, e).to_string() - )); + // Only the first input starts at the requested line + let mut from_line = options.from_line; + if read_stdin { + if let Some(e) = copy_until_read_error(&mut stdin.lock(), &mut out)? { + show!(USimpleError::new( + 0, + MoreError::CannotRead(None, e).to_string() + )); + } + from_line = 0; } let show_header = read_stdin || files.len() > 1; for file_os in files { @@ -249,13 +255,22 @@ fn copy_to_stdout(files: &[&OsString]) -> UResult<()> { out.write_all(file_os.as_encoded_bytes())?; writeln!(out, "\n{HEADER_RULE}")?; } + let mut reader = BufReader::new(file); // A read error only skips the rest of this file, a write error stops - if let Some(e) = copy_until_read_error(&mut BufReader::new(file), &mut out)? { + let read_error = match skip_to_start(&mut reader, from_line, options.pattern.as_deref()) { + Ok(start) => { + out.write_all(&start)?; + copy_until_read_error(&mut reader, &mut out)? + } + Err(e) => Some(e), + }; + if let Some(e) = read_error { show!(USimpleError::new( 0, MoreError::CannotRead(Some(file_os), e).to_string() )); } + from_line = 0; } out.flush()?; Ok(()) @@ -280,6 +295,41 @@ fn copy_until_read_error( } } +/// Skip `from_line` lines, then up to the first line containing `pattern`. +/// +/// Returns the matching line, to be written before the rest of `reader`. +/// When no line matches, `reader` goes back to where the search started if +/// it can seek, so only one line is held in memory at a time. +fn skip_to_start( + reader: &mut (impl BufRead + Seek), + from_line: usize, + pattern: Option<&str>, +) -> std::io::Result> { + let mut line = Vec::new(); + for _ in 0..from_line { + line.clear(); + if reader.read_until(b'\n', &mut line)? == 0 { + return Ok(Vec::new()); + } + } + let Some(pattern) = pattern else { + return Ok(Vec::new()); + }; + let search_start = reader.stream_position().ok(); + loop { + line.clear(); + if reader.read_until(b'\n', &mut line)? == 0 { + if let Some(position) = search_start { + reader.seek(SeekFrom::Start(position))?; + } + return Ok(Vec::new()); + } + if String::from_utf8_lossy(&line).contains(pattern) { + return Ok(line); + } + } +} + pub fn uu_app() -> Command { Command::new("more") .about(translate!("more-about")) diff --git a/tests/by-util/test_more.rs b/tests/by-util/test_more.rs index 72e29ef72d1..6df8737740f 100644 --- a/tests/by-util/test_more.rs +++ b/tests/by-util/test_more.rs @@ -306,27 +306,25 @@ fn test_pipe_output_multiple_files() { #[test] #[cfg(unix)] -fn test_pipe_output_ignores_start() { - // The start line and pattern only apply when paging - more_to_pipe(&["-F", "4", "-P", "a2", "a.txt", "b.txt"]) +fn test_pipe_output_from_line() { + // Only the first file starts at the requested line + more_to_pipe(&["-F", "4", "a.txt", "b.txt"]) .success() .stdout_only( - "::::::::::::::\na.txt\n::::::::::::::\na1\n\n\na2\n\ + "::::::::::::::\na.txt\n::::::::::::::\na2\n\ ::::::::::::::\nb.txt\n::::::::::::::\nb1\nb2", ); +} - let (at, mut ucmd) = at_and_ucmd!(); - at.write("a.txt", "a1\na2\n"); - ucmd.args(&["-F", "2", "a.txt"]) - .pipe_in("p1\np2\n") - .succeeds() - .stdout_only("p1\np2\n::::::::::::::\na.txt\n::::::::::::::\na1\na2\n"); - - new_ucmd!() - .args(&["-F", "2", "-P", "p2"]) - .pipe_in("p1\np2\n") - .succeeds() - .stdout_only("p1\np2\n"); +#[test] +#[cfg(unix)] +fn test_pipe_output_pattern() { + more_to_pipe(&["-P", "a2", "a.txt"]) + .success() + .stdout_only("a2\n"); + more_to_pipe(&["-P", "none", "a.txt"]) + .success() + .stdout_only("a1\n\n\na2\n"); } #[test] @@ -345,6 +343,49 @@ fn test_pipe_output_piped_stdin() { .stdout_only("piped\n::::::::::::::\na.txt\n::::::::::::::\na1\n"); } +#[test] +#[cfg(unix)] +fn test_pipe_output_pattern_fifo() { + let (path, _controller, _replica) = pty_path(); + let (at, mut ucmd) = at_and_ucmd!(); + at.mkfifo("fifo"); + let fifo = at.plus("fifo"); + let writer = std::thread::spawn(move || std::fs::write(fifo, "x\ny\nz\n").unwrap()); + ucmd.set_stdin(File::open(&path).unwrap()) + .args(&["-P", "y", "fifo"]) + .succeeds() + .stdout_only("y\nz\n"); + writer.join().unwrap(); +} + +#[test] +#[cfg(unix)] +fn test_pipe_output_pattern_fifo_not_found() { + // A FIFO can't be read again, so nothing is kept to show when no line matches + let (path, _controller, _replica) = pty_path(); + let (at, mut ucmd) = at_and_ucmd!(); + at.mkfifo("fifo"); + let fifo = at.plus("fifo"); + let writer = std::thread::spawn(move || std::fs::write(fifo, "x\ny\nz\n").unwrap()); + ucmd.set_stdin(File::open(&path).unwrap()) + .args(&["-P", "none", "fifo"]) + .succeeds() + .no_output(); + writer.join().unwrap(); +} + +#[test] +#[cfg(unix)] +fn test_pipe_output_piped_stdin_is_first_input() { + // stdin is the first input, so the file is shown from its first line + let (at, mut ucmd) = at_and_ucmd!(); + at.write("a.txt", "a1\na2\n"); + ucmd.args(&["-F", "2", "a.txt"]) + .pipe_in("p1\np2\n") + .succeeds() + .stdout_only("p1\np2\n::::::::::::::\na.txt\n::::::::::::::\na1\na2\n"); +} + #[test] #[cfg(target_os = "linux")] fn test_pipe_output_write_error_stops() {