[pacman-dev] [PATCH 1/1] scripts/library: add config_parser.sh

lolilolicon lolilolicon at gmail.com
Fri Sep 30 07:37:48 EDT 2011


config_parser.sh provides functions to support parsing simple config
files, pacman.conf in particular.  Our scripts should never use a
simple eval to get config values such as DBPath.

conf_key_val() is modified from pacman-key's get_from() function. Please
note conf_key_val() and conf_key_set() both read config file from stdin,
instead of $1.

Signed-off-by: lolilolicon <lolilolicon at gmail.com>
---
 scripts/library/README           |    3 ++
 scripts/library/config_parser.sh |   56 ++++++++++++++++++++++++++++++++++++++
 2 files changed, 59 insertions(+), 0 deletions(-)
 create mode 100644 scripts/library/config_parser.sh

diff --git a/scripts/library/README b/scripts/library/README
index 1e9c962..4fb70dd 100644
--- a/scripts/library/README
+++ b/scripts/library/README
@@ -1,6 +1,9 @@
 This folder contains code snippets that can be reused by multiple
 scripts.  A brief description of each file follows.
 
+config_parser.sh:
+Parses simple config files such as pacman.conf.
+
 output_format.sh:
 Provides basic output formatting functions with levels 'msg', 'msg2',
 'warning' and 'error'.  The 'msg' amd 'msg2' functions print to stdout
diff --git a/scripts/library/config_parser.sh b/scripts/library/config_parser.sh
new file mode 100644
index 0000000..1d125eb
--- /dev/null
+++ b/scripts/library/config_parser.sh
@@ -0,0 +1,56 @@
+shopt -s extglob
+
+# Parse value of a non-repeating key from a config file.
+#
+# stdin: config file
+# $1: key - shall not contain '=', or start/end with whitespaces
+# $2: default value if not defined in config file [optional]
+# return:
+#   0 - print value of key
+#   1 - print nothing
+conf_key_val() {
+	local key val
+	while IFS='=' read -r key val; do
+		# strip whitespaces
+		key=${key##*([[:space:]])}
+		key=${key%%*([[:space:]])}
+		val=${val##*([[:space:]])}
+		val=${val%%*([[:space:]])}
+		# ignore comments and invalid lines
+		[[ ${key:0:1} == '#' || -z $key || -z $val ]] && continue
+		# return success as soon as a value is found
+		if [[ $key == "$1" ]]; then
+			printf '%s' "$val"
+			return 0
+		fi
+	done
+	# fallback to default value if specified
+	if [[ -n $2 ]]; then
+		printf '%s' "$2"
+		return 0
+	fi
+	return 1
+}
+
+# Check whether an on/off key is set (on) in a config file.
+#
+#	stdin: config file
+# $1: key - shall not contain '=', or start/end with whitespaces
+# return:
+#   0 - key is set
+#   1 - key is not set
+conf_key_set() {
+	local key
+	while read -r key; do
+		# strip whitespaces, ignore comments
+		key=${key##*([[:space:]])}
+		key=${key%%*([[:space:]])}
+		# ignore comments and invalid lines
+		[[ ${key:0:1} == '#' || -z $key ]] && continue
+		# return success as soon as the key is found
+		if [[ $key == "$1" ]]; then
+			return 0
+		fi
+	done
+	return 1
+}
-- 
1.7.6.4



More information about the pacman-dev mailing list