From 481f9ba1aee62fea092184f2243d210a8686781f Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Thu, 14 Jun 2018 18:13:04 +0200 Subject: Add portable environment variable manipulation functions --- libbutl/path.cxx | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) (limited to 'libbutl/path.cxx') diff --git a/libbutl/path.cxx b/libbutl/path.cxx index 11a34c9..47d691b 100644 --- a/libbutl/path.cxx +++ b/libbutl/path.cxx @@ -17,7 +17,7 @@ #else # include // struct passwd, getpwuid_r() # include // EINVAL -# include // realpath(), getenv() +# include // realpath() # include // PATH_MAX # include // getcwd(), chdir() # include // strlen(), strcpy() @@ -29,6 +29,7 @@ #ifndef __cpp_lib_modules #include +#include #include #include @@ -123,33 +124,39 @@ namespace butl } #ifndef _WIN32 - static const char* + static const vector tmp_vars ({"TMPDIR", "TMP", "TEMP", "TEMPDIR"}); + + static string temp_directory () { - const char* dir (nullptr); - const char* env[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR", nullptr}; + optional dir; - for (auto e (env); dir == nullptr && *e != nullptr; ++e) - dir = getenv (*e); + for (const string& v: tmp_vars) + { + dir = getenv (v); + + if (dir) + break; + } - if (dir == nullptr) + if (!dir) dir = "/tmp"; struct stat s; - if (stat (dir, &s) != 0) + if (stat (dir->c_str (), &s) != 0) throw_generic_error (errno); if (!S_ISDIR (s.st_mode)) throw_generic_error (ENOTDIR); - return dir; + return *dir; } static string home () { - if (const char* h = getenv ("HOME")) - return h; + if (optional h = getenv ("HOME")) + return *h; // Struct passwd has 5 members that will use this buffer. Two are the // home directory and shell paths. The other three are the user login @@ -214,8 +221,8 @@ namespace butl #else // Could be set by, e.g., MSYS and Cygwin shells. // - if (const char* h = getenv ("HOME")) - return h; + if (optional h = getenv ("HOME")) + return *h; char h[_MAX_PATH]; HRESULT r (SHGetFolderPathA (NULL, CSIDL_PROFILE, NULL, 0, h)); -- cgit v1.1