logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git/

mktemp.sh (1985B)


  1. #!/bin/sh
  2. # SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. # SPDX-License-Identifier: MPL-2.0
  4. target="$(dirname "$0")/../cmd/mktemp"
  5. plans=12
  6. . "$(dirname "$0")/tap.sh"
  7. t_mktemp()
  8. {
  9. count=$((count+1))
  10. # Append a final slash so sh(1) doesn't trims final newlines
  11. out="$("${target?}" $2 2>&1;r=$?;echo -n /;exit $r)"
  12. ret="$?"
  13. out="${out%/}"
  14. test -f "${out%
  15. }"
  16. test_ret="$?"
  17. rm -f "${out%
  18. }"
  19. if [ "$ret" = 0 ] && [ "$test_ret" = 0 ]; then
  20. printf 'ok %d - %s\n' "$count" "$1"
  21. else
  22. printf 'not ok %d - %s\n' "$count" "$1"
  23. printf '# exit code: %d\n' "$ret"
  24. printf '# test -f => %d\n' "$test_ret"
  25. err=1
  26. fi
  27. printf "$out" | sed -e 's;^;# ;'
  28. }
  29. t_mkdtemp()
  30. {
  31. count=$((count+1))
  32. # Append a final slash so sh(1) doesn't trims final newlines
  33. out="$("${target?}" $2 2>&1;r=$?;echo -n /;exit $r)"
  34. ret="$?"
  35. out="${out%/}"
  36. test -d "${out%
  37. }"
  38. test_ret="$?"
  39. rm -fr "${out%
  40. }"
  41. if [ "$ret" = 0 ] && [ "$test_ret" = 0 ]; then
  42. printf 'ok %d - %s\n' "$count" "$1"
  43. else
  44. printf 'not ok %d - %s\n' "$count" "$1"
  45. printf '# exit code: %d\n' "$ret"
  46. printf '# test -d => %d\n' "$test_ret"
  47. err=1
  48. fi
  49. printf "$out" | sed -e 's;^;# ;'
  50. }
  51. # TODO: Figure a way to do harsher tests, for example testing patterns, directory contents, …
  52. t_mktemp noargs ''
  53. t_mktemp template 'template.XXXXXX'
  54. t_mktemp tmpdir '-t'
  55. t_mktemp tmpdir '-t template.XXXXXX'
  56. t_mkdtemp dir '-d'
  57. t_mkdtemp dir_template '-d template.XXXXXX'
  58. t_mkdtemp dir_tmpdir '-dt'
  59. t --exit=1 templ2 'foo bar' 'mktemp: error: Only one template argument is supported, got 2
  60. '
  61. cmd_mktemp_u() {
  62. if tmpfile=$("$target" "$@"); then
  63. if test -e "$tmpfile"; then
  64. printf '# Unexpectedly created a file: %s\n' "$tmpfile"
  65. return 1
  66. fi
  67. return 0
  68. else
  69. return 1
  70. fi
  71. }
  72. t_cmd unsafe:file '' cmd_mktemp_u -u
  73. t_cmd unsafe:file_template '' cmd_mktemp_u -u template.XXXXXX
  74. t_cmd unsafe:dir '' cmd_mktemp_u -u -d
  75. t_cmd unsafe:dir_template '' cmd_mktemp_u -u -d template.XXXXXX