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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
|
//! File modification watcher.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::Duration;
use smithay::reexports::calloop::channel::SyncSender;
pub struct Watcher {
should_stop: Arc<AtomicBool>,
}
impl Drop for Watcher {
fn drop(&mut self) {
self.should_stop.store(true, Ordering::SeqCst);
}
}
impl Watcher {
pub fn new<T: Send + 'static>(
path: PathBuf,
process: impl FnMut(&Path) -> T + Send + 'static,
changed: SyncSender<T>,
) -> Self {
Self::with_start_notification(path, process, changed, None)
}
pub fn with_start_notification<T: Send + 'static>(
path: PathBuf,
mut process: impl FnMut(&Path) -> T + Send + 'static,
changed: SyncSender<T>,
started: Option<mpsc::SyncSender<()>>,
) -> Self {
let should_stop = Arc::new(AtomicBool::new(false));
{
let should_stop = should_stop.clone();
thread::Builder::new()
.name(format!("Filesystem Watcher for {}", path.to_string_lossy()))
.spawn(move || {
// this "should" be as simple as mtime, but it does not quite work in practice;
// it doesn't work if the config is a symlink, and its target changes but the
// new target and old target have identical mtimes.
//
// in practice, this does not occur on any systems other than nix.
// because, on nix practically everything is a symlink to /nix/store
// and due to reproducibility, /nix/store keeps no mtime (= 1970-01-01)
// so, symlink targets change frequently when mtime doesn't.
let mut last_props = path
.canonicalize()
.and_then(|canon| Ok((canon.metadata()?.modified()?, canon)))
.ok();
if let Some(started) = started {
let _ = started.send(());
}
loop {
thread::sleep(Duration::from_millis(500));
if should_stop.load(Ordering::SeqCst) {
break;
}
if let Ok(new_props) = path
.canonicalize()
.and_then(|canon| Ok((canon.metadata()?.modified()?, canon)))
{
if last_props.as_ref() != Some(&new_props) {
trace!("file changed: {}", path.to_string_lossy());
let rv = process(&path);
if let Err(err) = changed.send(rv) {
warn!("error sending change notification: {err:?}");
break;
}
last_props = Some(new_props);
}
}
}
debug!("exiting watcher thread for {}", path.to_string_lossy());
})
.unwrap();
}
Self { should_stop }
}
}
#[cfg(test)]
mod tests {
use std::error::Error;
use std::fs::File;
use std::io::Write;
use std::sync::atomic::AtomicU8;
use calloop::channel::sync_channel;
use calloop::EventLoop;
use smithay::reexports::rustix::fs::{futimens, Timestamps};
use smithay::reexports::rustix::time::Timespec;
use xshell::{cmd, Shell};
use super::*;
fn check(
setup: impl FnOnce(&Shell) -> Result<(), Box<dyn Error>>,
change: impl FnOnce(&Shell) -> Result<(), Box<dyn Error>>,
) {
let sh = Shell::new().unwrap();
let temp_dir = sh.create_temp_dir().unwrap();
sh.change_dir(temp_dir.path());
// let dir = sh.create_dir("xshell").unwrap();
// sh.change_dir(dir);
let mut config_path = sh.current_dir();
config_path.push("niri");
config_path.push("config.kdl");
setup(&sh).unwrap();
let changed = AtomicU8::new(0);
let mut event_loop = EventLoop::try_new().unwrap();
let loop_handle = event_loop.handle();
let (tx, rx) = sync_channel(1);
let (started_tx, started_rx) = mpsc::sync_channel(1);
let _watcher =
Watcher::with_start_notification(config_path.clone(), |_| (), tx, Some(started_tx));
loop_handle
.insert_source(rx, |_, _, _| {
changed.fetch_add(1, Ordering::SeqCst);
})
.unwrap();
started_rx.recv().unwrap();
// HACK: if we don't sleep, files might have the same mtime.
thread::sleep(Duration::from_millis(100));
change(&sh).unwrap();
event_loop
.dispatch(Duration::from_millis(750), &mut ())
.unwrap();
assert_eq!(changed.load(Ordering::SeqCst), 1);
// Verify that the watcher didn't break.
sh.write_file(&config_path, "c").unwrap();
event_loop
.dispatch(Duration::from_millis(750), &mut ())
.unwrap();
assert_eq!(changed.load(Ordering::SeqCst), 2);
}
#[test]
fn change_file() {
check(
|sh| {
sh.write_file("niri/config.kdl", "a")?;
Ok(())
},
|sh| {
sh.write_file("niri/config.kdl", "b")?;
Ok(())
},
);
}
#[test]
fn create_file() {
check(
|sh| {
sh.create_dir("niri")?;
Ok(())
},
|sh| {
sh.write_file("niri/config.kdl", "a")?;
Ok(())
},
);
}
#[test]
fn create_dir_and_file() {
check(
|_sh| Ok(()),
|sh| {
sh.write_file("niri/config.kdl", "a")?;
Ok(())
},
);
}
#[test]
fn change_linked_file() {
check(
|sh| {
sh.write_file("niri/config2.kdl", "a")?;
cmd!(sh, "ln -s config2.kdl niri/config.kdl").run()?;
Ok(())
},
|sh| {
sh.write_file("niri/config2.kdl", "b")?;
Ok(())
},
);
}
#[test]
fn change_file_in_linked_dir() {
check(
|sh| {
sh.write_file("niri2/config.kdl", "a")?;
cmd!(sh, "ln -s niri2 niri").run()?;
Ok(())
},
|sh| {
sh.write_file("niri2/config.kdl", "b")?;
Ok(())
},
);
}
#[test]
fn recreate_file() {
check(
|sh| {
sh.write_file("niri/config.kdl", "a")?;
Ok(())
},
|sh| {
sh.remove_path("niri/config.kdl")?;
sh.write_file("niri/config.kdl", "b")?;
Ok(())
},
);
}
#[test]
fn recreate_dir() {
check(
|sh| {
sh.write_file("niri/config.kdl", "a")?;
Ok(())
},
|sh| {
sh.remove_path("niri")?;
sh.write_file("niri/config.kdl", "b")?;
Ok(())
},
);
}
#[test]
fn swap_dir() {
check(
|sh| {
sh.write_file("niri/config.kdl", "a")
|