Debian Codegraph @

src/core/filecache.cpp

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-3.0-or-later
2 // Copyright 2019 Juan Palacios <[email protected]>
3
4 #include "filecache.h"
5
6 #include "common/fileutils.h"
7 #include <exception>
8 #include <format>
9 #include <spdlog/spdlog.h>
10 #include <stdexcept>
11 #include <utility>
12
13 namespace fs = std::filesystem;
14
15 FileCache::FileCache(std::filesystem::path &&path) noexcept
16 : path_(std::move(path))
17 {
18 }
19
20 void FileCache::init()
21 {
22 if (!fs::exists(path_)) {
23 fs::create_directories(path_);
24 fs::permissions(path_, fs::perms::owner_all | fs::perms::group_read |
25 fs::perms::group_exec | fs::perms::others_read |
26 fs::perms::others_exec);
27 }
28
29 if (!fs::is_directory(path_))
30 throw std::runtime_error(
31 std::format("{} is not a directory.", path_.c_str()));
32 }
33
34 std::optional<std::filesystem::path>
35 FileCache::add(std::filesystem::path const &path, std::string const &name)
36 {
37 if (cacheDirectoryExist()) {
38 if (Utils::File::isFilePathValid(path)) {
39 auto target = path_ / name;
40 if (path != target) {
41 try {
42 fs::copy_file(path, target, fs::copy_options::overwrite_existing);
43 return {target};
44 }
45 catch (std::exception const &e) {
46 SPDLOG_DEBUG(e.what());
47 }
48 }
49 else // file is on cache
50 return {target};
51 }
52 else
53 SPDLOG_DEBUG("Cannot add {} to cache. Invalid or missing file.",
54 path.c_str());
55 }
56
57 return {};
58 }
59
60 std::optional<std::filesystem::path>
61 FileCache::add(std::vector<char> const &data, std::string const &name)
62 {
63 if (cacheDirectoryExist()) {
64 auto target = path_ / name;
65 if (Utils::File::writeFile(target, data))
66 return {target};
67 }
68
69 return {};
70 }
71
72 void FileCache::remove(std::string const &name)
73 {
74 if (cacheDirectoryExist()) {
75 auto target = path_ / name;
76 try {
77 fs::remove(target);
78 }
79 catch (std::exception const &e) {
80 SPDLOG_DEBUG(e.what());
81 }
82 }
83 }
84
85 std::optional<std::filesystem::path>
86 FileCache::get(std::string const &name,
87 std::filesystem::path const &defaultPath) const
88 {
89 if (cacheDirectoryExist()) {
90 auto target = path_ / name;
91 if (Utils::File::isFilePathValid(target))
92 return {target};
93 else
94 SPDLOG_WARN("Cannot get {} from cache. Invalid or missing file.",
95 target.c_str());
96 }
97
98 if (!defaultPath.empty())
99 return {defaultPath};
100 else
101 return {};
102 }
103
104 std::filesystem::path FileCache::path() const
105 {
106 return path_;
107 }
108
109 bool FileCache::cacheDirectoryExist() const
110 {
111 if (Utils::File::isDirectoryPathValid(path_))
112 return true;
113
114 SPDLOG_DEBUG("Missing or invalid cache directory {}", path_.c_str());
115 return false;
116 }