-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathFileWatcher.hpp
More file actions
75 lines (61 loc) · 2.39 KB
/
FileWatcher.hpp
File metadata and controls
75 lines (61 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#pragma once
#include <filesystem>
#include <chrono>
#include <thread>
#include <unordered_map>
#include <functional>
#include <Geode/Geode.hpp>
#include "Macros.hpp"
using namespace geode::prelude;
/**
* https://github.com/sol-prog/cpp17-filewatcher/blob/master/FileWatcher.h
*/
enum class FileStatus {created, modified, erased};
class FileWatcher {
public:
FileWatcher(std::filesystem::path pathToWatch, std::chrono::duration<int, std::milli> delay) : m_pathToWatch(pathToWatch), m_delay{delay} {
if (std::filesystem::is_directory(pathToWatch)) {
for (auto& file : std::filesystem::recursive_directory_iterator(pathToWatch)) {
m_paths[file.path()] = std::filesystem::last_write_time(file);
}
}
}
void stop() {
m_running = false;
}
void start(const std::function<void (std::filesystem::path, FileStatus)> &action) {
while (m_running) {
std::this_thread::sleep_for(m_delay);
if (std::filesystem::is_directory(m_pathToWatch)) {
auto it = m_paths.begin();
while (it != m_paths.end()) {
if (!std::filesystem::exists(it->first)) {
action(it->first, FileStatus::erased);
it = m_paths.erase(it);
}
else it++;
}
for (auto& file : std::filesystem::recursive_directory_iterator(m_pathToWatch)) {
auto currentFileLastWriteTime = std::filesystem::last_write_time(file);
if (!contains(file.path())) {
m_paths[file.path()] = currentFileLastWriteTime;
action(file.path(), FileStatus::created);
} else if (m_paths[file.path()] != currentFileLastWriteTime) {
m_paths[file.path()] = currentFileLastWriteTime;
action(file.path(), FileStatus::modified);
}
}
}
}
delete this;
}
private:
std::unordered_map<std::filesystem::path, std::filesystem::file_time_type> m_paths;
std::chrono::duration<int, std::milli> m_delay;
std::filesystem::path m_pathToWatch = "";
bool m_running = true;
bool contains(const std::filesystem::path &key) {
auto el = m_paths.find(key);
return el != m_paths.end();
}
};