From 526e2bfcdb5f55f2bd94b29cf314f8cb4c37bf4f Mon Sep 17 00:00:00 2001 From: davidovski Date: Mon, 14 Feb 2022 00:24:11 +0000 Subject: made parseconf 4 times faster --- src/parseconf.sh | 85 ++++++++++++++++++++++++++++++++------------------------ test/test.conf | 41 +++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 37 deletions(-) diff --git a/src/parseconf.sh b/src/parseconf.sh index 44089b7..aa5885d 100755 --- a/src/parseconf.sh +++ b/src/parseconf.sh @@ -13,45 +13,52 @@ Arguments: EOF } +getlevel() { + for i in $*; do + printf $i + printf '.' + done +} + +parse_line() { + [ $# == "0" ] && return + + local line="$@" + local key=$1 + shift + local value="$@" + + [ "$key" = "include" ] && parse $value && return + [ "$key" = "]" ] && unset list[-1] && printf "\n" && return + [ "$key" = "}" ] && unset level[-1] && return + + case ${value: -1} in + "{") + level+=("$key") + ;; + "[") + list+=("$key") + printf "$(getlevel ${level[@]})$key:" + ;; + *) + + [ "${#list[@]}" == "0" ] && + printf "$(getlevel ${level[@]})$key:$value\n" || + printf "$line " + ;; + esac +} + # print the parsed values from the config file in key:value format # parse () { local file="$1" - local level="" - local list="" + export level=() + export list=() while IFS= read -r line; do - line=$(sed "s/\s\+/ /g" <<< "$line" | sed "s/^\s\|\s$\|;*$//g") - - grep -q "^#" <<< "$line" && continue - grep -q "." <<< "$line" || continue - - local key=$(echo $line | cut -d" " -f1) - local value=$(echo $line | cut -d" " -f2-) - - [ "$key" = "include" ] && parse $value && continue - - case ${value: -1} in - "{") - level="$level$key." - ;; - "[") - list="$list$key." - printf "$level$key:" - ;; - "}") - level=$(sed "s/[^\.]\w*\.$//g" <<< "$level") - ;; - "]") - printf "\n" - list=$(sed "s/[^\.]\w*\.$//g" <<< "$list") - ;; - *) - - grep -q "." <<< "$list" && - printf "$line " || - printf "$level$key:$value\n" - ;; - esac + # strip whitespace + line=$(sed "s/^#.*$\|\s(\s\+)\|^\s\|\s^\|;*$//g" <<< "$line") + parse_line $line done < "$file" } @@ -99,8 +106,12 @@ done shift $((OPTIND-1)) -[ -z ${count} ] && - filter "$@" || - filter "$@" | tail -n $count +if echo $@ | grep -q "."; then + [ -z ${count} ] && + filter "$@" || + filter "$@" | tail -n $count +else + parse $CONF_FILE +fi diff --git a/test/test.conf b/test/test.conf index 139597f..8ac673f 100644 --- a/test/test.conf +++ b/test/test.conf @@ -1,2 +1,43 @@ +key1 value +key2 value + key3 value +key5 value; +key6 value;; +include test/external.conf + +dict { +a 1 + b 2 + c 3 + d 4 + e 5 +} + +list [ + alpha + beta + gamma + delta +] + + +other_dict { + contained_list [ + a listo + of values + to be + parsed + ] + + value1 parsed + value2 parsed + + builtin { + this that + that the other + then now + } + +} -- cgit v1.2.1