From 6260333415cba80b59936257f0995f5ee9553c3f Mon Sep 17 00:00:00 2001 From: Jeffrey Finkelstein Date: Wed, 18 May 2022 18:33:53 -0400 Subject: [PATCH] mktemp: fix error msg when suffix has path sep. Correct the error message when the template argument contains a path separator in its suffix. Before this commit: $ mktemp aXXX/b mktemp: too few X's in template 'b' After this commit: $ mktemp aXXX/b mktemp: invalid suffix '/b', contains directory separator This error message is more appropriate and matches the behavior of GNU mktemp. --- src/uu/mktemp/src/mktemp.rs | 15 ++++++++++++++- tests/by-util/test_mktemp.rs | 15 +++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/uu/mktemp/src/mktemp.rs b/src/uu/mktemp/src/mktemp.rs index 20b95f009..8cefc7982 100644 --- a/src/uu/mktemp/src/mktemp.rs +++ b/src/uu/mktemp/src/mktemp.rs @@ -17,7 +17,7 @@ use std::env; use std::error::Error; use std::fmt::Display; use std::iter; -use std::path::{is_separator, Path, PathBuf}; +use std::path::{is_separator, Path, PathBuf, MAIN_SEPARATOR}; use rand::Rng; use tempfile::Builder; @@ -129,6 +129,19 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { }; let filename = path.file_name(); let template = filename.unwrap().to_str().unwrap(); + // If the command line was `mktemp aXXX/b`, then we will + // find that `tmp`, which is the result of getting the + // parent when treating the argument as a path, contains + // at least three consecutive Xs. This means that there + // was a path separator in the suffix, which is not + // allowed. + if tmp.display().to_string().contains("XXX") { + return Err(MkTempError::SuffixContainsDirSeparator(format!( + "{}{}", + MAIN_SEPARATOR, template + )) + .into()); + } (template, tmp) } } else { diff --git a/tests/by-util/test_mktemp.rs b/tests/by-util/test_mktemp.rs index 9fce0e591..962ab565b 100644 --- a/tests/by-util/test_mktemp.rs +++ b/tests/by-util/test_mktemp.rs @@ -496,3 +496,18 @@ fn test_template_path_separator() { "a/bXXX".quote() )); } + +/// Test that a suffix with a path separator is invalid. +#[test] +fn test_suffix_path_separator() { + #[cfg(not(windows))] + new_ucmd!() + .arg("aXXX/b") + .fails() + .stderr_only("mktemp: invalid suffix '/b', contains directory separator\n"); + #[cfg(windows)] + new_ucmd!() + .arg(r"aXXX\b") + .fails() + .stderr_only("mktemp: invalid suffix '\\b', contains directory separator\n"); +}