-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromises.sh
126 lines (94 loc) · 2.35 KB
/
promises.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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/bin/sh
################################################################################
#
# Bash Promise library
# https://github.com/Aschen/bash-promises
#
################################################################################
# Init the promise library.
#
# {param} mode - Set to "strict" to terminate the program if a promise fail (like set -e)
init_promises () {
catch_mode=$1
promises=0
rm -rf .bash-promise/
mkdir -p .bash-promise/
}
# Run a command in a subprocess
#
# Example: promise_run echo "Hello, world"
#
# {return} - Returns the promise ID
promise_run () {
local command=$@
local identifier=$promises
local promise_dir=.bash-promise/$identifier
local lockfile=$promise_dir/lock
local pidfile=$promise_dir/pid
local resolve=$promise_dir/resolve
local reject=$promise_dir/reject
test -d $promise_dir && rm -rf $promise_dir
mkdir -p $promise_dir
eval $command \
&& [[ $? -eq 0 ]] \
&& (test -f $resolve && eval "$(cat $resolve)" && touch $lockfile || touch $lockfile) \
|| ([[ $catch_mode = "strict" ]] && _promise_exit || test -f $reject && eval "$(cat $reject)" \
&& touch $lockfile || touch $lockfile) \
&
echo $! > $pidfile
promises=$((promises+1))
return $identifier
}
_promise_exit () {
local parent_pid=$$
for pidfile in $(find .bash-promise/ -name pid);
do
pid=$(cat $pidfile)
pid_lines=$(ps $pid | wc -l)
if [[ ! $pid_lines = "1" ]];
then
kill $pid
fi
done
kill $parent_pid
}
promise_then () {
local identifier=$?
local command=$@
local resolve=.bash-promise/$identifier/resolve
echo "$command" > $resolve
return $identifier
}
promise_catch () {
local identifier=$?
local command=$@
local reject=.bash-promise/$identifier/reject
echo "$command" > $reject
return $identifier
}
# Wait for every current promises to be fulfilled
await_promises () {
local resolved=0
until [ $resolved -eq $promises ]
do
resolved=0
i=0
while [ $i -ne $promises ]
do
test -f .bash-promise/$i/lock && resolved=$((resolved+1))
i=$((i+1))
done
sleep 0.1
done
}
# Wait for the last executed promise to be fulfilled
await_promise () {
local lockfile=.bash-promise/$?/lock
local resolved=0
until [ $resolved -eq 1 ]
do
resolved=0
test -f $lockfile && resolved=1
sleep 0.1
done
}