-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfilebackend.cpp
More file actions
363 lines (322 loc) · 10.4 KB
/
Copy pathfilebackend.cpp
File metadata and controls
363 lines (322 loc) · 10.4 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
#include "filebackend.h"
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <system_error>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <io.h>
#else
#include <unistd.h>
#endif
std::mutex FileBackends::mutex_;
std::shared_ptr<FileBackend> FileBackends::current_ = std::make_shared<LocalFileBackend>();
namespace {
std::int64_t unixSeconds(std::filesystem::file_time_type value) {
const auto system_time = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
value - std::filesystem::file_time_type::clock::now() + std::chrono::system_clock::now());
return std::chrono::duration_cast<std::chrono::seconds>(system_time.time_since_epoch()).count();
}
std::string errorMessage(const std::error_code& ec) {
return ec ? ec.message() : std::string{};
}
#ifdef _WIN32
std::wstring widenUtf8(const std::string& input) {
if (input.empty()) return {};
const int length = MultiByteToWideChar(CP_UTF8, 0, input.data(), static_cast<int>(input.size()), nullptr, 0);
if (length <= 0) return {};
std::wstring result(static_cast<std::size_t>(length), L'\0');
MultiByteToWideChar(CP_UTF8, 0, input.data(), static_cast<int>(input.size()), result.data(), length);
return result;
}
#endif
bool atomicWriteLocal(const std::filesystem::path& target, const std::vector<std::uint8_t>& bytes, std::string& error) {
std::error_code ec;
if (!target.parent_path().empty()) {
std::filesystem::create_directories(target.parent_path(), ec);
if (ec) {
error = "could not create parent directory: " + ec.message();
return false;
}
}
#ifdef _WIN32
const auto pid = static_cast<unsigned long>(GetCurrentProcessId());
#else
const auto pid = static_cast<unsigned long>(::getpid());
#endif
const auto temp = target.parent_path() / (target.filename().string() + ".cwtmp-" + std::to_string(pid));
std::FILE* file = std::fopen(temp.string().c_str(), "wb");
if (!file) {
error = "could not open temporary file";
return false;
}
if (!bytes.empty() && std::fwrite(bytes.data(), 1, bytes.size(), file) != bytes.size()) {
error = "could not write temporary file";
std::fclose(file);
std::filesystem::remove(temp, ec);
return false;
}
std::fflush(file);
#ifdef _WIN32
_commit(_fileno(file));
#else
fsync(fileno(file));
#endif
std::fclose(file);
#ifdef _WIN32
const auto source = widenUtf8(temp.string());
const auto destination = widenUtf8(target.string());
if (!ReplaceFileW(destination.c_str(), source.c_str(), nullptr, REPLACEFILE_WRITE_THROUGH, nullptr, nullptr) &&
!MoveFileExW(source.c_str(), destination.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
error = "could not replace destination file";
std::filesystem::remove(temp, ec);
return false;
}
#else
std::filesystem::rename(temp, target, ec);
if (ec) {
error = "could not replace destination file: " + ec.message();
std::filesystem::remove(temp, ec);
return false;
}
#endif
return true;
}
} // namespace
bool FileBackend::exists(const std::string& path, bool& result, std::string& error) {
BackendFileStat info;
if (!stat(path, info, error)) return false;
result = info.exists;
return true;
}
bool FileBackend::isBinary(const std::string& path, bool& result, std::string& error) {
std::vector<std::uint8_t> bytes;
if (!readFile(path, bytes, error)) return false;
const auto count = std::min<std::size_t>(bytes.size(), 4096);
if (count == 0) {
result = false;
return true;
}
std::size_t controls = 0;
for (std::size_t i = 0; i < count; ++i) {
const auto c = bytes[i];
if (c == 0) {
result = true;
return true;
}
if (c < 9 || (c > 13 && c < 32)) {
++controls;
if (controls > count / 100) {
result = true;
return true;
}
}
}
result = false;
return true;
}
bool FileBackend::modificationTime(const std::string& path, std::int64_t& result, std::string& error) {
BackendFileStat info;
if (!stat(path, info, error) || !info.exists) {
if (error.empty()) error = "file does not exist";
return false;
}
result = info.mtime;
return true;
}
bool FileBackend::fileSize(const std::string& path, std::uintmax_t& result, std::string& error) {
BackendFileStat info;
if (!stat(path, info, error) || !info.exists) {
if (error.empty()) error = "file does not exist";
return false;
}
result = info.size;
return true;
}
std::string FileBackend::join(const std::string& parent, const std::string& child) const {
if (parent.empty()) return child;
if (child.empty()) return parent;
const char separator = pathSeparator();
if (parent.back() == '/' || parent.back() == '\\') return parent + child;
return parent + separator + child;
}
std::string FileBackend::filename(const std::string& path) const {
const auto position = path.find_last_of("/\\");
return position == std::string::npos ? path : path.substr(position + 1);
}
char LocalFileBackend::pathSeparator() const {
return std::filesystem::path::preferred_separator;
}
std::string LocalFileBackend::homeDirectory() const {
#ifdef _WIN32
const char* home = std::getenv("USERPROFILE");
#else
const char* home = std::getenv("HOME");
#endif
return home ? home : std::string{};
}
bool LocalFileBackend::readFile(const std::string& path, std::vector<std::uint8_t>& bytes, std::string& error) {
std::ifstream file(path, std::ios::binary | std::ios::ate);
if (!file) {
error = "could not open file";
return false;
}
const auto size = file.tellg();
if (size < 0) {
error = "could not determine file size";
return false;
}
bytes.resize(static_cast<std::size_t>(size));
file.seekg(0, std::ios::beg);
if (!bytes.empty() && !file.read(reinterpret_cast<char*>(bytes.data()), size)) {
error = "could not read file";
bytes.clear();
return false;
}
return true;
}
bool LocalFileBackend::readFilePartial(const std::string& path,
std::vector<std::uint8_t>& bytes,
std::size_t maxBytes,
std::string& error)
{
std::ifstream file(path, std::ios::binary);
if (!file) {
error = "could not open file";
return false;
}
bytes.resize(maxBytes);
file.read(reinterpret_cast<char*>(bytes.data()), maxBytes);
// gcount() gets the actual number of bytes read
const std::streamsize bytesRead = file.gcount();
if (bytesRead < 0) {
error = "could not read file";
bytes.clear();
return false;
}
bytes.resize(static_cast<std::size_t>(bytesRead));
return true;
}
bool LocalFileBackend::isBinary(const std::string& path, bool& result, std::string& error) {
constexpr std::size_t kMaxCheckBytes = 4096;
std::vector<std::uint8_t> bytes;
if (!readFilePartial(path, bytes, kMaxCheckBytes, error)) {
return false;
}
if (bytes.empty()) {
result = false; // Empty file is treated as non-binary
return true;
}
const std::size_t count = bytes.size();
std::size_t controls = 0;
for (std::size_t i = 0; i < count; ++i) {
const auto c = bytes[i];
// Null byte indicates binary content immediately
if (c == 0) {
result = true;
return true;
}
// Count unprintable control characters (excluding tab \t, LF \n, CR \r, etc.)
if (c < 9 || (c > 13 && c < 32)) {
++controls;
if (controls > count / 100) {
result = true;
return true;
}
}
}
result = false;
return true;
}
bool LocalFileBackend::writeFile(const std::string& path, const std::vector<std::uint8_t>& bytes, std::string& error) {
return atomicWriteLocal(std::filesystem::path(path), bytes, error);
}
bool LocalFileBackend::stat(const std::string& path, BackendFileStat& result, std::string& error) {
std::error_code ec;
const auto status = std::filesystem::status(path, ec);
if (ec == std::errc::no_such_file_or_directory) {
result = {};
return true;
}
if (ec) {
error = errorMessage(ec);
return false;
}
result.exists = std::filesystem::exists(status);
result.is_directory = std::filesystem::is_directory(status);
if (!result.exists) return true;
if (!result.is_directory) {
result.size = std::filesystem::file_size(path, ec);
if (ec) ec.clear();
}
const auto modified = std::filesystem::last_write_time(path, ec);
if (!ec) result.mtime = unixSeconds(modified);
return true;
}
bool LocalFileBackend::listDirectory(const std::string& path, std::vector<BackendDirectoryEntry>& entries, std::string& error) {
entries.clear();
std::error_code ec;
for (std::filesystem::directory_iterator iterator(path, ec), end; !ec && iterator != end; iterator.increment(ec)) {
const auto& item = *iterator;
BackendDirectoryEntry entry;
entry.name = item.path().filename().string();
entry.is_directory = item.is_directory(ec);
if (ec) {
ec.clear();
continue;
}
if (!entry.is_directory) {
entry.size = item.file_size(ec);
if (ec) ec.clear();
}
const auto modified = item.last_write_time(ec);
if (!ec) entry.mtime = unixSeconds(modified);
else ec.clear();
entries.push_back(std::move(entry));
}
if (ec) {
error = errorMessage(ec);
return false;
}
std::sort(entries.begin(), entries.end(), [](const auto& left, const auto& right) {
if (left.is_directory != right.is_directory) return left.is_directory > right.is_directory;
return left.name < right.name;
});
return true;
}
bool LocalFileBackend::remove(const std::string& path, std::string& error) {
std::error_code ec;
const bool removed = std::filesystem::remove(path, ec);
if (ec) error = errorMessage(ec);
return removed && !ec;
}
bool LocalFileBackend::rename(const std::string& old_path, const std::string& new_path, std::string& error) {
std::error_code ec;
std::filesystem::rename(old_path, new_path, ec);
if (ec) error = errorMessage(ec);
return !ec;
}
bool LocalFileBackend::createDirectories(const std::string& path, std::string& error) {
std::error_code ec;
std::filesystem::create_directories(path, ec);
if (ec) error = errorMessage(ec);
return !ec;
}
std::shared_ptr<FileBackend> FileBackends::current() {
std::lock_guard<std::mutex> lock(mutex_);
return current_;
}
void FileBackends::use(std::shared_ptr<FileBackend> backend) {
std::lock_guard<std::mutex> lock(mutex_);
current_ = backend ? std::move(backend) : std::make_shared<LocalFileBackend>();
}
void FileBackends::useLocal() {
use(std::make_shared<LocalFileBackend>());
}
bool FileBackends::isRemote() {
return current()->isRemote();
}