summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--deps.mk1
-rwxr-xr-xsrc/htmlesc118
2 files changed, 119 insertions, 0 deletions
diff --git a/deps.mk b/deps.mk
index 44b6820..a4831c0 100644
--- a/deps.mk
+++ b/deps.mk
@@ -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 &gt; 5 &amp;&amp; !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|&amp;|\&|g' \
+ -e 's|&lt;|<|g' \
+ -e 's|&gt;|>|g' \
+ -e 's|&quot;|"|g' \
+ -e "s|&apos;|'|g"
+}
+
+encode() {
+ sed \
+ -e 's|&|\&amp;|g' \
+ -e 's|<|\&lt;|g' \
+ -e 's|>|\&gt;|g' \
+ -e 's|"|\&quot;|g' \
+ -e "s|'|\&apos;|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