Debian Codegraph @

Utilities/KWSys/Glob.cxx

raw
1 /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
2 file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
3 #include "kwsysPrivate.h"
4 #include KWSYS_HEADER(Glob.hxx)
5
6 #include KWSYS_HEADER(Configure.hxx)
7
8 #include KWSYS_HEADER(RegularExpression.hxx)
9 #include KWSYS_HEADER(SystemTools.hxx)
10 #include KWSYS_HEADER(Directory.hxx)
11
12 // Work-around CMake dependency scanning limitation. This must
13 // duplicate the above list of headers.
14 #if 0
15 # include "Configure.hxx.in"
16 # include "Directory.hxx.in"
17 # include "Glob.hxx.in"
18 # include "RegularExpression.hxx.in"
19 # include "SystemTools.hxx.in"
20 #endif
21
22 #include <algorithm>
23 #include <string>
24 #include <vector>
25
26 #include <cctype>
27 #include <cstdio>
28 #include <cstring>
29 namespace KWSYS_NAMESPACE {
30 #if defined(_WIN32) || defined(__APPLE__)
31 // On Windows and Apple, no difference between lower and upper case
32 # define KWSYS_GLOB_CASE_INDEPENDENT
33 #endif
34
35 #if defined(_WIN32) || defined(__CYGWIN__)
36 // Handle network paths
37 # define KWSYS_GLOB_SUPPORT_NETWORK_PATHS
38 #endif
39
40 class GlobInternals
41 {
42 public:
43 std::vector<std::string> Files;
44 std::vector<kwsys::RegularExpression> Expressions;
45 };
46
47 Glob::Glob()
48 {
49 this->Internals = new GlobInternals;
50 this->Recurse = false;
51 this->Relative = "";
52
53 this->RecurseThroughSymlinks = true;
54 // RecurseThroughSymlinks is true by default for backwards compatibility,
55 // not because it's a good idea...
56 this->FollowedSymlinkCount = 0;
57
58 // Keep separate variables for directory listing for back compatibility
59 this->ListDirs = true;
60 this->RecurseListDirs = false;
61 }
62
63 Glob::~Glob()
64 {
65 delete this->Internals;
66 }
67
68 std::vector<std::string>& Glob::GetFiles()
69 {
70 return this->Internals->Files;
71 }
72
73 std::string Glob::PatternToRegex(const std::string& pattern,
74 bool require_whole_string, bool preserve_case)
75 {
76 // Incrementally build the regular expression from the pattern.
77 std::string regex = require_whole_string ? "^" : "";
78 std::string::const_iterator pattern_first = pattern.begin();
79 std::string::const_iterator pattern_last = pattern.end();
80 for (std::string::const_iterator i = pattern_first; i != pattern_last; ++i) {
81 int c = *i;
82 if (c == '*') {
83 // A '*' (not between brackets) matches any string.
84 // We modify this to not match slashes since the original glob
85 // pattern documentation was meant for matching file name
86 // components separated by slashes.
87 regex += "[^/]*";
88 } else if (c == '?') {
89 // A '?' (not between brackets) matches any single character.
90 // We modify this to not match slashes since the original glob
91 // pattern documentation was meant for matching file name
92 // components separated by slashes.
93 regex += "[^/]";
94 } else if (c == '[') {
95 // Parse out the bracket expression. It begins just after the
96 // opening character.
97 std::string::const_iterator bracket_first = i + 1;
98 std::string::const_iterator bracket_last = bracket_first;
99
100 // The first character may be complementation '!' or '^'.
101 if (bracket_last != pattern_last &&
102 (*bracket_last == '!' || *bracket_last == '^')) {
103 ++bracket_last;
104 }
105
106 // If the next character is a ']' it is included in the brackets
107 // because the bracket string may not be empty.
108 if (bracket_last != pattern_last && *bracket_last == ']') {
109 ++bracket_last;
110 }
111
112 // Search for the closing ']'.
113 while (bracket_last != pattern_last && *bracket_last != ']') {
114 ++bracket_last;
115 }
116
117 // Check whether we have a complete bracket string.
118 if (bracket_last == pattern_last) {
119 // The bracket string did not end, so it was opened simply by
120 // a '[' that is supposed to be matched literally.
121 regex += "\\[";
122 } else {
123 // Convert the bracket string to its regex equivalent.
124 std::string::const_iterator k = bracket_first;
125
126 // Open the regex block.
127 regex += "[";
128
129 // A regex range complement uses '^' instead of '!'.
130 if (k != bracket_last && *k == '!') {
131 regex += "^";
132 ++k;
133 }
134
135 // Convert the remaining characters.
136 for (; k != bracket_last; ++k) {
137 // Backslashes must be escaped.
138 if (*k == '\\') {
139 regex += "\\";
140 }
141
142 // Store this character.
143 regex += *k;
144 }
145
146 // Close the regex block.
147 regex += "]";
148
149 // Jump to the end of the bracket string.
150 i = bracket_last;
151 }
152 } else {
153 // A single character matches itself.
154 int ch = c;
155 if (!(('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
156 ('0' <= ch && ch <= '9'))) {
157 // Escape the non-alphanumeric character.
158 regex += "\\";
159 }
160 #if defined(KWSYS_GLOB_CASE_INDEPENDENT)
161 else {
162 // On case-insensitive systems file names are converted to lower
163 // case before matching.
164 if (!preserve_case) {
165 ch = tolower(ch);
166 }
167 }
168 #endif
169 (void)preserve_case;
170 // Store the character.
171 regex.append(1, static_cast<char>(ch));
172 }
173 }
174
175 if (require_whole_string) {
176 regex += "$";
177 }
178 return regex;
179 }
180
181 bool Glob::RecurseDirectory(std::string::size_type start,
182 const std::string& dir, GlobMessages* messages)
183 {
184 kwsys::Directory d;
185 std::string errorMessage;
186 if (!d.Load(dir, &errorMessage)) {
187 if (messages) {
188 if (!errorMessage.empty()) {
189 messages->push_back(Message(Glob::warning,
190 "Error listing directory '" + dir +
191 "'! Reason: '" + errorMessage + "'"));
192 }
193 }
194 return true;
195 }
196 unsigned long cc;
197 std::string realname;
198 std::string fname;
199 for (cc = 0; cc < d.GetNumberOfFiles(); cc++) {
200 fname = d.GetFile(cc);
201 if (fname == "." || fname == "..") {
202 continue;
203 }
204
205 if (start == 0) {
206 realname = dir + fname;
207 } else {
208 realname = dir + "/" + fname;
209 }
210
211 #if defined(KWSYS_GLOB_CASE_INDEPENDENT)
212 // On Windows and Apple, no difference between lower and upper case
213 fname = kwsys::SystemTools::LowerCase(fname);
214 #endif
215
216 bool isDir = d.FileIsDirectory(cc);
217 bool isSymLink = d.FileIsSymlink(cc);
218
219 if (isDir && (!isSymLink || this->RecurseThroughSymlinks)) {
220 if (isSymLink) {
221 ++this->FollowedSymlinkCount;
222 std::string realPathErrorMessage;
223 std::string canonicalPath(
224 SystemTools::GetRealPath(dir, &realPathErrorMessage));
225
226 if (!realPathErrorMessage.empty()) {
227 if (messages) {
228 messages->push_back(
229 Message(Glob::error,
230 "Canonical path generation from path '" + dir +
231 "' failed! Reason: '" + realPathErrorMessage + "'"));
232 }
233 return false;
234 }
235
236 if (std::find(this->VisitedSymlinks.begin(),
237 this->VisitedSymlinks.end(),
238 canonicalPath) == this->VisitedSymlinks.end()) {
239 if (this->RecurseListDirs) {
240 // symlinks are treated as directories
241 this->AddFile(this->Internals->Files, realname);
242 }
243
244 this->VisitedSymlinks.push_back(canonicalPath);
245 if (!this->RecurseDirectory(start + 1, realname, messages)) {
246 this->VisitedSymlinks.pop_back();
247
248 return false;
249 }
250 this->VisitedSymlinks.pop_back();
251 }
252 // else we have already visited this symlink - prevent cyclic recursion
253 else if (messages) {
254 std::string message;
255 for (std::vector<std::string>::const_iterator pathIt =
256 std::find(this->VisitedSymlinks.begin(),
257 this->VisitedSymlinks.end(), canonicalPath);
258 pathIt != this->VisitedSymlinks.end(); ++pathIt) {
259 message += *pathIt + "\n";
260 }
261 message += canonicalPath + "/" + fname;
262 messages->push_back(Message(Glob::cyclicRecursion, message));
263 }
264 } else {
265 if (this->RecurseListDirs) {
266 this->AddFile(this->Internals->Files, realname);
267 }
268 if (!this->RecurseDirectory(start + 1, realname, messages)) {
269 return false;
270 }
271 }
272 } else {
273 if (!this->Internals->Expressions.empty() &&
274 this->Internals->Expressions.back().find(fname)) {
275 this->AddFile(this->Internals->Files, realname);
276 }
277 }
278 }
279
280 return true;
281 }
282
283 void Glob::ProcessDirectory(std::string::size_type start,
284 const std::string& dir, GlobMessages* messages)
285 {
286 // std::cout << "ProcessDirectory: " << dir << std::endl;
287 bool last = (start == this->Internals->Expressions.size() - 1);
288 if (last && this->Recurse) {
289 if (kwsys::SystemTools::FileIsDirectory(dir)) {
290 this->RecurseDirectory(start, dir, messages);
291 }
292 return;
293 }
294
295 if (start >= this->Internals->Expressions.size()) {
296 return;
297 }
298
299 kwsys::Directory d;
300 if (!d.Load(dir)) {
301 return;
302 }
303 unsigned long cc;
304 std::string realname;
305 std::string fname;
306 for (cc = 0; cc < d.GetNumberOfFiles(); cc++) {
307 fname = d.GetFile(cc);
308 if (fname == "." || fname == "..") {
309 continue;
310 }
311
312 if (start == 0) {
313 realname = dir + fname;
314 } else {
315 realname = dir + "/" + fname;
316 }
317
318 #if defined(KWSYS_GLOB_CASE_INDEPENDENT)
319 // On case-insensitive file systems convert to lower case for matching.
320 fname = kwsys::SystemTools::LowerCase(fname);
321 #endif
322
323 // std::cout << "Look at file: " << fname << std::endl;
324 // std::cout << "Match: "
325 // << this->Internals->TextExpressions[start].c_str() << std::endl;
326 // std::cout << "Real name: " << realname << std::endl;
327
328 if ((!last && !kwsys::SystemTools::FileIsDirectory(realname)) ||
329 (!this->ListDirs && last &&
330 kwsys::SystemTools::FileIsDirectory(realname))) {
331 continue;
332 }
333
334 if (this->Internals->Expressions[start].find(fname)) {
335 if (last) {
336 this->AddFile(this->Internals->Files, realname);
337 } else {
338 this->ProcessDirectory(start + 1, realname, messages);
339 }
340 }
341 }
342 }
343
344 bool Glob::FindFiles(const std::string& inexpr, GlobMessages* messages)
345 {
346 std::string cexpr;
347 std::string::size_type cc;
348 std::string expr = inexpr;
349
350 this->Internals->Expressions.clear();
351 this->Internals->Files.clear();
352
353 if (!kwsys::SystemTools::FileIsFullPath(expr)) {
354 expr = kwsys::SystemTools::GetCurrentWorkingDirectory();
355 expr += "/" + inexpr;
356 }
357 std::string fexpr = expr;
358
359 std::string::size_type skip = 0;
360 std::string::size_type last_slash = 0;
361 for (cc = 0; cc < expr.size(); cc++) {
362 if (cc > 0 && expr[cc] == '/' && expr[cc - 1] != '\\') {
363 last_slash = cc;
364 }
365 if (cc > 0 && (expr[cc] == '[' || expr[cc] == '?' || expr[cc] == '*') &&
366 expr[cc - 1] != '\\') {
367 break;
368 }
369 }
370 if (last_slash > 0) {
371 // std::cout << "I can skip: " << fexpr.substr(0, last_slash)
372 // << std::endl;
373 skip = last_slash;
374 }
375 if (skip == 0) {
376 #if defined(KWSYS_GLOB_SUPPORT_NETWORK_PATHS)
377 // Handle network paths
378 if (expr[0] == '/' && expr[1] == '/') {
379 int cnt = 0;
380 for (cc = 2; cc < expr.size(); cc++) {
381 if (expr[cc] == '/') {
382 cnt++;
383 if (cnt == 2) {
384 break;
385 }
386 }
387 }
388 skip = int(cc + 1);
389 } else
390 #endif
391 // Handle drive letters on Windows
392 if (expr[1] == ':' && expr[0] != '/') {
393 skip = 2;
394 }
395 }
396
397 if (skip > 0) {
398 expr.erase(0, skip);
399 }
400
401 for (cc = 0; cc < expr.size(); cc++) {
402 int ch = expr[cc];
403 if (ch == '/') {
404 if (!cexpr.empty()) {
405 this->AddExpression(cexpr);
406 }
407 cexpr = "";
408 } else {
409 cexpr.append(1, static_cast<char>(ch));
410 }
411 }
412 if (!cexpr.empty()) {
413 this->AddExpression(cexpr);
414 }
415
416 // Handle network paths
417 if (skip > 0) {
418 this->ProcessDirectory(0, fexpr.substr(0, skip) + "/", messages);
419 } else {
420 this->ProcessDirectory(0, "/", messages);
421 }
422 return true;
423 }
424
425 void Glob::AddExpression(const std::string& expr)
426 {
427 this->Internals->Expressions.emplace_back(this->PatternToRegex(expr));
428 }
429
430 void Glob::SetRelative(const char* dir)
431 {
432 if (!dir) {
433 this->Relative = "";
434 return;
435 }
436 this->Relative = dir;
437 }
438
439 const char* Glob::GetRelative()
440 {
441 if (this->Relative.empty()) {
442 return nullptr;
443 }
444 return this->Relative.c_str();
445 }
446
447 void Glob::AddFile(std::vector<std::string>& files, const std::string& file)
448 {
449 if (!this->Relative.empty()) {
450 files.push_back(kwsys::SystemTools::RelativePath(this->Relative, file));
451 } else {
452 files.push_back(file);
453 }
454 }
455
456 } // namespace KWSYS_NAMESPACE