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
1 change: 1 addition & 0 deletions src/uu/more/locales/en-US.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/uu/more/locales/fr-FR.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -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é
Expand Down
222 changes: 181 additions & 41 deletions src/uu/more/src/more.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -29,13 +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(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) => {
Expand All @@ -59,20 +62,39 @@ impl std::fmt::Display for MoreError {
)
)
}
Self::CannotRead(path, error) => {
let error = strip_errno(error);
let message = if let Some(path) = path {
translate!(
"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"))
}
}
}
}

impl std::error::Error for MoreError {}
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";
Expand Down Expand Up @@ -142,28 +164,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::<OsString>(options::FILES) {
let files: Vec<&OsString> = matches
.get_many::<OsString>(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(
Expand All @@ -174,18 +196,140 @@ 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<File> {
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 {
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 {
let Some(file) = open_file(file_os) else {
continue;
};
if show_header {
writeln!(out, "{HEADER_RULE}")?;
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 {
show!(USimpleError::new(
0,
MoreError::CannotRead(Some(file_os), e).to_string()
));
}
from_line = 0;
}
out.flush()?;
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<Option<std::io::Error>> {
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 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<Vec<u8>> {
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"))
Expand Down Expand Up @@ -605,21 +749,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<()> {
Expand Down
Loading
Loading