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  if (auto xdgCacheDir = Env::get<std::filesystem::path>("XDG_CACHE_HOME"))
45  return std::move(*xdgCacheDir);
46 
47  const auto homeDir = get();
48  if (homeDir.empty())
49  return {};
50 
51  return homeDir / ".cache";
52  }
53 
59  static std::filesystem::path createCacheDir(const std::filesystem::path &subdir) noexcept {
60  auto cache = getCacheDir();
61  if (cache.empty())
62  return {};
63  cache /= subdir;
64 
65  std::error_code ec;
66  std::filesystem::create_directories(cache, ec);
67  if (ec)
68  return {};
69 
70  return cache;
71  }
72 };
73 
74 }
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:59
static std::filesystem::path getCacheDir() noexcept
Obtains directory for caching.
Definition: HomeDir.h:43
Definition: Color.h:8