|
| 1 | +#!/usr/bin/env bash |
| 2 | +# |
| 3 | +# btidy.sh |
| 4 | +# |
| 5 | +# Use HTML tidy on just the body of an HTML file. |
| 6 | +# See https://www.html-tidy.org/ for documentation on tidy. |
| 7 | +# |
| 8 | +# When used as a filter, this will enclose each line of tidy output in |
| 9 | +# an HTML comment. |
| 10 | +# |
| 11 | +# Usage: |
| 12 | +# ./btidy.sh <filename> [options] ... |
| 13 | +# |
| 14 | +# # From vi family editors, assuming btidy.sh is in your path: |
| 15 | +# :% ! btidy.sh [options] |
| 16 | +# # vi example in a marked section: |
| 17 | +# :'a,'b ! btidy.sh -i |
| 18 | +# |
| 19 | +# Copyright (C) 2024 by The Obscure Organization |
| 20 | +# |
| 21 | +# MIT licensed. See the LICENSE file for details. |
| 22 | +# |
| 23 | +# Release History: |
| 24 | +# |
| 25 | +# 1.0 (Sat Dec 14, 2024) |
| 26 | +# First public release |
| 27 | + |
| 28 | +# Use bash unofficial strict mode |
| 29 | +set -euo pipefail |
| 30 | +IFS=$'\n\t' |
| 31 | + |
| 32 | +DEBUG=${DEBUG:-false} |
| 33 | + |
| 34 | +# Thanks https://stackoverflow.com/a/17805088 |
| 35 | +$DEBUG && export PS4='${LINENO}: ' && set -x |
| 36 | + |
| 37 | +TMPFILE=$(mktemp /tmp/btidy.XXXXXX) |
| 38 | +TMPERR=$(mktemp /tmp/btidy-err.XXXXXX) |
| 39 | +TMPOUT=$(mktemp /tmp/btidy-out.XXXXXX) |
| 40 | + |
| 41 | +# remove tempfile on exit |
| 42 | +function finish { |
| 43 | + rm -f "$TMPFILE" "$TMPERR" |
| 44 | +} |
| 45 | +trap finish EXIT |
| 46 | + |
| 47 | +# Nice, thanks https://www.cyberciti.biz/faq/linux-unix-bsd-apple-osx-bash-get-last-argument/ |
| 48 | +FILE="${BASH_ARGV[0]:-}" |
| 49 | +if [ -z "$FILE" ]; then |
| 50 | + ARGS="$*" |
| 51 | + FILE=/dev/stdin |
| 52 | +elif [ -f "$FILE" ]; then |
| 53 | + # If a file is specified as the last CLI option, consume the last parameter |
| 54 | + # tricksy - thanks https://unix.stackexchange.com/a/273531 |
| 55 | + # shellcheck disable=2124 |
| 56 | + ARGS="${@:1:$#-1}" |
| 57 | +else |
| 58 | + ARGS="$*" |
| 59 | + FILE=/dev/stdin |
| 60 | +fi |
| 61 | + |
| 62 | +cat <<EOF > "$TMPFILE" |
| 63 | +<!doctype html> |
| 64 | +<html><head><title>invisible</title></head> |
| 65 | +<body> |
| 66 | +EOF |
| 67 | +cat "$FILE" >> "$TMPFILE" |
| 68 | +set +e |
| 69 | +# shellcheck disable=SC2048,SC2086 |
| 70 | +tidy -q --show-body-only y $ARGS "$TMPFILE" > "$TMPOUT" 2>"$TMPERR" |
| 71 | +EXITCODE=$? |
| 72 | +set -e |
| 73 | + |
| 74 | +if [[ "$EXITCODE" -gt 0 ]]; then |
| 75 | + echo "WARNING: tidy had non-zero exit $EXITCODE" >> "$TMPERR" |
| 76 | +fi |
| 77 | +if [[ "$FILE" != "/dev/stdin" ]] \ |
| 78 | + && echo "$ARGS" | grep --quiet -E -- '-m|--modify' |
| 79 | +then |
| 80 | + cat "$TMPFILE" > "$FILE" |
| 81 | +else |
| 82 | + if [[ -s "$TMPERR" ]]; then |
| 83 | + TV="$(tidy --version)" |
| 84 | + printf '<!-- %s -->\n' "$TV" |
| 85 | + sed 's/^\(.*\)$/<!-- \1 -->/' "$TMPERR" |
| 86 | + fi |
| 87 | + cat "$TMPOUT" |
| 88 | +fi |
| 89 | + |
| 90 | +exit $EXITCODE |
0 commit comments