From 6cfb0f0b741a603ac6d70476e2c1430da079ca7e Mon Sep 17 00:00:00 2001 From: Junji Wei Date: Thu, 9 Jun 2022 14:48:05 +0800 Subject: [PATCH] mktemp: respect POSIXLY_CORRECT env var when parsing args Signed-off-by: Junji Wei --- src/uu/mktemp/src/mktemp.rs | 23 ++++++++++++++++++++++- tests/by-util/test_mktemp.rs | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/uu/mktemp/src/mktemp.rs b/src/uu/mktemp/src/mktemp.rs index 6a848b7ad19..61713ca6138 100644 --- a/src/uu/mktemp/src/mktemp.rs +++ b/src/uu/mktemp/src/mktemp.rs @@ -53,6 +53,7 @@ enum MkTempError { /// The template suffix contains a path separator (e.g. `"XXXa/b"`). SuffixContainsDirSeparator(String), InvalidTemplate(String), + TooManyTemplates, } impl UError for MkTempError {} @@ -85,6 +86,13 @@ impl Display for MkTempError { "invalid template, {}; with --tmpdir, it may not be absolute", s.quote() ), + TooManyTemplates => { + write!( + f, + "too many templates\nTry '{} --help' for more information.", + uucore::execution_phrase() + ) + } } } } @@ -308,11 +316,24 @@ impl Params { #[uucore::main] pub fn uumain(args: impl uucore::Args) -> UResult<()> { - let matches = uu_app().try_get_matches_from(args)?; + let args = args.collect_str_lossy().accept_any(); + + let matches = uu_app().try_get_matches_from(&args)?; // Parse command-line options into a format suitable for the // application logic. let options = Options::from(&matches); + + if env::var("POSIXLY_CORRECT").is_ok() { + // If POSIXLY_CORRECT was set, template MUST be the last argument. + if is_tmpdir_argument_actually_the_template(&matches) || matches.is_present(ARG_TEMPLATE) { + // Template argument was provided, check if was the last one. + if args.last().unwrap() != &options.template { + return Err(Box::new(MkTempError::TooManyTemplates)); + } + } + } + let dry_run = options.dry_run; let suppress_file_err = options.quiet; let make_dir = options.directory; diff --git a/tests/by-util/test_mktemp.rs b/tests/by-util/test_mktemp.rs index 79ff9271d6a..9e4a2742cd8 100644 --- a/tests/by-util/test_mktemp.rs +++ b/tests/by-util/test_mktemp.rs @@ -641,3 +641,25 @@ fn test_suffix_empty_template() { .fails() .stderr_is("mktemp: with --suffix, template '' must end in X\n"); } + +#[test] +fn test_mktemp_with_posixly_correct() { + let scene = TestScenario::new(util_name!()); + + scene + .ucmd() + .env("POSIXLY_CORRECT", "1") + .args(&["aXXXX", "--suffix=b"]) + .fails() + .stderr_is(&format!( + "mktemp: too many templates\nTry '{} {} --help' for more information.\n", + scene.bin_path.to_string_lossy(), + scene.util_name + )); + + scene + .ucmd() + .env("POSIXLY_CORRECT", "1") + .args(&["--suffix=b", "aXXXX"]) + .succeeds(); +}