refactor(tvix): getEnv(): Return std::optional

This allows distinguishing between an empty value and no value.

Patch ported from upstream at
ba87b08f85

Change-Id: I061cc8e16b1a7a0341adfc3b0edca1c0c51d5c97
Reviewed-on: https://cl.tvl.fyi/c/depot/+/1884
Tested-by: BuildkiteCI
Reviewed-by: kanepyork <rikingcoding@gmail.com>
This commit is contained in:
Eelco Dolstra 2019-11-22 16:06:44 +01:00 committed by glittershark
parent c5f3b12f04
commit 785cb3a754
17 changed files with 66 additions and 66 deletions

View file

@ -287,11 +287,11 @@ EvalState::EvalState(const Strings& _searchPath, const ref<Store>& store)
staticBaseEnv(false, nullptr) { staticBaseEnv(false, nullptr) {
expr::InitGC(); expr::InitGC();
countCalls = getEnv("NIX_COUNT_CALLS", "0") != "0"; countCalls = getEnv("NIX_COUNT_CALLS").value_or("0") != "0";
/* 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) { for (auto& i : _searchPath) {
addToSearchPath(i); addToSearchPath(i);
} }
@ -1644,7 +1644,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);
@ -1658,7 +1658,7 @@ void EvalState::printStats() {
nrAttrsets * sizeof(Bindings) + nrAttrsInAttrsets * sizeof(Attr); nrAttrsets * sizeof(Bindings) + nrAttrsInAttrsets * sizeof(Attr);
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);

View file

@ -413,7 +413,7 @@ static void prim_getEnv(EvalState& state, const Pos& pos, Value** args,
std::string name = state.forceStringNoCtx(*args[0], pos); std::string name = state.forceStringNoCtx(*args[0], pos);
mkString(v, evalSettings.restrictEval || evalSettings.pureEval mkString(v, evalSettings.restrictEval || evalSettings.pureEval
? "" ? ""
: getEnv(name)); : getEnv(name).value_or(""));
} }
/* Evaluate the first argument, then return the second argument. */ /* Evaluate the first argument, then return the second argument. */

View file

@ -2582,7 +2582,7 @@ void DerivationGoal::initEnv() {
if (fixedOutput) { if (fixedOutput) {
for (auto& i : for (auto& i :
parsedDrv->getStringsAttr("impureEnvVars").value_or(Strings())) { parsedDrv->getStringsAttr("impureEnvVars").value_or(Strings())) {
env[i] = getEnv(i); env[i] = getEnv(i).value_or("");
} }
} }

View file

@ -906,7 +906,8 @@ 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").value_or("");
auto getAvail = [this]() -> uint64_t { auto getAvail = [this]() -> uint64_t {
if (!fakeFreeSpaceFile.empty()) { if (!fakeFreeSpaceFile.empty()) {

View file

@ -31,19 +31,22 @@ static GlobalConfig::Register r1(&settings);
Settings::Settings() Settings::Settings()
: nixPrefix(NIX_PREFIX), : nixPrefix(NIX_PREFIX),
nixStore(canonPath( nixStore(canonPath(
getEnv("NIX_STORE_DIR", getEnv("NIX_STORE", NIX_STORE_DIR)))), getEnv("NIX_STORE_DIR")
nixDataDir(canonPath(getEnv("NIX_DATA_DIR", NIX_DATA_DIR))), .value_or(getEnv("NIX_STORE").value_or(NIX_STORE_DIR)))),
nixLogDir(canonPath(getEnv("NIX_LOG_DIR", NIX_LOG_DIR))), nixDataDir(canonPath(getEnv("NIX_DATA_DIR").value_or(NIX_DATA_DIR))),
nixStateDir(canonPath(getEnv("NIX_STATE_DIR", NIX_STATE_DIR))), nixLogDir(canonPath(getEnv("NIX_LOG_DIR").value_or(NIX_LOG_DIR))),
nixConfDir(canonPath(getEnv("NIX_CONF_DIR", NIX_CONF_DIR))), nixStateDir(canonPath(getEnv("NIX_STATE_DIR").value_or(NIX_STATE_DIR))),
nixLibexecDir(canonPath(getEnv("NIX_LIBEXEC_DIR", NIX_LIBEXEC_DIR))), nixConfDir(canonPath(getEnv("NIX_CONF_DIR").value_or(NIX_CONF_DIR))),
nixBinDir(canonPath(getEnv("NIX_BIN_DIR", NIX_BIN_DIR))), nixLibexecDir(
canonPath(getEnv("NIX_LIBEXEC_DIR").value_or(NIX_LIBEXEC_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").value_or("1") == "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.empty()) { if (caFile.empty()) {
for (auto& fn : for (auto& fn :
{"/etc/ssl/certs/ca-certificates.crt", {"/etc/ssl/certs/ca-certificates.crt",
@ -58,9 +61,9 @@ Settings::Settings()
/* Backwards compatibility. */ /* Backwards compatibility. */
// TODO(tazjin): still? // TODO(tazjin): still?
auto s = getEnv("NIX_REMOTE_SYSTEMS"); auto s = getEnv("NIX_REMOTE_SYSTEMS");
if (!s.empty()) { if (s) {
Strings ss; Strings ss;
for (auto p : absl::StrSplit(s, absl::ByChar(':'), absl::SkipEmpty())) { for (auto p : absl::StrSplit(*s, absl::ByChar(':'), absl::SkipEmpty())) {
ss.push_back(absl::StrCat("@", p)); ss.push_back(absl::StrCat("@", p));
} }
builders = concatStringsSep(" ", ss); builders = concatStringsSep(" ", ss);

View file

@ -61,8 +61,8 @@ class Settings : public Config {
/* 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"),
"The default Nix store to use."}; "store", "The default Nix store to use."};
Setting<bool> keepFailed{ Setting<bool> keepFailed{
this, false, "keep-failed", this, false, "keep-failed",

View file

@ -98,8 +98,9 @@ class LocalStore : public LocalFSStore {
public: public:
// Hack for build-remote.cc. // Hack for build-remote.cc.
// TODO(tazjin): remove this when we've got gRPC // TODO(tazjin): remove this when we've got gRPC
PathSet locksHeld = absl::StrSplit( PathSet locksHeld =
getEnv("NIX_HELD_LOCKS"), absl::ByAnyChar(" \t\n\r"), absl::SkipEmpty()); absl::StrSplit(getEnv("NIX_HELD_LOCKS").value_or(""),
absl::ByAnyChar(" \t\n\r"), absl::SkipEmpty());
/* Initialise the local store, upgrading the schema if /* Initialise the local store, upgrading the schema if
necessary. */ necessary. */

View file

@ -22,8 +22,8 @@ SSHMaster::SSHMaster(const std::string& host, std::string keyFile,
void SSHMaster::addCommonSSHOpts(Strings& args) { void SSHMaster::addCommonSSHOpts(Strings& args) {
for (auto& i : for (auto& i :
absl::StrSplit(getEnv("NIX_SSHOPTS"), absl::ByAnyChar(" \t\n\r"), absl::StrSplit(getEnv("NIX_SSHOPTS").value_or(""),
absl::SkipEmpty())) { absl::ByAnyChar(" \t\n\r"), absl::SkipEmpty())) {
args.push_back(std::string(i)); args.push_back(std::string(i));
} }
if (!keyFile.empty()) { if (!keyFile.empty()) {

View file

@ -45,9 +45,10 @@ std::string SysError::addErrno(const std::string& s) {
return s + ": " + strerror(errNo); return s + ": " + strerror(errNo);
} }
std::string getEnv(const std::string& key, const std::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 != nullptr ? std::string(value) : def; if (value == nullptr) return {};
return std::string(value);
} }
std::map<std::string, std::string> getEnv() { std::map<std::string, std::string> getEnv() {
@ -466,8 +467,9 @@ 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 = tmpRoot = canonPath(
canonPath(tmpRoot.empty() ? getEnv("TMPDIR", "/tmp") : tmpRoot, true); tmpRoot.empty() ? getEnv("TMPDIR").value_or("/tmp") : tmpRoot, true);
if (includePid) { if (includePid) {
return (format("%1%/%2%-%3%-%4%") % tmpRoot % prefix % getpid() % counter++) return (format("%1%/%2%-%3%-%4%") % tmpRoot % prefix % getpid() % counter++)
.str(); .str();
@ -507,16 +509,17 @@ Path createTempDir(const Path& tmpRoot, const Path& prefix, bool includePid,
std::string getUserName() { std::string getUserName() {
auto pw = getpwuid(geteuid()); auto pw = getpwuid(geteuid());
std::string name = pw != nullptr ? pw->pw_name : getEnv("USER", ""); std::optional<std::string> name =
if (name.empty()) { pw != nullptr ? pw->pw_name : getEnv("USER");
if (!name.has_value()) {
throw Error("cannot figure out user name"); throw Error("cannot figure out user name");
} }
return name; return *name;
} }
static Lazy<Path> getHome2([]() { static Lazy<Path> getHome2([]() {
Path homeDir = getEnv("HOME"); std::optional<Path> 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;
@ -524,32 +527,24 @@ static Lazy<Path> getHome2([]() {
(pw == nullptr) || (pw->pw_dir == nullptr) || (pw->pw_dir[0] == 0)) { (pw == nullptr) || (pw->pw_dir == nullptr) || (pw->pw_dir[0] == 0)) {
throw Error("cannot determine user's home directory"); throw Error("cannot determine user's home directory");
} }
homeDir = pw->pw_dir; return std::string(pw->pw_dir);
} }
return homeDir; return homeDir.value();
}); });
Path getHome() { return getHome2(); } Path getHome() { return getHome2(); }
Path getCacheDir() { Path getCacheDir() {
Path cacheDir = getEnv("XDG_CACHE_HOME"); return getEnv("XDG_CACHE_HOME").value_or(getHome() + "/.cache");
if (cacheDir.empty()) {
cacheDir = getHome() + "/.cache";
}
return cacheDir;
} }
Path getConfigDir() { Path getConfigDir() {
Path configDir = getEnv("XDG_CONFIG_HOME"); return getEnv("XDG_CONFIG_HOME").value_or(getHome() + "/.config");
if (configDir.empty()) {
configDir = getHome() + "/.config";
}
return configDir;
} }
std::vector<Path> getConfigDirs() { std::vector<Path> getConfigDirs() {
Path configHome = getConfigDir(); Path configHome = getConfigDir();
std::string configDirs = getEnv("XDG_CONFIG_DIRS"); std::string configDirs = getEnv("XDG_CONFIG_DIRS").value_or("");
std::vector<std::string> result = std::vector<std::string> result =
absl::StrSplit(configDirs, absl::ByChar(':'), absl::SkipEmpty()); absl::StrSplit(configDirs, absl::ByChar(':'), absl::SkipEmpty());
result.insert(result.begin(), configHome); result.insert(result.begin(), configHome);
@ -557,11 +552,7 @@ std::vector<Path> getConfigDirs() {
} }
Path getDataDir() { Path getDataDir() {
Path dataDir = getEnv("XDG_DATA_HOME"); return getEnv("XDG_DATA_HOME").value_or(getHome() + "/.local/share");
if (dataDir.empty()) {
dataDir = getHome() + "/.local/share";
}
return dataDir;
} }
// TODO(grfn): Remove in favor of std::filesystem::create_directories // TODO(grfn): Remove in favor of std::filesystem::create_directories

View file

@ -26,7 +26,7 @@ struct Source;
extern const std::string nativeSystem; extern const std::string nativeSystem;
/* Return an environment variable. */ /* Return an environment variable. */
std::string getEnv(const std::string& key, const std::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

@ -377,9 +377,12 @@ 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 opt_shell = getEnv("NIX_BUILD_SHELL");
std::string shell;
if (shell.empty()) { if (opt_shell.has_value()) {
shell = opt_shell.value();
} else {
try { try {
auto expr = state->parseExprFromString( auto expr = state->parseExprFromString(
"(import <nixpkgs> {}).bashInteractive", absPath(".")); "(import <nixpkgs> {}).bashInteractive", absPath("."));
@ -427,7 +430,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").value_or(getEnv("XDG_RUNTIME_DIR").value_or("/tmp"));
if (pure) { if (pure) {
decltype(env) newEnv; decltype(env) newEnv;

View file

@ -1516,7 +1516,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.empty()) { if (globals.profile.empty()) {
globals.profile = getEnv("NIX_PROFILE", ""); globals.profile = getEnv("NIX_PROFILE").value_or("");
} }
if (globals.profile.empty()) { if (globals.profile.empty()) {

View file

@ -59,7 +59,7 @@ static int _main(int argc, char** argv) {
{ {
HashType ht = htSHA256; HashType ht = htSHA256;
std::vector<std::string> args; std::vector<std::string> args;
bool printPath = !getEnv("PRINT_PATH").empty(); bool printPath = getEnv("PRINT_PATH").has_value();
bool fromExpr = false; bool fromExpr = false;
std::string attrPath; std::string attrPath;
bool unpack = false; bool unpack = false;

View file

@ -48,8 +48,8 @@ struct CmdDoctor final : StoreCommand {
static bool checkNixInPath() { static bool checkNixInPath() {
PathSet dirs; PathSet dirs;
for (auto& dir : for (auto& dir : absl::StrSplit(getEnv("PATH").value_or(""),
absl::StrSplit(getEnv("PATH"), absl::ByChar(':'), absl::SkipEmpty())) { absl::ByChar(':'), absl::SkipEmpty())) {
if (pathExists(absl::StrCat(dir, "/nix-env"))) { if (pathExists(absl::StrCat(dir, "/nix-env"))) {
dirs.insert(dirOf(canonPath(absl::StrCat(dir, "/nix-env"), true))); dirs.insert(dirOf(canonPath(absl::StrCat(dir, "/nix-env"), true)));
} }
@ -72,8 +72,8 @@ struct CmdDoctor final : StoreCommand {
static bool checkProfileRoots(const ref<Store>& store) { static bool checkProfileRoots(const ref<Store>& store) {
PathSet dirs; PathSet dirs;
for (auto dir : for (auto dir : absl::StrSplit(getEnv("PATH").value_or(""),
absl::StrSplit(getEnv("PATH"), absl::ByChar(':'), absl::SkipEmpty())) { absl::ByChar(':'), absl::SkipEmpty())) {
Path profileDir = dirOf(dir); Path profileDir = dirOf(dir);
try { try {
Path userEnv = canonPath(profileDir, true); Path userEnv = canonPath(profileDir, true);

View file

@ -53,7 +53,7 @@ struct CmdEdit final : InstallableCommand {
throw Error("cannot parse line number '%s'", pos); throw Error("cannot parse line number '%s'", pos);
} }
auto editor = getEnv("EDITOR", "cat"); auto editor = getEnv("EDITOR").value_or("cat");
Strings args = Strings args =
absl::StrSplit(editor, absl::ByAnyChar(" \t\n\r"), absl::SkipEmpty()); absl::StrSplit(editor, absl::ByAnyChar(" \t\n\r"), absl::SkipEmpty());

View file

@ -123,8 +123,8 @@ struct CmdRun final : InstallablesCommand {
todo.push(path); todo.push(path);
} }
Strings unixPath = Strings unixPath = absl::StrSplit(getEnv("PATH").value_or(""),
absl::StrSplit(getEnv("PATH"), absl::ByChar(':'), absl::SkipEmpty()); absl::ByChar(':'), absl::SkipEmpty());
while (!todo.empty()) { while (!todo.empty()) {
Path path = todo.front(); Path path = todo.front();

View file

@ -103,8 +103,8 @@ struct CmdUpgradeNix final : MixDryRun, StoreCommand {
static Path getProfileDir(const ref<Store>& store) { static Path getProfileDir(const ref<Store>& store) {
Path where; Path where;
for (auto& dir : for (auto& dir : absl::StrSplit(getEnv("PATH").value_or(""),
absl::StrSplit(getEnv("PATH"), absl::ByChar(':'), absl::SkipEmpty())) { absl::ByChar(':'), absl::SkipEmpty())) {
if (pathExists(absl::StrCat(dir, "/nix-env"))) { if (pathExists(absl::StrCat(dir, "/nix-env"))) {
where = dir; where = dir;
break; break;