getEnv(): Return std::optional

This allows distinguishing between an empty value and no value.
This commit is contained in:
Eelco Dolstra 2019-11-22 16:06:44 +01:00
parent fd900c45b5
commit ba87b08f85
No known key found for this signature in database
GPG key ID: 8170B4726D7198DE
17 changed files with 60 additions and 63 deletions

View file

@ -217,7 +217,7 @@ void initGC()
that GC_expand_hp() causes a lot of virtual, but not physical that GC_expand_hp() causes a lot of virtual, but not physical
(resident) memory to be allocated. This might be a problem on (resident) memory to be allocated. This might be a problem on
systems that don't overcommit. */ systems that don't overcommit. */
if (!getenv("GC_INITIAL_HEAP_SIZE")) { if (!getEnv("GC_INITIAL_HEAP_SIZE")) {
size_t size = 32 * 1024 * 1024; size_t size = 32 * 1024 * 1024;
#if HAVE_SYSCONF && defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES) #if HAVE_SYSCONF && defined(_SC_PAGESIZE) && defined(_SC_PHYS_PAGES)
size_t maxSize = 384 * 1024 * 1024; size_t maxSize = 384 * 1024 * 1024;
@ -306,7 +306,7 @@ EvalState::EvalState(const Strings & _searchPath, ref<Store> store)
, baseEnv(allocEnv(128)) , baseEnv(allocEnv(128))
, staticBaseEnv(false, 0) , staticBaseEnv(false, 0)
{ {
countCalls = getEnv("NIX_COUNT_CALLS", "0") != "0"; countCalls = getEnv("NIX_COUNT_CALLS").value_or("0") != "0";
assert(gcInitialised); assert(gcInitialised);
@ -314,7 +314,7 @@ EvalState::EvalState(const Strings & _searchPath, ref<Store> store)
/* Initialise the Nix expression search path. */ /* Initialise the Nix expression search path. */
if (!evalSettings.pureEval) { if (!evalSettings.pureEval) {
Strings paths = parseNixPath(getEnv("NIX_PATH", "")); Strings paths = parseNixPath(getEnv("NIX_PATH").value_or(""));
for (auto & i : _searchPath) addToSearchPath(i); for (auto & i : _searchPath) addToSearchPath(i);
for (auto & i : paths) addToSearchPath(i); for (auto & i : paths) addToSearchPath(i);
} }
@ -1753,7 +1753,7 @@ bool EvalState::eqValues(Value & v1, Value & v2)
void EvalState::printStats() void EvalState::printStats()
{ {
bool showStats = getEnv("NIX_SHOW_STATS", "0") != "0"; bool showStats = getEnv("NIX_SHOW_STATS").value_or("0") != "0";
struct rusage buf; struct rusage buf;
getrusage(RUSAGE_SELF, &buf); getrusage(RUSAGE_SELF, &buf);
@ -1769,7 +1769,7 @@ void EvalState::printStats()
GC_get_heap_usage_safe(&heapSize, 0, 0, 0, &totalBytes); GC_get_heap_usage_safe(&heapSize, 0, 0, 0, &totalBytes);
#endif #endif
if (showStats) { if (showStats) {
auto outPath = getEnv("NIX_SHOW_STATS_PATH","-"); auto outPath = getEnv("NIX_SHOW_STATS_PATH").value_or("-");
std::fstream fs; std::fstream fs;
if (outPath != "-") if (outPath != "-")
fs.open(outPath, std::fstream::out); fs.open(outPath, std::fstream::out);
@ -1861,7 +1861,7 @@ void EvalState::printStats()
} }
} }
if (getEnv("NIX_SHOW_SYMBOLS", "0") != "0") { if (getEnv("NIX_SHOW_SYMBOLS").value_or("0") != "0") {
auto list = topObj.list("symbols"); auto list = topObj.list("symbols");
symbols.dump([&](const std::string & s) { list.elem(s); }); symbols.dump([&](const std::string & s) { list.elem(s); });
} }

View file

@ -469,7 +469,7 @@ static void prim_tryEval(EvalState & state, const Pos & pos, Value * * args, Val
static void prim_getEnv(EvalState & state, const Pos & pos, Value * * args, Value & v) static void prim_getEnv(EvalState & state, const Pos & pos, Value * * args, Value & v)
{ {
string name = state.forceStringNoCtx(*args[0], pos); string name = state.forceStringNoCtx(*args[0], pos);
mkString(v, evalSettings.restrictEval || evalSettings.pureEval ? "" : getEnv(name)); mkString(v, evalSettings.restrictEval || evalSettings.pureEval ? "" : getEnv(name).value_or(""));
} }

View file

@ -2503,7 +2503,7 @@ void DerivationGoal::initEnv()
already know the cryptographic hash of the output). */ already know the cryptographic hash of the output). */
if (fixedOutput) { if (fixedOutput) {
for (auto & i : parsedDrv->getStringsAttr("impureEnvVars").value_or(Strings())) for (auto & i : parsedDrv->getStringsAttr("impureEnvVars").value_or(Strings()))
env[i] = getEnv(i); env[i] = getEnv(i).value_or("");
} }
/* Currently structured log messages piggyback on stderr, but we /* Currently structured log messages piggyback on stderr, but we
@ -3075,7 +3075,7 @@ void DerivationGoal::runChild()
/* The tmpDir in scope points at the temporary build directory for our derivation. Some packages try different mechanisms /* The tmpDir in scope points at the temporary build directory for our derivation. Some packages try different mechanisms
to find temporary directories, so we want to open up a broader place for them to dump their files, if needed. */ to find temporary directories, so we want to open up a broader place for them to dump their files, if needed. */
Path globalTmpDir = canonPath(getEnv("TMPDIR", "/tmp"), true); Path globalTmpDir = canonPath(getEnv("TMPDIR").value_or("/tmp"), true);
/* They don't like trailing slashes on subpath directives */ /* They don't like trailing slashes on subpath directives */
if (globalTmpDir.back() == '/') globalTmpDir.pop_back(); if (globalTmpDir.back() == '/') globalTmpDir.pop_back();

View file

@ -870,11 +870,11 @@ void LocalStore::collectGarbage(const GCOptions & options, GCResults & results)
void LocalStore::autoGC(bool sync) void LocalStore::autoGC(bool sync)
{ {
static auto fakeFreeSpaceFile = getEnv("_NIX_TEST_FREE_SPACE_FILE", ""); static auto fakeFreeSpaceFile = getEnv("_NIX_TEST_FREE_SPACE_FILE");
auto getAvail = [this]() -> uint64_t { auto getAvail = [this]() -> uint64_t {
if (!fakeFreeSpaceFile.empty()) if (fakeFreeSpaceFile)
return std::stoll(readFile(fakeFreeSpaceFile)); return std::stoll(readFile(*fakeFreeSpaceFile));
struct statvfs st; struct statvfs st;
if (statvfs(realStoreDir.c_str(), &st)) if (statvfs(realStoreDir.c_str(), &st))

View file

@ -32,20 +32,20 @@ static GlobalConfig::Register r1(&settings);
Settings::Settings() Settings::Settings()
: nixPrefix(NIX_PREFIX) : nixPrefix(NIX_PREFIX)
, nixStore(canonPath(getEnv("NIX_STORE_DIR", getEnv("NIX_STORE", NIX_STORE_DIR)))) , nixStore(canonPath(getEnv("NIX_STORE_DIR").value_or(getEnv("NIX_STORE").value_or(NIX_STORE_DIR))))
, nixDataDir(canonPath(getEnv("NIX_DATA_DIR", NIX_DATA_DIR))) , nixDataDir(canonPath(getEnv("NIX_DATA_DIR").value_or(NIX_DATA_DIR)))
, nixLogDir(canonPath(getEnv("NIX_LOG_DIR", NIX_LOG_DIR))) , nixLogDir(canonPath(getEnv("NIX_LOG_DIR").value_or(NIX_LOG_DIR)))
, nixStateDir(canonPath(getEnv("NIX_STATE_DIR", NIX_STATE_DIR))) , nixStateDir(canonPath(getEnv("NIX_STATE_DIR").value_or(NIX_STATE_DIR)))
, nixConfDir(canonPath(getEnv("NIX_CONF_DIR", NIX_CONF_DIR))) , nixConfDir(canonPath(getEnv("NIX_CONF_DIR").value_or(NIX_CONF_DIR)))
, nixLibexecDir(canonPath(getEnv("NIX_LIBEXEC_DIR", NIX_LIBEXEC_DIR))) , nixLibexecDir(canonPath(getEnv("NIX_LIBEXEC_DIR").value_or(NIX_LIBEXEC_DIR)))
, nixBinDir(canonPath(getEnv("NIX_BIN_DIR", NIX_BIN_DIR))) , nixBinDir(canonPath(getEnv("NIX_BIN_DIR").value_or(NIX_BIN_DIR)))
, nixManDir(canonPath(NIX_MAN_DIR)) , nixManDir(canonPath(NIX_MAN_DIR))
, nixDaemonSocketFile(canonPath(nixStateDir + DEFAULT_SOCKET_PATH)) , nixDaemonSocketFile(canonPath(nixStateDir + DEFAULT_SOCKET_PATH))
{ {
buildUsersGroup = getuid() == 0 ? "nixbld" : ""; buildUsersGroup = getuid() == 0 ? "nixbld" : "";
lockCPU = getEnv("NIX_AFFINITY_HACK", "1") == "1"; lockCPU = getEnv("NIX_AFFINITY_HACK") == "1";
caFile = getEnv("NIX_SSL_CERT_FILE", getEnv("SSL_CERT_FILE", "")); caFile = getEnv("NIX_SSL_CERT_FILE").value_or(getEnv("SSL_CERT_FILE").value_or(""));
if (caFile == "") { if (caFile == "") {
for (auto & fn : {"/etc/ssl/certs/ca-certificates.crt", "/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt"}) for (auto & fn : {"/etc/ssl/certs/ca-certificates.crt", "/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt"})
if (pathExists(fn)) { if (pathExists(fn)) {
@ -56,9 +56,9 @@ Settings::Settings()
/* Backwards compatibility. */ /* Backwards compatibility. */
auto s = getEnv("NIX_REMOTE_SYSTEMS"); auto s = getEnv("NIX_REMOTE_SYSTEMS");
if (s != "") { if (s) {
Strings ss; Strings ss;
for (auto & p : tokenizeString<Strings>(s, ":")) for (auto & p : tokenizeString<Strings>(*s, ":"))
ss.push_back("@" + p); ss.push_back("@" + p);
builders = concatStringsSep(" ", ss); builders = concatStringsSep(" ", ss);
} }

View file

@ -66,7 +66,7 @@ public:
/* File name of the socket the daemon listens to. */ /* File name of the socket the daemon listens to. */
Path nixDaemonSocketFile; Path nixDaemonSocketFile;
Setting<std::string> storeUri{this, getEnv("NIX_REMOTE", "auto"), "store", Setting<std::string> storeUri{this, getEnv("NIX_REMOTE").value_or("auto"), "store",
"The default Nix store to use."}; "The default Nix store to use."};
Setting<bool> keepFailed{this, false, "keep-failed", Setting<bool> keepFailed{this, false, "keep-failed",

View file

@ -107,7 +107,7 @@ private:
public: public:
// Hack for build-remote.cc. // Hack for build-remote.cc.
PathSet locksHeld = tokenizeString<PathSet>(getEnv("NIX_HELD_LOCKS")); PathSet locksHeld;
/* Initialise the local store, upgrading the schema if /* Initialise the local store, upgrading the schema if
necessary. */ necessary. */

View file

@ -16,7 +16,7 @@ SSHMaster::SSHMaster(const std::string & host, const std::string & keyFile, bool
void SSHMaster::addCommonSSHOpts(Strings & args) void SSHMaster::addCommonSSHOpts(Strings & args)
{ {
for (auto & i : tokenizeString<Strings>(getEnv("NIX_SSHOPTS"))) for (auto & i : tokenizeString<Strings>(getEnv("NIX_SSHOPTS").value_or("")))
args.push_back(i); args.push_back(i);
if (!keyFile.empty()) if (!keyFile.empty())
args.insert(args.end(), {"-i", keyFile}); args.insert(args.end(), {"-i", keyFile});

View file

@ -58,10 +58,11 @@ std::string SysError::addErrno(const std::string & s)
} }
string getEnv(const string & key, const string & def) std::optional<std::string> getEnv(const std::string & key)
{ {
char * value = getenv(key.c_str()); char * value = getenv(key.c_str());
return value ? string(value) : def; if (!value) return {};
return std::string(value);
} }
@ -438,7 +439,7 @@ void deletePath(const Path & path, unsigned long long & bytesFreed)
static Path tempName(Path tmpRoot, const Path & prefix, bool includePid, static Path tempName(Path tmpRoot, const Path & prefix, bool includePid,
int & counter) int & counter)
{ {
tmpRoot = canonPath(tmpRoot.empty() ? getEnv("TMPDIR", "/tmp") : tmpRoot, true); tmpRoot = canonPath(tmpRoot.empty() ? getEnv("TMPDIR").value_or("/tmp") : tmpRoot, true);
if (includePid) if (includePid)
return (format("%1%/%2%-%3%-%4%") % tmpRoot % prefix % getpid() % counter++).str(); return (format("%1%/%2%-%3%-%4%") % tmpRoot % prefix % getpid() % counter++).str();
else else
@ -480,7 +481,7 @@ Path createTempDir(const Path & tmpRoot, const Path & prefix,
std::string getUserName() std::string getUserName()
{ {
auto pw = getpwuid(geteuid()); auto pw = getpwuid(geteuid());
std::string name = pw ? pw->pw_name : getEnv("USER", ""); std::string name = pw ? pw->pw_name : getEnv("USER").value_or("");
if (name.empty()) if (name.empty())
throw Error("cannot figure out user name"); throw Error("cannot figure out user name");
return name; return name;
@ -488,8 +489,8 @@ std::string getUserName()
static Lazy<Path> getHome2([]() { static Lazy<Path> getHome2([]() {
Path homeDir = getEnv("HOME"); auto homeDir = getEnv("HOME");
if (homeDir.empty()) { if (!homeDir) {
std::vector<char> buf(16384); std::vector<char> buf(16384);
struct passwd pwbuf; struct passwd pwbuf;
struct passwd * pw; struct passwd * pw;
@ -498,7 +499,7 @@ static Lazy<Path> getHome2([]() {
throw Error("cannot determine user's home directory"); throw Error("cannot determine user's home directory");
homeDir = pw->pw_dir; homeDir = pw->pw_dir;
} }
return homeDir; return *homeDir;
}); });
Path getHome() { return getHome2(); } Path getHome() { return getHome2(); }
@ -506,25 +507,21 @@ Path getHome() { return getHome2(); }
Path getCacheDir() Path getCacheDir()
{ {
Path cacheDir = getEnv("XDG_CACHE_HOME"); auto cacheDir = getEnv("XDG_CACHE_HOME");
if (cacheDir.empty()) return cacheDir ? *cacheDir : getHome() + "/.cache";
cacheDir = getHome() + "/.cache";
return cacheDir;
} }
Path getConfigDir() Path getConfigDir()
{ {
Path configDir = getEnv("XDG_CONFIG_HOME"); auto configDir = getEnv("XDG_CONFIG_HOME");
if (configDir.empty()) return configDir ? *configDir : getHome() + "/.config";
configDir = getHome() + "/.config";
return configDir;
} }
std::vector<Path> getConfigDirs() std::vector<Path> getConfigDirs()
{ {
Path configHome = getConfigDir(); Path configHome = getConfigDir();
string configDirs = getEnv("XDG_CONFIG_DIRS"); string configDirs = getEnv("XDG_CONFIG_DIRS").value_or("");
std::vector<Path> result = tokenizeString<std::vector<string>>(configDirs, ":"); std::vector<Path> result = tokenizeString<std::vector<string>>(configDirs, ":");
result.insert(result.begin(), configHome); result.insert(result.begin(), configHome);
return result; return result;
@ -533,10 +530,8 @@ std::vector<Path> getConfigDirs()
Path getDataDir() Path getDataDir()
{ {
Path dataDir = getEnv("XDG_DATA_HOME"); auto dataDir = getEnv("XDG_DATA_HOME");
if (dataDir.empty()) return dataDir ? *dataDir : getHome() + "/.local/share";
dataDir = getHome() + "/.local/share";
return dataDir;
} }

View file

@ -35,7 +35,7 @@ extern const std::string nativeSystem;
/* Return an environment variable. */ /* Return an environment variable. */
string getEnv(const string & key, const string & def = ""); std::optional<std::string> getEnv(const std::string & key);
/* Get the entire environment. */ /* Get the entire environment. */
std::map<std::string, std::string> getEnv(); std::map<std::string, std::string> getEnv();

View file

@ -344,9 +344,9 @@ static void _main(int argc, char * * argv)
/* Figure out what bash shell to use. If $NIX_BUILD_SHELL /* Figure out what bash shell to use. If $NIX_BUILD_SHELL
is not set, then build bashInteractive from is not set, then build bashInteractive from
<nixpkgs>. */ <nixpkgs>. */
auto shell = getEnv("NIX_BUILD_SHELL", ""); auto shell = getEnv("NIX_BUILD_SHELL");
if (shell == "") { if (!shell) {
try { try {
auto expr = state->parseExprFromString("(import <nixpkgs> {}).bashInteractive", absPath(".")); auto expr = state->parseExprFromString("(import <nixpkgs> {}).bashInteractive", absPath("."));
@ -382,7 +382,8 @@ static void _main(int argc, char * * argv)
// Set the environment. // Set the environment.
auto env = getEnv(); auto env = getEnv();
auto tmp = getEnv("TMPDIR", getEnv("XDG_RUNTIME_DIR", "/tmp")); auto tmp = getEnv("TMPDIR");
if (!tmp) tmp = getEnv("XDG_RUNTIME_DIR").value_or("/tmp");
if (pure) { if (pure) {
decltype(env) newEnv; decltype(env) newEnv;
@ -394,7 +395,7 @@ static void _main(int argc, char * * argv)
env["__ETC_PROFILE_SOURCED"] = "1"; env["__ETC_PROFILE_SOURCED"] = "1";
} }
env["NIX_BUILD_TOP"] = env["TMPDIR"] = env["TEMPDIR"] = env["TMP"] = env["TEMP"] = tmp; env["NIX_BUILD_TOP"] = env["TMPDIR"] = env["TEMPDIR"] = env["TMP"] = env["TEMP"] = *tmp;
env["NIX_STORE"] = store->storeDir; env["NIX_STORE"] = store->storeDir;
env["NIX_BUILD_CORES"] = std::to_string(settings.buildCores); env["NIX_BUILD_CORES"] = std::to_string(settings.buildCores);
@ -439,8 +440,8 @@ static void _main(int argc, char * * argv)
(Path) tmpDir, (Path) tmpDir,
(pure ? "" : "p=$PATH; "), (pure ? "" : "p=$PATH; "),
(pure ? "" : "PATH=$PATH:$p; unset p; "), (pure ? "" : "PATH=$PATH:$p; unset p; "),
dirOf(shell), dirOf(*shell),
shell, *shell,
(getenv("TZ") ? (string("export TZ='") + getenv("TZ") + "'; ") : ""), (getenv("TZ") ? (string("export TZ='") + getenv("TZ") + "'; ") : ""),
envCommand)); envCommand));
@ -460,9 +461,9 @@ static void _main(int argc, char * * argv)
restoreSignals(); restoreSignals();
execvp(shell.c_str(), argPtrs.data()); execvp(shell->c_str(), argPtrs.data());
throw SysError("executing shell '%s'", shell); throw SysError("executing shell '%s'", *shell);
} }
else { else {

View file

@ -161,8 +161,9 @@ static void daemonLoop(char * * argv)
AutoCloseFD fdSocket; AutoCloseFD fdSocket;
/* Handle socket-based activation by systemd. */ /* Handle socket-based activation by systemd. */
if (getEnv("LISTEN_FDS") != "") { auto listenFds = getEnv("LISTEN_FDS");
if (getEnv("LISTEN_PID") != std::to_string(getpid()) || getEnv("LISTEN_FDS") != "1") if (listenFds) {
if (getEnv("LISTEN_PID") != std::to_string(getpid()) || listenFds != "1")
throw Error("unexpected systemd environment variables"); throw Error("unexpected systemd environment variables");
fdSocket = SD_LISTEN_FDS_START; fdSocket = SD_LISTEN_FDS_START;
closeOnExec(fdSocket.get()); closeOnExec(fdSocket.get());

View file

@ -1425,7 +1425,7 @@ static int _main(int argc, char * * argv)
globals.instSource.autoArgs = myArgs.getAutoArgs(*globals.state); globals.instSource.autoArgs = myArgs.getAutoArgs(*globals.state);
if (globals.profile == "") if (globals.profile == "")
globals.profile = getEnv("NIX_PROFILE", ""); globals.profile = getEnv("NIX_PROFILE").value_or("");
if (globals.profile == "") { if (globals.profile == "") {
Path profileLink = getHome() + "/.nix-profile"; Path profileLink = getHome() + "/.nix-profile";

View file

@ -156,7 +156,7 @@ void StorePathCommand::run(ref<Store> store)
Strings editorFor(const Pos & pos) Strings editorFor(const Pos & pos)
{ {
auto editor = getEnv("EDITOR", "cat"); auto editor = getEnv("EDITOR").value_or("cat");
auto args = tokenizeString<Strings>(editor); auto args = tokenizeString<Strings>(editor);
if (pos.line > 0 && ( if (pos.line > 0 && (
editor.find("emacs") != std::string::npos || editor.find("emacs") != std::string::npos ||

View file

@ -68,7 +68,7 @@ struct CmdDoctor : StoreCommand
{ {
PathSet dirs; PathSet dirs;
for (auto & dir : tokenizeString<Strings>(getEnv("PATH"), ":")) for (auto & dir : tokenizeString<Strings>(getEnv("PATH").value_or(""), ":"))
if (pathExists(dir + "/nix-env")) if (pathExists(dir + "/nix-env"))
dirs.insert(dirOf(canonPath(dir + "/nix-env", true))); dirs.insert(dirOf(canonPath(dir + "/nix-env", true)));
@ -87,7 +87,7 @@ struct CmdDoctor : StoreCommand
{ {
PathSet dirs; PathSet dirs;
for (auto & dir : tokenizeString<Strings>(getEnv("PATH"), ":")) { for (auto & dir : tokenizeString<Strings>(getEnv("PATH").value_or(""), ":")) {
Path profileDir = dirOf(dir); Path profileDir = dirOf(dir);
try { try {
Path userEnv = canonPath(profileDir, true); Path userEnv = canonPath(profileDir, true);

View file

@ -128,7 +128,7 @@ struct CmdRun : InstallablesCommand
std::queue<Path> todo; std::queue<Path> todo;
for (auto & path : outPaths) todo.push(path); for (auto & path : outPaths) todo.push(path);
auto unixPath = tokenizeString<Strings>(getEnv("PATH"), ":"); auto unixPath = tokenizeString<Strings>(getEnv("PATH").value_or(""), ":");
while (!todo.empty()) { while (!todo.empty()) {
Path path = todo.front(); Path path = todo.front();

View file

@ -106,7 +106,7 @@ struct CmdUpgradeNix : MixDryRun, StoreCommand
{ {
Path where; Path where;
for (auto & dir : tokenizeString<Strings>(getEnv("PATH"), ":")) for (auto & dir : tokenizeString<Strings>(getEnv("PATH").value_or(""), ":"))
if (pathExists(dir + "/nix-env")) { if (pathExists(dir + "/nix-env")) {
where = dir; where = dir;
break; break;