From 0e2ab0500092dfb4c2ca6990b3a31e573be991b4 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Mon, 13 Jun 2022 15:50:59 +0200 Subject: [PATCH] libsolutil: Adding findFilesRecursively() helper to find files recursively. --- libsolutil/CommonIO.h | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/libsolutil/CommonIO.h b/libsolutil/CommonIO.h index e6cd0c161..56f62f0ac 100644 --- a/libsolutil/CommonIO.h +++ b/libsolutil/CommonIO.h @@ -48,6 +48,46 @@ inline std::ostream& operator<<(std::ostream& os, bytes const& _bytes) namespace util { +namespace detail +{ + +template +struct RecursiveFileCollector +{ + Predicate predicate; + std::vector result {}; + + RecursiveFileCollector& operator()(boost::filesystem::path const& _directory) + { + if (!boost::filesystem::is_directory(_directory)) + return *this; + auto iterator = boost::filesystem::directory_iterator(_directory); + auto const iteratorEnd = boost::filesystem::directory_iterator(); + + while (iterator != iteratorEnd) + { + if (boost::filesystem::is_directory(iterator->status())) + (*this)(iterator->path()); + + if (predicate(iterator->path())) + result.push_back(iterator->path()); + + ++iterator; + } + return *this; + } +}; + +template +RecursiveFileCollector(Predicate) -> RecursiveFileCollector; +} + +template +std::vector findFilesRecursively(boost::filesystem::path const& _rootDirectory, Predicate _predicate) +{ + return detail::RecursiveFileCollector{_predicate}(_rootDirectory).result; +} + /// Retrieves and returns the contents of the given file as a std::string. /// If the file doesn't exist, it will throw a FileNotFound exception. /// If the file exists but is not a regular file, it will throw NotAFile exception.