8000 tee: Correctly handle read-only files, avoid unnecessary wrapping by BenWiederhake · Pull Request #6157 · uutils/coreutils · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

tee: Correctly handle read-only files, avoid unnecessary wrapping #6157

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 31, 2024
Merged
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
58 changes: 28 additions & 30 deletions src/uu/tee/src/tee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

use clap::{builder::PossibleValue, crate_version, Arg, ArgAction, Command};
use std::fs::OpenOptions;
use std::io::{copy, sink, stdin, stdout, Error, ErrorKind, Read, Result, Write};
use std::io::{copy, stdin, stdout, Error, ErrorKind, Read, Result, Write};
use std::path::PathBuf;
use uucore::display::Quotable;
use uucore::error::UResult;
Expand Down Expand Up @@ -148,15 +148,10 @@ fn tee(options: &Options) -> Result<()> {
}
let mut writers: Vec<NamedWriter> = options
.files
.clone()
.into_iter()
.map(|file| {
Ok(NamedWriter {
name: file.clone(),
inner: open(file, options.append, options.output_error.as_ref())?,
})
})
.iter()
.filter_map(|file| open(file, options.append, options.output_error.as_ref()))
.collect::<Result<Vec<NamedWriter>>>()?;
let had_open_errors = writers.len() != options.files.len();

writers.insert(
0,
Expand All @@ -181,38 +176,41 @@ fn tee(options: &Options) -> Result<()> {
_ => Ok(()),
};

if res.is_err() || output.flush().is_err() || output.error_occurred() {
if had_open_errors || res.is_err() || output.flush().is_err() || output.error_occurred() {
Err(Error::from(ErrorKind::Other))
} else {
Ok(())
}
}

/// Tries to open the indicated file and return it. Reports an error if that's not possible.
/// If that error should lead to program termination, this function returns Some(Err()),
/// otherwise it returns None.
fn open(
name: String,
name: &str,
append: bool,
output_error: Option<&OutputErrorMode>,
) -> Result<Box<dyn Write>> {
let path = PathBuf::from(name.clone());
let inner: Box<dyn Write> = {
let mut options = OpenOptions::new();
let mode = if append {
options.append(true)
} else {
options.truncate(true)
};
match mode.write(true).create(true).open(path.as_path()) {
Ok(file) => Box::new(file),
Err(f) => {
show_error!("{}: {}", name.maybe_quote(), f);
match output_error {
Some(OutputErrorMode::Exit | OutputErrorMode::ExitNoPipe) => return Err(f),
_ => Box::new(sink()),
}
) -> Option<Result<NamedWriter>> {
let path = PathBuf::from(name);
let mut options = OpenOptions::new();
let mode = if append {
options.append(true)
} else {
options.truncate(true)
};
match mode.write(true).create(true).open(path.as_path()) {
Ok(file) => Some(Ok(NamedWriter {
inner: Box::new(file),
name: name.to_owned(),
})),
Err(f) => {
show_error!("{}: {}", name.maybe_quote(), f);
match output_error {
Some(OutputErrorMode::Exit | OutputErrorMode::ExitNoPipe) => Some(Err(f)),
_ => None,
}
}
};
Ok(Box::new(NamedWriter { inner, name }) as Box<dyn Write>)
}
}

struct MultiWriter {
Expand Down
22 changes: 22 additions & 0 deletions tests/by-util/test_tee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
use crate::common::util::TestScenario;
use regex::Regex;
#[cfg(target_os = "linux")]
use std::fmt::Write;

Expand Down Expand Up @@ -92,6 +93,27 @@ fn test_tee_no_more_writeable_1() {
assert_eq!(at.read(file_out), content);
}

#[test]
fn test_readonly() {
let (at, mut ucmd) = at_and_ucmd!();
let content_tee = "hello";
let content_file = "world";
let file_out = "tee_file_out";
let writable_file = "tee_file_out2";
at.write(file_out, content_file);
at.set_readonly(file_out);
ucmd.arg(file_out)
.arg(writable_file)
.pipe_in(content_tee)
.ignore_stdin_write_error()
.fails()
.stdout_is(content_tee)
// Windows says "Access is denied" for some reason.
.stderr_matches(&Regex::new("(Permission|Access is) denied").unwrap());
assert_eq!(at.read(file_out), content_file);
assert_eq!(at.read(writable_file), content_tee);
}

#[test]
#[cfg(target_os = "linux")]
fn test_tee_no_more_writeable_2() {
Expand Down
0