From: Eric Fahlgren Date: Sat, 8 Feb 2025 16:41:56 +0000 (-0800) Subject: luci-base: add uci.get_bool to allow cleanup of app code X-Git-Url: http://git.openwrt.org/?a=commitdiff_plain;h=dea8d79888f862c82953b775e55f4d0c672cc897;p=project%2Fluci.git luci-base: add uci.get_bool to allow cleanup of app code 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 --- diff --git a/modules/luci-base/htdocs/luci-static/resources/uci.js b/modules/luci-base/htdocs/luci-static/resources/uci.js index d18e9d98fe..ecd5063e4e 100644 --- a/modules/luci-base/htdocs/luci-static/resources/uci.js +++ b/modules/luci-base/htdocs/luci-static/resources/uci.js @@ -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