From 1d06d940586729e192254e96e4659bbe20ef745d Mon Sep 17 00:00:00 2001 From: emma Date: Mon, 21 Nov 2022 23:10:24 -0500 Subject: [PATCH] implement outputting values of keys not in tables --- README.md | 10 ++++++++++ tomcat | 34 ++++++++++++++++------------------ 2 files changed, 26 insertions(+), 18 deletions(-) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..0e8f751 --- /dev/null +++ b/README.md @@ -0,0 +1,10 @@ +`tomcat` – a [TOML](https://toml.io) parser in POSIX shell + +## Installation + +### From Source + +Clone this repository and move the `tomcat` binary wherever your operating +system stores locally-installed binaries. This is usually `/usr/local/bin` or +`$HOME/.local/bin` for your user. Make sure the installation location is in your +`$PATH`. diff --git a/tomcat b/tomcat index 9e503a8..7d65ff5 100755 --- a/tomcat +++ b/tomcat @@ -2,18 +2,13 @@ set -e -ARG="$(printf "%s\n" "$1" | sed -n '/-/p')" +argv1="$1" +argv2="$2" # check usage if ! test -n "$1"; then printf "Usage: %s [OPTIONS] [TABLE.KEY[INDEX]] [FILE]\n" "$0" 1>&2 exit 64 # sysexits(3) EX_USAGE -elif test -n "$ARG"; then - argv1="$2" - argv2="$3" -else - argv1="$1" - argv2="$2" fi # test if input has a period @@ -22,10 +17,10 @@ if test -n "$(printf "%s\n" "$argv1" | sed -n '/.*\..*/p')"; then TABLE=$(printf "%s\n" "$argv1" | sed -n 's/\..*//p') # cut out everything before the first period for KEY - KEY=$(printf "%s\n" "$argv1" | sed -n 's/^[^.]\+\.//p') + KEY=$(printf "%s\n" "$argv1" | sed -n 's/^[^.]*\.//p') else - # set key to input if there is no table specified - KEY=$argv1 + # assume the argument is a table + TABLE="$argv1" fi # remove array index from KEY @@ -42,10 +37,18 @@ else TOML=$(printf "%s\n" "$argv2" | sed 's/[^"#]#\+.*//g') fi -# set VAL to the parsed TOML -VAL=$(printf "%s\n" "$TOML" |\ +if test -n "$TABLE"; then + KEYS=$(printf "%s\n" "$TOML" |\ # output only lines between TABLE and the next table - awk "/^\[$TABLE\]/{flag=1; next} /^\[/{flag=0} flag" - |\ + awk "/^\[$TABLE\]/{flag=1; next} /^\[/{flag=0} flag" - ) +else + KEYS=$(printf "%s\n" "$TOML" |\ + # output only lines before the first table + awk '1;/^\[/{exit}' - | sed -n '/^[^[]/p') +fi + +# set VAL to the parsed KEYS list +VAL=$(printf "%s\n" "$KEYS" |\ # remove the key from the string and delineate arrays, removing # brackets, trailing commas, and leading spaces sed -n "s/$KEY *= *//p" | sed 's/", "/ /g' | tr -d '[]"' |\ @@ -57,11 +60,6 @@ if test -n "$ARR"; then printf "%s\n" "$VAL" | sed 's/ /\n/g' | head -n "$ARR" |\ tail -n 1 else - if test -n "$ARG"; then - if [ "$1" = "-c" ] || [ "$1" = "--count" ]; then - VAL="$(printf "%s\n" "$VAL" | sed 's/ /\n/g' | wc -l)" - fi - fi printf "%s\n" "$VAL" fi