From 0b09242ac025f0c2bd0c7d1ce33c742ff5d484de Mon Sep 17 00:00:00 2001 From: anulax1225 Date: Sun, 24 Mar 2024 19:11:36 +0100 Subject: [PATCH] Created a basic file watcher --- src/bakatools/file_system/file_watcher.cpp | 47 ++++++++++++++++++++++ src/bakatools/file_system/file_watcher.h | 27 +++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 src/bakatools/file_system/file_watcher.cpp create mode 100644 src/bakatools/file_system/file_watcher.h diff --git a/src/bakatools/file_system/file_watcher.cpp b/src/bakatools/file_system/file_watcher.cpp new file mode 100644 index 0000000..4adc842 --- /dev/null +++ b/src/bakatools/file_system/file_watcher.cpp @@ -0,0 +1,47 @@ +#include "file_watcher.h" + +FileWatcher::FileWatcher(std::string path, TimeSpan ts) +: target(path), ttm(ts) +{ + for (const std::filesystem::directory_entry& file : std::filesystem::recursive_directory_iterator(target)) + paths[file.path().string()] = std::filesystem::last_write_time(file); +} + +FileWatcher::~FileWatcher() { stop(); } + +void FileWatcher::start(const std::function& action) +{ + std::function task([&]() + { + auto it = paths.begin(); + while (it != paths.end()) + { + if (!std::filesystem::exists(it->first)) + { + action(it->first, FileStatus::Deleted); + it = paths.erase(it); + } + else it++; + } + for (const std::filesystem::directory_entry& file : std::filesystem::recursive_directory_iterator(target)) + { + auto current_file_last_write_time = std::filesystem::last_write_time(file); + if (contains(file.path().string())) + { + if(paths[file.path().string()] != current_file_last_write_time) { + paths[file.path().string()] = current_file_last_write_time; + action(file.path().string(), FileStatus::Modified); + } + } else + { + paths[file.path().string()] = current_file_last_write_time; + action(file.path().string(), FileStatus::Created); + } + } + }); + ttm.start(std::make_unique>(task)); +} + +void FileWatcher::stop() { ttm.stop(); } + +bool FileWatcher::contains(std::string path) { return paths.find(path) != paths.end(); } \ No newline at end of file diff --git a/src/bakatools/file_system/file_watcher.h b/src/bakatools/file_system/file_watcher.h new file mode 100644 index 0000000..6def1e0 --- /dev/null +++ b/src/bakatools/file_system/file_watcher.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include + +enum class FileStatus +{ + Created = 0, + Modified = 1, + Deleted = 2, +}; + +class FileWatcher +{ + public: + FileWatcher(std::string path, TimeSpan ts); + ~FileWatcher(); + + void start(const std::function& action); + void stop(); + bool contains(std::string path); + + private: + std::string target; + std::unordered_map paths; + TaskTimer ttm; +}; \ No newline at end of file