Mingw: Use _wgetenv to get user's home directory

Fixes GH-342
pull/353/head
Tatsuhiro Tsujikawa 2015-02-21 01:47:36 +09:00
parent ba0e32abae
commit 649c49dcc6
2 changed files with 39 additions and 17 deletions

View File

@ -146,6 +146,13 @@ std::string wCharToUtf8(const std::wstring& wsrc)
} }
} }
std::string toForwardSlash(const std::string &src) {
auto dst = src;
std::transform(std::begin(dst), std::end(dst), std::begin(dst),
[](char c) { return c == '\\' ? '/' : c; });
return dst;
}
#endif // __MINGW32__ #endif // __MINGW32__
namespace util { namespace util {
@ -1288,35 +1295,47 @@ void setGlobalSignalHandler(int sig, sigset_t* mask, signal_handler_t handler,
#endif // HAVE_SIGACTION #endif // HAVE_SIGACTION
} }
#ifndef __MINGW32__
std::string getHomeDir() std::string getHomeDir()
{ {
const char* p = getenv("HOME"); const char* p = getenv("HOME");
if (p) { if (p) {
return p; return p;
} }
#ifdef __MINGW32__ #ifdef HAVE_PWD_H
p = getenv("USERPROFILE"); auto pw = getpwuid(geteuid());
if (p) { if (pw && pw->pw_dir) {
return p;
}
p = getenv("HOMEDRIVE");
if (p) {
std::string homeDir = p;
p = getenv("HOMEPATH");
if (p) {
homeDir += p;
return homeDir;
}
}
#elif HAVE_PWD_H
passwd* pw = getpwuid(geteuid());
if(pw && pw->pw_dir) {
return pw->pw_dir; return pw->pw_dir;
} }
#endif // HAVE_PWD_H #endif // HAVE_PWD_H
return A2STR::NIL; return A2STR::NIL;
} }
#else // __MINGW32__
std::string getHomeDir()
{
auto p = _wgetenv(L"HOME");
if (p) {
return toForwardSlash(wCharToUtf8(p));
}
p = _wgetenv(L"USERPROFILE");
if (p) {
return toForwardSlash(wCharToUtf8(p));
}
p = _wgetenv(L"HOMEDRIVE");
if (p) {
std::wstring homeDir = p;
p = _wgetenv(L"HOMEPATH");
if (p) {
homeDir += p;
return toForwardSlash(wCharToUtf8(homeDir));
}
}
return A2STR::NIL;
}
#endif // __MINGW32__
int64_t getRealSize(const std::string& sizeWithUnit) int64_t getRealSize(const std::string& sizeWithUnit)
{ {
std::string::size_type p = sizeWithUnit.find_first_of("KMkm"); std::string::size_type p = sizeWithUnit.find_first_of("KMkm");

View File

@ -108,6 +108,9 @@ std::wstring utf8ToWChar(const std::string& src);
std::wstring utf8ToWChar(const char* str); std::wstring utf8ToWChar(const char* str);
std::string wCharToUtf8(const std::wstring& wsrc); std::string wCharToUtf8(const std::wstring& wsrc);
// replace any backslash '\' in |src| with '/' and returns it.
std::string toForwardSlash(const std::string &src);
#else // !__MINGW32__ #else // !__MINGW32__
# define utf8ToWChar(src) src # define utf8ToWChar(src) src
# define utf8ToNative(src) src # define utf8ToNative(src) src