SlHelpers
HomeDir.h
1 // SPDX-License-Identifier: GPL-2.0-only
2 
3 #pragma once
4 
5 #include <filesystem>
6 #include <pwd.h>
7 #include <sys/types.h>
8 #include <unistd.h>
9 
10 #include "Misc.h"
11 
12 namespace SlHelpers {
13 
17 class HomeDir {
18 public:
19  HomeDir() = delete;
20 
25  static std::filesystem::path get() noexcept {
26  if (auto homeDir = Env::get<std::filesystem::path>("HOME"))
27  if (std::filesystem::exists(*homeDir))
28  return std::move(*homeDir);
29 
30  if (const auto pw = ::getpwuid(::getuid())) {
31  std::filesystem::path dir = pw->pw_dir;
32  if (std::filesystem::exists(dir))
33  return dir;
34  }
35 
36  return {};
37  }
38 
43  static std::filesystem::path getCacheDir() noexcept {
44  // XDG spec: empty or relative values are to be ignored
45  if (auto xdgCacheDir = Env::get<std::filesystem::path>("XDG_CACHE_HOME"))
46  if (xdgCacheDir->is_absolute())
47  return std::move(*xdgCacheDir);
48 
49  const auto homeDir = get();
50  if (homeDir.empty())
51  return {};
52 
53  return homeDir / ".cache";
54  }
55 
61  static std::filesystem::path createCacheDir(const std::filesystem::path &subdir) noexcept {
62  auto cache = getCacheDir();
63  if (cache.empty())
64  return {};
65  cache /= subdir;
66 
67  std::error_code ec;
68  std::filesystem::create_directories(cache, ec);
69  if (ec)
70  return {};
71 
72  return cache;
73  }
74 };
75 
76 }
Helpers for $HOME directory.
Definition: HomeDir.h:17
static std::filesystem::path createCacheDir(const std::filesystem::path &subdir) noexcept
Creates (if not existing) and returns getCacheDir() / subdir.
Definition: HomeDir.h:61
static std::filesystem::path getCacheDir() noexcept
Obtains directory for caching.
Definition: HomeDir.h:43
Definition: Color.h:8