diff options
-rw-r--r-- | deps.mk | 1 | ||||
-rwxr-xr-x | src/htmlesc | 118 |
2 files changed, 119 insertions, 0 deletions
@@ -2,6 +2,7 @@ sources.sh = \ src/assert-arg \ src/clock \ src/color \ + src/htmlesc \ src/ifnew \ src/minutes \ src/mkdtemp \ diff --git a/src/htmlesc b/src/htmlesc new file mode 100755 index 0000000..5f3694f --- /dev/null +++ b/src/htmlesc @@ -0,0 +1,118 @@ +#!/bin/sh +set -eu + + +usage() { + cat <<-'EOF' + Usage: + htmlesc [-e|d] [CONTENT...] + htmlesc -h + EOF +} + +help() { + cat <<-'EOF' + + + Options: + -e escape the string (the default action) + -d unescape (de-escape?) the string + -h, --help show this message + + CONTENT a literal string to be escaped + + + Convert data to/from HTML escaping. If CONTENT is not given, + get data from STDIN. + + + Examples: + + Escape HTML control characters in a string: + + $ htmlesc 'a > 5 && !b' + a > 5 && !b + + + Unescape the content from a file: + + $ htmlesc -d < file.html + EOF +} + + +for flag in "$@"; do + case "$flag" in + (--) + break + ;; + (--help) + usage + help + exit + ;; + (*) + ;; + esac +done + +ENCODE=false +DECODE=false +while getopts 'edh' flag; do + case "$flag" in + (e) + ENCODE=true + ;; + (d) + DECODE=true + ;; + (h) + usage + help + exit + ;; + (*) + usage >&2 + exit 2 + ;; + esac +done +shift $((OPTIND - 1)) + +if [ "$ENCODE" = true ] && [ "$DECODE" = true ]; then + printf 'Both -e and -d given. Pick one.\n' >&2 + usage >&2 + exit 2 +fi + +decode() { + sed \ + -e 's|&|\&|g' \ + -e 's|<|<|g' \ + -e 's|>|>|g' \ + -e 's|"|"|g' \ + -e "s|'|'|g" +} + +encode() { + sed \ + -e 's|&|\&|g' \ + -e 's|<|\<|g' \ + -e 's|>|\>|g' \ + -e 's|"|\"|g' \ + -e "s|'|\'|g" +} + +if [ "$DECODE" = true ]; then + FN=decode +else + FN=encode +fi + +if [ $# = 0 ]; then + "$FN" +else + for s in "$@"; do + printf '%s\n' "$s" | "$FN" + done +fi |