Skip to content

Commit b8e0a7d

Browse files
committed
fdsdump: add glob methods to common
1 parent 99a792b commit b8e0a7d

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/tools/fdsdump/src/common/common.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,12 @@
88
*/
99

1010
#include <common/common.hpp>
11+
1112
#include <algorithm>
13+
#include <memory>
14+
#include <stdexcept>
1215

16+
#include <glob.h>
1317

1418
namespace fdsdump {
1519

@@ -130,4 +134,52 @@ memcpy_bits(uint8_t *dst, uint8_t *src, unsigned int n_bits)
130134
}
131135
}
132136

137+
std::vector<std::string>
138+
glob_files(const std::string &pattern)
139+
{
140+
glob_t globbuf = {};
141+
const int flags = GLOB_MARK | GLOB_BRACE | GLOB_TILDE;
142+
int ret = glob(pattern.c_str(), flags, NULL, &globbuf);
143+
switch (ret) {
144+
case 0:
145+
break;
146+
case GLOB_NOMATCH:
147+
return {};
148+
case GLOB_NOSPACE:
149+
throw std::bad_alloc();
150+
case GLOB_ABORTED:
151+
throw std::runtime_error("glob() failed: GLOB_ABORTED");
152+
default:
153+
throw std::runtime_error("glob() failed: " + std::to_string(ret));
154+
}
155+
156+
std::unique_ptr<glob_t, decltype(&globfree)> glob_ptr{&globbuf, &globfree};
157+
std::vector<std::string> files;
158+
159+
for (size_t i = 0; i < globbuf.gl_pathc; i++) {
160+
std::string filename = globbuf.gl_pathv[i];
161+
162+
if (filename.back() == '/') {
163+
// Skip directories
164+
continue;
165+
}
166+
167+
files.push_back(std::move(filename));
168+
}
169+
170+
return files;
171+
}
172+
173+
std::vector<std::string>
174+
glob_files(const std::vector<std::string> &patterns)
175+
{
176+
std::vector<std::string> files;
177+
for (const auto &pattern : patterns) {
178+
for (const auto &file : glob_files(pattern)) {
179+
files.push_back(file);
180+
}
181+
}
182+
return files;
183+
}
184+
133185
} // fdsdump

src/tools/fdsdump/src/common/common.hpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,4 +144,10 @@ parse_number(const std::string &s)
144144
return value;
145145
}
146146

147+
std::vector<std::string>
148+
glob_files(const std::string &pattern);
149+
150+
std::vector<std::string>
151+
glob_files(const std::vector<std::string> &patterns);
152+
147153
} // fdsdump

0 commit comments

Comments
 (0)