Repository navigation
Expand file tree
/
Copy pathdatabase.cpp
More file actions
300 lines (247 loc) · 8.53 KB
/
Copy pathdatabase.cpp
File metadata and controls
300 lines (247 loc) · 8.53 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
#include "database.hpp"
#include "error.hpp"
#include <algorithm>
#include <charconv>
#include <fstream>
#include <limits>
#include <sstream>
namespace dynamic_file_binder {
namespace {
constexpr const char* kHeaderPrefix = "#DFBDB\t";
constexpr int kCurrentSchemaVersion = 1;
std::string SerializePath(const std::filesystem::path& path)
{
return path.u8string();
}
std::filesystem::path DeserializePath(const std::string& value)
{
return std::filesystem::u8path(value);
}
std::vector<std::string> Split(const std::string& line)
{
std::vector<std::string> parts;
std::string part;
std::istringstream stream(line);
while (std::getline(stream, part, '\t')) {
parts.push_back(part);
}
return parts;
}
bool StartsWith(const std::string& text, const std::string& prefix)
{
return text.rfind(prefix, 0) == 0;
}
bool ParseUnsigned(const std::string& value, std::size_t& out)
{
unsigned long long temp = 0;
const auto* begin = value.data();
const auto* end = value.data() + value.size();
const auto result = std::from_chars(begin, end, temp);
if (result.ec != std::errc() || result.ptr != end || temp > std::numeric_limits<std::size_t>::max()) {
return false;
}
out = static_cast<std::size_t>(temp);
return true;
}
bool ParseSignedTime(const std::string& value, std::time_t& out)
{
long long temp = 0;
const auto* begin = value.data();
const auto* end = value.data() + value.size();
const auto result = std::from_chars(begin, end, temp);
if (result.ec != std::errc() || result.ptr != end) {
return false;
}
out = static_cast<std::time_t>(temp);
return true;
}
void ReportDbError(const std::string& code, const std::string& message, const std::filesystem::path& path, ErrorSeverity severity)
{
ErrorManager::Instance().Report({
ErrorDomain::Database,
severity,
code,
message,
path,
});
}
} // namespace
Database::Database(const std::filesystem::path& dbPath)
: dbPath_(dbPath)
{
std::error_code errorCode;
std::filesystem::create_directories(dbPath_.parent_path(), errorCode);
}
Database::LoadResult Database::Load() const
{
LoadResult result;
std::error_code errorCode;
if (!std::filesystem::exists(dbPath_, errorCode)) {
return result;
}
std::ifstream input(dbPath_);
if (!input.is_open()) {
result.ok = false;
ReportDbError("DB_OPEN_FAILED", "Die Datenbankdatei konnte nicht geoeffnet werden.", dbPath_, ErrorSeverity::Recoverable);
return result;
}
std::string line;
bool firstDataLineHandled = false;
while (std::getline(input, line)) {
if (line.empty()) {
continue;
}
if (!firstDataLineHandled) {
firstDataLineHandled = true;
if (StartsWith(line, kHeaderPrefix)) {
const std::string versionString = line.substr(std::char_traits<char>::length(kHeaderPrefix));
int version = 0;
try {
version = std::stoi(versionString);
} catch (...) {
result.ok = false;
ReportDbError("DB_HEADER_INVALID", "Die Datenbank besitzt einen ungueltigen Versionsheader.", dbPath_, ErrorSeverity::Recoverable);
return result;
}
if (version != kCurrentSchemaVersion) {
result.ok = false;
ReportDbError(
"DB_VERSION_MISMATCH",
"Die Datenbankversion wird nicht unterstuetzt (gefunden: " + std::to_string(version) + ", erwartet: " + std::to_string(kCurrentSchemaVersion) + ").",
dbPath_,
ErrorSeverity::Fatal);
return result;
}
continue;
}
}
const std::vector<std::string> parts = Split(line);
if (parts.size() < 6) {
ReportDbError("DB_ROW_SKIPPED", "Eine unvollstaendige Datenbankzeile wurde ignoriert.", dbPath_, ErrorSeverity::Warning);
continue;
}
DbFile file;
std::size_t parsedSize = 0;
std::time_t parsedLastUsed = 0;
if (!ParseUnsigned(parts[2], parsedSize) || !ParseSignedTime(parts[3], parsedLastUsed)) {
ReportDbError("DB_ROW_PARSE_FAILED", "Eine Datenbankzeile konnte nicht geparst werden und wurde uebersprungen.", dbPath_, ErrorSeverity::Warning);
continue;
}
file.sourcePath = DeserializePath(parts[0]);
file.localPath = DeserializePath(parts[1]);
file.size = parsedSize;
file.lastUsed = parsedLastUsed;
file.type = parts[4];
file.isSymbolicLink = parts[5] == "1";
if (parts.size() >= 7) {
file.contentHash = parts[6];
}
result.files.push_back(file);
}
return result;
}
bool Database::Save(const std::vector<DbFile>& files) const
{
const auto loaded = Load();
if (!loaded.ok) {
return false;
}
const std::filesystem::path tempPath = dbPath_.string() + ".tmp";
const std::filesystem::path backupPath = dbPath_.string() + ".bak";
std::ofstream output(tempPath, std::ios::trunc);
if (!output.is_open()) {
ReportDbError("DB_SAVE_OPEN_FAILED", "Die temporaere Datenbankdatei konnte nicht erstellt werden.", tempPath, ErrorSeverity::Recoverable);
return false;
}
output << kHeaderPrefix << kCurrentSchemaVersion << '\n';
for (const DbFile& file : files) {
output << SerializePath(file.sourcePath) << '\t'
<< SerializePath(file.localPath) << '\t'
<< file.size << '\t'
<< file.lastUsed << '\t'
<< file.type << '\t'
<< (file.isSymbolicLink ? 1 : 0) << '\t'
<< file.contentHash << '\n';
}
output.flush();
output.close();
std::error_code errorCode;
std::filesystem::remove(backupPath, errorCode);
if (std::filesystem::exists(dbPath_, errorCode)) {
std::filesystem::rename(dbPath_, backupPath, errorCode);
if (errorCode) {
ReportDbError("DB_BACKUP_FAILED", "Die vorhandene Datenbank konnte nicht gesichert werden.", dbPath_, ErrorSeverity::Recoverable);
std::filesystem::remove(tempPath, errorCode);
return false;
}
}
std::filesystem::rename(tempPath, dbPath_, errorCode);
if (errorCode) {
ReportDbError("DB_COMMIT_FAILED", "Die neue Datenbankdatei konnte nicht aktiviert werden.", dbPath_, ErrorSeverity::Recoverable);
if (std::filesystem::exists(backupPath, errorCode)) {
std::error_code restoreError;
std::filesystem::rename(backupPath, dbPath_, restoreError);
if (restoreError) {
ReportDbError("DB_RESTORE_FAILED", "Die gesicherte Datenbank konnte nach Fehler nicht wiederhergestellt werden.", dbPath_, ErrorSeverity::Fatal);
}
}
std::filesystem::remove(tempPath, errorCode);
return false;
}
std::filesystem::remove(backupPath, errorCode);
return true;
}
bool Database::UpsertFile(const DbFile& file)
{
LoadResult loaded = Load();
if (!loaded.ok) {
return false;
}
std::vector<DbFile>& files = loaded.files;
bool updated = false;
for (DbFile& existing : files) {
if (existing.localPath == file.localPath) {
existing = file;
updated = true;
break;
}
}
if (!updated) {
files.push_back(file);
}
return Save(files);
}
bool Database::RemoveFile(const std::filesystem::path& localPath)
{
LoadResult loaded = Load();
if (!loaded.ok) {
return false;
}
std::vector<DbFile>& files = loaded.files;
const auto newEnd = std::remove_if(files.begin(), files.end(), [&](const DbFile& file) {
return file.localPath == localPath;
});
files.erase(newEnd, files.end());
return Save(files);
}
std::vector<DbFile> Database::GetFilesOlderThan(int days) const
{
const LoadResult loaded = Load();
if (!loaded.ok) {
return {};
}
const std::vector<DbFile>& files = loaded.files;
std::vector<DbFile> result;
const std::time_t cutoff = std::time(nullptr) - static_cast<std::time_t>(days) * 24 * 60 * 60;
for (const DbFile& file : files) {
if (file.lastUsed <= cutoff) {
result.push_back(file);
}
}
return result;
}
std::vector<DbFile> Database::GetAllFiles() const
{
return Load().files;
}
} // namespace dynamic_file_binder