From 52a6dfb42c17ea79b73ff56a7a7e88c77dcb9b38 Mon Sep 17 00:00:00 2001 From: Michael Carlberg Date: Wed, 14 Dec 2016 20:14:31 +0100 Subject: [PATCH] refactor(config): Use defined fallback for environment refs --- include/components/config.hpp | 23 ++++++++++++++++------- src/utils/env.cpp | 4 +++- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/include/components/config.hpp b/include/components/config.hpp index 3ff48818..af67f170 100644 --- a/include/components/config.hpp +++ b/include/components/config.hpp @@ -204,7 +204,7 @@ class config { * Dereference value reference */ template - T dereference(const string& section, const string& key, const string& var, T fallback) const { + T dereference(const string& section, const string& key, const string& var, const T& fallback) const { if (var.substr(0, 2) != "${" || var.substr(var.length() - 1) != "}") { return fallback; } @@ -254,19 +254,28 @@ class config { * ${env:key:fallback value} */ template - T dereference_env(string var, T fallback) const { + T dereference_env(string var, const T&) const { size_t pos; + string env_default{""}; if ((pos = var.find(":")) != string::npos) { - fallback = convert(var.substr(pos + 1)); + env_default = var.substr(pos + 1); var.erase(pos); } if (env_util::has(var.c_str())) { - return convert(env_util::get(var.c_str())); - } else { - return fallback; + string env_value{env_util::get(var.c_str())}; + m_logger.info("Found matching environment variable ${" + var + "} with the value \"" + env_value + "\""); + return convert(move(env_value)); } + + if (!env_default.empty()) { + m_logger.info("The environment variable ${" + var + "} is undefined or empty, using defined fallback value \"" + env_default + "\""); + } else { + m_logger.info("The environment variable ${" + var + "} is undefined or empty"); + } + + return convert(move(env_default)); } /** @@ -275,7 +284,7 @@ class config { * ${xrdb:key:fallback value} */ template - T dereference_xrdb(string var, T fallback) const { + T dereference_xrdb(string var, const T& fallback) const { size_t pos; if ((pos = var.find(":")) != string::npos) { diff --git a/src/utils/env.cpp b/src/utils/env.cpp index 0c1b415c..5aee338a 100644 --- a/src/utils/env.cpp +++ b/src/utils/env.cpp @@ -1,5 +1,6 @@ #include #include +#include #include "utils/env.hpp" @@ -7,7 +8,8 @@ POLYBAR_NS namespace env_util { bool has(const char* var) { - return std::getenv(var) != nullptr; + const char* env{std::getenv(var)}; + return env != nullptr && strlen(env) > 0; } string get(const char* var, string fallback) {