Debian Codegraph @

src/utils.cc

raw
1 #include <cctype>
2 #include <cstddef>
3 #include <string>
4
5 #include "utils.h"
6 #include "error.h"
7
8 // If dirent is not unknown, just return it, otherwise stat the file and get
9 // the filetype from that.
10 uv_dirent_type_t get_dirent_type(
11 const char* path, const uv_dirent_type_t& entry_type, bool fail) {
12 if (entry_type == UV_DIRENT_UNKNOWN) {
13 uv_fs_t req;
14 uv_fs_lstat(uv_default_loop(), &req, path, NULL);
15 if (!fail && warn_for_error(req, "Failed to stat '%s'", path)) {
16 return UV_DIRENT_UNKNOWN;
17 }
18 stop_for_error(req, "Failed to stat '%s'", path);
19 uv_dirent_type_t type;
20 switch (req.statbuf.st_mode & S_IFMT) {
21 case S_IFBLK:
22 type = UV_DIRENT_BLOCK;
23 break;
24 case S_IFCHR:
25 type = UV_DIRENT_CHAR;
26 break;
27 case S_IFDIR:
28 type = UV_DIRENT_DIR;
29 break;
30 case S_IFIFO:
31 type = UV_DIRENT_FIFO;
32 break;
33 case S_IFLNK:
34 type = UV_DIRENT_LINK;
35 break;
36 case S_IFREG:
37 type = UV_DIRENT_FILE;
38 break;
39 #ifndef __WIN32
40 case S_IFSOCK:
41 type = UV_DIRENT_SOCKET;
42 break;
43 #endif
44 default:
45 type = UV_DIRENT_UNKNOWN;
46 break;
47 }
48 uv_fs_req_cleanup(&req);
49 return type;
50 }
51
52 return entry_type;
53 }
54
55 bool is_windows_path(const std::string& x) {
56 if (x.length() < 2) {
57 return false;
58 }
59 char first = x.at(0);
60
61 return ((first >= 'A' && first <= 'Z') || (first >= 'a' && first <= 'z')) &&
62 x.at(1) == ':';
63 }
64
65 std::string path_tidy_(const std::string& in) {
66 std::string out;
67 out.reserve(in.size());
68 char prev = '\0';
69 size_t i = 0;
70 size_t n = in.length();
71 while (i < n) {
72 char curr = in.at(i++);
73
74 // convert `\\` to `/`
75 if (curr == '\\') {
76 curr = '/';
77 }
78
79 // convert multiple // to single /, as long as they are not at the start
80 // (when they could be UNC paths).
81 if (i > 2 && prev == '/' && curr == '/') {
82 while (i < n && prev == '/' && curr == '/') {
83 prev = curr;
84 curr = in.at(i++);
85 }
86 if (i == n && curr == '/') {
87 break;
88 }
89 }
90
91 prev = curr;
92 out.push_back(prev);
93 }
94
95 if (is_windows_path(out)) {
96 // Ensure the first letter is capitalized
97 out[0] = toupper(out[0]);
98
99 // Append a / if this is a root path
100 if (out.length() == 2) {
101 out.push_back('/');
102 } else if (out.length() > 3 && *out.rbegin() == '/') {
103 out.erase(out.end() - 1);
104 }
105 return out;
106 }
107
108 // Remove trailing / from paths (that aren't also the beginning)
109 if (out.length() > 1 && *out.rbegin() == '/') {
110 out.erase(out.end() - 1);
111 }
112
113 return out;
114 }