-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshowmd
executable file
·79 lines (67 loc) · 1.62 KB
/
showmd
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
#!/bin/bash
# I'm lazy today and just using Bash for SRANDOM O:-)
set -eu
pandoc_header_include=$(
cat <<-EOT
<script>
async function reloadIfChanged() {
const resp = await fetch(location + ".stamp.txt");
if (!resp.ok) {
return;
}
const stamp = parseFloat(await resp.text());
const oldStamp = history.state ?? 0.0;
if (stamp > oldStamp) {
history.replaceState(stamp, "");
location.reload();
}
}
setInterval(reloadIfChanged, 1000);
</script>
EOT
)
cleanup()
{
rm -fr -- "$tmpdir"
[ -z "${pid-}" ] || kill "$pid" 2>/dev/null || :
}
if command -v pandoc >/dev/null; then
md2html()
{
if pandoc -H<(printf '%s' "$pandoc_header_include") -o"$2" -s --quiet "$1"; then
date '+%s.%N' >"${2}.stamp.txt"
fi
}
elif command -v markdown >/dev/null; then
md2html()
{
markdown "$1" > "$2" || :
}
else
# shellcheck disable=SC2016
printf 'Missing any of `markdown` or `pandoc`\n' >&2
exit 2
fi
: "${bind_address:=127.0.0.1}"
: "${port:=$(( SRANDOM % (65535 - 1024 + 1) + 1024 ))}"
if [ $# -ne 1 ]; then
printf "Missing Markdown file\n" >&2
exit 2
fi
md_file="$1"
tmpdir=$(mktemp -d) || exit 1
trap cleanup EXIT HUP INT TERM
html_file="${tmpdir}/${md_file##*/}.html"
md2html "$md_file" "$html_file"
python3 -m http.server -b "$bind_address" -d "$tmpdir" -- "$port" 2>/dev/null &
pid=$!
open "http://${bind_address}:${port}/${html_file##*/}"
if command -v inotifywait >/dev/null; then
printf "Watching for changes ...\n"
while inotifywait -qq "$md_file"; do
md2html "$md_file" "$html_file"
done
else
printf "Missing inotifywait, not watching for changes\n" >&2
wait "$pid"
fi