refactor(config): Use defined fallback for environment refs

This commit is contained in:
Michael Carlberg 2016-12-14 20:14:31 +01:00
parent 3489ac7852
commit 52a6dfb42c
2 changed files with 19 additions and 8 deletions

View File

@ -204,7 +204,7 @@ class config {
* Dereference value reference
*/
template <typename T>
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 <typename T>
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<T>(var.substr(pos + 1));
env_default = var.substr(pos + 1);
var.erase(pos);
}
if (env_util::has(var.c_str())) {
return convert<T>(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<T>(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<T>(move(env_default));
}
/**
@ -275,7 +284,7 @@ class config {
* ${xrdb:key:fallback value}
*/
template <typename T>
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) {

View File

@ -1,5 +1,6 @@
#include <thread>
#include <utility>
#include <cstring>
#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) {