luci-base: add uci.get_bool to allow cleanup of app code
authorEric Fahlgren <[email protected]>
Sat, 8 Feb 2025 16:41:56 +0000 (08:41 -0800)
committerPaul Donald <[email protected]>
Tue, 11 Mar 2025 14:06:09 +0000 (15:06 +0100)
Any number of apps read boolean values from configuration files, then use
various inconsistent means for checking truth values.  The get_bool function
allows app authors to fetch the value without regard for how it is represented
in the config file.

For example, this

    let enabled = uci.get('system', 'ntp', 'enable_server');
    if (enabled == '1') ...

could become the more natural

    let enabled = uci.get_bool('system', 'ntp', 'enable_server');
    if (enabled) ...

Signed-off-by: Eric Fahlgren <[email protected]>
modules/luci-base/htdocs/luci-static/resources/uci.js

index d18e9d98fe10d8f606b95391f1a1936b25407a62..ecd5063e4ed41ad288e8ee87f05da5ce98ec9632 100644 (file)
@@ -704,6 +704,40 @@ return baseclass.extend(/** @lends LuCI.uci.prototype */ {
                return this.get(conf, sid, opt);
        },
 
+       /**
+        * A special case of `get` that always returns either `true` or 
+        * `false`.
+        *
+        * Many configuration files contain boolean settings, such as
+        * `enabled` or `advanced_mode`, where there is no consistent
+        * definition for the values.  This function allows users to
+        * enter any of the values `"yes"`, `"on"`, `"true"` or `1` in
+        * their config files and we return the expected boolean result.
+        *
+        * Character case is not significant, so for example, any of
+        * "YES", "Yes" or "yes" will be interpreted as a `true` value.
+        *
+        * @param {string} conf
+        * The name of the configuration to read.
+        *
+        * @param {string} sid
+        * The name or ID of the section to read.
+        *
+        * @param {string} [opt]
+        * The option name from which to read the value. If the option
+        * name is omitted or `null`, the value `false` is returned.
+        *
+        * @returns {boolean}
+        * - Returns boolean `true` if the configuration value is defined
+        *   and looks like a true value, otherwise returns `false`.
+        */
+       get_bool(conf, type, opt) {
+               let value = this.get(conf, type, opt);
+               if (typeof(value) == 'string')
+                       return ['1', 'on', 'true', 'yes', 'enabled'].includes(value.toLowerCase());
+               return false;
+       },
+
        /**
         * Sets the value of the given option within the first found section
         * of the given configuration matching the specified type or within