-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWatcher.mpp
More file actions
266 lines (243 loc) · 8.24 KB
/
Watcher.mpp
File metadata and controls
266 lines (243 loc) · 8.24 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
module;
#include <CppUtils/System/OS.hpp>
#include <CppUtils/System/Windows.hpp>
#if defined(OS_LINUX)
# include <cerrno>
# include <unistd.h>
# include <sys/epoll.h>
# include <sys/inotify.h>
#elif defined(OS_MACOS)
# include <sys/event.h>
# include <CoreServices/CoreServices.h>
#endif
export module CppUtils.FileSystem.Watcher;
import std;
import CppUtils.Chrono;
import CppUtils.Container;
import CppUtils.FileSystem.Event;
import CppUtils.FileSystem.Directory;
import CppUtils.System;
import CppUtils.Thread;
import CppUtils.Type;
/* Todo:
Windows: FindFirstChangeNotification -> https://learn.microsoft.com/fr-fr/windows/win32/api/fileapi/nf-fileapi-findfirstchangenotificationa?redirectedfrom=MSDN
MacOS: FSEvents (privilégié à kqueue) -> https://stackoverflow.com/a/11557250
exceptions -> std::expected
*/
export namespace CppUtils::FileSystem
{
class Watcher final
{
static inline constexpr auto maxEvents = 2uz;
public:
#if defined(OS_LINUX)
using SubscribeFunction = std::function<void(Event, const std::filesystem::path&)>;
using WatchDescriptor = int;
#endif
inline Watcher():
m_threadLoop{std::bind(&Watcher::listener, this), std::bind(&Watcher::interruptFunction, this)}
{
auto lockGuard = std::unique_lock{m_mutex};
#if defined(OS_LINUX)
m_eventPoll = epoll_create1(0);
{
m_inotify = inotify_init1(IN_NONBLOCK);
m_event.events = EPOLLIN | EPOLLET;
m_event.data.fd = m_inotify;
System::throwErrno(
epoll_ctl(m_eventPoll, EPOLL_CTL_ADD, m_inotify, std::addressof(m_event)),
"Can't add inotify file descriptor to epoll");
}
{
m_stopEvent.events = EPOLLIN | EPOLLET;
m_stopEvent.data.fd = m_stopPipe.read;
System::throwErrno(
epoll_ctl(m_eventPoll, EPOLL_CTL_ADD, m_stopPipe.read, std::addressof(m_stopEvent)),
"Can't add pipe file descriptor to epoll");
}
#elif defined(OS_MACOS)
/*
m_filesystemEventStream = FSEventStreamCreate(CFAllocatorRef allocator,
FSEventStreamCallback callback,
FSEventStreamContext * context,
CFArrayRef pathsToWatch,
FSEventStreamEventId sinceWhen,
CFTimeInterval latency,
FSEventStreamCreateFlags flags);
*/
#endif
start();
}
~Watcher()
{
stop();
// unwatchAll(); // Déjà fait par linux via close(m_inotify);
#if defined(OS_LINUX)
epoll_ctl(m_eventPoll, EPOLL_CTL_DEL, m_inotify, 0);
epoll_ctl(m_eventPoll, EPOLL_CTL_DEL, m_stopPipe.read, 0);
#endif
}
[[nodiscard]] inline auto isRunning() const noexcept -> bool
{
return m_threadLoop.isRunning();
}
inline auto start() -> void
{
m_threadLoop.start();
}
inline auto stop() -> void
{
m_threadLoop.stop();
}
inline auto listener() -> void
{
#if defined(OS_WINDOWS)
switch (WaitForMultipleObjects(static_cast<DWORD>(std::size(m_changeHandles)), std::data(m_changeHandles), false, INFINITE))
{
case WAIT_OBJECT_0: // An event occurred on a file
System::throwLastErrorIf(not FindNextChangeNotification(m_changeHandles[0]), "FindNextChangeNotification failed");
break;
case WAIT_OBJECT_0 + 1: // An event occurred on a directory
System::throwLastErrorIf(not FindNextChangeNotification(m_changeHandles[1]), "FindNextChangeNotification failed");
break;
case WAIT_TIMEOUT: break;
default:
System::throwLastError("CppUtils/FileSystem/Watcher/listener: Unhandled wait status");
break;
}
// Todo: https://learn.microsoft.com/fr-fr/windows/win32/fileio/obtaining-directory-change-notifications?redirectedfrom=MSDN
#elif defined(OS_LINUX)
auto nbFileDescriptorsReady = 0uz;
{
auto epollWaitResult = epoll_wait(m_eventPoll, std::data(m_events), maxEvents, 1);
if (epollWaitResult == -1)
return;
[[assume(epollWaitResult >= 0)]];
nbFileDescriptorsReady = static_cast<std::size_t>(epollWaitResult);
}
for (auto i = 0uz; i < nbFileDescriptorsReady; ++i)
{
auto buffer = std::array<std::byte, 4'096>{};
auto length = 0z;
{
auto eventFileDescriptor = m_events[i].data.fd;
if (eventFileDescriptor == m_stopPipe.read)
continue;
length = read(eventFileDescriptor, std::data(buffer), std::size(buffer));
if (length == -1 and errno == EINTR)
break;
}
for (auto offset = std::ptrdiff_t{0}; offset < length;)
{
auto inotifyEvent = *reinterpret_cast<INotifyEvent*>(std::data(buffer) + offset);
offset += sizeof(INotifyEvent);
auto filename = std::string_view{reinterpret_cast<const char*>(std::data(buffer) + offset)};
offset += inotifyEvent.len;
auto lockGuard = std::unique_lock{m_mutex};
if (Event::Ignored & static_cast<Event>(inotifyEvent.mask))
{
m_watchDescriptors.eraseRight(inotifyEvent.wd);
continue;
}
if (auto it = m_watchDescriptors.findRight(inotifyEvent.wd);
it != std::cend(m_watchDescriptors))
{
auto path = it->first;
if (std::filesystem::is_directory(path))
path /= filename;
if (std::filesystem::is_directory(path))
inotifyEvent.mask |= static_cast<std::underlying_type_t<Event>>(Event::IsDirectory);
for (const auto& [event, subscribedFunction] : m_subscribedFunctions)
if (event & static_cast<Event>(inotifyEvent.mask))
subscribedFunction(static_cast<Event>(inotifyEvent.mask), path);
}
}
}
#endif
}
#if defined(OS_LINUX)
inline auto watch(const std::filesystem::path& path, Event event = Event::All) -> void
{
if (not std::filesystem::exists(path))
return;
forDirectories(path, [this, event](const auto& path) -> void {
watch(path, event);
}, true);
auto lockGuard = std::unique_lock{m_mutex};
auto watchDescriptor = System::throwErrno(
inotify_add_watch(m_inotify, path.string().c_str(), static_cast<std::underlying_type_t<Event>>(event)),
std::format("Failed to watch the file {}", path.string()));
m_watchDescriptors.insert({path, watchDescriptor});
}
#elif defined(OS_WINDOWS)
inline auto watch(const std::filesystem::path& path) -> void
{
auto changeHandle = FindFirstChangeNotification(
path.string().c_str(), true, FILE_NOTIFY_CHANGE_FILE_NAME);
if (changeHandle == INVALID_HANDLE_VALUE)
throw std::runtime_error{std::format("Failed to watch the file {}", path.string())}; // Todo: utiliser GetLastError()
m_changeHandles.push_back(changeHandle);
}
#endif
inline auto unwatch(const std::filesystem::path& directoryPath) -> void
{
forDirectories(directoryPath, [this](const auto& directoryPath) -> void {
unwatch(directoryPath);
}, true);
auto lockGuard = std::unique_lock{m_mutex};
#if defined(OS_LINUX)
System::throwErrno(
inotify_rm_watch(m_inotify, m_watchDescriptors.left(directoryPath)),
std::format("Failed to stop watching the file {}", directoryPath.string()));
m_watchDescriptors.eraseLeft(directoryPath);
#endif
}
inline auto unwatchAll() -> void
{
auto lockGuard = std::unique_lock{m_mutex};
#if defined(OS_LINUX)
for (const auto& [path, fileDescriptor] : m_watchDescriptors)
System::throwErrno(
inotify_rm_watch(m_inotify, fileDescriptor),
std::format("Failed to stop watching the file {}", path.string()));
m_watchDescriptors.clear();
#endif
}
#if defined(OS_LINUX)
inline auto onEvent(Event event, const SubscribeFunction& function) -> void
{
auto lockGuard = std::unique_lock{m_mutex};
m_subscribedFunctions.push_back({event, function});
}
inline auto onEvent(const SubscribeFunction& function) -> void
{
auto lockGuard = std::unique_lock{m_mutex};
m_subscribedFunctions.push_back({Event::All, function});
}
#endif
private:
inline auto interruptFunction() -> void
{
#if defined(OS_LINUX)
auto value = std::uint8_t{0};
write(m_stopPipe.write, std::addressof(value), 1uz);
#endif
}
std::mutex m_mutex;
Thread::ThreadLoop m_threadLoop;
#if defined(OS_WINDOWS)
std::vector<System::Handle> m_changeHandles;
#elif defined(OS_LINUX)
System::FileDescriptor m_eventPoll;
System::FileDescriptor m_inotify;
System::Pipe m_stopPipe;
epoll_event m_event;
epoll_event m_stopEvent;
std::array<epoll_event, maxEvents> m_events;
Container::BidirectionalMap<std::filesystem::path, WatchDescriptor> m_watchDescriptors;
std::vector<std::pair<Event, SubscribeFunction>> m_subscribedFunctions;
#elif defined(OS_MACOS)
[[maybe_unused]] FSEventStreamRef m_filesystemEventStream;
#endif
};
}