blag/blag
2024-12-16 22:44:26 +03:00

119 lines
2.4 KiB
Bash
Executable file

#!/usr/bin/env bash
#shellcheck disable=SC2155
error() {
echo "error: $*" >&2
}
escape() {
jq -Rr @html
}
_json_str() {
printf '%s' "$1" | jq -Rr @json
}
_json_str_opt() {
if [[ "${1:+x}" == 'x' ]]; then
_json_str "$1"
else
printf 'null'
fi
}
#shellcheck disable=SC2153
metadata() {
local title=$(_json_str "${TITLE?}")
local description=$(_json_str "${DESCRIPTION?}")
local author=$(_json_str "${AUTHOR:-$(id -un)}")
local icon=$(_json_str_opt "$ICON")
local icon_alt=$(_json_str_opt "$ICON_ALT")
local color=$(_json_str_opt "$COLOR")
local created_at=$(_json_str_opt "$CREATED_AT")
local modified_at=$(_json_str_opt "$MODIFIED_AT")
local tags=$(for tag in "${TAGS[@]}"; do printf '%s' "$tag" | jq -Rs .; done | jq -sr @json)
local dont_cache=false
[[ "${DONT_CACHE:+x}" == 'x' ]] && dont_cache=true
printf '{"title":%s,"description":%s,"author":%s,"icon":%s,"icon_alt":%s,"color":%s,"created_at":%s,"modified_at":%s,"tags":%s,"dont_cache":%s}\n' \
"$title" "$description" "$author" \
"$icon" "$icon_alt" "$color" \
"$created_at" "$modified_at" \
"$tags" "$dont_cache"
}
header() {
level=${1?need header level}
if ! (( level >= 1 && level <= 5 )); then
error "header level must be a number from 1 to 5"
return 1
fi
printf '<h%d>%s</h%d>' "$level" "$(</dev/stdin)" "$level"
}
paragraph() {
printf '<p>%s</p>' "$(</dev/stdin)"
}
image() {
src=${1?need src}
alt=${2?need alt}
printf '<img src="%s" alt="%s">' "$(printf '%s' "$src" | escape)" "$(printf '%s' "$alt" | escape)"
}
link() {
href=${1?need href}
printf '<a href="%s">%s</a>' "$(printf '%s' "$href" | escape)" "$(</dev/stdin)"
}
br() {
echo '<br>'
}
br_lines() {
read -r first_line
echo "$first_line"
while read -r line; do
printf '<br>%s\n' "$line"
done
}
codeblock() {
printf '<pre><code>'
escape
printf '</code></pre>'
}
render() {
local birth=$(stat -c'%W' "$1")
if (( birth > 0 )); then
CREATED_AT=$(date --rfc-3339=seconds -d "@$birth")
fi
MODIFIED_AT=$(date --rfc-3339=seconds -d "@$(stat -c '%Y' "$1")")
#shellcheck disable=SC1090
( . "$1"; ) # the moment you've all been waiting for
}
print_help() {
echo "Usage: $0 <SCRIPT>
$0 -h|--help"
}
if ! ( return &>/dev/null ); then
script=$1
if [[ "${script:+x}" != 'x' ]]; then
print_help
exit 1
elif [[ "$script" == "--help"
|| "$script" == "-h" ]]; then
print_help
else
render "$script"
fi
fi