91 lines
2.6 KiB
C++
91 lines
2.6 KiB
C++
|
/**
|
||
|
* @file monitor.hpp
|
||
|
* A dir_monitor wrapper for specific paths
|
||
|
*
|
||
|
* @author Tobias Schmidl
|
||
|
* @copyright Copyright © 2022, Tobias Schmidl
|
||
|
* SPDX-License-Identifier: MIT
|
||
|
*/
|
||
|
|
||
|
#pragma once
|
||
|
#include <dir_monitor/dir_monitor.hpp>
|
||
|
#include <filesystem>
|
||
|
#include <regex>
|
||
|
|
||
|
namespace collector::monitor {
|
||
|
|
||
|
class Monitor
|
||
|
{
|
||
|
private:
|
||
|
boost::asio::dir_monitor _monitor;
|
||
|
std::filesystem::path _root_path;
|
||
|
|
||
|
public:
|
||
|
explicit Monitor(boost::asio::io_service& io_service,
|
||
|
std::filesystem::path&& root_path)
|
||
|
: _monitor(io_service)
|
||
|
, _root_path(std::move(root_path))
|
||
|
{
|
||
|
_monitor.add_directory(_root_path);
|
||
|
for (const auto& dir_entry :
|
||
|
std::filesystem::recursive_directory_iterator(_root_path)) {
|
||
|
if (dir_entry.is_directory())
|
||
|
_monitor.add_directory(dir_entry.path());
|
||
|
}
|
||
|
}
|
||
|
|
||
|
explicit Monitor(boost::asio::io_service& io_service,
|
||
|
const std::filesystem::path& root_path)
|
||
|
: _monitor(io_service)
|
||
|
, _root_path(root_path)
|
||
|
{
|
||
|
_monitor.add_directory(_root_path);
|
||
|
for (const auto& dir_entry :
|
||
|
std::filesystem::recursive_directory_iterator(_root_path)) {
|
||
|
if (dir_entry.is_directory())
|
||
|
_monitor.add_directory(dir_entry.path());
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* watches any for any event that matches the given search_pattern
|
||
|
*/
|
||
|
boost::asio::dir_monitor_event watch(const std::regex& search_pattern)
|
||
|
{
|
||
|
boost::asio::dir_monitor_event monitored_event;
|
||
|
do {
|
||
|
monitored_event = _monitor.monitor();
|
||
|
} while (!std::regex_match(
|
||
|
monitored_event.path.filename().generic_string(), search_pattern));
|
||
|
return monitored_event;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* watches any for the specified event_type that also matches the given
|
||
|
* search_pattern
|
||
|
*/
|
||
|
boost::asio::dir_monitor_event watch(
|
||
|
const std::regex& search_pattern,
|
||
|
const boost::asio::dir_monitor_event::event_type event_type)
|
||
|
{
|
||
|
boost::asio::dir_monitor_event monitored_event;
|
||
|
do {
|
||
|
monitored_event = _monitor.monitor();
|
||
|
} while (
|
||
|
!std::regex_match(monitored_event.path.filename().generic_string(),
|
||
|
search_pattern) ||
|
||
|
monitored_event.type != event_type);
|
||
|
return monitored_event;
|
||
|
}
|
||
|
|
||
|
const auto& get_root_path() const { return _root_path; }
|
||
|
virtual ~Monitor() = default;
|
||
|
|
||
|
Monitor() = delete;
|
||
|
Monitor(Monitor&& other) = delete;
|
||
|
Monitor(const Monitor& other) = delete;
|
||
|
Monitor& operator=(Monitor&& other) = delete;
|
||
|
Monitor& operator=(const Monitor& other) = delete;
|
||
|
};
|
||
|
}
|