Skip to content

Commit

Permalink
Windows: Fixed environment variables not read as unicode.
Browse files Browse the repository at this point in the history
  • Loading branch information
Klaim committed Mar 28, 2023
1 parent 6ed35f8 commit 7588673
Showing 1 changed file with 8 additions and 28 deletions.
36 changes: 8 additions & 28 deletions libmamba/src/core/environment.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

#ifdef _WIN32
#include "mamba/core/output.hpp"
#include "mamba/core/util_os.hpp"
#endif

namespace mamba
Expand All @@ -18,43 +19,19 @@ namespace mamba
std::optional<std::string> get(const std::string& key)
{
#ifdef _WIN32
const size_t initial_size = 1024;
std::unique_ptr<char[]> temp_small = std::make_unique<char[]>(initial_size);
std::size_t size = GetEnvironmentVariableA(key.c_str(), temp_small.get(), initial_size);
if (size == 0) // Error or empty/missing
const std::wstring unicode_key(key.begin(), key.end());
if (const auto value = _wgetenv(unicode_key.c_str()))
{
// Note that on Windows environment variables can never be empty,
// only missing. See https://stackoverflow.com/a/39095782
auto last_err = GetLastError();
if (last_err != ERROR_ENVVAR_NOT_FOUND)
{
LOG_ERROR << "Could not get environment variable: " << last_err;
}
return {};
}
else if (size > initial_size) // Buffer too small
{
std::unique_ptr<char[]> temp_large = std::make_unique<char[]>(size);
GetEnvironmentVariableA(key.c_str(), temp_large.get(), size);
std::string res(temp_large.get());
return res;
}
else // Success
{
std::string res(temp_small.get());
return res;
return mamba::to_utf8(value);
}
#else
const char* value = std::getenv(key.c_str());
if (value)
{
return value;
}
else
{
return {};
}
#endif
return {};
}

bool set(const std::string& key, const std::string& value)
Expand Down Expand Up @@ -208,6 +185,7 @@ namespace mamba

fs::u8path home_directory()
{
LOG_ERROR << "Looking for HOME...";
#ifdef _WIN32
std::string maybe_home = env::get("USERPROFILE").value_or("");
if (maybe_home.empty())
Expand All @@ -219,10 +197,12 @@ namespace mamba
}
if (maybe_home.empty())
{
LOG_ERROR << "WOW WE FAILED TO DETERMINE THE HOME!";
throw std::runtime_error(
"Cannot determine HOME (checked USERPROFILE, HOMEDRIVE and HOMEPATH env vars)"
);
}
LOG_ERROR << "Home found: " << maybe_home;
#else
std::string maybe_home = env::get("HOME").value_or("");
if (maybe_home.empty())
Expand Down

0 comments on commit 7588673

Please sign in to comment.