-
Notifications
You must be signed in to change notification settings - Fork 1
/
tmp.bash
102 lines (89 loc) · 2.26 KB
/
tmp.bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/env bash
import traps
import log
tmp__to_remove=()
tmp__trap_exists=0
tmp::mktemp() {
local tag="$1"
local flags="$2"
local tmpdir="$3"
if [[ "$OSTYPE" == "darwin"* ]]; then
if [ -n "$tmpdir" ];then
# shellcheck disable=SC2086
mktemp $flags "$tmpdir/$tag"
else
# shellcheck disable=SC2086
mktemp $flags "$tag"
fi
else
# shellcheck disable=SC2086
mktemp $flags -t "$tag" -p "$tmpdir"
fi
}
tmp::create_persistent_dir() {
local -n output_var=$1
local tag=${2:-"bash-lib"}
local inside="${3:-"${TMPDIR:-/tmp}"}"
local dir
dir=$(tmp::mktemp "$tag.XXXXXXXXXX" "-d" "$inside")
tmp::_init
log::debug "New dir $dir"
output_var="$dir"
}
tmp::create_dir() {
tmp::create_persistent_dir "$@"
local -n output_var=$1
log::debug "Scheduling removal of $output_var"
tmp__to_remove+=("$output_var")
}
tmp::create_persistent_file() {
local -n output_var=$1
local tag=${2:-"bash-lib"}
local inside="${3:-"${TMPDIR:-/tmp}"}"
local file
file=$(tmp::mktemp "$tag.XXXXXXXXXX" "" "$inside")
tmp::_init
log::debug "New file $file"
output_var="$file"
}
tmp::create_file() {
tmp::create_persistent_file "$@"
local -n output_var=$1
log::debug "Scheduling removal of $output_var"
tmp__to_remove+=("$output_var")
}
tmp::cleanup() {
for tmp in "${tmp__to_remove[@]}";do
log::debug "Purging $tmp"
rm -rf "$tmp"
done
tmp__to_remove=()
}
tmp::_init() {
if [ "$tmp__trap_exists" = "0" ];then
traps::add_exit_trap tmp::cleanup
tmp__trap_exists=1
fi
}
tmp_test::test_dir() {
local test_dir=""
local child_dir=""
tmp::create_dir test_dir
unit::assert_success [ -d $test_dir ]
tmp::create_dir child_dir "" "$test_dir"
unit::assert_success [ -d $child_dir ]
unit::assert_eq "$test_dir" "$(dirname $child_dir)"
tmp::cleanup
unit::assert_failed [ -d $test_dir ]
}
tmp_test::test_file() {
local test_file=""
tmp::create_file test_file
unit::assert_success [ -f $test_file ]
tmp::cleanup
unit::assert_failed [ -f $test_file ]
}
tmp_test::all() {
unit::test tmp_test::test_dir
unit::test tmp_test::test_file
}