diff --git a/lib/bash/std/lib_std.sh b/lib/bash/std/lib_std.sh index 8fd06e6..b0103f6 100644 --- a/lib/bash/std/lib_std.sh +++ b/lib/bash/std/lib_std.sh @@ -1769,13 +1769,25 @@ __std_make_temp_path__() { fi __std_temp_root="${TMPDIR:-/tmp}" - __std_temp_root="${__std_temp_root%/}" + if [[ "$__std_temp_root" != /* ]]; then + if ! __std_temp_root="$(cd -- "$__std_temp_root" 2>/dev/null && pwd -P)"; then + log_error -l base_bash_libs.std "$__std_temp_helper_name: TMPDIR is not a directory: ${TMPDIR:-/tmp}" + return 1 + fi + fi + while [[ "$__std_temp_root" != "/" && "$__std_temp_root" == */ ]]; do + __std_temp_root="${__std_temp_root%/}" + done if [[ -z "$__std_temp_root" || ! -d "$__std_temp_root" ]]; then log_error -l base_bash_libs.std "$__std_temp_helper_name: TMPDIR is not a directory: ${TMPDIR:-/tmp}" return 1 fi - __std_temp_template="$__std_temp_root/$__std_temp_prefix.XXXXXXXXXX" + if [[ "$__std_temp_root" == "/" ]]; then + __std_temp_template="/$__std_temp_prefix.XXXXXXXXXX" + else + __std_temp_template="$__std_temp_root/$__std_temp_prefix.XXXXXXXXXX" + fi if [[ "$__std_temp_path_kind" == "dir" ]]; then __std_temp_path="$(mktemp -d "$__std_temp_template" 2>/dev/null)" || { log_error -l base_bash_libs.std "$__std_temp_helper_name: failed to create temporary directory." diff --git a/lib/bash/std/tests/lib_std.bats b/lib/bash/std/tests/lib_std.bats index 7e0a739..44e6640 100644 --- a/lib/bash/std/tests/lib_std.bats +++ b/lib/bash/std/tests/lib_std.bats @@ -2100,6 +2100,59 @@ EOF [ ! -e "$created_path" ] } +@test "std_make_temp_file accepts TMPDIR=/" { + local script="$TEST_TMPDIR/temp-file-root.sh" + local path_file="$TEST_TMPDIR/temp-file-root.path" + local created_path + + create_script "$script" < "$TEST_TMPDIR/root-temp-file" + printf '%s\n' "$TEST_TMPDIR/root-temp-file" +} +std_make_temp_file temp_file root-temp +[[ -f "\$temp_file" ]] || exit 44 +printf '%s\n' "\$temp_file" > "$path_file" +EOF + + bats_run bash "$script" + + [ "$status" -eq 0 ] + created_path="$(cat "$path_file")" + [ "$created_path" = "$TEST_TMPDIR/root-temp-file" ] + [ ! -e "$created_path" ] +} + +@test "std_make_temp_file resolves relative and trailing-slash TMPDIR values" { + local script="$TEST_TMPDIR/temp-file-relative.sh" + local temp_root="$TEST_TMPDIR/temp-relative-root" + local path_file="$TEST_TMPDIR/temp-file-relative.path" + local created_path expected_root + + mkdir -p "$temp_root" + create_script "$script" < "$path_file" +EOF + + bats_run bash "$script" + + [ "$status" -eq 0 ] + created_path="$(cat "$path_file")" + expected_root="$(cd "$temp_root" && pwd -P)" + [[ "$created_path" == "$expected_root"/relative-temp.* ]] + [ ! -e "$created_path" ] +} + @test "std_make_temp_dir creates a directory under TMPDIR and cleans it up" { local script="$TEST_TMPDIR/temp-dir.sh" local temp_root="$TEST_TMPDIR/temp-dir-root"