-
Notifications
You must be signed in to change notification settings - Fork 2
/
memoize.sh
57 lines (51 loc) · 1.28 KB
/
memoize.sh
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
#!/bin/sh
bashfoo_require temp
normalize_name_as_file()
{
echo "$@" | tr "/{} \"'" "_______"
}
memoized()
{
#set -x
local mangled_file_name="$(normalize_name_as_file $@)"
#TBD, consider bashfoo.mktempname (which doesn't exist yet)
local tmp_cached_file_name="/tmp/.memoized_$USER_$$_$mangled_file_name"
if [ ! -f $tmp_cached_file_name ] ; then
"$@" > $tmp_cached_file_name
local r="$?"
if [ "$r" = 1 ] ; then
cat $tmp_cached_file_name
rm -f $tmp_cached_file_name
return $r
else
bashfoo.mktemp.register "$tmp_cached_file_name"
memoized_files="$memoized_files $tmp_cached_file_name"
fi
#else
# log "reusing output for $*"
fi
#set +x
cat $tmp_cached_file_name
}
memoized_result()
{
local mangled_file_name="bf_memoized_result_$(normalize_name_as_file $@)"
if ! variable_exists "$mangled_file_name" ; then
if "$@" ; then
local r=0
else
local r=$?
fi
variable_set "$mangled_file_name" "$r"
else
local r="$(variable_get "$mangled_file_name")"
fi
return $r
}
clean_memoize_cache()
{
if [ -n "$memoized_files" ] ; then
#rm -rf $memoized_files
true
fi
}