about summary refs log tree commit diff stats
path: root/ht.sh
diff options
context:
space:
mode:
authorCase Duckworth2022-05-19 11:49:53 -0500
committerCase Duckworth2022-05-19 11:49:53 -0500
commitaf52a71c9b2d6d66ff00fb39386d8d7a5330b2b0 (patch)
treed5cfca7f6ce469b45bf4c38e4d53ae22d7bfff0a /ht.sh
downloadhat-trick-af52a71c9b2d6d66ff00fb39386d8d7a5330b2b0.tar.gz
hat-trick-af52a71c9b2d6d66ff00fb39386d8d7a5330b2b0.zip
Initial commit
I'm doing content + generation in this ... who knows if it's smart, lol.
Diffstat (limited to 'ht.sh')
-rwxr-xr-xht.sh66
1 files changed, 66 insertions, 0 deletions
diff --git a/ht.sh b/ht.sh new file mode 100755 index 0000000..de58fe1 --- /dev/null +++ b/ht.sh
@@ -0,0 +1,66 @@
1#!/bin/sh
2# HAT TRICK
3# (C) 2022 C. Duckworth
4
5[ "x$DEBUG" = "xYES" ] && set -x
6
7: "${HTDAT:=$(date +%s)}"
8: "${HTTMP:=/tmp/ht}"; mkdir -p "$HTTMP"
9: "${HTENV:=$HTTMP/env-$HTDAT.sh}"
10: "${HTBOD:=$HTTMP/bod-$HTDAT.txt}"
11export HTDAT HTTMP HTENV HTBOD
12
13HT_TMPL_COUNT=1
14HT_TMPL_PRE=:
15
16print() { # print STRING...
17 ## A sane version of `echo`.
18 printf '%s\n' "$*"
19}
20
21htt() { # htt FILES...
22 # Like `cat`, but with templating.
23 ht_end="ht_main_$HTDAT_$HT_TMPL_COUNT" # be extra double sure
24 eval "$(print "cat <<$ht_end"; cat "$@"; print; print "$ht_end")"
25 HT_TMPL_COUNT=$(expr $HT_TMPL_COUNT + 1)
26}
27
28ht_build_env() { # ht_build_env FILE...
29 print "body() { cat \"$HTBOD\"; }" > "$HTENV"
30 while read -r line; do
31 case "$line" in
32 *@@*:*@@*) # "simple" metadata; just a string
33 print "$line" |
34 sed 's/.*@@\([^:]*\): \?\(.*\)@@.*/\1() { print "\2"; }/'
35 ;;
36 *@@*::*@@*) # "complex" metadata: can be anything
37 print "$line" |
38 sed 's/.*@@\([^:]*\):: \?\(.*\)@@.*/\1() { \2 ; }/'
39 ;;
40 esac >> "$HTENV"
41 # Still print the line to the body (no need to escape or w/e)
42 print "$line" >> "$HTBOD"
43 done
44 env | grep '^HT' | sort | uniq >> "$HTENV"
45}
46
47ht_main() { # main TEMPLATE < INPUT
48 ## Apply TEMPLATE to INPUT and print it.
49 # TEMPLATE will be interpreted as a heredoc.
50 if [ $# -eq 0 ]; then
51 print "ht.sh TEMPLATE < INPUT" >&2
52 exit 1
53 fi
54
55 eval "ht_build_env; . \"$HTENV\"; print \"\$(htt \"\$@\")\";";
56}
57
58# To keep this POSIX-compliant, we can't use a bashism like
59# [[ "$0" == # "$BASH_SOURCE[0]" ]]. However, there are still ways to guess
60# whether the user is sourcing this file as a library or executing it as a
61# script.
62
63case "$0" in
64 *ht.sh) ht_main "$@" ;;
65 *) print "Sourcing ht.sh" ;;
66esac