Skip to content

Commit 6d8d61a

Browse files
Fix fs_get_cache_directory
Ensure it works even if both XDG_CACHE_HOME and HOME are unset. This might happen in containers. Signed-off-by: Aaron Teo <[email protected]>
1 parent 5b79489 commit 6d8d61a

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

common/common.cpp

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,11 @@
5151
#include <unistd.h>
5252
#endif
5353

54+
#if defined(__linux__)
55+
#include <sys/types.h>
56+
#include <pwd.h>
57+
#endif
58+
5459
#if defined(_MSC_VER)
5560
#pragma warning(disable: 4244 4267) // possible loss of data
5661
#endif
@@ -865,8 +870,20 @@ std::string fs_get_cache_directory() {
865870
#if defined(__linux__) || defined(__FreeBSD__) || defined(_AIX) || defined(__OpenBSD__)
866871
if (std::getenv("XDG_CACHE_HOME")) {
867872
cache_directory = std::getenv("XDG_CACHE_HOME");
868-
} else {
873+
} else if (std::getenv("HOME")) {
869874
cache_directory = std::getenv("HOME") + std::string("/.cache/");
875+
} else {
876+
#if defined(__linux__)
877+
/* no $HOME is defined, fallback to getpwuid */
878+
struct passwd *pw = getpwuid(getuid());
879+
if ((!pw) || (!pw->pw_dir)) {
880+
throw std::runtime_error("Failed to find $HOME directory");
881+
}
882+
883+
cache_directory = std::string(pw->pw_dir) + std::string("/.cache/");
884+
#else /* defined(__linux__) */
885+
throw std::runtime_error("Failed to find $HOME directory");
886+
#endif /* defined(__linux__) */
870887
}
871888
#elif defined(__APPLE__)
872889
cache_directory = std::getenv("HOME") + std::string("/Library/Caches/");

0 commit comments

Comments
 (0)