Initial commit

This commit is contained in:
faumaray committed 2026-02-01 23:07:06 +03:00
commit 8b8a7f4f9a
17 files changed
+4930

No files matched your search

+94
View File
@@ -0,0 +1,94 @@
#include "echoion/plugin/FileWatcher.hpp"
#include <format>
#include <iostream>
#include <chrono>
namespace Echoion::Plugin {
FileWatcher::FileWatcher() = default;
FileWatcher::~FileWatcher() {
stopWatching();
}
void FileWatcher::startWatching(
const std::filesystem::path& filePath,
ChangeCallback callback,
std::chrono::milliseconds intervalMs) {
std::lock_guard<std::mutex> lock(mutex_);
if (watching_.load()) {
stopWatching();
}
watchedPath_ = filePath;
callback_ = std::move(callback);
intervalMs_ = intervalMs;
stopRequested_ = false;
// Get initial file state
if (std::filesystem::exists(watchedPath_)) {
lastWriteTime_ = std::filesystem::last_write_time(watchedPath_);
lastFileSize_ = std::filesystem::file_size(watchedPath_);
}
watching_ = true;
watchThread_ = std::thread(&FileWatcher::watchLoop, this);
}
void FileWatcher::stopWatching() {
stopRequested_ = true;
if (watchThread_.joinable()) {
watchThread_.join();
}
watching_ = false;
}
bool FileWatcher::isWatching() const noexcept {
return watching_.load();
}
void FileWatcher::watchLoop() {
while (!stopRequested_.load()) {
// Sleep first to avoid checking immediately
std::this_thread::sleep_for(intervalMs_);
if (stopRequested_.load()) {
break;
}
std::lock_guard<std::mutex> lock(mutex_);
if (!std::filesystem::exists(watchedPath_)) {
continue;
}
try {
auto currentWriteTime = std::filesystem::last_write_time(watchedPath_);
auto currentFileSize = std::filesystem::file_size(watchedPath_);
// Check if file has changed (time or size)
if (currentWriteTime != lastWriteTime_ || currentFileSize != lastFileSize_) {
// Update stored values
lastWriteTime_ = currentWriteTime;
lastFileSize_ = currentFileSize;
// Trigger callback
if (callback_) {
try {
callback_();
} catch (const std::exception& e) {
std::cerr << std::format("FileWatcher callback error: {}", e.what()) << std::endl;
}
}
}
} catch (const std::exception& e) {
// Ignore errors (file might be locked during write)
}
}
}
} // namespace Echoion::Plugin