forked from JuneKelly/manuel-contrib-watch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanuel-contrib-watch.manuel
91 lines (71 loc) · 1.64 KB
/
manuel-contrib-watch.manuel
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
#! /usr/bin/env bash
# manuel-contrib-watch
# act on changes to files
# Usage: manuel_watch [directory]
# must declare `actions` as an associative array.
#
# Example:
#
# function do_something {
#
# declare -A actions=(
# [".*\.js$"]="echo 'we should concat and minify the js again'"
# [".*\.go$"]="go build ."
# )
#
# manuel_watch .
# }
# get the systems md5 utility
function _get_md5_command {
if [[ ! -z $(command -v md5) ]]; then
which md5
elif [[ ! -z $(command -v md5sum) ]]; then
which md5sum
else
echo -e ">> Error: neither md5 nor md5sum found on PATH" 1>&2
exit 1
fi
}
# hash the results of a find
function _hash_find {
search_dir=$1
glob_pattern=$2
md5_command=$(_get_md5_command)
result=$(
find "$search_dir" -name "$glob_pattern" -printf '%Tc %p\n' | $md5_command
)
echo "$result"
}
# main task
function manuel_watch {
target_dir=$(readlink -f "$1") # a directory to watch for changes in
# keep an associative array of hashes of results
declare -A last_results
# get initial hashes
for k in "${!actions[@]}"
do
if [[ "$k" == 0 ]]; then
continue
fi
h=$(_hash_find "$target_dir" "$k")
last_results["$k"]=$h
done
echo -e ">> Watching $target_dir"
while true; do
for k in "${!actions[@]}"
do
if [[ "$k" == "0" ]]; then
continue
fi
# hash result
h=$(_hash_find "$target_dir" "$k")
# check against previous hash
if [[ ${last_results["$k"]} != $h ]]; then
last_results["$k"]=$h
echo ">> Change detected for pattern $k"
eval "${actions[$k]}"
fi
done
sleep 1
done
}