]> git.ipfire.org Git - ipfire-2.x.git/commitdiff
initscript functions: add readhash
authorJonatan Schlag <jonatan.schlag@ipfire.org>
Sun, 16 Jun 2024 16:02:37 +0000 (18:02 +0200)
committerMichael Tremer <michael.tremer@ipfire.org>
Sat, 24 Aug 2024 12:19:56 +0000 (12:19 +0000)
To avoid the usage of eval and to store the config in an key value
array, we introduce an new function. The tests only check if we
read the correct value to the correct variable.

One comment on the implementation as this has created some headache:

>From https://www.gnu.org/software/bash/manual/bash.html#Bourne-Shell-Builtins

"When used in a function, declare makes each name local, as with the local command, unless the -g option is used."

So we need to use -g here

Signed-off-by: Jonatan Schlag <jonatan.schlag@ipfire.org>
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/initscripts/system/functions
tests/src/initscripts/system/functions/data/1 [new file with mode: 0644]
tests/src/initscripts/system/functions/test.sh [new file with mode: 0755]

index 1fa256e80bd806321151487af3068e6c8ed440c1..dd141db6e85fd8b073a474dbe52f6d0798df5d73 100644 (file)
@@ -890,3 +890,18 @@ volume_fs_type() {
 
        stat -f --format="%T" ${1}
 }
+
+readhash() {
+       local array="${1}"
+       local file="${2}"
+
+       declare -A -g "${array}"
+
+       local line
+       while read -r line; do
+               local key="${line%=*}"
+               local val="${line#*=}"
+
+               printf -v "${array}[${key}]" "%s" "${val}"
+       done < "${file}"
+}
diff --git a/tests/src/initscripts/system/functions/data/1 b/tests/src/initscripts/system/functions/data/1
new file mode 100644 (file)
index 0000000..8aca942
--- /dev/null
@@ -0,0 +1,17 @@
+CONFIG_TYPE=3
+GREEN_DEV=green0
+GREEN_MACADDR=00:c0:08:8a:a0:47
+GREEN_DRIVER=r8175
+RED_DEV=red0
+RED_MACADDR=00:c0:08:8a:a0:56
+RED_DRIVER=r8283
+BLUE_DEV='blue0 net0'
+BLUE_MACADDR=bc:30:7d:58:6b:e3
+BLUE_DRIVER=rt2800
+RED_DHCP_HOSTNAME=ipfire
+RED_DHCP_FORCE_MTU=
+RED_ADDRESS=0.0.0.0
+RED_NETMASK=0.0.0.0
+RED_TYPE=PPPOE
+RED_NETADDRESS=0.0.0.0
+
diff --git a/tests/src/initscripts/system/functions/test.sh b/tests/src/initscripts/system/functions/test.sh
new file mode 100755 (executable)
index 0000000..dbb2d8a
--- /dev/null
@@ -0,0 +1,16 @@
+#!/usr/bin/bash
+
+SCRIPT_PATH="$(dirname "$(readlink -f "$0")")"
+
+ROOT="$(readlink -f "${SCRIPT_PATH}/../../../../..")"
+
+. ${ROOT}/tests/lib.sh
+
+. ${ROOT}/src/initscripts/system/functions
+
+# read the date in
+readhash "CONFIG" "${SCRIPT_PATH}/data/1"
+
+# test if we read the correct data
+test_value_in_array "CONFIG" "RED_DHCP_HOSTNAME" "ipfire"
+test_value_in_array "CONFIG" "BLUE_MACADDR" "bc:30:7d:58:6b:e3"