diff options
author | jade <lix@jade.fyi> | 2024-05-30 02:33:05 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@lix-systems> | 2024-05-30 02:33:05 +0000 |
commit | 562ff516ab27b8e98490646dd30ac96e7e2c36bb (patch) | |
tree | 1798a20b33da0101bd91acf7da26c891f0cda620 /src/libutil/environment-variables.cc | |
parent | c71f21da3ac4d95ef9a42a26416ccee71639dbd6 (diff) | |
parent | a39ba22ff7112cd3984bbf28d8610d84dd525a0f (diff) |
Merge changes from topic "libutil-split" into main
* changes:
util.hh: Delete remaining file and clean up headers
util.hh: Move nativeSystem to local-derivation-goal.cc
util.hh: Move stuff to types.hh
util.cc: Delete remaining file
util.{hh,cc}: Move ignoreException to error.{hh,cc}
util.{hh,cc}: Split out namespaces.{hh,cc}
util.{hh,cc}: Split out users.{hh,cc}
util.{hh,cc}: Split out strings.{hh,cc}
util.{hh,cc}: Split out unix-domain-socket.{hh,cc}
util.{hh,cc}: Split out child.{hh,cc}
util.{hh,cc}: Split out current-process.{hh,cc}
util.{hh,cc}: Split out processes.{hh,cc}
util.{hh,cc}: Split out file-descriptor.{hh,cc}
util.{hh,cc}: Split out file-system.{hh,cc}
util.{hh,cc}: Split out terminal.{hh,cc}
util.{hh,cc}: Split out environment-variables.{hh,cc}
Diffstat (limited to 'src/libutil/environment-variables.cc')
-rw-r--r-- | src/libutil/environment-variables.cc | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/libutil/environment-variables.cc b/src/libutil/environment-variables.cc new file mode 100644 index 000000000..71c404a0e --- /dev/null +++ b/src/libutil/environment-variables.cc @@ -0,0 +1,51 @@ +#include <cstring> +#include <map> +#include <optional> +#include <string> + +extern char * * environ __attribute__((weak)); + +namespace nix { + +std::optional<std::string> getEnv(const std::string & key) +{ + char * value = getenv(key.c_str()); + if (!value) return {}; + return std::string(value); +} + +std::optional<std::string> getEnvNonEmpty(const std::string & key) { + auto value = getEnv(key); + if (value == "") return {}; + return value; +} + +std::map<std::string, std::string> getEnv() +{ + std::map<std::string, std::string> env; + for (size_t i = 0; environ[i]; ++i) { + auto s = environ[i]; + auto eq = strchr(s, '='); + if (!eq) + // invalid env, just keep going + continue; + env.emplace(std::string(s, eq), std::string(eq + 1)); + } + return env; +} + + +void clearEnv() +{ + for (auto & name : getEnv()) + unsetenv(name.first.c_str()); +} + +void replaceEnv(const std::map<std::string, std::string> & newEnv) +{ + clearEnv(); + for (auto & newEnvVar : newEnv) + setenv(newEnvVar.first.c_str(), newEnvVar.second.c_str(), 1); +} + +} |