aboutsummaryrefslogtreecommitdiff
path: root/src/xdg.cpp
blob: 929315123a62e04907197fed881100c3f014fe8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "xdg.hpp"

#include <unistd.h>

namespace wanda
{

std::string xdg_variable(xdg_directory directory)
{
    switch (directory)
    {
    case xdg_directory::data_home:
        return "XDG_DATA_HOME";
    case xdg_directory::config_home:
        return "XDG_CONFIG_HOME";
    case xdg_directory::cache_home:
        return "XDG_CACHE_HOME";
    case xdg_directory::runtime_dir:
        return "XDG_RUNTIME_DIR";
    }
    return "XDG_INVALID_PATH";
}

std::filesystem::path xdg_path_for(xdg_directory directory, environment const &environment)
{
    if (auto path = environment[xdg_variable(directory)]; !path.empty())
    {
        return path;
    }

    auto home = std::filesystem::path{environment["HOME"]};
    switch (directory)
    {
    case xdg_directory::data_home:
        return home / ".local/share";
    case xdg_directory::config_home:
        return home / ".config";
    case xdg_directory::cache_home:
        return home / ".cache";
    case xdg_directory::runtime_dir:
        return std::filesystem::path{"/run/user"} / std::to_string(::getuid());
    }

    return "";
}

} // namespace wanda