forked from pioneerspacesim/pioneer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileSystem.cpp
More file actions
436 lines (384 loc) · 11.7 KB
/
FileSystem.cpp
File metadata and controls
436 lines (384 loc) · 11.7 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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// Copyright © 2008-2024 Pioneer Developers. See AUTHORS.txt for details
// Licensed under the terms of the GPL v3. See licenses/GPL-3.txt
#include "FileSystem.h"
#include "StringRange.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <map>
#include <sstream>
#include <stdexcept>
namespace FileSystem {
static FileSourceFS dataFilesApp(GetDataDir(), true);
static FileSourceFS dataFilesUser(JoinPath(GetUserDir(), "data"));
FileSourceUnion gameDataFiles;
FileSourceFS userFiles(GetUserDir());
// note: some functions (GetUserDir(), GetDataDir()) are in FileSystem{Posix,Win32}.cpp
std::string SanitiseFileName(const std::string &a)
{
const char *disabled_chars = "\\/'\":?<>|&*";
std::ostringstream ss;
if (a.empty() || (a[0] == '.')) {
ss << "x";
}
for (const char *c = a.c_str(), *end = c + a.size(); c != end; ++c) {
if (strchr(disabled_chars, *c) || (*c < ' ')) {
ss << "_";
ss.setf(std::ios::hex, std::ios::basefield);
ss.fill('0');
ss.width(2);
ss << int(*c);
} else if (*c == ' ') {
ss << '_';
} else {
ss << *c;
}
}
return ss.str();
}
std::string JoinPath(const std::string &a, const std::string &b)
{
if (!b.empty()) {
if (b[0] == '/' || a.empty())
return b;
else
return a + "/" + b;
} else
return a;
}
static void normalise_path(std::string &result, const StringRange &path)
{
StringRange part(path.begin, path.end);
if (!path.Empty() && (path[0] == '/')) {
result += '/';
++part.begin;
}
const size_t initial_result_length = result.size();
while (true) {
part.end = part.FindChar('/'); // returns part.end if the char is not found
if (part.Empty() || (part == ".")) {
// skip this part
} else if (part == "..") {
// pop the last component
if (result.size() <= initial_result_length)
throw std::invalid_argument(path.ToString());
size_t pos = result.rfind('/');
if (pos == std::string::npos) {
pos = 0;
}
assert(pos >= initial_result_length);
result.erase(pos);
} else {
// push the new component
if (result.size() > initial_result_length)
result += '/';
result.append(part.begin, part.Size());
}
if (part.end == path.end) {
break;
}
assert(*part.end == '/');
part.begin = part.end + 1;
part.end = path.end;
}
}
std::string NormalisePath(const std::string &path)
{
std::string result;
result.reserve(path.size());
normalise_path(result, StringRange(path.c_str(), path.size()));
return result;
}
std::string JoinPathBelow(const std::string &base, const std::string &path)
{
if (base.empty())
return path;
if (!path.empty()) {
if ((path[0] == '/') && (base != "/"))
throw std::invalid_argument(path);
else {
std::string result(base);
result.reserve(result.size() + 1 + path.size());
if (result[result.size() - 1] != '/')
result += '/';
StringRange rhs(path.c_str(), path.size());
if (path[0] == '/') {
assert(base == "/");
++rhs.begin;
}
normalise_path(result, rhs);
return result;
}
} else
return base;
}
std::string GetRelativePath(const std::string &base, const std::string &path)
{
// catch all common errors early
if (base.empty() || path.empty() || path.size() < base.size())
return path;
// can't strip a non-root prefix from a root path and vice-versa
if ((path[0] == '/' || base[0] == '/') && (path[0] != base[0]))
return path;
// check if <path> exactly starts with <base>
if (path.compare(0, base.size(), base) == 0) {
if (path.size() == base.size())
return ""; // strip the entire base and return an empty path
else if (path[base.size()] == '/')
return path.substr(base.size() + 1); // strip the base and the trailing separator
}
// if <path> isn't relative to <base>, return the original <path>
return path;
}
bool CopyDir(FileSource &sourceFS, std::string sourceDir, FileSourceFS &targetFS, std::string targetDir, FileSystem::CopyMode copymode)
{
// NOTE: copymode var is not used, because only mode ONLY_MISSING_IN_TARGET is implemented
if (!sourceFS.Lookup(sourceDir).IsDir() || !targetFS.Lookup(targetDir).IsDir())
return false;
// collect files, that are already in the target
// NOTE: modification time (in map value) probably will be needed in another mode
std::map<std::string, Time::DateTime> targetFiles;
if (copymode != CopyMode::OVERWRITE) {
// don't bother collecting target file data if we're overwriting
for (FileSystem::FileEnumerator files(targetFS, targetDir, FileSystem::FileEnumerator::Recurse | FileSystem::FileEnumerator::IncludeDirs); !files.Finished(); files.Next())
targetFiles[files.Current().GetPath()] = files.Current().GetModificationTime();
}
for (FileSystem::FileEnumerator files(sourceFS, sourceDir, FileSystem::FileEnumerator::Recurse | FileSystem::FileEnumerator::IncludeDirs); !files.Finished(); files.Next()) {
const FileSystem::FileInfo &info = files.Current();
const std::string targetPath = FileSystem::JoinPathBelow(targetDir, FileSystem::GetRelativePath(sourceDir, info.GetPath()));
const auto &oldFile = targetFiles.find(targetPath);
if (oldFile == targetFiles.end()) { // there is no such file (or dir) in the target
if (info.IsFile()) {
//copy file
RefCountedPtr<FileData> fileData = info.Read();
FILE *outfile = targetFS.OpenWriteStream(targetPath);
fwrite(fileData->GetData(), 1, fileData->GetSize(), outfile);
fclose(outfile);
// Output("copy %s to %s\n", info.GetAbsolutePath(), FileSystem::JoinPath(targetFS.GetRoot(), targetPath));
} else if (info.IsDir()) {
//create the subdir
targetFS.MakeDirectory(targetPath);
// Output("create dir %s\n", FileSystem::JoinPath(targetFS.GetRoot(), targetPath));
}
} else
//this file is no longer needed when searching
targetFiles.erase(oldFile);
}
return true;
}
void Init()
{
gameDataFiles.AppendSource(&dataFilesUser);
gameDataFiles.AppendSource(&dataFilesApp);
}
void Uninit()
{
}
FileInfo::FileInfo(FileSource *source, const std::string &path, FileType type, Time::DateTime modTime) :
m_source(source),
m_path(path),
m_modTime(modTime),
m_dirLen(0),
m_type(type)
{
if (!m_path.empty() && m_path[m_path.size() - 1] == '/') {
// remove trailing slash
m_path.pop_back();
}
std::size_t slashpos = m_path.rfind('/');
if (slashpos != std::string::npos) {
m_dirLen = slashpos + 1;
} else {
m_dirLen = 0;
}
}
FileInfo FileSource::MakeFileInfo(const std::string &path, FileInfo::FileType fileType, Time::DateTime modTime)
{
return FileInfo(this, path, fileType, modTime);
}
FileInfo FileSource::MakeFileInfo(const std::string &path, FileInfo::FileType fileType)
{
return MakeFileInfo(path, fileType, Time::DateTime());
}
FileSourceUnion::FileSourceUnion() :
FileSource(":union:") {}
FileSourceUnion::~FileSourceUnion() {}
void FileSourceUnion::PrependSource(FileSource *fs)
{
assert(fs);
RemoveSource(fs);
m_sources.insert(m_sources.begin(), fs);
}
void FileSourceUnion::AppendSource(FileSource *fs)
{
assert(fs);
RemoveSource(fs);
m_sources.push_back(fs);
}
void FileSourceUnion::RemoveSource(FileSource *fs)
{
std::vector<FileSource *>::iterator nend = std::remove(m_sources.begin(), m_sources.end(), fs);
m_sources.erase(nend, m_sources.end());
}
FileInfo FileSourceUnion::Lookup(const std::string &path)
{
for (std::vector<FileSource *>::const_iterator
it = m_sources.begin();
it != m_sources.end(); ++it) {
FileInfo info = (*it)->Lookup(path);
if (info.Exists()) {
return info;
}
}
return MakeFileInfo(path, FileInfo::FT_NON_EXISTENT);
}
std::vector<FileInfo> FileSourceUnion::LookupAll(const std::string &path)
{
std::vector<FileInfo> outFiles;
for (FileSource *fs : m_sources) {
FileInfo info = fs->Lookup(path);
if (info.Exists()) outFiles.push_back(info);
}
return outFiles;
}
RefCountedPtr<FileData> FileSourceUnion::ReadFile(const std::string &path)
{
for (std::vector<FileSource *>::const_iterator
it = m_sources.begin();
it != m_sources.end(); ++it) {
RefCountedPtr<FileData> data = (*it)->ReadFile(path);
if (data) {
return data;
}
}
return RefCountedPtr<FileData>();
}
// Merge two sets of FileInfo's, by path.
// Input vectors must be sorted. Output will be sorted.
// Where a path is present in both inputs, directories are selected
// in preference to non-directories; otherwise, the FileInfo from the
// first vector is selected in preference to the second vector.
static void file_union_merge(
std::vector<FileInfo>::const_iterator a, std::vector<FileInfo>::const_iterator aend,
std::vector<FileInfo>::const_iterator b, std::vector<FileInfo>::const_iterator bend,
std::vector<FileInfo> &output)
{
while ((a != aend) && (b != bend)) {
int order = a->GetPath().compare(b->GetPath());
int which = order;
if (which == 0) {
if (b->IsDir() && !a->IsDir()) {
which = 1;
} else {
which = -1;
}
}
if (which < 0) {
output.push_back(*a++);
if (order == 0) ++b;
} else {
output.push_back(*b++);
if (order == 0) ++a;
}
}
if (a != aend) {
std::copy(a, aend, std::back_inserter(output));
}
if (b != bend) {
std::copy(b, bend, std::back_inserter(output));
}
}
bool FileSourceUnion::ReadDirectory(const std::string &path, std::vector<FileInfo> &output)
{
if (m_sources.empty()) {
return false;
}
if (m_sources.size() == 1) {
return m_sources.front()->ReadDirectory(path, output);
}
bool founddir = false;
std::vector<FileInfo> merged;
for (std::vector<FileSource *>::const_iterator
it = m_sources.begin();
it != m_sources.end(); ++it) {
std::vector<FileInfo> nextfiles;
if ((*it)->ReadDirectory(path, nextfiles)) {
founddir = true;
std::vector<FileInfo> prevfiles;
prevfiles.swap(merged);
// merge order is important
// file_union_merge selects from its first input preferentially
file_union_merge(
prevfiles.begin(), prevfiles.end(),
nextfiles.begin(), nextfiles.end(),
merged);
}
}
output.reserve(output.size() + merged.size());
std::copy(merged.begin(), merged.end(), std::back_inserter(output));
return founddir;
}
FileEnumerator::FileEnumerator(FileSource &fs, int flags) :
m_source(&fs),
m_flags(flags) {}
FileEnumerator::FileEnumerator(FileSource &fs, const std::string &path, int flags) :
m_source(&fs),
m_flags(flags)
{
AddSearchRoot(path);
}
FileEnumerator::~FileEnumerator() {}
void FileEnumerator::AddSearchRoot(const std::string &path)
{
const FileInfo fi = m_source->Lookup(path);
if (fi.IsDir()) {
QueueDirectoryContents(fi);
ExpandDirQueue();
}
}
void FileEnumerator::Next()
{
m_queue.pop_front();
ExpandDirQueue();
}
void FileEnumerator::ExpandDirQueue()
{
while (m_queue.empty() && !m_dirQueue.empty()) {
const FileInfo &nextDir = m_dirQueue.front();
assert(nextDir.IsDir());
QueueDirectoryContents(nextDir);
m_dirQueue.pop_front();
}
}
void FileEnumerator::QueueDirectoryContents(const FileInfo &info)
{
assert(info.IsDir());
std::vector<FileInfo> entries;
m_source->ReadDirectory(info.GetPath(), entries);
for (std::vector<FileInfo>::const_iterator
it = entries.begin();
it != entries.end(); ++it) {
switch (it->GetType()) {
case FileInfo::FT_DIR:
if (m_flags & IncludeDirs) {
m_queue.push_back(*it);
}
if (m_flags & Recurse) {
m_dirQueue.push_back(*it);
}
break;
case FileInfo::FT_FILE:
if (!(m_flags & ExcludeFiles)) {
m_queue.push_back(*it);
}
break;
case FileInfo::FT_SPECIAL:
if (m_flags & IncludeSpecials) {
m_queue.push_back(*it);
}
break;
default: assert(0); break;
}
}
}
} // namespace FileSystem