1 // ANNA - Anna is Not Nothingness Anymore //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
9 #include <anna/core/util/Environment.hpp>
11 #include <anna/config/defines.hpp>
12 #include <anna/core/tracing/Logger.hpp>
13 #include <anna/core/tracing/TraceMethod.hpp>
14 #include <anna/core/functions.hpp>
16 #include <stdlib.h> // getenv / setenv
26 void Environment::initialize(char **envp) throw() {
27 LOGMETHOD(TraceMethod tm("Environment", "initialize", ANNA_FILE_LOCATION));
34 std::string assignment, var, val;
38 std::size_t equalPos = assignment.find("=");
40 if(equalPos != string::npos) { // protection
41 var = assignment.substr(0, equalPos - 1);
42 val = assignment.substr(equalPos, assignment.size() - 1);
50 std::string Environment::getValue(const char* variableName, bool exceptionIfMissing) throw(RuntimeException) {
52 throw RuntimeException("Invalid NULL variable name!", ANNA_FILE_LOCATION);
54 std::string var = variableName;
55 return getValue(var, exceptionIfMissing);
58 std::string Environment::getValue(const std::string &variableName, bool exceptionIfMissing) throw(RuntimeException) {
59 std::string result = "";
60 std::map<std::string, std::string>::const_iterator it = a_vars.find(variableName);
62 if(it == a_vars.end()) {
63 char *current = getenv(variableName.c_str());
66 std::string msg = "The variable '";
68 msg += "' is not defined in the environment.";
69 LOGDEBUG(Logger::debug(msg, ANNA_FILE_LOCATION));
71 if(exceptionIfMissing) throw RuntimeException(msg, ANNA_FILE_LOCATION);
74 a_vars[variableName] = current;
85 void Environment::setVariable(const std::string &name, const std::string &value, bool overwrite) throw(RuntimeException) {
86 if(name == "") throw RuntimeException("Must provide non-empty variable name", ANNA_FILE_LOCATION);
88 if(setenv(name.c_str(), value.c_str(), overwrite ? 1 : 0) != 0) {
89 std::string msg = "Cannot set the environment variable '";
93 msg += "\"'. The errno is ";
94 msg += anna::functions::asString(errno);
95 throw RuntimeException(msg, ANNA_FILE_LOCATION);
100 a_vars[name] = value;
104 void Environment::unsetVariable(const std::string &name) throw(RuntimeException) {
105 if(name == "") throw RuntimeException("Must provide non-empty variable name", ANNA_FILE_LOCATION);
107 if(unsetenv(name.c_str()) != 0) {
108 std::string msg = "Cannot unset the environment variable named '";
110 msg += "'. The errno is ";
111 msg += anna::functions::asString(errno);
112 throw RuntimeException(msg, ANNA_FILE_LOCATION);
115 std::map<std::string, std::string>::iterator it = a_vars.find(name);
117 if(it != a_vars.end()) a_vars.erase(it);