Skip to content

Commit a64b023

Browse files
committed
Optimise directory traversal
1 parent 07c33b3 commit a64b023

File tree

1 file changed

+17
-31
lines changed

1 file changed

+17
-31
lines changed

include/file_collector.h

Lines changed: 17 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,6 @@ class FileCollector {
1818
int verbosity;
1919

2020
void collectFromDirectory(const std::string& dirPath, int currentDepth = 0) {
21-
// Check depth limit
22-
if (maxDepth >= 0 && currentDepth > maxDepth) {
23-
if (verbosity >= 2) {
24-
std::cout << "Skipping directory (depth limit): " << dirPath << std::endl;
25-
}
26-
return;
27-
}
28-
2921
if (verbosity >= 1) {
3022
std::cout << "Scanning directory: " << dirPath << " (depth " << currentDepth << ")" << std::endl;
3123
}
@@ -37,36 +29,30 @@ class FileCollector {
3729
}
3830

3931
struct dirent* entry;
40-
std::vector<std::string> dirEntries; // Collect entries first
4132
while ((entry = readdir(dir)) != nullptr) {
4233
std::string filename = entry->d_name;
4334
if (filename != "." && filename != "..") {
44-
dirEntries.push_back(filename);
45-
}
46-
}
47-
closedir(dir);
48-
49-
// Sort entries for deterministic processing order
50-
std::sort(dirEntries.begin(), dirEntries.end());
51-
52-
// Process sorted entries
53-
for (const std::string& filename : dirEntries) {
54-
std::string fullPath = dirPath + "/" + filename;
55-
if (FileUtils::isDirectory(fullPath)) {
56-
if (recursive) {
57-
collectFromDirectory(fullPath, currentDepth + 1);
58-
}
59-
} else {
60-
if (FileUtils::matchesExtension(filename, extensionFilter)) {
61-
if (verbosity >= 2) {
62-
std::cout << " Found file: " << fullPath << std::endl;
35+
std::string fullPath = dirPath + "/" + filename;
36+
if (FileUtils::isDirectory(fullPath)) {
37+
// Check depth limit BEFORE recursing to avoid unnecessary work
38+
if (recursive && (maxDepth < 0 || currentDepth < maxDepth)) {
39+
collectFromDirectory(fullPath, currentDepth + 1);
40+
} else if (verbosity >= 2 && recursive && maxDepth >= 0) {
41+
std::cout << " Skipping subdirectory (depth limit): " << fullPath << std::endl;
42+
}
43+
} else {
44+
if (FileUtils::matchesExtension(filename, extensionFilter)) {
45+
if (verbosity >= 2) {
46+
std::cout << " Found file: " << fullPath << std::endl;
47+
}
48+
files.push_back(fullPath);
49+
} else if (verbosity >= 2 && !extensionFilter.empty()) {
50+
std::cout << " Skipping (extension): " << fullPath << std::endl;
6351
}
64-
files.push_back(fullPath);
65-
} else if (verbosity >= 2 && !extensionFilter.empty()) {
66-
std::cout << " Skipping (extension): " << fullPath << std::endl;
6752
}
6853
}
6954
}
55+
closedir(dir);
7056
}
7157

7258
public:

0 commit comments

Comments
 (0)