mirror of
https://github.com/NixOS/nix
synced 2025-07-07 06:01:48 +02:00
Clean up env var logic in preparation for Windows
It's a little weird we don't check the return status for these, but changing that would introduce risk so I did not. Co-authored-by: Théophane Hufschmitt <7226587+thufschmitt@users.noreply.github.com>
This commit is contained in:
parent
6b889e0588
commit
ef2d10f7e7
8 changed files with 32 additions and 20 deletions
|
@ -32,4 +32,17 @@ std::map<std::string, std::string> getEnv()
|
|||
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());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -28,6 +28,14 @@ std::optional<std::string> getEnvNonEmpty(const std::string & key);
|
|||
*/
|
||||
std::map<std::string, std::string> getEnv();
|
||||
|
||||
/**
|
||||
* Like POSIX `setenv`, but always overrides.
|
||||
*
|
||||
* We don't need the non-overriding version, and this is easier to
|
||||
* reimplement on Windows.
|
||||
*/
|
||||
int setEnv(const char * name, const char * value);
|
||||
|
||||
/**
|
||||
* Clear the environment.
|
||||
*/
|
||||
|
|
|
@ -1,21 +1,12 @@
|
|||
#include "util.hh"
|
||||
#include "environment-variables.hh"
|
||||
#include <cstdlib>
|
||||
|
||||
extern char * * environ __attribute__((weak));
|
||||
#include "environment-variables.hh"
|
||||
|
||||
namespace nix {
|
||||
|
||||
void clearEnv()
|
||||
int setEnv(const char * name, const char * value)
|
||||
{
|
||||
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);
|
||||
return ::setenv(name, value, 1);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue