1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-28 03:27:44 +00:00

mktemp: respect path given in template argument

Fix a bug in `mktemp` where it was not respecting the path given by
the positional argument. Previously, it would place the temporary file
whose name is induced by a given template in the `/tmp` directory,
like this:

    $ mktemp XXX
    /tmp/LJr

    $ mktemp d/XXX
    /tmp/d/IhS

After this commit, it respects the directory given in the template
argument:

    $ mktemp XXX
    LJr

    $ mktemp d/XXX
    d/IhS

Fixes #3440.
This commit is contained in:
Jeffrey Finkelstein 2022-05-01 12:03:02 -04:00
parent f869fafd03
commit aa6aefbd64
2 changed files with 105 additions and 7 deletions

View file

@ -411,3 +411,71 @@ fn test_mktemp_directory_tmpdir() {
result.no_stderr().stdout_contains("apt-key-gpghome.");
assert!(PathBuf::from(result.stdout_str().trim()).is_dir());
}
/// Decide whether a string matches a given template.
///
/// In the template, the character `'X'` is treated as a wildcard,
/// that is, it matches anything. All other characters in `template`
/// and `s` must match exactly.
///
/// # Examples
///
/// ```rust,ignore
/// # These all match.
/// assert!(matches_template("abc", "abc"));
/// assert!(matches_template("aXc", "abc"));
/// assert!(matches_template("XXX", "abc"));
///
/// # None of these match
/// assert!(matches_template("abc", "abcd"));
/// assert!(matches_template("abc", "ab"));
/// assert!(matches_template("aXc", "abd"));
/// assert!(matches_template("XXX", "abcd"));
/// ```
///
fn matches_template(template: &str, s: &str) -> bool {
if template.len() != s.len() {
return false;
}
for (a, b) in template.chars().zip(s.chars()) {
if !(a == 'X' || a == b) {
return false;
}
}
true
}
/// An assertion that uses [`matches_template`] and adds a helpful error message.
macro_rules! assert_matches_template {
($template:expr, $s:expr) => {{
assert!(
matches_template($template, $s),
"\"{}\" != \"{}\"",
$template,
$s
);
}};
}
/// Test that the file is created in the directory given by the template.
#[test]
fn test_respect_template() {
let (at, mut ucmd) = at_and_ucmd!();
let template = "XXX";
let result = ucmd.arg(template).succeeds();
let filename = result.no_stderr().stdout_str().trim_end();
assert_matches_template!(template, filename);
assert!(at.file_exists(filename));
}
/// Test that the file is created in the directory given by the template.
#[test]
fn test_respect_template_directory() {
let (at, mut ucmd) = at_and_ucmd!();
at.mkdir("d");
let template = "d/XXX";
let result = ucmd.arg(template).succeeds();
let filename = result.no_stderr().stdout_str().trim_end();
assert_matches_template!(template, filename);
assert!(at.file_exists(filename));
}