-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath-util.cpp
More file actions
735 lines (674 loc) · 17.1 KB
/
path-util.cpp
File metadata and controls
735 lines (674 loc) · 17.1 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
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
/* vim: set ai noet ts=4 sw=4 tw=115: */
//
// Copyright (c) 2014 Nikolay Zapolnov (zapolnov@gmail.com).
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "path-util.h"
#include <sstream>
#include <stdexcept>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef INCLUDE_DIRENT_H
#include INCLUDE_DIRENT_H
#else
#include <yip-imports/dirent.h>
#endif
#ifndef _WIN32
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#ifdef __FreeBSD__
#include <sys/sysctl.h>
#endif
#else
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <shlwapi.h>
#include <userenv.h>
#endif
std::string pathToNativeSeparators(const std::string & path)
{
#ifndef _WIN32
return path;
#else
std::string result = path;
for (char & ch : result)
{
if (ch == '/')
ch = '\\';
}
return result;
#endif
}
std::string pathToUnixSeparators(const std::string & path)
{
#ifndef _WIN32
return path;
#else
std::string result = path;
for (char & ch : result)
{
if (ch == '\\')
ch = '/';
}
return result;
#endif
}
const char * pathSeparator()
{
#ifdef _WIN32
return "\\";
#else
return "/";
#endif
}
bool pathIsSeparator(char ch)
{
if (ch == '/')
return true;
#ifndef _WIN32
return false;
#else
return ch == '\\';
#endif
}
bool pathIsWin32DriveLetter(char ch)
{
return ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'));
}
bool pathIsWin32PathWithDriveLetter(const std::string & path)
{
return (path.length() >= 2 && path[1] == ':' && pathIsWin32DriveLetter(path[0]));
}
std::string pathGetCurrentDirectory()
{
#ifndef _WIN32
std::vector<char> buf(std::max(static_cast<size_t>(PATH_MAX), static_cast<size_t>(2048)));
if (!getcwd(buf.data(), buf.size()))
{
int err = errno;
std::stringstream ss;
ss << "unable to determine current directory: " << strerror(err);
throw std::runtime_error(ss.str());
}
return buf.data();
#else
DWORD size = GetCurrentDirectoryA(0, nullptr);
if (size == 0)
{
DWORD err = GetLastError();
std::stringstream ss;
ss << "unable to determine current directory (code " << err << ").";
throw std::runtime_error(ss.str());
}
std::vector<char> buf(size);
DWORD len = GetCurrentDirectoryA(size, buf.data());
if (len == 0 || len >= size)
{
DWORD err = GetLastError();
std::stringstream ss;
ss << "unable to determine current directory (code " << err << ").";
throw std::runtime_error(ss.str());
}
return std::string(buf.data(), len);
#endif
}
std::string pathGetUserHomeDirectory()
{
#ifndef _WIN32
const char * env = getenv("HOME");
if (env)
return env;
struct passwd * pw = getpwuid(getuid());
if (pw && pw->pw_dir && pw->pw_dir[0])
return pw->pw_dir;
throw std::runtime_error("unable to determine path to the user home directory.");
#else
std::string result;
HANDLE hToken = nullptr;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
{
DWORD err = GetLastError();
std::stringstream ss;
ss << "unable to determine path to the user home directory (code " << err << ").";
throw std::runtime_error(ss.str());
}
try
{
std::vector<char> buf(MAX_PATH);
DWORD size = MAX_PATH;
if (!GetUserProfileDirectoryA(hToken, buf.data(), &size))
{
DWORD err = GetLastError();
std::stringstream ss;
ss << "unable to determine path to the user home directory (code " << err << ").";
throw std::runtime_error(ss.str());
}
result = buf.data();
}
catch (...)
{
CloseHandle(hToken);
throw;
}
CloseHandle(hToken);
return result;
#endif
}
bool pathIsAbsolute(const std::string & path)
{
#ifndef _WIN32
if (path.length() >= 1 && path[0] == '~')
return (path.length() == 1 || pathIsSeparator(path[1]));
return pathIsSeparator(path[0]);
#else
if (PathIsRelativeA(path.c_str()))
return false;
return (path.length() > 2 && pathIsWin32PathWithDriveLetter(path) && pathIsSeparator(path[2]));
#endif
}
std::string pathMakeAbsolute(const std::string & path, const std::string & basePath)
{
#ifndef _WIN32
if (path.length() >= 1 && path[0] == '~')
{
if (path.length() == 1)
return pathGetUserHomeDirectory();
else if (pathIsSeparator(path[1]))
return pathSimplify(pathConcat(pathGetUserHomeDirectory(), path.substr(2)));
}
if (pathIsSeparator(path[0]))
return pathSimplify(path);
#else
if (pathIsWin32PathWithDriveLetter(path) || (path.length() > 0 && pathIsSeparator(path[0])))
return pathMakeAbsolute(path);
#endif
return pathSimplify(pathConcat(basePath, path));
}
std::string pathMakeAbsolute(const std::string & path)
{
#ifndef _WIN32
return pathMakeAbsolute(path, pathGetCurrentDirectory());
#else
DWORD size = GetFullPathNameA(path.c_str(), 0, nullptr, nullptr);
if (size == 0)
{
DWORD err = GetLastError();
std::stringstream ss;
ss << "unable to determine absolute path for file '" << path << "' (code " << err << ").";
throw std::runtime_error(ss.str());
}
std::vector<char> buf(size);
DWORD len = GetFullPathNameA(path.c_str(), size, buf.data(), nullptr);
if (len == 0 || len >= size)
{
DWORD err = GetLastError();
std::stringstream ss;
ss << "unable to determine absolute path for file '" << path << "' (code " << err << ").";
throw std::runtime_error(ss.str());
}
return std::string(buf.data(), len);
#endif
}
size_t pathIndexOfFirstSeparator(const std::string & path, size_t start)
{
size_t pos = path.find('/', start);
#ifdef _WIN32
size_t pos2 = path.find('\\', start);
if (pos2 != std::string::npos && (pos == std::string::npos || pos2 < pos))
pos = pos2;
#endif
return pos;
}
std::string pathSimplify(const std::string & path)
{
std::vector<std::string> parts;
std::stringstream ss;
size_t off = 0;
#ifndef _WIN32
if (path.length() > 0 && path[0] == '~')
{
if (path.length() == 1)
return path;
else if (pathIsSeparator(path[1]))
{
ss << '~' << pathSeparator();
off = 2;
}
}
else if (path.length() > 0 && pathIsSeparator(path[0]))
{
off = 1;
ss << pathSeparator();
}
#else
if (path.length() >= 2 && path[0] == path[1] && pathIsSeparator(path[0]))
{
off = pathIndexOfFirstSeparator(path, 2);
if (off == std::string::npos)
return pathToNativeSeparators(path);
ss << path.substr(0, off) << pathSeparator();
++off;
}
else if (pathIsWin32PathWithDriveLetter(path))
{
off = 2;
ss << path.substr(0, off);
if (path.length() > 2 && pathIsSeparator(path[2]))
{
++off;
ss << pathSeparator();
}
}
else if (path.length() > 0 && pathIsSeparator(path[0]))
{
off = 1;
ss << pathSeparator();
}
#endif
for (;;)
{
size_t pos = pathIndexOfFirstSeparator(path, off);
if (pos == std::string::npos)
{
std::string part = path.substr(off);
if (part.length() > 0)
parts.push_back(part);
break;
}
std::string part = path.substr(off, pos - off);
off = pos + 1;
if (part.length() > 0 && part != ".")
{
if (part == ".." && parts.size() > 0 && parts.back() != "..")
parts.pop_back();
else
parts.push_back(part);
}
}
const char * prefix = "";
for (const std::string & part : parts)
{
ss << prefix << part;
prefix = pathSeparator();
}
return ss.str();
}
std::string pathMakeCanonical(const std::string & path)
{
#ifndef _WIN32
std::vector<char> buf(std::max(static_cast<size_t>(PATH_MAX), static_cast<size_t>(2048)));
if (!realpath(path.c_str(), buf.data()))
{
int err = errno;
std::stringstream ss;
ss << "unable to canonicalize path '" << path << "': " << strerror(err);
throw std::runtime_error(ss.str());
}
return buf.data();
#else
return pathMakeAbsolute(path);
#endif
}
std::string pathConcat(const std::string & path1, const std::string & path2)
{
if (path1.length() == 0)
return path2;
if (path2.length() == 0)
return path1;
if (pathIsSeparator(path1[path1.length() - 1]))
return path1 + path2;
else
return path1 + pathSeparator() + path2;
}
size_t pathIndexOfFileName(const std::string & path)
{
size_t pos = path.rfind('/');
#ifdef _WIN32
size_t pos2 = path.rfind('\\');
if (pos2 != std::string::npos && (pos == std::string::npos || pos2 > pos))
pos = pos2;
if (pos == std::string::npos && pathIsWin32PathWithDriveLetter(path))
pos = 1;
#endif
return (pos != std::string::npos ? pos + 1 : 0);
}
std::string pathGetDirectory(const std::string & path)
{
size_t pos = pathIndexOfFileName(path);
if (pos > 0)
--pos;
return path.substr(0, pos);
}
std::string pathGetFileName(const std::string & path)
{
return path.substr(pathIndexOfFileName(path));
}
std::string pathGetShortFileExtension(const std::string & path)
{
size_t pos = path.rfind('.');
if (pos == std::string::npos)
return std::string();
size_t offset = pathIndexOfFileName(path);
if (pos < offset)
return std::string();
return path.substr(pos);
}
std::string pathGetFullFileExtension(const std::string & path)
{
size_t offset = pathIndexOfFileName(path);
size_t pos = path.find('.', offset);
return (pos == std::string::npos ? std::string() : path.substr(pos));
}
std::string pathReplaceFullFileExtension(const std::string & path, const std::string & ext)
{
size_t offset = pathIndexOfFileName(path);
size_t pos = path.find('.', offset);
return (pos == std::string::npos ? path + ext : path.substr(0, pos) + ext);
}
bool pathCreate(const std::string & path)
{
std::string dir = pathMakeAbsolute(path);
bool result = false;
size_t off = 0;
#ifndef _WIN32
if (pathIsSeparator(dir[0]))
off = 1;
else
{
std::stringstream ss;
ss << "invalid path '" << dir << "'.";
throw std::runtime_error(ss.str());
}
#else
if (pathIsWin32PathWithDriveLetter(dir))
off = 3;
else if (PathIsUNCA(dir.c_str()))
{
off = pathIndexOfFirstSeparator(dir, 2);
if (off == std::string::npos)
{
std::stringstream ss;
ss << "invalid path '" << dir << "'.";
throw std::runtime_error(ss.str());
}
++off;
}
else
{
std::stringstream ss;
ss << "invalid path '" << dir << "'.";
throw std::runtime_error(ss.str());
}
#endif
size_t end;
do
{
end = pathIndexOfFirstSeparator(dir, off);
off = end + 1;
std::string subdir;
if (end == std::string::npos)
subdir = dir;
else
subdir = dir.substr(0, end);
#ifndef _WIN32
if (mkdir(subdir.c_str(), 0755) == 0)
result = true;
else
{
int err = errno;
if (err != EEXIST)
{
std::stringstream ss;
ss << "unable to create directory '" << subdir << "': " << strerror(err);
throw std::runtime_error(ss.str());
}
}
#else
if (CreateDirectoryA(subdir.c_str(), nullptr))
result = true;
else
{
DWORD err = GetLastError();
if (err != ERROR_ALREADY_EXISTS)
{
std::stringstream ss;
ss << "unable to create directory '" << subdir << "' (code " << err << ").";
throw std::runtime_error(ss.str());
}
}
#endif
}
while (end != std::string::npos);
return result;
}
bool pathIsExistent(const std::string & path)
{
struct stat st;
int err = stat(path.c_str(), &st);
return (err == 0);
}
bool pathIsFile(const std::string & path)
{
#ifndef _WIN32
struct stat st;
int err = stat(path.c_str(), &st);
if (err < 0)
{
err = errno;
if (err == ENOENT)
return false;
std::stringstream ss;
ss << "unable to stat file '" << path << "': " << strerror(err);
throw std::runtime_error(ss.str());
}
return S_ISREG(st.st_mode);
#else
DWORD attr = GetFileAttributesA(path.c_str());
if (attr == INVALID_FILE_ATTRIBUTES)
{
DWORD err = GetLastError();
if (err = ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND ||
err == ERROR_INVALID_DRIVE || err == ERROR_BAD_NETPATH)
return false;
std::stringstream ss;
ss << "unable to get attributes for file '" << path << "' (code " << err << ").";
throw std::runtime_error(ss.str());
}
return (attr & (FILE_ATTRIBUTE_DEVICE | FILE_ATTRIBUTE_DIRECTORY)) == 0;
#endif
}
time_t pathGetModificationTime(const std::string & path)
{
struct stat st;
int err = stat(path.c_str(), &st);
if (err < 0)
{
err = errno;
std::stringstream ss;
ss << "unable to stat file '" << path << "': " << strerror(err);
throw std::runtime_error(ss.str());
}
return st.st_mtime;
}
std::string pathGetThisExecutableFile()
{
#ifdef _WIN32
char buf[MAX_PATH];
if (!GetModuleFileNameA(nullptr, buf, sizeof(buf)))
{
DWORD err = GetLastError();
std::stringstream ss;
ss << "unable to determine file name of executable file (code " << err << ").";
throw std::runtime_error(ss.str());
}
return buf;
#elif defined(__APPLE__)
uint32_t size = 0;
char tempChar = 0;
if (_NSGetExecutablePath(&tempChar, &size) >= 0 || size == 0)
{
throw std::runtime_error(
"unable to determine file name of executable file (_NSGetExecutablePath has weird behavior).");
}
std::vector<char> buf(size + 1);
if (_NSGetExecutablePath(buf.data(), &size) < 0)
{
throw std::runtime_error
("unable to determine file name of executable file (_NSGetExecutablePath has failed).");
}
return buf.data();
#elif defined(__linux__) || defined(__ANDROID__)
std::vector<char> buf(PATH_MAX + 1);
if (readlink("/proc/self/exe", buf.data(), PATH_MAX) < 0)
{
int err = errno;
std::stringstream ss;
ss << "unable to read link '/proc/self/exe': " << strerror(err);
throw std::runtime_error(ss.str());
}
return buf.data();
#elif defined(__FreeBSD__)
int mib[4] = {
CTL_KERN,
KERN_PROC,
KERN_PROC_PATHNAME,
-1
};
std::vector<char> buf(PATH_MAX + 1);
if (sysctl(mib, 4, buf, PATH_MAX, nullptr, 0) < 0)
{
int err = errno;
std::stringstream ss;
ss << "unable to determine file name of executable file: " << strerror(err);
throw std::runtime_error(ss.str());
}
return buf.data();
#elif defined(sun) || defined(__sun) || defined(SUNOS)
const char * path = getexecname();
if (!path || !*path)
throw std::runtime_error("unable to determine file name of executable file.");
return path;
#else
throw std::runtime_error("unable to determine file name of executable file (not implemented).");
#endif
}
std::string pathCreateSymLink(const std::string & from, const std::string & to)
{
#ifdef _WIN32
if (!CreateSymbolicLinkA(to.c_str(), from.c_str(), 0))
{
DWORD err = GetLastError();
std::stringstream ss;
ss << "unable to create symlink from '" << from << "' to '" << to << " (code " << err << ").";
throw std::runtime_error(ss.str());
}
#else
int r = symlink(from.c_str(), to.c_str());
if (r < 0)
{
int err = errno;
if (err == EEXIST)
{
std::vector<char> buf(PATH_MAX + 1);
if (readlink(to.c_str(), buf.data(), PATH_MAX) >= 0 && from == buf.data())
return to;
}
std::stringstream ss;
ss << "unable to create symlink from '" << from << "' to '" << to << "': " << strerror(err);
throw std::runtime_error(ss.str());
}
#endif
return to;
}
DirEntryList pathEnumDirectoryContents(const std::string & path)
{
DirEntryList list;
DIR * dir;
dir = opendir(path.c_str());
if (!dir)
{
int err = errno;
std::stringstream ss;
ss << "unable to enumerate contents of directory '" << path << "': " << strerror(err);
throw std::runtime_error(ss.str());
}
try
{
struct dirent * ent;
while ((ent = readdir(dir)) != nullptr)
{
DirEntry entry;
entry.name = ent->d_name;
if (entry.name == "." || entry.name == "..")
continue;
switch (ent->d_type)
{
case DT_REG: entry.type = DirEntry_RegularFile; break;
case DT_DIR: entry.type = DirEntry_Directory; break;
#ifndef _WIN32
case DT_FIFO: entry.type = DirEntry_FIFO; break;
case DT_SOCK: entry.type = DirEntry_Socket; break;
case DT_CHR: entry.type = DirEntry_CharDevice; break;
case DT_BLK: entry.type = DirEntry_BlockDevice; break;
case DT_LNK: entry.type = DirEntry_Link; break;
#endif
default: entry.type = DirEntry_Unknown; break;
}
list.push_back(entry);
}
}
catch (...)
{
closedir(dir);
throw;
}
closedir(dir);
return list;
}
void pathDeleteFile(const std::string & path)
{
#ifndef _WIN32
if (unlink(path.c_str()) < 0)
{
int err = errno;
std::stringstream ss;
ss << "unable to delete file '" << path << "': " << strerror(err);
throw std::runtime_error(ss.str());
}
#else
if (!DeleteFileA(path.c_str()))
{
DWORD err = GetLastError();
std::stringstream ss;
ss << "unable to delete file '" << path << "' (code " << err << ").";
throw std::runtime_error(ss.str());
}
#endif
}