-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathFileSystem.cpp
2640 lines (2242 loc) · 62.7 KB
/
FileSystem.cpp
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: 2002-2025 PCSX2 Dev Team
// SPDX-License-Identifier: GPL-3.0+
#include "FileSystem.h"
#include "Error.h"
#include "Path.h"
#include "Assertions.h"
#include "Console.h"
#include "StringUtil.h"
#include "Path.h"
#include "ProgressCallback.h"
#include <algorithm>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <numeric>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#include <stdlib.h>
#include <sys/param.h>
#endif
#ifdef __FreeBSD__
#include <sys/sysctl.h>
#endif
#if defined(_WIN32)
#include "RedtapeWindows.h"
#include <io.h>
#include <malloc.h>
#include <pathcch.h>
#include <winioctl.h>
#include <share.h>
#include <shlobj.h>
#else
#include <fcntl.h>
#include <dirent.h>
#include <errno.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#ifdef _WIN32
static std::time_t ConvertFileTimeToUnixTime(const FILETIME& ft)
{
// based off https://stackoverflow.com/a/6161842
static constexpr s64 WINDOWS_TICK = 10000000;
static constexpr s64 SEC_TO_UNIX_EPOCH = 11644473600LL;
const s64 full = static_cast<s64>((static_cast<u64>(ft.dwHighDateTime) << 32) | static_cast<u64>(ft.dwLowDateTime));
return static_cast<std::time_t>(full / WINDOWS_TICK - SEC_TO_UNIX_EPOCH);
}
template <class T>
static bool IsUNCPath(const T& path)
{
return (path.length() >= 3 && path[0] == '\\' && path[1] == '\\');
}
#endif
static inline bool FileSystemCharacterIsSane(char32_t c, bool strip_slashes)
{
#ifdef _WIN32
// https://docs.microsoft.com/en-gb/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN#naming-conventions
if ((c == U'/' || c == U'\\') && strip_slashes)
return false;
if (c == U'<' || c == U'>' || c == U':' || c == U'"' || c == U'|' || c == U'?' || c == U'*' || c == 0 ||
c <= static_cast<char32_t>(31))
{
return false;
}
#else
if (c == '/' && strip_slashes)
return false;
// drop asterisks too, they make globbing annoying
if (c == '*')
return false;
// macos doesn't allow colons, apparently
#ifdef __APPLE__
if (c == U':')
return false;
#endif
#endif
return true;
}
template <typename T>
static inline void PathAppendString(std::string& dst, const T& src)
{
if (dst.capacity() < (dst.length() + src.length()))
dst.reserve(dst.length() + src.length());
bool last_separator = (!dst.empty() && dst.back() == FS_OSPATH_SEPARATOR_CHARACTER);
size_t index = 0;
#ifdef _WIN32
// special case for UNC paths here
if (dst.empty() && src.length() >= 3 && src[0] == '\\' && src[1] == '\\' && src[2] != '\\')
{
dst.append("\\\\");
index = 2;
}
#endif
for (; index < src.length(); index++)
{
const char ch = src[index];
#ifdef _WIN32
// convert forward slashes to backslashes
if (ch == '\\' || ch == '/')
#else
if (ch == '/')
#endif
{
if (last_separator)
continue;
last_separator = true;
dst.push_back(FS_OSPATH_SEPARATOR_CHARACTER);
}
else
{
last_separator = false;
dst.push_back(ch);
}
}
}
std::string Path::SanitizeFileName(const std::string_view str, bool strip_slashes /* = true */)
{
std::string ret;
ret.reserve(str.length());
size_t pos = 0;
while (pos < str.length())
{
char32_t ch;
pos += StringUtil::DecodeUTF8(str, pos, &ch);
ch = FileSystemCharacterIsSane(ch, strip_slashes) ? ch : U'_';
StringUtil::EncodeAndAppendUTF8(ret, ch);
}
#ifdef _WIN32
// Windows: Can't end filename with a period.
if (ret.length() > 0 && ret.back() == '.')
ret.back() = '_';
#endif
return ret;
}
void Path::SanitizeFileName(std::string* str, bool strip_slashes /* = true */)
{
const size_t len = str->length();
char small_buf[128];
std::unique_ptr<char[]> large_buf;
char* str_copy = small_buf;
if (len >= std::size(small_buf))
{
large_buf = std::make_unique<char[]>(len + 1);
str_copy = large_buf.get();
}
std::memcpy(str_copy, str->c_str(), sizeof(char) * (len + 1));
str->clear();
size_t pos = 0;
while (pos < len)
{
char32_t ch;
pos += StringUtil::DecodeUTF8(str_copy + pos, pos - len, &ch);
ch = FileSystemCharacterIsSane(ch, strip_slashes) ? ch : U'_';
StringUtil::EncodeAndAppendUTF8(*str, ch);
}
#ifdef _WIN32
// Windows: Can't end filename with a period.
if (str->length() > 0 && str->back() == '.')
str->back() = '_';
#endif
}
bool Path::IsValidFileName(const std::string_view str, bool allow_slashes)
{
const size_t len = str.length();
size_t pos = 0;
while (pos < len)
{
char32_t ch;
pos += StringUtil::DecodeUTF8(str.data() + pos, pos - len, &ch);
if (!FileSystemCharacterIsSane(ch, !allow_slashes))
return false;
}
#ifdef _WIN32
// Windows: Can't end filename with a period.
if (len > 0 && str.back() == '.')
return false;
#endif
return true;
}
#ifdef _WIN32
bool FileSystem::GetWin32Path(std::wstring* dest, std::string_view str)
{
// Just convert to wide if it's a relative path, MAX_PATH still applies.
if (!Path::IsAbsolute(str))
return StringUtil::UTF8StringToWideString(*dest, str);
// PathCchCanonicalizeEx() thankfully takes care of everything.
// But need to widen the string first, avoid the stack allocation.
int wlen = MultiByteToWideChar(CP_UTF8, 0, str.data(), static_cast<int>(str.length()), nullptr, 0);
if (wlen <= 0) [[unlikely]]
return false;
// So copy it to a temp wide buffer first.
wchar_t* wstr_buf = static_cast<wchar_t*>(_malloca(sizeof(wchar_t) * (static_cast<size_t>(wlen) + 1)));
wlen = MultiByteToWideChar(CP_UTF8, 0, str.data(), static_cast<int>(str.length()), wstr_buf, wlen);
if (wlen <= 0) [[unlikely]]
{
_freea(wstr_buf);
return false;
}
// And use PathCchCanonicalizeEx() to fix up any non-direct elements.
wstr_buf[wlen] = '\0';
dest->resize(std::max<size_t>(static_cast<size_t>(wlen) + (IsUNCPath(str) ? 9 : 5), 16));
for (;;)
{
const HRESULT hr =
PathCchCanonicalizeEx(dest->data(), dest->size(), wstr_buf, PATHCCH_ENSURE_IS_EXTENDED_LENGTH_PATH);
if (SUCCEEDED(hr))
{
dest->resize(std::wcslen(dest->data()));
_freea(wstr_buf);
return true;
}
else if (hr == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
{
dest->resize(dest->size() * 2);
continue;
}
else [[unlikely]]
{
Console.ErrorFmt("PathCchCanonicalizeEx() returned {:08X}", static_cast<unsigned>(hr));
_freea(wstr_buf);
return false;
}
}
}
std::wstring FileSystem::GetWin32Path(std::string_view str)
{
std::wstring ret;
if (!GetWin32Path(&ret, str))
ret.clear();
return ret;
}
#endif
bool Path::IsAbsolute(const std::string_view path)
{
#ifdef _WIN32
return (path.length() >= 3 && ((path[0] >= 'A' && path[0] <= 'Z') || (path[0] >= 'a' && path[0] <= 'z')) &&
path[1] == ':' && (path[2] == '/' || path[2] == '\\')) ||
(path.length() >= 3 && path[0] == '\\' && path[1] == '\\');
#else
return (path.length() >= 1 && path[0] == '/');
#endif
}
std::string Path::RealPath(const std::string_view path)
{
// Resolve non-absolute paths first.
std::vector<std::string_view> components;
if (!IsAbsolute(path))
components = Path::SplitNativePath(Path::Combine(FileSystem::GetWorkingDirectory(), path));
else
components = Path::SplitNativePath(path);
std::string realpath;
if (components.empty())
return realpath;
// Different to path because relative.
realpath.reserve(std::accumulate(components.begin(), components.end(), static_cast<size_t>(0),
[](size_t l, const std::string_view& s) { return l + s.length(); }) +
components.size() + 1);
#ifdef _WIN32
std::wstring wrealpath;
std::vector<WCHAR> symlink_buf;
wrealpath.reserve(realpath.size());
symlink_buf.resize(path.size() + 1);
// Check for any symbolic links throughout the path while adding components.
const bool skip_first = IsUNCPath(path);
bool test_symlink = true;
for (const std::string_view& comp : components)
{
if (!realpath.empty())
{
realpath.push_back(FS_OSPATH_SEPARATOR_CHARACTER);
realpath.append(comp);
}
else if (skip_first)
{
realpath.append(comp);
continue;
}
else
{
realpath.append(comp);
}
if (test_symlink)
{
DWORD attribs;
if (FileSystem::GetWin32Path(&wrealpath, realpath) &&
(attribs = GetFileAttributesW(wrealpath.c_str())) != INVALID_FILE_ATTRIBUTES)
{
// if not a link, go to the next component
if (attribs & FILE_ATTRIBUTE_REPARSE_POINT)
{
const HANDLE hFile =
CreateFileW(wrealpath.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr);
if (hFile != INVALID_HANDLE_VALUE)
{
// is a link! resolve it.
DWORD ret = GetFinalPathNameByHandleW(hFile, symlink_buf.data(), static_cast<DWORD>(symlink_buf.size()),
FILE_NAME_NORMALIZED);
if (ret > symlink_buf.size())
{
symlink_buf.resize(ret);
ret = GetFinalPathNameByHandleW(hFile, symlink_buf.data(), static_cast<DWORD>(symlink_buf.size()),
FILE_NAME_NORMALIZED);
}
if (ret != 0)
StringUtil::WideStringToUTF8String(realpath, std::wstring_view(symlink_buf.data(), ret));
else
test_symlink = false;
CloseHandle(hFile);
}
}
}
else
{
// not a file or link
test_symlink = false;
}
}
}
// GetFinalPathNameByHandleW() adds a \\?\ prefix, so remove it.
if (realpath.starts_with("\\\\?\\") && IsAbsolute(std::string_view(realpath.data() + 4, realpath.size() - 4)))
{
realpath.erase(0, 4);
}
else if (realpath.starts_with("\\\\?\\UNC\\"))
{
realpath.erase(0, 7);
realpath.insert(realpath.begin(), '\\');
}
#else
// Why this monstrosity instead of calling realpath()? realpath() only works on files that exist.
std::string basepath;
std::string symlink;
basepath.reserve(realpath.capacity());
symlink.resize(realpath.capacity());
// Check for any symbolic links throughout the path while adding components.
bool test_symlink = true;
for (const std::string_view& comp : components)
{
if (!test_symlink)
{
realpath.push_back(FS_OSPATH_SEPARATOR_CHARACTER);
realpath.append(comp);
continue;
}
basepath = realpath;
if (realpath.empty() || realpath.back() != FS_OSPATH_SEPARATOR_CHARACTER)
realpath.push_back(FS_OSPATH_SEPARATOR_CHARACTER);
realpath.append(comp);
// Check if the last component added is a symlink
struct stat sb;
if (lstat(realpath.c_str(), &sb) != 0)
{
// Don't bother checking any further components once we error out.
test_symlink = false;
continue;
}
else if (!S_ISLNK(sb.st_mode))
{
// Nope, keep going.
continue;
}
for (;;)
{
ssize_t sz = readlink(realpath.c_str(), symlink.data(), symlink.size());
if (sz < 0)
{
// shouldn't happen, due to the S_ISLNK check above.
test_symlink = false;
break;
}
else if (static_cast<size_t>(sz) == symlink.size())
{
// need a larger buffer
symlink.resize(symlink.size() * 2);
continue;
}
else
{
// is a link, and we resolved it. gotta check if the symlink itself is relative :(
symlink.resize(static_cast<size_t>(sz));
if (!Path::IsAbsolute(symlink))
{
// symlink is relative to the directory of the symlink
realpath = basepath;
if (realpath.empty() || realpath.back() != FS_OSPATH_SEPARATOR_CHARACTER)
realpath.push_back(FS_OSPATH_SEPARATOR_CHARACTER);
realpath.append(symlink);
}
else
{
// Use the new, symlinked path.
realpath = symlink;
}
break;
}
}
}
// If any relative symlinks were resolved, there may be '.' and '..'
// components in the resultant path, which must be removed.
realpath = Path::Canonicalize(realpath);
#endif
return realpath;
}
std::string Path::ToNativePath(const std::string_view path)
{
std::string ret;
PathAppendString(ret, path);
// remove trailing slashes
if (ret.length() > 1)
{
while (ret.back() == FS_OSPATH_SEPARATOR_CHARACTER)
ret.pop_back();
}
return ret;
}
void Path::ToNativePath(std::string* path)
{
*path = Path::ToNativePath(*path);
}
std::string Path::Canonicalize(const std::string_view path)
{
std::vector<std::string_view> components = Path::SplitNativePath(path);
std::vector<std::string_view> new_components;
new_components.reserve(components.size());
for (const std::string_view& component : components)
{
if (component == ".")
{
// current directory, so it can be skipped, unless it's the only component
if (components.size() == 1)
new_components.push_back(std::move(component));
}
else if (component == "..")
{
// parent directory, pop one off if we're not at the beginning, otherwise preserve.
if (!new_components.empty())
new_components.pop_back();
else
new_components.push_back(std::move(component));
}
else
{
// anything else, preserve
new_components.push_back(std::move(component));
}
}
return Path::JoinNativePath(new_components);
}
void Path::Canonicalize(std::string* path)
{
*path = Canonicalize(*path);
}
std::string Path::MakeRelative(const std::string_view path, const std::string_view relative_to)
{
// simple algorithm, we just work on the components. could probably be better, but it'll do for now.
std::vector<std::string_view> path_components(SplitNativePath(path));
std::vector<std::string_view> relative_components(SplitNativePath(relative_to));
std::vector<std::string_view> new_components;
// both must be absolute paths
if (Path::IsAbsolute(path) && Path::IsAbsolute(relative_to))
{
// find the number of same components
size_t num_same = 0;
for (size_t i = 0; i < path_components.size() && i < relative_components.size(); i++)
{
if (path_components[i] == relative_components[i])
num_same++;
else
break;
}
// we need at least one same component
if (num_same > 0)
{
// from the relative_to directory, back up to the start of the common components
const size_t num_ups = relative_components.size() - num_same;
for (size_t i = 0; i < num_ups; i++)
new_components.emplace_back("..");
// and add the remainder of the path components
for (size_t i = num_same; i < path_components.size(); i++)
new_components.push_back(std::move(path_components[i]));
}
else
{
// no similarity
new_components = std::move(path_components);
}
}
else
{
// not absolute
new_components = std::move(path_components);
}
return JoinNativePath(new_components);
}
std::string_view Path::GetExtension(const std::string_view path)
{
const std::string_view::size_type pos = path.rfind('.');
if (pos == std::string_view::npos)
return std::string_view();
else
return path.substr(pos + 1);
}
std::string_view Path::StripExtension(const std::string_view path)
{
const std::string_view::size_type pos = path.rfind('.');
if (pos == std::string_view::npos)
return path;
return path.substr(0, pos);
}
std::string Path::ReplaceExtension(const std::string_view path, const std::string_view new_extension)
{
const std::string_view::size_type pos = path.rfind('.');
if (pos == std::string_view::npos)
return std::string(path);
std::string ret(path, 0, pos + 1);
ret.append(new_extension);
return ret;
}
static std::string_view::size_type GetLastSeperatorPosition(const std::string_view filename, bool include_separator)
{
std::string_view::size_type last_separator = filename.rfind('/');
if (include_separator && last_separator != std::string_view::npos)
last_separator++;
#if defined(_WIN32)
std::string_view::size_type other_last_separator = filename.rfind('\\');
if (other_last_separator != std::string_view::npos)
{
if (include_separator)
other_last_separator++;
if (last_separator == std::string_view::npos || other_last_separator > last_separator)
last_separator = other_last_separator;
}
#endif
return last_separator;
}
std::string_view Path::GetDirectory(const std::string_view path)
{
const std::string::size_type pos = GetLastSeperatorPosition(path, false);
if (pos == std::string_view::npos)
return {};
return path.substr(0, pos);
}
std::string_view Path::GetFileName(const std::string_view path)
{
const std::string_view::size_type pos = GetLastSeperatorPosition(path, true);
if (pos == std::string_view::npos)
return path;
return path.substr(pos);
}
std::string_view Path::GetFileTitle(const std::string_view path)
{
const std::string_view filename(GetFileName(path));
const std::string::size_type pos = filename.rfind('.');
if (pos == std::string_view::npos)
return filename;
return filename.substr(0, pos);
}
std::string Path::ChangeFileName(const std::string_view path, const std::string_view new_filename)
{
std::string ret;
PathAppendString(ret, path);
const std::string_view::size_type pos = GetLastSeperatorPosition(ret, true);
if (pos == std::string_view::npos)
{
ret.clear();
PathAppendString(ret, new_filename);
}
else
{
if (!new_filename.empty())
{
ret.erase(pos);
PathAppendString(ret, new_filename);
}
else
{
ret.erase(pos - 1);
}
}
return ret;
}
void Path::ChangeFileName(std::string* path, const std::string_view new_filename)
{
*path = ChangeFileName(*path, new_filename);
}
std::string Path::AppendDirectory(const std::string_view path, const std::string_view new_dir)
{
std::string ret;
if (!new_dir.empty())
{
const std::string_view::size_type pos = GetLastSeperatorPosition(path, true);
ret.reserve(path.length() + new_dir.length() + 1);
if (pos != std::string_view::npos)
PathAppendString(ret, path.substr(0, pos));
while (!ret.empty() && ret.back() == FS_OSPATH_SEPARATOR_CHARACTER)
ret.pop_back();
if (!ret.empty())
ret += FS_OSPATH_SEPARATOR_CHARACTER;
PathAppendString(ret, new_dir);
if (pos != std::string_view::npos)
{
const std::string_view filepart(path.substr(pos));
if (!filepart.empty())
{
ret += FS_OSPATH_SEPARATOR_CHARACTER;
PathAppendString(ret, filepart);
}
}
else if (!path.empty())
{
ret += FS_OSPATH_SEPARATOR_CHARACTER;
PathAppendString(ret, path);
}
}
else
{
PathAppendString(ret, path);
}
return ret;
}
void Path::AppendDirectory(std::string* path, const std::string_view new_dir)
{
*path = AppendDirectory(*path, new_dir);
}
std::vector<std::string_view> Path::SplitWindowsPath(const std::string_view path)
{
std::vector<std::string_view> parts;
std::string::size_type start = 0;
std::string::size_type pos = 0;
// preserve unc paths
if (path.size() > 2 && path[0] == '\\' && path[1] == '\\')
pos = 2;
while (pos < path.size())
{
if (path[pos] != '/' && path[pos] != '\\')
{
pos++;
continue;
}
// skip consecutive separators
if (pos != start)
parts.push_back(path.substr(start, pos - start));
pos++;
start = pos;
}
if (start != pos)
parts.push_back(path.substr(start));
return parts;
}
std::string Path::JoinWindowsPath(const std::vector<std::string_view>& components)
{
return StringUtil::JoinString(components.begin(), components.end(), '\\');
}
std::vector<std::string_view> Path::SplitNativePath(const std::string_view path)
{
#ifdef _WIN32
return SplitWindowsPath(path);
#else
std::vector<std::string_view> parts;
std::string::size_type start = 0;
std::string::size_type pos = 0;
while (pos < path.size())
{
if (path[pos] != '/')
{
pos++;
continue;
}
// skip consecutive separators
// for unix, we create an empty element at the beginning when it's an absolute path
// that way, when it's re-joined later, we preserve the starting slash.
if (pos != start || pos == 0)
parts.push_back(path.substr(start, pos - start));
pos++;
start = pos;
}
if (start != pos)
parts.push_back(path.substr(start));
return parts;
#endif
}
std::string Path::JoinNativePath(const std::vector<std::string_view>& components)
{
return StringUtil::JoinString(components.begin(), components.end(), FS_OSPATH_SEPARATOR_CHARACTER);
}
std::vector<std::string> FileSystem::GetRootDirectoryList()
{
std::vector<std::string> results;
#if defined(_WIN32)
char buf[256];
const DWORD size = GetLogicalDriveStringsA(sizeof(buf), buf);
if (size != 0 && size < (sizeof(buf) - 1))
{
const char* ptr = buf;
while (*ptr != '\0')
{
const std::size_t len = std::strlen(ptr);
results.emplace_back(ptr, len);
ptr += len + 1u;
}
}
#else
const char* home_path = std::getenv("HOME");
if (home_path)
results.push_back(home_path);
results.push_back("/");
#endif
return results;
}
std::string Path::BuildRelativePath(const std::string_view filename, const std::string_view new_filename)
{
std::string new_string;
std::string_view::size_type pos = GetLastSeperatorPosition(filename, true);
if (pos != std::string_view::npos)
new_string.assign(filename, 0, pos);
new_string.append(new_filename);
return new_string;
}
std::string Path::Combine(const std::string_view base, const std::string_view next)
{
std::string ret;
ret.reserve(base.length() + next.length() + 1);
PathAppendString(ret, base);
while (!ret.empty() && ret.back() == FS_OSPATH_SEPARATOR_CHARACTER)
ret.pop_back();
ret += FS_OSPATH_SEPARATOR_CHARACTER;
PathAppendString(ret, next);
while (!ret.empty() && ret.back() == FS_OSPATH_SEPARATOR_CHARACTER)
ret.pop_back();
return ret;
}
std::string Path::URLEncode(std::string_view str)
{
std::string ret;
ret.reserve(str.length() + ((str.length() + 3) / 4) * 3);
for (size_t i = 0, l = str.size(); i < l; i++)
{
const char c = str[i];
if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '-' || c == '_' ||
c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')')
{
ret.push_back(c);
}
else
{
ret.push_back('%');
const unsigned char n1 = static_cast<unsigned char>(c) >> 4;
const unsigned char n2 = static_cast<unsigned char>(c) & 0x0F;
ret.push_back((n1 >= 10) ? ('a' + (n1 - 10)) : ('0' + n1));
ret.push_back((n2 >= 10) ? ('a' + (n2 - 10)) : ('0' + n2));
}
}
return ret;
}
std::string Path::URLDecode(std::string_view str)
{
std::string ret;
ret.reserve(str.length());
for (size_t i = 0, l = str.size(); i < l; i++)
{
const char c = str[i];
if (c == '+')
{
ret.push_back(c);
}
else if (c == '%')
{
if ((i + 2) >= str.length())
break;
const char clower = str[i + 1];
const char cupper = str[i + 2];
const unsigned char lower =
(clower >= '0' && clower <= '9') ?
static_cast<unsigned char>(clower - '0') :
((clower >= 'a' && clower <= 'f') ?
static_cast<unsigned char>(clower - 'a') :
((clower >= 'A' && clower <= 'F') ? static_cast<unsigned char>(clower - 'A') : 0));
const unsigned char upper =
(cupper >= '0' && cupper <= '9') ?
static_cast<unsigned char>(cupper - '0') :
((cupper >= 'a' && cupper <= 'f') ?
static_cast<unsigned char>(cupper - 'a') :
((cupper >= 'A' && cupper <= 'F') ? static_cast<unsigned char>(cupper - 'A') : 0));
const char dch = static_cast<char>(lower | (upper << 4));
ret.push_back(dch);
}
else
{
ret.push_back(c);
}
}
return std::string(str);
}
std::string Path::CreateFileURL(std::string_view path)
{
pxAssert(IsAbsolute(path));
std::string ret;
ret.reserve(path.length() + 10);
ret.append("file://");
const std::vector<std::string_view> components = SplitNativePath(path);
pxAssertRel(!components.empty(), "Trying to create a URL from an empty path.");
const std::string_view& first = components.front();
#ifdef _WIN32
// Windows doesn't urlencode the drive letter.
// UNC paths should be omit the leading slash.
if (first.starts_with("\\\\"))
{
// file://hostname/...
ret.append(first.substr(2));
}
else
{
// file:///c:/...
fmt::format_to(std::back_inserter(ret), "/{}", first);
}
#else
// Don't append a leading slash for the first component.
ret.append(first);
#endif
for (size_t comp = 1; comp < components.size(); comp++)
{
fmt::format_to(std::back_inserter(ret), "/{}", URLEncode(components[comp]));
}
return ret;
}
std::FILE* FileSystem::OpenCFile(const char* filename, const char* mode, Error* error)
{
#ifdef _WIN32
const std::wstring wfilename = GetWin32Path(filename);
const std::wstring wmode = GetWin32Path(mode);
if (!wfilename.empty() && !wmode.empty())
{
std::FILE* fp;
const errno_t err = _wfopen_s(&fp, wfilename.c_str(), wmode.c_str());
if (err != 0)
{
Error::SetErrno(error, err);
return nullptr;
}
return fp;
}
std::FILE* fp;
const errno_t err = fopen_s(&fp, filename, mode);
if (err != 0)
{
Error::SetErrno(error, err);
return nullptr;
}
return fp;
#else
std::FILE* fp = std::fopen(filename, mode);
if (!fp)
Error::SetErrno(error, errno);
return fp;
#endif
}