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
23 changes: 21 additions & 2 deletions src/uu/mktemp/src/mktemp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ use std::io::ErrorKind;
use std::iter;
use std::path::{MAIN_SEPARATOR, Path, PathBuf};

#[cfg(unix)]
use std::fs;
#[cfg(unix)]
use std::os::unix::prelude::PermissionsExt;
Expand Down Expand Up @@ -435,7 +434,27 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
} else {
res
};
println_verbatim(res?).map_err_context(|| translate!("mktemp-error-failed-print"))
let path = res?;
match println_verbatim(&path) {
Ok(()) => Ok(()),
Err(e) => {
// We created the temporary file or directory but failed to print
// its name to stdout. Since the caller will never learn the name,
// the entry is unreachable, so remove it to match GNU mktemp.
// The tempfile builder's automatic cleanup was disabled via
// `keep()`, so removal must be done manually here. This is
// best-effort: if removal fails, still report the original
// print error.
if !dry_run {
let _ = if make_dir {
fs::remove_dir(&path)
} else {
fs::remove_file(&path)
};
}
Err(e).map_err_context(|| translate!("mktemp-error-failed-print"))
}
}
}

pub fn uu_app() -> Command {
Expand Down
39 changes: 39 additions & 0 deletions tests/by-util/test_mktemp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1209,3 +1209,42 @@ fn test_mktemp_hidden_file_single_dot() {
template_name.len()
);
}

#[test]
#[cfg(target_os = "linux")]
fn test_mktemp_cleanup_on_write_error() {
use std::fs::{File, read_dir};

// Simulate a write failure by directing stdout to /dev/full (Linux only).
// Skip if /dev/full is unavailable, mirroring the GNU test's guard.
let Ok(dev_full) = File::create("/dev/full") else {
return;
};

// Case 1: a temporary file is created, but printing its name fails.
let (at, mut ucmd) = at_and_ucmd!();
at.mkdir("d");
ucmd.arg("-p")
.arg("d")
.set_stdout(dev_full.try_clone().unwrap())
.fails()
.code_is(1);
assert!(
read_dir(at.plus("d")).unwrap().next().is_none(),
"mktemp left an orphaned temp file after a write error"
);

// Case 2: a temporary directory is created, but printing its name fails.
let (at, mut ucmd) = at_and_ucmd!();
at.mkdir("d");
ucmd.arg("-p")
.arg("d")
.arg("-d")
.set_stdout(dev_full)
.fails()
.code_is(1);
assert!(
read_dir(at.plus("d")).unwrap().next().is_none(),
"mktemp left an orphaned temp directory after a write error"
);
}
Loading